dsh-crate 0.0.0-stage → 0.5.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.
Files changed (132) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +288 -2
  3. package/README.zh.md +263 -0
  4. package/UPDATE-API-V1.md +207 -0
  5. package/assets/logo.svg +37 -0
  6. package/client/client.js +18964 -0
  7. package/cordis.patch.yml +4 -0
  8. package/lib/accelerate.js +194 -0
  9. package/lib/agents.js +67 -0
  10. package/lib/backup.js +688 -0
  11. package/lib/body-progress.js +173 -0
  12. package/lib/catalog-local-match.js +160 -0
  13. package/lib/catalog-npm.js +180 -0
  14. package/lib/changelog.js +462 -0
  15. package/lib/channels.js +64 -0
  16. package/lib/check.js +1557 -0
  17. package/lib/compatibility.js +265 -0
  18. package/lib/crate-catalog.js +179 -0
  19. package/lib/diagnostics.js +49 -0
  20. package/lib/discovery-compatibility.js +476 -0
  21. package/lib/drain-journal.js +164 -0
  22. package/lib/drain.js +1043 -0
  23. package/lib/dsh-cli.js +1373 -0
  24. package/lib/dsh-install.js +259 -0
  25. package/lib/entry-identity.js +85 -0
  26. package/lib/gist.js +369 -0
  27. package/lib/groups.js +108 -0
  28. package/lib/home-paths.js +29 -0
  29. package/lib/host-recovery.js +187 -0
  30. package/lib/hot.js +918 -0
  31. package/lib/http.js +252 -0
  32. package/lib/index.js +394 -0
  33. package/lib/install.js +1147 -0
  34. package/lib/lifecycle.js +37 -0
  35. package/lib/log-redaction.js +24 -0
  36. package/lib/log.js +204 -0
  37. package/lib/ndjson.js +154 -0
  38. package/lib/net.js +174 -0
  39. package/lib/official-desktop.js +619 -0
  40. package/lib/order.js +284 -0
  41. package/lib/patch.js +943 -0
  42. package/lib/pending-rows.js +142 -0
  43. package/lib/pending-updates.js +346 -0
  44. package/lib/pnpm-compat.js +972 -0
  45. package/lib/presets.js +282 -0
  46. package/lib/probe-context.js +20 -0
  47. package/lib/proc-text.js +69 -0
  48. package/lib/profile.js +1989 -0
  49. package/lib/recovery.js +1059 -0
  50. package/lib/region-probe.js +93 -0
  51. package/lib/regions.js +283 -0
  52. package/lib/registry.js +308 -0
  53. package/lib/release-candidates.js +115 -0
  54. package/lib/release-updates.js +70 -0
  55. package/lib/restart.js +688 -0
  56. package/lib/routes.js +7960 -0
  57. package/lib/settings.js +164 -0
  58. package/lib/shelfry-catalog.js +179 -0
  59. package/lib/snapshot.js +506 -0
  60. package/lib/source-migration.js +164 -0
  61. package/lib/sources.js +1005 -0
  62. package/lib/state.js +38 -0
  63. package/lib/store.js +163 -0
  64. package/lib/themes.js +350 -0
  65. package/lib/trial.js +125 -0
  66. package/lib/types/accelerate.d.ts +85 -0
  67. package/lib/types/agents.d.ts +52 -0
  68. package/lib/types/backup.d.ts +171 -0
  69. package/lib/types/body-progress.d.ts +94 -0
  70. package/lib/types/catalog-local-match.d.ts +39 -0
  71. package/lib/types/catalog-npm.d.ts +77 -0
  72. package/lib/types/changelog.d.ts +131 -0
  73. package/lib/types/channels.d.ts +56 -0
  74. package/lib/types/check.d.ts +381 -0
  75. package/lib/types/compatibility.d.ts +83 -0
  76. package/lib/types/crate-catalog.d.ts +48 -0
  77. package/lib/types/diagnostics.d.ts +29 -0
  78. package/lib/types/discovery-compatibility.d.ts +145 -0
  79. package/lib/types/drain-journal.d.ts +25 -0
  80. package/lib/types/drain.d.ts +306 -0
  81. package/lib/types/dsh-cli.d.ts +481 -0
  82. package/lib/types/dsh-install.d.ts +106 -0
  83. package/lib/types/entry-identity.d.ts +68 -0
  84. package/lib/types/gist.d.ts +79 -0
  85. package/lib/types/groups.d.ts +34 -0
  86. package/lib/types/home-paths.d.ts +13 -0
  87. package/lib/types/host-recovery.d.ts +95 -0
  88. package/lib/types/hot.d.ts +434 -0
  89. package/lib/types/http.d.ts +114 -0
  90. package/lib/types/index.d.ts +52 -0
  91. package/lib/types/install.d.ts +463 -0
  92. package/lib/types/lifecycle.d.ts +14 -0
  93. package/lib/types/log-redaction.d.ts +2 -0
  94. package/lib/types/log.d.ts +43 -0
  95. package/lib/types/ndjson.d.ts +52 -0
  96. package/lib/types/net.d.ts +94 -0
  97. package/lib/types/official-desktop.d.ts +59 -0
  98. package/lib/types/order.d.ts +100 -0
  99. package/lib/types/patch.d.ts +218 -0
  100. package/lib/types/pending-rows.d.ts +81 -0
  101. package/lib/types/pending-updates.d.ts +161 -0
  102. package/lib/types/pnpm-compat.d.ts +102 -0
  103. package/lib/types/presets.d.ts +94 -0
  104. package/lib/types/probe-context.d.ts +14 -0
  105. package/lib/types/proc-text.d.ts +29 -0
  106. package/lib/types/profile.d.ts +551 -0
  107. package/lib/types/recovery.d.ts +342 -0
  108. package/lib/types/region-probe.d.ts +50 -0
  109. package/lib/types/regions.d.ts +134 -0
  110. package/lib/types/registry.d.ts +160 -0
  111. package/lib/types/release-candidates.d.ts +42 -0
  112. package/lib/types/release-updates.d.ts +15 -0
  113. package/lib/types/restart.d.ts +279 -0
  114. package/lib/types/routes.d.ts +130 -0
  115. package/lib/types/settings.d.ts +112 -0
  116. package/lib/types/shelfry-catalog.d.ts +48 -0
  117. package/lib/types/snapshot.d.ts +93 -0
  118. package/lib/types/source-migration.d.ts +100 -0
  119. package/lib/types/sources.d.ts +391 -0
  120. package/lib/types/state.d.ts +20 -0
  121. package/lib/types/store.d.ts +47 -0
  122. package/lib/types/themes.d.ts +46 -0
  123. package/lib/types/trial.d.ts +61 -0
  124. package/lib/types/update-api-v1.d.ts +83 -0
  125. package/lib/types/updates.d.ts +273 -0
  126. package/lib/types/verify.d.ts +277 -0
  127. package/lib/update-api-v1.js +273 -0
  128. package/lib/updates.js +981 -0
  129. package/lib/verify.js +930 -0
  130. package/locale/en.json +5 -0
  131. package/locale/zh.json +6 -0
  132. package/package.json +113 -4
package/lib/check.js ADDED
@@ -0,0 +1,1557 @@
1
+ /**
2
+ * Profile composition diagnostics — issue #98 (phase 1): the check-only
3
+ * "plugin loading layer and conflict view".
4
+ *
5
+ * Pure filesystem analysis of one dsh profile directory; no processes, no
6
+ * network, no writes. It answers, for the profile the market is serving:
7
+ *
8
+ * 1. What is the actual bundle stack (dsh.profile.bundles order) and where
9
+ * does each layer come from (official in-box bundle vs community, the
10
+ * dependency spec, the resolved directory)?
11
+ * 2. Which loader entry ids does the composed tree contain, and are any
12
+ * duplicated across layers (the "duplicate loader entry id" boot failure
13
+ * from #98)? Which rows does a later layer override?
14
+ * 3. Does any installed plugin pull a DSH host core package
15
+ * (@deepseek-ai/dsh, @deepseek-ai/dsh-tools, @deepseek-ai/cordis, …) in
16
+ * as an ordinary dependency — the dsh-excel-chat failure mode where the
17
+ * plugin's copy gets hoisted to the profile root and shadows the host's
18
+ * version (tool calls die, minimal preset fails to mount)?
19
+ * 4. Are there multiple versions of one core package in the lockfile, and
20
+ * do plugin peerDependencies ranges match the resolved core version?
21
+ * 5. Do effective user/home patch entries reference npm package roots that
22
+ * are installed in the profile-visible node_modules ancestry?
23
+ *
24
+ * The composition step mirrors @deepseek-ai/dsh-app-boot's applyEntryPatches
25
+ * (same js-yaml dialect incl. `!!js` scalars), so the rows reported here are
26
+ * what actually mounts at boot.
27
+ */
28
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
29
+ import { createRequire, isBuiltin } from 'node:module';
30
+ import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
31
+ import { JSON_SCHEMA, Type, load } from 'js-yaml';
32
+ import { desktopApplicationRoots, findDshInstallDir } from './dsh-install.js';
33
+ import { resolveDshHome } from './home-paths.js';
34
+ import { hostNodeModulesRoot } from './install.js';
35
+ import { INBOX_BUNDLES, readBundleRules, suggestOrder, validateOrder } from './order.js';
36
+ // Electron's app.asar packages can be loadable by the host while invisible to
37
+ // filesystem probes made from a profile plugin. This is a property of the
38
+ // LAYOUT, not of any particular package: inside an archive every probe
39
+ // answers "absent" for every name, so the fallback keys on the layout, on
40
+ // whether the name is DeepSeek's (`@deepseek-ai/` — only they publish the
41
+ // host), and on nothing else.
42
+ //
43
+ // It used to be two fixed name lists — `dsh-experimental-agent-team-profile`
44
+ // as a bundle, `dsh-mcp-client` as a loader — and every name a Desktop build
45
+ // shipped that was not on them reproduced the same false "will fail to boot"
46
+ // (#676: two reporters, `dsh-experimental-agent-team-profile` AND
47
+ // `dsh-experimental-agent-team-web-profile`). A list of which bundles a host
48
+ // ships cannot be maintained from inside a market that cannot see the host.
49
+ function isPackagedDesktopInstall(dshInstallDir) {
50
+ return dshInstallDir !== null && /[/\\]app\.asar[/\\]/iu.test(dshInstallDir);
51
+ }
52
+ export { findDshInstallDir } from './dsh-install.js';
53
+ /** js-yaml dialect for `!!js` scalars — identical to dsh-app-boot's entryListSchema. */
54
+ const jsExpr = new Type('tag:yaml.org,2002:js', {
55
+ kind: 'scalar',
56
+ resolve: (data) => typeof data === 'string',
57
+ construct: (data) => ({ __jsExpr: String(data) }),
58
+ });
59
+ const entrySchema = JSON_SCHEMA.extend(jsExpr);
60
+ function isRecord(value) {
61
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
62
+ }
63
+ /** Parse entry-list source with the DSH dialect; null when it is not a list. */
64
+ export function parsePatchText(text) {
65
+ try {
66
+ const value = load(text, { schema: entrySchema });
67
+ return Array.isArray(value) ? value : null;
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ /** Parse one entry-list patch file with the DSH dialect; null when unreadable. */
74
+ export function parsePatchFile(path) {
75
+ try {
76
+ return parsePatchText(readFileSync(path, 'utf8'));
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ }
82
+ /** Whether `name` goes through the Loader's bare-module resolver. */
83
+ function isBareLoaderSpecifier(name) {
84
+ return !name.startsWith('.')
85
+ && !name.startsWith('#')
86
+ && !isAbsolute(name)
87
+ && !/^[a-z][a-z\d+.-]*:/i.test(name);
88
+ }
89
+ /** Npm package root owning one bare Loader specifier. */
90
+ function packageRoot(specifier) {
91
+ const parts = specifier.split('/');
92
+ const segments = specifier.startsWith('@') ? parts.slice(0, 2) : parts.slice(0, 1);
93
+ if (segments.length !== (specifier.startsWith('@') ? 2 : 1))
94
+ return null;
95
+ if (segments.some(segment => segment === '' || segment === '.' || segment === '..'
96
+ || segment.includes('%') || segment.includes('\\')))
97
+ return null;
98
+ if (specifier.startsWith('@') && (segments[0]?.length ?? 0) <= 1)
99
+ return null;
100
+ return segments.join('/');
101
+ }
102
+ /**
103
+ * Package-root presence from the Loader-visible profile ancestry only.
104
+ * An explicit walk avoids CommonJS global lookup directories that
105
+ * `createRequire(...).resolve.paths()` appends but Node ESM does not search.
106
+ */
107
+ function profilePackageInstalled(profileDirectory, name) {
108
+ try {
109
+ const profile = JSON.parse(readFileSync(join(profileDirectory, 'package.json'), 'utf8'));
110
+ if (isRecord(profile) && profile.name === name
111
+ && profile.exports !== undefined && profile.exports !== null)
112
+ return true;
113
+ }
114
+ catch { /* not a self-referencing profile package */ }
115
+ let directory = resolve(profileDirectory);
116
+ while (true) {
117
+ const packageDirectory = join(directory, 'node_modules', name);
118
+ // Node stops at the nearest matching package directory. A partial install
119
+ // there shadows any healthy parent copy and must not be accepted.
120
+ try {
121
+ if (statSync(packageDirectory).isDirectory()) {
122
+ return existsSync(join(packageDirectory, 'package.json'));
123
+ }
124
+ }
125
+ catch { /* keep walking */ }
126
+ const parent = dirname(directory);
127
+ if (parent === directory)
128
+ return false;
129
+ directory = parent;
130
+ }
131
+ }
132
+ /** Every id in one patch row's insert list, recursively (group configs included). */
133
+ function collectInsertIds(rows) {
134
+ const ids = [];
135
+ const walk = (value) => {
136
+ if (!Array.isArray(value))
137
+ return;
138
+ for (const entry of value) {
139
+ if (!isRecord(entry) || typeof entry.id !== 'string')
140
+ continue;
141
+ ids.push(entry.id);
142
+ if (Array.isArray(entry.config))
143
+ walk(entry.config);
144
+ }
145
+ };
146
+ for (const patch of rows) {
147
+ if (!isRecord(patch) || !Array.isArray(patch.insert))
148
+ continue;
149
+ walk(patch.insert);
150
+ }
151
+ return ids;
152
+ }
153
+ /** DSH host core packages: what the dsh installation ships under @deepseek-ai. */
154
+ export function corePackageNames(dshInstallDir) {
155
+ const names = new Set([
156
+ // Curated fallback seed (used when the install dir cannot be located).
157
+ '@deepseek-ai/dsh',
158
+ '@deepseek-ai/dsh-base',
159
+ '@deepseek-ai/dsh-web-app',
160
+ '@deepseek-ai/dsh-headless',
161
+ '@deepseek-ai/dsh-app-boot',
162
+ '@deepseek-ai/dsh-home-paths',
163
+ '@deepseek-ai/dsh-launch-environment',
164
+ '@deepseek-ai/dsh-cmdline',
165
+ '@deepseek-ai/dsh-tools',
166
+ '@deepseek-ai/dsh-llm',
167
+ '@deepseek-ai/dsh-system-prompt',
168
+ '@deepseek-ai/dsh-attachment',
169
+ '@deepseek-ai/dsh-agent',
170
+ '@deepseek-ai/dsh-agent-loop',
171
+ '@deepseek-ai/dsh-session',
172
+ '@deepseek-ai/dsh-subagent',
173
+ '@deepseek-ai/cordis',
174
+ '@deepseek-ai/cordis-plugin-loader',
175
+ '@deepseek-ai/cordis-plugin-include',
176
+ '@deepseek-ai/cordis-plugin-hmr',
177
+ '@deepseek-ai/cordis-plugin-timer',
178
+ '@deepseek-ai/cordis-plugin-group',
179
+ ]);
180
+ if (dshInstallDir === null)
181
+ return names;
182
+ try {
183
+ // The install's own node_modules is the authoritative host-core inventory:
184
+ // everything under @deepseek-ai whose bare name starts with dsh or cordis,
185
+ // plus the app package itself.
186
+ //
187
+ // `dshHostInfo()` answers either a PACKAGE directory (the CLI layout
188
+ // `<prefix>/node_modules/@deepseek-ai/dsh`, and the #778 nested form
189
+ // `<resources>/app.asar/dsh/node_modules/@deepseek-ai/dsh`) or a flat
190
+ // Desktop deployment root — never a constant "installation root".
191
+ // Splicing `node_modules` onto whichever arrived only happened to work
192
+ // for the flat shape. For a package directory the splice landed two
193
+ // levels deep and readdirSync threw, so the curated seed silently stood
194
+ // in for the real inventory — and when the host package carries its own
195
+ // nested `@deepseek-ai` scope (pnpm isolated trees), it read that
196
+ // truncated subset instead (#676: every package the real inventory has
197
+ // and the answer lacked became a fresh "will fail to boot").
198
+ // hostNodeModulesRoot() already derives the shared root from both shapes.
199
+ for (const entry of readdirSync(join(hostNodeModulesRoot(dshInstallDir), '@deepseek-ai'), { withFileTypes: true })) {
200
+ if (!entry.isDirectory() && !entry.isSymbolicLink())
201
+ continue;
202
+ if (/^(?:dsh|cordis)/.test(entry.name))
203
+ names.add(`@deepseek-ai/${entry.name}`);
204
+ }
205
+ }
206
+ catch { /* install node_modules unreadable — the curated seed stands */ }
207
+ try {
208
+ const manifest = JSON.parse(readFileSync(join(dshInstallDir, 'package.json'), 'utf8'));
209
+ if (typeof manifest.name === 'string')
210
+ names.add(manifest.name);
211
+ }
212
+ catch { /* not a package dir */ }
213
+ return names;
214
+ }
215
+ /** Version of `name` as physically resolved at `base`/node_modules, or null. */
216
+ function readNodeModulesVersion(base, name) {
217
+ try {
218
+ const manifest = JSON.parse(readFileSync(join(base, 'node_modules', name, 'package.json'), 'utf8'));
219
+ return typeof manifest.version === 'string' ? manifest.version : null;
220
+ }
221
+ catch {
222
+ return null;
223
+ }
224
+ }
225
+ /**
226
+ * Resolve one package's directory the way the dsh boot does
227
+ * (dsh-app-boot's resolveBundleDir): probe Node's own node_modules search
228
+ * paths from the installation anchor first, then the profile directory.
229
+ * Node resolution walks upward, so this also finds pnpm's workspace-root
230
+ * hoisting (`<profiles>/node_modules/…` when the profile lives under
231
+ * `<profiles>/<name>`) and mirrors the Loader's package search roots.
232
+ */
233
+ function resolvePackageDir(anchorPackageJson, name, ignoredPackageDirectory) {
234
+ let paths = [];
235
+ try {
236
+ paths = createRequire(anchorPackageJson).resolve.paths(name) ?? [];
237
+ }
238
+ catch {
239
+ return null;
240
+ }
241
+ const ignored = ignoredPackageDirectory === undefined
242
+ ? null
243
+ : resolve(ignoredPackageDirectory);
244
+ for (const searchPath of paths) {
245
+ const candidate = join(searchPath, name);
246
+ if (ignored !== null) {
247
+ const resolvedCandidate = resolve(candidate);
248
+ const matchesIgnored = process.platform === 'win32'
249
+ ? resolvedCandidate.toLowerCase() === ignored.toLowerCase()
250
+ : resolvedCandidate === ignored;
251
+ if (matchesIgnored)
252
+ continue;
253
+ }
254
+ if (existsSync(join(candidate, 'package.json')))
255
+ return candidate;
256
+ }
257
+ return null;
258
+ }
259
+ /**
260
+ * Version of `name` visible to the profile's dependency tree: the profile's
261
+ * own node_modules first, then the workspace root (pnpm hoists shared deps
262
+ * there when the profile is a workspace member — the dsh layout keeps
263
+ * `<profiles>/node_modules` as the shared store for all profiles).
264
+ */
265
+ function readProfileVisibleVersion(profileDirectory, name) {
266
+ const direct = readNodeModulesVersion(profileDirectory, name);
267
+ if (direct !== null)
268
+ return direct;
269
+ const workspaceRoot = dirname(profileDirectory);
270
+ if (workspaceRoot === profileDirectory)
271
+ return null;
272
+ return readNodeModulesVersion(workspaceRoot, name);
273
+ }
274
+ /** Top-level installed package names (incl. scoped), excluding pnpm internals. */
275
+ function installedPackageNames(profileDir) {
276
+ const names = [];
277
+ // Windows `link:` installs are junctions; Dirent.isDirectory() is false for
278
+ // them on some Node versions, so treat symlinks as packages too (B2).
279
+ const isPkgDir = (entry) => entry.isDirectory() || entry.isSymbolicLink();
280
+ let root;
281
+ try {
282
+ root = readdirSync(join(profileDir, 'node_modules'), { withFileTypes: true })
283
+ .filter(entry => isPkgDir(entry) && entry.name !== '.bin' && entry.name !== '.pnpm' && entry.name !== '.dsh-plugin-backups')
284
+ .map(entry => entry.name);
285
+ }
286
+ catch {
287
+ return names;
288
+ }
289
+ for (const name of root) {
290
+ if (!name.startsWith('@')) {
291
+ names.push(name);
292
+ continue;
293
+ }
294
+ try {
295
+ for (const scoped of readdirSync(join(profileDir, 'node_modules', name), { withFileTypes: true })) {
296
+ if (isPkgDir(scoped))
297
+ names.push(`${name}/${scoped.name}`);
298
+ }
299
+ }
300
+ catch { /* empty scope dir */ }
301
+ }
302
+ return names;
303
+ }
304
+ const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
305
+ function parseSemver(value) {
306
+ const m = SEMVER_RE.exec(value.trim());
307
+ if (m === null)
308
+ return null;
309
+ return {
310
+ major: Number(m[1]),
311
+ minor: Number(m[2]),
312
+ patch: Number(m[3]),
313
+ pre: m[4] === undefined ? [] : m[4].split('.'),
314
+ };
315
+ }
316
+ /**
317
+ * Rewrite a comparator whose target is a PARTIAL version into the full
318
+ * comparators node-semver desugars it to. Anything else comes back as is.
319
+ *
320
+ * The `@deepseek-ai/dsh-*` peers of a whole family of connector plugins are
321
+ * written this way (`>=0.1.5 <0.3`, `>=0.1.7-rc <2`, `>=0.2.0-rc.0 <0.3`).
322
+ * Read as unknown, they left the activation gate standing aside: measured
323
+ * against the host's own evaluator over 699 live catalog manifests, those
324
+ * were the last 7 of 2796 (package, runtime) pairs where the host refuses a
325
+ * plugin and the market still promised a restart would apply it.
326
+ *
327
+ * Zero-filling the target is right for `>=` and wrong for the rest. A partial
328
+ * names a whole release line, so node-semver (`replaceXRange`, `replaceTilde`,
329
+ * `replaceCaret`) moves the bound to the edge of that line:
330
+ *
331
+ * `<0.3` → `<0.3.0-0` `<=0.3` → `<0.4.0-0`
332
+ * `>0.3` → `>=0.4.0` `>1` → `>=2.0.0`
333
+ * `~1` → `>=1.0.0 <2.0.0-0` `^0` → `>=0.0.0 <1.0.0-0`
334
+ * `^0.0` → `>=0.0.0 <0.1.0-0`
335
+ *
336
+ * Comparing against the raw partial string instead ordered `9.1.0` above
337
+ * `10` and `0.10.0` below `0.3`, character by character.
338
+ *
339
+ * A BARE partial (`1.2`) has no operator and is an x-range in semver
340
+ * (`>=1.2.0 <1.3.0`), so it stays as is and parses as unknown below rather
341
+ * than being mistaken for the exact version `1.2.0`.
342
+ */
343
+ export function expandPartialComparator(part, includePrerelease) {
344
+ const m = /^(\^|~|>=|<=|>|<)(\d+)(?:\.(\d+))?$/u.exec(part.trim());
345
+ if (m === null)
346
+ return [part];
347
+ const op = m[1];
348
+ const major = Number(m[2]);
349
+ const minor = m[3] === undefined ? null : Number(m[3]);
350
+ // node-semver lowers a desugared floor to `-0` under includePrerelease, so
351
+ // `>=0.3` admits `0.3.0-rc.1` there. Ceilings always carry `-0`.
352
+ const z = includePrerelease ? '-0' : '';
353
+ const floor = `${String(major)}.${String(minor ?? 0)}.0`;
354
+ const nextLine = minor === null ? `${String(major + 1)}.0.0` : `${String(major)}.${String(minor + 1)}.0`;
355
+ switch (op) {
356
+ case '>=':
357
+ return [`>=${floor}${z}`];
358
+ case '>':
359
+ return [`>=${nextLine}${z}`];
360
+ case '<':
361
+ return [`<${exclusiveUpperBound(floor)}`];
362
+ case '<=':
363
+ return [`<${exclusiveUpperBound(nextLine)}`];
364
+ case '~':
365
+ return [`>=${floor}${z}`, `<${exclusiveUpperBound(nextLine)}`];
366
+ default: {
367
+ // `^`: the next major, except inside 0.x where the minor is breaking.
368
+ const ceiling = major > 0 || minor === null ? `${String(major + 1)}.0.0` : `0.${String(minor + 1)}.0`;
369
+ return [`>=${floor}${z}`, `<${exclusiveUpperBound(ceiling)}`];
370
+ }
371
+ }
372
+ }
373
+ function comparePre(a, b) {
374
+ const len = Math.max(a.length, b.length);
375
+ for (let i = 0; i < len; i += 1) {
376
+ const x = a[i];
377
+ const y = b[i];
378
+ if (x === undefined)
379
+ return y === undefined ? 0 : -1; // a has fewer parts → a < b
380
+ if (y === undefined)
381
+ return 1;
382
+ if (x === y)
383
+ continue;
384
+ const xn = /^\d+$/.test(x);
385
+ const yn = /^\d+$/.test(y);
386
+ if (xn && yn)
387
+ return Number(x) - Number(y) || 0;
388
+ if (xn)
389
+ return -1; // numeric identifiers sort before alphanumeric
390
+ if (yn)
391
+ return 1;
392
+ return x < y ? -1 : 1;
393
+ }
394
+ return 0;
395
+ }
396
+ /** Compare two semver strings: negative | zero | positive (prerelease < release of same base). */
397
+ /** Whether a string is a well-formed semver `compareSemver` can order. */
398
+ export function isSemver(value) {
399
+ return parseSemver(value) !== null;
400
+ }
401
+ export function compareSemver(a, b) {
402
+ const av = parseSemver(a);
403
+ const bv = parseSemver(b);
404
+ if (av === null || bv === null)
405
+ return a < b ? -1 : a > b ? 1 : 0;
406
+ if (av.major !== bv.major)
407
+ return av.major - bv.major || 0;
408
+ if (av.minor !== bv.minor)
409
+ return av.minor - bv.minor || 0;
410
+ if (av.patch !== bv.patch)
411
+ return av.patch - bv.patch || 0;
412
+ if (av.pre.length === 0 && bv.pre.length === 0)
413
+ return 0;
414
+ if (av.pre.length === 0)
415
+ return 1; // release > prerelease
416
+ if (bv.pre.length === 0)
417
+ return -1;
418
+ return comparePre(av.pre, bv.pre);
419
+ }
420
+ function gte(a, b) {
421
+ const cmp = compareSemver(`${a.major}.${a.minor}.${a.patch}${a.pre.length > 0 ? `-${a.pre.join('.')}` : ''}`, `${b.major}.${b.minor}.${b.patch}${b.pre.length > 0 ? `-${b.pre.join('.')}` : ''}`);
422
+ return cmp >= 0;
423
+ }
424
+ /** String form of a parsed Semver (the boundary objects carry no prerelease). */
425
+ function semverStr(v) {
426
+ return `${v.major}.${v.minor}.${v.patch}${v.pre.length > 0 ? `-${v.pre.join('.')}` : ''}`;
427
+ }
428
+ /**
429
+ * The exclusive ceiling `^` / `~` compares against, in node-semver's own
430
+ * notation: `0.2.0` becomes `0.2.0-0`, never the bare release.
431
+ *
432
+ * `^0.1.1-rc.2` and `~0.1.7` both expand to a ceiling of `0.2.0`, and npm's
433
+ * ceiling is exclusive. Comparing against the bare release made the test
434
+ * `0.2.0 > 0.2.0-rc.2` true — the ceiling outranks the prerelease of its own
435
+ * base version — so `0.2.0-rc.2` slipped under every `^0.1.x` range. That is
436
+ * the host line every plugin on the 0.1 release train declares, judged by the
437
+ * 0.2 host it is being installed onto: the market answered "compatible" for
438
+ * releases the dsh gate (node-semver, `evaluatePluginCompatibility`) refuses.
439
+ *
440
+ * node-semver writes the ceiling as `<0.2.0-0`, which sorts below every
441
+ * prerelease of `0.2.0` and still excludes the release itself. `compatibility.
442
+ * ts` has always built its bounds this way (`nextBound`); this is the
443
+ * comparator catching up with it.
444
+ */
445
+ function exclusiveUpperBound(release) {
446
+ return `${release}-0`;
447
+ }
448
+ /**
449
+ * Minimal range matcher for the peer-range check: `*`, exact (with or without =),
450
+ * ^, ~, >=, >, <=, <, whitespace-separated pairs, and `||` alternatives. Anything else
451
+ * returns null (unknown — reported, not asserted).
452
+ *
453
+ * Prerelease handling follows npm's semver rule, evaluated at the comparator
454
+ * SET level (one `||` alternative is one set): a version carrying a
455
+ * prerelease tag only satisfies a set when at least one comparator in that
456
+ * set shares the version's [major, minor, patch] tuple AND carries a
457
+ * prerelease of its own; then every comparator is checked normally. So
458
+ * `^0.1.0` never matches `0.2.0-rc.1` (nor `0.1.0-rc.5`), while
459
+ * `>=1.2.3-rc.1 <2.0.0` does match `1.2.3-rc.2` (issue #98 analysis).
460
+ * Discovery can opt into npm's `includePrerelease` behaviour because every
461
+ * published DSH host line is itself prerelease; diagnostics retain the npm
462
+ * default unless a caller explicitly asks for that wider admission.
463
+ *
464
+ * `includePrerelease` widens ADMISSION only — which prereleases may be
465
+ * considered at all. It does not move a `^` / `~` ceiling, so a cross-minor
466
+ * host line stays outside a range that declared the previous minor, exactly
467
+ * as node-semver decides it (see {@link exclusiveUpperBound}).
468
+ */
469
+ export function satisfiesRange(version, range, options = {}) {
470
+ const v = parseSemver(version);
471
+ if (v === null)
472
+ return null;
473
+ const versionHasPre = v.pre.length > 0;
474
+ // Mirror pnpm's peer-dependency publish transform. Unlike ordinary
475
+ // dependency specs, a workspace token may sit inside a larger peer range.
476
+ // Operator-only (or bare) tokens receive the linked sibling's version;
477
+ // explicit versions only lose the protocol prefix. Unsupported alias/path
478
+ // forms become an unknown range below rather than a definite mismatch.
479
+ const workspaceSemver = /workspace:([\^~*]|>=|>|<=|<)?((\d+|[xX*])(\.(\d+|[xX*])){0,2})?/;
480
+ let normalizedRange = range;
481
+ if (range.includes('workspace:')) {
482
+ const match = workspaceSemver.exec(range);
483
+ if (match === null) {
484
+ normalizedRange = range.replace('workspace:', '');
485
+ }
486
+ else if (match[2] !== undefined) {
487
+ normalizedRange = range.replace('workspace:', '');
488
+ }
489
+ else {
490
+ const operator = match[1] === '*' ? '' : (match[1] ?? '');
491
+ normalizedRange = range.replace(workspaceSemver, `${operator}${semverStr(v)}`);
492
+ }
493
+ }
494
+ const single = (part) => {
495
+ const p = part.trim();
496
+ if (p === '' || p === '*' || p === 'x' || p === 'X')
497
+ return true;
498
+ const m = /^(\^|~|>=|<=|>|<|=)?(.*)$/.exec(p);
499
+ const op = m?.[1] === '=' ? '' : (m?.[1] ?? '');
500
+ const target = (m?.[2] ?? '').trim();
501
+ const tv = parseSemver(target);
502
+ if (tv === null)
503
+ return null;
504
+ const major = tv.major;
505
+ const minor = tv.minor;
506
+ const patch = tv.patch;
507
+ switch (op) {
508
+ case '':
509
+ return compareSemver(version, target) === 0;
510
+ case '>=':
511
+ return gte(v, tv);
512
+ case '<=':
513
+ return gte(tv, v);
514
+ case '>':
515
+ return compareSemver(version, target) > 0;
516
+ case '<':
517
+ return compareSemver(version, target) < 0;
518
+ case '^': {
519
+ // npm caret semantics: >= given, strictly < the next breaking bump.
520
+ const bound = major > 0
521
+ ? `${major + 1}.0.0`
522
+ : minor > 0
523
+ ? `0.${minor + 1}.0`
524
+ : `0.0.${patch + 1}`;
525
+ return gte(v, tv) && compareSemver(exclusiveUpperBound(bound), version) > 0;
526
+ }
527
+ case '~': {
528
+ // npm tilde semantics: >= given, strictly < the next minor.
529
+ return gte(v, tv) && compareSemver(exclusiveUpperBound(`${major}.${minor + 1}.0`), version) > 0;
530
+ }
531
+ default:
532
+ return null;
533
+ }
534
+ };
535
+ /** Parse one comparator part into op + target; null when unknown. */
536
+ const comparator = (part) => {
537
+ const p = part.trim();
538
+ if (p === '' || p === '*' || p === 'x' || p === 'X')
539
+ return { op: '', target: '' };
540
+ const m = /^(\^|~|>=|<=|>|<|=)?(.*)$/.exec(p);
541
+ if (m === null)
542
+ return null;
543
+ const op = m[1] === '=' ? '' : (m[1] ?? '');
544
+ const target = (m[2] ?? '').trim();
545
+ // Enforce this function's documented unknown-range contract before the
546
+ // prerelease admission gate. Otherwise an unknown protocol such as
547
+ // `workspace:^` or `catalog:default` is misreported as a definite false
548
+ // whenever the resolved version happens to carry a prerelease tag.
549
+ if (parseSemver(target) === null)
550
+ return null;
551
+ return { op, target };
552
+ };
553
+ /** Evaluate ONE comparator set (a `||` alternative) as a conjunction. */
554
+ const evaluateSet = (set) => {
555
+ const parts = set.trim().split(/\s+/).filter(part => part !== '')
556
+ .flatMap(part => expandPartialComparator(part, options.includePrerelease === true));
557
+ if (parts.length === 0)
558
+ return true;
559
+ const parsed = parts.map(part => comparator(part));
560
+ if (parsed.some(part => part === null))
561
+ return null;
562
+ if (versionHasPre && options.includePrerelease !== true) {
563
+ // npm gate (set-level): the set admits prerelease versions only when a
564
+ // comparator pins the SAME base tuple with a prerelease of its own.
565
+ const admitted = parsed.some((part) => {
566
+ if (part?.target === '')
567
+ return false;
568
+ const tv = parseSemver(part?.target ?? '');
569
+ return tv !== null && tv.pre.length > 0
570
+ && v.major === tv.major && v.minor === tv.minor && v.patch === tv.patch;
571
+ });
572
+ if (!admitted)
573
+ return false;
574
+ }
575
+ const results = parsed.map(part => single(part?.op !== undefined ? `${part.op}${part.target}` : ''));
576
+ if (results.some(r => r === null))
577
+ return null;
578
+ return results.every(r => r === true);
579
+ };
580
+ if (normalizedRange.includes('||')) {
581
+ const outcomes = normalizedRange.split('||').map(part => evaluateSet(part));
582
+ if (outcomes.some(out => out === true))
583
+ return true;
584
+ if (outcomes.some(out => out === null))
585
+ return null;
586
+ return false;
587
+ }
588
+ return evaluateSet(normalizedRange);
589
+ }
590
+ /** Flatten a tree of entries (group configs included) into row records. */
591
+ function flattenEntries(nodes) {
592
+ const rows = [];
593
+ const walk = (list, inheritedLayer) => {
594
+ for (const node of list) {
595
+ // Nested group configs come straight from the parsed patch and do not
596
+ // carry the synthetic layer metadata attached to their parent insert.
597
+ const layer = typeof node.layer === 'string' ? node.layer : inheritedLayer;
598
+ if (layer === undefined)
599
+ continue;
600
+ rows.push({ id: node.id, layer, kind: 'insert', name: node.name });
601
+ if (node.group === true && Array.isArray(node.config)) {
602
+ walk(node.config, layer);
603
+ }
604
+ }
605
+ };
606
+ walk(nodes);
607
+ return rows;
608
+ }
609
+ /** Literal values use Loader Boolean semantics; `!!js` stays indeterminate. */
610
+ function disabledState(value) {
611
+ if (isRecord(value) && typeof value.__jsExpr === 'string')
612
+ return 'conditional';
613
+ return Boolean(value) ? 'disabled' : 'active';
614
+ }
615
+ function combineDisabled(parent, own) {
616
+ if (parent === 'disabled' || own === 'disabled')
617
+ return 'disabled';
618
+ if (parent === 'conditional' || own === 'conditional')
619
+ return 'conditional';
620
+ return 'active';
621
+ }
622
+ /**
623
+ * Rows whose specifiers the Loader can attempt to import. Group rows are
624
+ * always imported even when disabled (their disabled state gates children),
625
+ * while expression-gated non-group rows are retained as conditional.
626
+ */
627
+ function resolvableEntries(nodes) {
628
+ const rows = [];
629
+ const walk = (list, inheritedLayer, parentDisabled = 'active') => {
630
+ for (const node of list) {
631
+ const layer = typeof node.layer === 'string' ? node.layer : inheritedLayer;
632
+ if (layer === undefined)
633
+ continue;
634
+ const descendantsDisabled = combineDisabled(parentDisabled, disabledState(node.disabled));
635
+ const activation = node.group === true ? 'required' : descendantsDisabled;
636
+ if (activation !== 'disabled') {
637
+ rows.push({
638
+ id: node.id,
639
+ layer,
640
+ kind: 'insert',
641
+ name: node.name,
642
+ activation: activation === 'conditional' ? 'conditional' : 'required',
643
+ });
644
+ }
645
+ if (node.group === true && Array.isArray(node.config)) {
646
+ walk(node.config, layer, descendantsDisabled);
647
+ }
648
+ }
649
+ };
650
+ walk(nodes);
651
+ return rows;
652
+ }
653
+ /**
654
+ * Apply the layer stack over an empty root exactly like the dsh boot include.
655
+ * Exported so the trial-start validation (src/trial.ts) can replay the
656
+ * composition with a candidate bundle order BEFORE anything is written.
657
+ */
658
+ export function composeLayers(layers) {
659
+ const tree = [];
660
+ const orphans = [];
661
+ const overrides = [];
662
+ /**
663
+ * The boot's entryMap, mirrored incrementally: the LAST row registered for
664
+ * an id (top-level or nested group member) is the patch target, and later
665
+ * inserts overwrite the map entry — exactly dsh-app-boot's applyEntryPatches
666
+ * buildMap. Keeping the map instead of re-walking the tree pins the
667
+ * duplicate-id resolution to the boot's behavior (issue #98 analysis:
668
+ * explicit composition boundaries).
669
+ */
670
+ const entryMap = new Map();
671
+ const buildMap = (nodes) => {
672
+ for (const node of nodes) {
673
+ if (node.id !== '')
674
+ entryMap.set(node.id, node);
675
+ if (node.group === true && Array.isArray(node.config))
676
+ buildMap(node.config);
677
+ }
678
+ };
679
+ for (const layer of layers) {
680
+ for (const patch of layer.patches) {
681
+ if (!isRecord(patch))
682
+ continue;
683
+ const { id, insert, name, ...overridesOf } = patch;
684
+ // Boot boundary: `insert` and `id` are truthiness-checked, so a falsy
685
+ // `insert` (null/''/0) falls through to the patch path and an empty id
686
+ // makes an insert a plain top-level append (applyEntryPatches).
687
+ const hasId = typeof id === 'string' ? id !== '' : Boolean(id);
688
+ const lookupKey = hasId ? String(id) : '';
689
+ if (insert) {
690
+ if (!Array.isArray(insert)) {
691
+ orphans.push({ id: lookupKey === '' ? '(anonymous)' : lookupKey, layer: layer.label, reason: 'insert is not an array' });
692
+ continue;
693
+ }
694
+ const nodes = insert.filter(isRecord).map((entry) => {
695
+ if (typeof entry.id !== 'string')
696
+ return null;
697
+ return {
698
+ id: entry.id,
699
+ name: typeof entry.name === 'string' ? entry.name : undefined,
700
+ layer: layer.label,
701
+ group: entry.group === true,
702
+ config: Array.isArray(entry.config) ? entry.config : undefined,
703
+ disabled: entry.disabled,
704
+ };
705
+ }).filter((n) => n !== null);
706
+ if (hasId) {
707
+ const target = entryMap.get(lookupKey);
708
+ if (target === undefined) {
709
+ orphans.push({ id: lookupKey, layer: layer.label, reason: 'insert target not found' });
710
+ continue;
711
+ }
712
+ if (target.group !== true) {
713
+ orphans.push({ id: lookupKey, layer: layer.label, reason: 'insert target is not a group' });
714
+ continue;
715
+ }
716
+ // Boot boundary: a group with a non-array config is fixed up to an
717
+ // empty array before the append (applyEntryPatches does the same).
718
+ if (!Array.isArray(target.config))
719
+ target.config = [];
720
+ target.config = [...target.config, ...nodes];
721
+ }
722
+ else {
723
+ tree.push(...nodes);
724
+ }
725
+ buildMap(nodes);
726
+ continue;
727
+ }
728
+ if (!hasId) {
729
+ orphans.push({ id: '(anonymous)', layer: layer.label, reason: 'id required for non-insert patch' });
730
+ continue;
731
+ }
732
+ const target = entryMap.get(lookupKey);
733
+ if (target === undefined) {
734
+ orphans.push({ id: lookupKey, layer: layer.label, reason: 'patch target not found' });
735
+ continue;
736
+ }
737
+ // Boot boundary: the name guard is truthiness-based — an empty-string
738
+ // name on the patch row does not trigger the mismatch skip.
739
+ if (name && name !== target.name) {
740
+ orphans.push({ id: lookupKey, layer: layer.label, reason: `name mismatch (expected ${String(target.name)}, got ${String(name)})` });
741
+ continue;
742
+ }
743
+ const priorLayers = [];
744
+ for (const node of flattenEntries(tree)) {
745
+ if (node.id === lookupKey && !priorLayers.includes(node.layer))
746
+ priorLayers.push(node.layer);
747
+ }
748
+ if (priorLayers.some(prior => prior !== layer.label)) {
749
+ overrides.push({ id: lookupKey, layer: layer.label, overriddenLayers: priorLayers.filter(prior => prior !== layer.label) });
750
+ }
751
+ for (const [key, value] of Object.entries(overridesOf)) {
752
+ if (key === 'id')
753
+ continue;
754
+ target[key] = value;
755
+ }
756
+ }
757
+ }
758
+ const rows = flattenEntries(tree);
759
+ const resolvableRows = resolvableEntries(tree);
760
+ const byId = new Map();
761
+ for (const row of rows) {
762
+ const layers = byId.get(row.id) ?? [];
763
+ if (!layers.includes(row.layer))
764
+ layers.push(row.layer);
765
+ byId.set(row.id, layers);
766
+ }
767
+ const duplicates = [];
768
+ const counts = new Map();
769
+ for (const row of rows)
770
+ counts.set(row.id, (counts.get(row.id) ?? 0) + 1);
771
+ for (const [id, count] of counts) {
772
+ if (count < 2)
773
+ continue;
774
+ duplicates.push({ id, layers: byId.get(id) ?? [], count });
775
+ }
776
+ duplicates.sort((a, b) => a.id.localeCompare(b.id));
777
+ return { rows, resolvableRows, duplicates, overrides, orphans };
778
+ }
779
+ /**
780
+ * Whether two rows sharing one loader id still stop the boot (#853).
781
+ *
782
+ * It depends on the loader, and the loader changed: up to
783
+ * `cordis-plugin-loader@1.0.3` `EntryGroup.update` threw
784
+ * `duplicate loader entry id` for a config array holding one id twice
785
+ * (measured against the published packages — 1.0.3 has the throw, 1.0.4 and
786
+ * 1.0.5 do not). From 1.0.4 the same array is folded into a Map keyed by id,
787
+ * so the LATER row wins and the earlier one is silently dropped.
788
+ *
789
+ * The market's rule was written against the old loader (#122: two bundles on
790
+ * one id really did refuse to start), and it is right on one. On a new one it
791
+ * is not a boot failure but a silent override — which is worth SAYING and not
792
+ * worth refusing every operation over. The reported shape is a package's own
793
+ * patch row plus a user-patch row on the same id: fatal forever meant every
794
+ * update of every plugin rolled back.
795
+ *
796
+ * An empty answer from the PROFILE lockfile is not "unknown" on the official
797
+ * Desktop: that host embeds the loader in `app.asar` and provides it to every
798
+ * profile, so no profile can ever name it (#943). Reading that as an old
799
+ * loader made the gate fatal for every update on 0.2.1-rc.2 — the exact report
800
+ * #853's fix was supposed to close. The host installation is asked before the
801
+ * evidence is treated as missing; only when both are silent does the
802
+ * conservative answer stand.
803
+ */
804
+ export function duplicateEntryIdsAreFatal(profileDirectory, dshInstallDir) {
805
+ const versions = lockfileCoreVersions(profileDirectory).get('@deepseek-ai/cordis-plugin-loader') ?? [];
806
+ if (versions.length > 0) {
807
+ const newest = versions.reduce((a, b) => (compareSemver(a, b) >= 0 ? a : b));
808
+ return compareSemver(newest, '1.0.4') < 0;
809
+ }
810
+ const install = dshInstallDir === undefined ? findDshInstallDir() : dshInstallDir;
811
+ const host = install === null ? null : hostLoaderVersion(install);
812
+ if (host === null)
813
+ return true;
814
+ return compareSemver(host, '1.0.4') < 0;
815
+ }
816
+ /**
817
+ * The loader version the host actually runs, given its install directory.
818
+ *
819
+ * `hostNodeModulesRoot()` answers "where a HOISTED install puts node_modules":
820
+ * right for the desktop's app.asar tree and an npm flat install, wrong for a
821
+ * global CLI whose dependencies stay nested inside the package (#1092). There
822
+ * the shared root holds only `dsh` itself, the probe answers null, this
823
+ * function returned `true`, and EVERY update in that layout was rolled back
824
+ * over a duplicate id the running loader only warns about. Node's own
825
+ * resolution from the install anchor covers all three layouts.
826
+ */
827
+ function hostLoaderVersion(install) {
828
+ const hoisted = readNodeModulesVersion(dirname(hostNodeModulesRoot(install)), '@deepseek-ai/cordis-plugin-loader');
829
+ if (hoisted !== null)
830
+ return hoisted;
831
+ try {
832
+ const resolved = createRequire(join(install, 'package.json'))
833
+ .resolve('@deepseek-ai/cordis-plugin-loader/package.json');
834
+ // Only a copy INSIDE the install tree is the host's own. Node's resolution
835
+ // walks upwards, and an unrelated ancestor's node_modules (a profile
836
+ // checked out inside some project, say) is not evidence about the host.
837
+ // A hoisted install resolves above the tree and is already answered by the
838
+ // probe above.
839
+ // realpath both sides: on macOS the temp directory resolves through a
840
+ // symlink (`/var` -> `/private/var`), and a plain prefix compare would
841
+ // read the host's OWN file as outside the tree.
842
+ if (!realpathSync(resolved).startsWith(`${realpathSync(install)}${sep}`))
843
+ return null;
844
+ const manifest = JSON.parse(readFileSync(resolved, 'utf8'));
845
+ return typeof manifest.version === 'string' ? manifest.version : null;
846
+ }
847
+ catch {
848
+ // Inside app.asar Node's resolver is blind — the hoisted probe above is
849
+ // the answer there, and a genuine miss still fails closed.
850
+ return null;
851
+ }
852
+ }
853
+ /** Distinct versions of `@deepseek-ai/{dsh,cordis}*` packages in the lockfile. */
854
+ function lockfileCoreVersions(profileDir) {
855
+ const found = new Map();
856
+ let text;
857
+ try {
858
+ text = readFileSync(join(profileDir, 'pnpm-lock.yaml'), 'utf8');
859
+ }
860
+ catch {
861
+ return new Map();
862
+ }
863
+ for (const m of text.matchAll(/(@deepseek-ai\/(?:dsh|cordis)[^@\s'"]*?)@([0-9][^\s:'"()]*)/g)) {
864
+ const name = m[1] ?? '';
865
+ // pnpm v9 peer-resolution keys carry a suffix: `name@1.0.0(peer@x)`. The
866
+ // version capture stops at the `(` — and at `)` too, so the peer
867
+ // reference INSIDE the suffix (`name@1.0.0(@deepseek-ai/dsh-base@4.0.1)`)
868
+ // never yields a fake `4.0.1)` version that would invent a phantom
869
+ // multi-version report on a healthy profile (issue #98 analysis).
870
+ const version = m[2] ?? '';
871
+ // Registry resolutions only: skip link:/git forms and anything that is
872
+ // not a well-formed semver (parseSemver double-checks the capture).
873
+ if (parseSemver(version) === null)
874
+ continue;
875
+ const versions = found.get(name) ?? new Set();
876
+ versions.add(version);
877
+ found.set(name, versions);
878
+ }
879
+ const out = new Map();
880
+ for (const [name, versions] of found)
881
+ out.set(name, [...versions].sort(compareSemver));
882
+ return out;
883
+ }
884
+ /**
885
+ * Build the bundle layer stack for a profile under a GIVEN bundle order —
886
+ * the manifest order for analyzeProfile, or a candidate order for trial
887
+ * validation (src/trial.ts). Bundle resolution mirrors the boot exactly:
888
+ * the dsh installation anchor first (in-box bundles always come from the
889
+ * running dsh, never a profile-local copy), then Node's module search from
890
+ * the profile directory (covers community bundles and pnpm workspace-root
891
+ * hoisting). A single code path keeps the check report and the trial
892
+ * validation from ever disagreeing about what a bundle is or where it lives.
893
+ */
894
+ export function buildBundleLayers(profileDirectory, bundleNames, specs, dshInstallDir) {
895
+ const bundles = bundleNames.map((name) => {
896
+ const officialScope = name.startsWith('@deepseek-ai/');
897
+ const hostProvided = INBOX_BUNDLES.has(name)
898
+ || (isPackagedDesktopInstall(dshInstallDir) && officialScope);
899
+ // The real loader gives the DSH installation first refusal for in-box
900
+ // bundles. Desktop keeps that installation private from plugins, so a
901
+ // DIRECT profile-local copy with the same official name is only a stale
902
+ // shadow, never evidence for the layer the running host loaded (#371).
903
+ // Keep walking the profile anchor's parent search paths: Desktop heals an
904
+ // authoritative host fallback at <profiles>/node_modules.
905
+ const ignoredProfilePackage = dshInstallDir === null && hostProvided
906
+ ? join(profileDirectory, 'node_modules', name)
907
+ : undefined;
908
+ const anchors = [
909
+ { anchor: dshInstallDir !== null ? join(dshInstallDir, 'package.json') : null },
910
+ {
911
+ anchor: join(profileDirectory, 'package.json'),
912
+ ignoredPackageDirectory: ignoredProfilePackage,
913
+ },
914
+ ];
915
+ let directory = null;
916
+ for (const { anchor, ignoredPackageDirectory } of anchors) {
917
+ if (anchor === null)
918
+ continue;
919
+ directory = resolvePackageDir(anchor, name, ignoredPackageDirectory);
920
+ if (directory !== null)
921
+ break;
922
+ }
923
+ const layer = {
924
+ name,
925
+ source: specs[name] ?? '(not a direct dependency)',
926
+ kind: hostProvided ? 'official' : 'community',
927
+ directory,
928
+ patchPath: null,
929
+ patchPaths: [],
930
+ error: null,
931
+ entries: [],
932
+ parseError: null,
933
+ };
934
+ if (directory === null) {
935
+ // An in-box bundle is supplied by the dsh INSTALLATION, not by the
936
+ // profile — that is what makes it in-box. So failing to find one says
937
+ // we could not locate the installation, not that the profile is
938
+ // broken: unusual or older hosts can still hide the in-box installation
939
+ // from both the CLI-entry and packaged-Desktop discovery anchors.
940
+ //
941
+ // Calling that "will fail to boot" turned a working composition into a
942
+ // fatal verdict and rolled back a good update (#369) — while `dsh
943
+ // --dump-config` on the same profile exited 0. Unknown has to read as
944
+ // unknown; the profile's own bundles are still judged normally.
945
+ //
946
+ // The same holds for an official bundle (#676). Two independent reasons
947
+ // one can be absent from every probe and still be supplied by the
948
+ // running host:
949
+ //
950
+ // - the installation is out of sight entirely — `dshHostInfo` found
951
+ // no anchor at all, which is what a packaged Desktop looks like
952
+ // from in here (#553, and the reporter who could not produce a
953
+ // `dsh --dump-config` because there is no `dsh` on PATH at all);
954
+ // - we have an anchor but it is an ARCHIVE, where a filesystem probe
955
+ // answers "absent" for every name, including the host's own.
956
+ //
957
+ // `hostProvided` is the second case; the first is the check below. Both
958
+ // are gaps in what this process can see, not defects in the profile, so
959
+ // both read as unknown. Community bundles are untouched by this: they
960
+ // resolve through the profile's own node_modules ancestry, which this
961
+ // process CAN probe, so a missing one stays fatal.
962
+ if (hostProvided || (officialScope && dshInstallDir === null)) {
963
+ layer.error = null;
964
+ layer.unresolvedInbox = true;
965
+ return layer;
966
+ }
967
+ layer.error = 'bundle package is not installed — the profile will fail to boot';
968
+ return layer;
969
+ }
970
+ let bundleManifest;
971
+ try {
972
+ bundleManifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));
973
+ }
974
+ catch {
975
+ layer.error = 'bundle package.json is unreadable';
976
+ return layer;
977
+ }
978
+ // A bundle may declare ONE patch file or a LIST of them: dsh 0.1.7's own
979
+ // `@deepseek-ai/dsh-web-app` ships five (a base patch plus four presets),
980
+ // and the official headless template includes that bundle — so requiring
981
+ // a string reported "the profile will fail to boot" for the DEFAULT
982
+ // layout, while `dsh --dump-config` composed it fine (#676).
983
+ const declared = bundleManifest.dsh?.bundle?.patch;
984
+ const declaredList = typeof declared === 'string'
985
+ ? [declared]
986
+ : Array.isArray(declared) ? declared.filter((item) => typeof item === 'string') : [];
987
+ if (declaredList.length === 0) {
988
+ layer.error = 'bundle declares no dsh.bundle.patch — the profile will fail to boot';
989
+ return layer;
990
+ }
991
+ const missing = declaredList.find(relative => !existsSync(join(directory, relative)));
992
+ if (missing !== undefined) {
993
+ layer.error = `declared patch ${missing} is missing — the profile will fail to boot`;
994
+ return layer;
995
+ }
996
+ // The first declared file is the layer's patch for reporting; every one
997
+ // of them contributes entries, because the composer applies them all.
998
+ layer.patchPath = join(directory, declaredList[0]);
999
+ layer.patchPaths = declaredList.map(relative => join(directory, relative));
1000
+ const parsed = declaredList.map(relative => parsePatchFile(join(directory, relative)));
1001
+ if (parsed.some(patches => patches === null)) {
1002
+ layer.parseError = 'patch file is not a valid entry list';
1003
+ return layer;
1004
+ }
1005
+ layer.entries = parsed.flatMap(patches => collectInsertIds(patches));
1006
+ const order = bundleManifest.dsh?.bundle?.order;
1007
+ if (order !== null && typeof order === 'object' && !Array.isArray(order)) {
1008
+ const listOf = (value) => Array.isArray(value)
1009
+ ? value.filter((item) => typeof item === 'string')
1010
+ : undefined;
1011
+ const after = listOf(order.after);
1012
+ const before = listOf(order.before);
1013
+ if (after !== undefined || before !== undefined) {
1014
+ layer.order = { ...(before !== undefined ? { before } : {}), ...(after !== undefined ? { after } : {}) };
1015
+ }
1016
+ }
1017
+ return layer;
1018
+ });
1019
+ const layers = bundles.map((bundle) => ({
1020
+ label: bundle.name,
1021
+ kind: 'bundle',
1022
+ // EVERY declared file, not the first: the composer applies them all, and
1023
+ // a composition built from one file would miss the preset rows — so a
1024
+ // duplicate id or an orphan in a second file was invisible here (#688).
1025
+ patches: bundle.parseError === null
1026
+ ? bundle.patchPaths.flatMap(path => parsePatchFile(path) ?? [])
1027
+ : [],
1028
+ parseError: bundle.parseError,
1029
+ }));
1030
+ return { bundles, layers };
1031
+ }
1032
+ /**
1033
+ * The installation's own bundle layer, when the installation package declares
1034
+ * one — the Desktop shell's `cordis.patch.yml`.
1035
+ *
1036
+ * The Desktop launcher applies that file by hand rather than through the
1037
+ * profile's `dsh.profile.bundles`, and splices it in directly behind the
1038
+ * `@deepseek-ai/dsh-web-app` layer. Composing without it made every user-patch
1039
+ * or home-patch row aimed at a row the shell inserts — `desktop-shell`,
1040
+ * `desktop-notifications`, `desktop-terminal`, `desktop-pnpm`, … — read as an
1041
+ * orphan ("patch target not found") although the running host resolves it. It
1042
+ * is not noise: those rows are the shell's own settings persistence, so a user
1043
+ * who believes the warning and deletes them loses the window mode and every
1044
+ * notification preference.
1045
+ *
1046
+ * WHERE that package root is is not where `dshInstallDir` points; see
1047
+ * {@link desktopApplicationRoots} for the candidates and why. A plain CLI
1048
+ * install is unaffected: `@deepseek-ai/dsh` declares no bundle patch, and
1049
+ * neither does any ancestor of a global install, so this returns null and the
1050
+ * composer sees exactly the layers it saw before.
1051
+ *
1052
+ * A candidate is accepted only when it is actually an installation — it must
1053
+ * ship the in-box `@deepseek-ai/dsh-web-app` bundle this overlay is spliced
1054
+ * behind (see the check below). A declared patch alone is not evidence: any
1055
+ * project may declare one.
1056
+ *
1057
+ * @param dshInstall - install directory the analysis located, or null.
1058
+ * @returns the overlay layer, or null when this installation declares none.
1059
+ */
1060
+ function installOverlayLayer(dshInstall, profileDirectory, declaredBundles) {
1061
+ for (const directory of desktopApplicationRoots(dshInstall)) {
1062
+ // A DSH installation ships the in-box web bundle, and the launcher splices
1063
+ // this very overlay directly behind that bundle's layer — where it is
1064
+ // absent, the launcher applies no overlay either, so composing one here
1065
+ // would describe a composition nobody runs (#749 review).
1066
+ const layer = overlayFromDirectory(directory, manifest => readNodeModulesVersion(directory, '@deepseek-ai/dsh-web-app') !== null);
1067
+ if (layer !== null)
1068
+ return layer;
1069
+ }
1070
+ // The official Desktop shell plugin's own patch (#807). On a build that packs
1071
+ // the whole runtime into one app.asar, no application-root candidate declares
1072
+ // it: the asar's root is `@deepseek-ai/dsh-desktop` and the nested
1073
+ // `app.asar/dsh` is `@deepseek-ai/dsh-desktop-runtime`, neither with a
1074
+ // `dsh.bundle.patch`, while the file that really supplies the shell's rows
1075
+ // (`desktop-shell`, `desktop-notifications`, …) is this package's own
1076
+ // `cordis.patch.yml`. Without it every user-patch row aimed at a shell row is
1077
+ // reported as an orphan, and a user who believes the warning deletes rows
1078
+ // that carry the window material and the notification preferences.
1079
+ //
1080
+ // Bounded by identity, not by location: the candidate must BE that package,
1081
+ // resolved from the profile's own module search, and must declare a patch.
1082
+ // A profile that lists it in `dsh.profile.bundles` gets it as an ordinary
1083
+ // bundle layer instead — composing both would add every row twice.
1084
+ if (!declaredBundles.includes(DESKTOP_SHELL_PLUGIN)) {
1085
+ const directory = resolvePackageDir(join(profileDirectory, 'package.json'), DESKTOP_SHELL_PLUGIN);
1086
+ if (directory !== null) {
1087
+ return overlayFromDirectory(directory, manifest => manifest.name === DESKTOP_SHELL_PLUGIN);
1088
+ }
1089
+ }
1090
+ return null;
1091
+ }
1092
+ /** The official Desktop shell plugin, whose patch the launcher applies by hand (#807). */
1093
+ const DESKTOP_SHELL_PLUGIN = 'dsh-plugin-desktop';
1094
+ /**
1095
+ * The overlay one candidate directory declares, or null when it declares none.
1096
+ *
1097
+ * `accept` is the caller's bound on what may stand in for the installation;
1098
+ * resolution and parsing are shared, because a second parsing path would be a
1099
+ * second set of answers about the same file.
1100
+ */
1101
+ function overlayFromDirectory(directory, accept) {
1102
+ let manifest;
1103
+ try {
1104
+ manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));
1105
+ }
1106
+ catch {
1107
+ return null;
1108
+ }
1109
+ const declared = manifest.dsh?.bundle?.patch;
1110
+ const declaredList = typeof declared === 'string'
1111
+ ? [declared]
1112
+ : Array.isArray(declared)
1113
+ ? declared.filter((relative) => typeof relative === 'string')
1114
+ : [];
1115
+ // A bundle patch alone does not make a directory an installation: ANY package
1116
+ // can declare one — this repository does, and so does every plugin repo.
1117
+ // Without the caller's bound the ancestor walk accepted the nearest such
1118
+ // project above the install directory and composed its rows as if they were
1119
+ // the installation's own, which invents rows and can mask a real orphan
1120
+ // warning (#749 review).
1121
+ if (declaredList.length === 0 || !accept(manifest))
1122
+ return null;
1123
+ const label = typeof manifest.name === 'string' && manifest.name !== '' ? manifest.name : 'install-overlay';
1124
+ const paths = declaredList.map(relative => join(directory, relative));
1125
+ if (paths.some(path => !existsSync(path))) {
1126
+ return { label, kind: 'bundle', patches: [], parseError: 'declared patch is missing' };
1127
+ }
1128
+ const parsed = paths.map(path => parsePatchFile(path));
1129
+ if (parsed.some(patches => patches === null)) {
1130
+ return { label, kind: 'bundle', patches: [], parseError: 'patch file is not a valid entry list' };
1131
+ }
1132
+ return { label, kind: 'bundle', patches: parsed.flatMap(patches => patches), parseError: null };
1133
+ }
1134
+ /**
1135
+ * Which directories in `node_modules` are leftovers (#663).
1136
+ *
1137
+ * Two shapes, and both need to be VISIBLE rather than cleaned: a directory
1138
+ * without a readable `package.json` (what a lock-blocked update leaves), and
1139
+ * pnpm's `<name>_tmp_<pid>_<n>` staging directory (what an interrupted one
1140
+ * leaves). Neither can be removed from in here in the case that produces
1141
+ * them — the plugin's own process holds the directory open, so the rename
1142
+ * and delete that would clear it are the operations that were just refused.
1143
+ * Telling the user what is on disk, and which of it is merely junk, is the
1144
+ * part this process can do.
1145
+ *
1146
+ * Bounded on purpose. The top level is scanned in full (that is where the
1147
+ * profile's own packages live), plus one level inside the virtual store:
1148
+ * pnpm stages a package's update in the `node_modules` beside it, so that is
1149
+ * where a dependency's temp directory appears. It does NOT recurse through
1150
+ * the whole virtual store: on a large Windows profile that is thousands of
1151
+ * directories for a page the user opens by hand, and the store's OWN temp
1152
+ * directories are already reclaimed by `cleanOrphanedStoreTmp`.
1153
+ */
1154
+ export function findResidualDirectories(profileDirectory, declared) {
1155
+ const out = [];
1156
+ // pnpm's staging name, from its own rename: `<name>_tmp_<pid>_<n>`.
1157
+ const tmpShape = /^(.+)_tmp_\d+_\w+$/;
1158
+ const consider = (directory, entry, relative) => {
1159
+ // pnpm's own bookkeeping lives in here beside the packages: `.pnpm` (the
1160
+ // virtual store), `.bin`, `.modules.yaml`, `.ignored`. None of them is a
1161
+ // package, so none of them is a broken one.
1162
+ if (entry.startsWith('.'))
1163
+ return;
1164
+ let stats;
1165
+ try {
1166
+ stats = lstatSync(join(directory, entry));
1167
+ }
1168
+ catch {
1169
+ return;
1170
+ }
1171
+ // A symlink is how pnpm links every installed package to its store
1172
+ // entry. A DANGLING one is a different failure (and `#708` cleans the
1173
+ // market's own); counting healthy links as leftovers would flag every
1174
+ // profile in existence.
1175
+ if (!stats.isDirectory())
1176
+ return;
1177
+ const tmp = tmpShape.exec(entry);
1178
+ if (tmp !== null) {
1179
+ out.push({ name: tmp[1], path: join(relative, entry), kind: 'tmp-directory', declared: declared.has(tmp[1]) });
1180
+ return;
1181
+ }
1182
+ if (declared.has(entry))
1183
+ return;
1184
+ let readable = false;
1185
+ try {
1186
+ JSON.parse(readFileSync(join(directory, entry, 'package.json'), 'utf8'));
1187
+ readable = true;
1188
+ }
1189
+ catch { /* missing or unparseable — that is the finding */ }
1190
+ if (!readable)
1191
+ out.push({ name: entry, path: join(relative, entry), kind: 'incomplete-package', declared: false });
1192
+ };
1193
+ const nodeModules = join(profileDirectory, 'node_modules');
1194
+ try {
1195
+ for (const entry of readdirSync(nodeModules))
1196
+ consider(nodeModules, entry, 'node_modules');
1197
+ }
1198
+ catch { /* no node_modules: nothing to report */ }
1199
+ const pnpmDirectory = join(nodeModules, '.pnpm');
1200
+ let pnpmEntries = [];
1201
+ try {
1202
+ pnpmEntries = readdirSync(pnpmDirectory);
1203
+ }
1204
+ catch { /* no virtual store */ }
1205
+ for (const entry of pnpmEntries) {
1206
+ const nested = join(pnpmDirectory, entry, 'node_modules');
1207
+ const relative = join('node_modules', '.pnpm', entry, 'node_modules');
1208
+ try {
1209
+ for (const name of readdirSync(nested))
1210
+ consider(nested, name, relative);
1211
+ }
1212
+ catch { /* unreadable nested node_modules */ }
1213
+ }
1214
+ out.sort((left, right) => left.path.localeCompare(right.path));
1215
+ return out;
1216
+ }
1217
+ /**
1218
+ * Analyze one profile directory (issue #98, phase 1). Pure function of the
1219
+ * directory contents — safe to call on every market open.
1220
+ */
1221
+ export function analyzeProfile(profileDirectory, options = {}) {
1222
+ const dshInstall = options.dshInstallDir ?? findDshInstallDir();
1223
+ const home = resolveDshHome(options.homeDir);
1224
+ const core = corePackageNames(dshInstall);
1225
+ // --- 1. bundle stack ---
1226
+ const manifest = (() => {
1227
+ try {
1228
+ return JSON.parse(readFileSync(join(profileDirectory, 'package.json'), 'utf8'));
1229
+ }
1230
+ catch {
1231
+ return null;
1232
+ }
1233
+ })();
1234
+ const bundleNames = Array.isArray(manifest?.dsh?.profile?.bundles)
1235
+ ? manifest.dsh.profile.bundles.filter((name) => typeof name === 'string')
1236
+ : [];
1237
+ const specs = manifest?.dependencies ?? {};
1238
+ // Declared = what the profile asks to load. A leftover directory under one
1239
+ // of these names is a boot problem (the bundle layers above judge it), and
1240
+ // an undeclared one is junk the user can clear — the distinction is the
1241
+ // whole point of the listing (#663).
1242
+ const declaredNames = new Set([...Object.keys(specs), ...bundleNames]);
1243
+ const built = buildBundleLayers(profileDirectory, bundleNames, specs, dshInstall);
1244
+ const bundles = built.bundles;
1245
+ const bundleLayers = built.layers;
1246
+ // The installation's own overlay rides directly behind the bundle the
1247
+ // Desktop launcher keys off, exactly where the launcher splices it — see
1248
+ // installOverlayLayer.
1249
+ const installOverlay = installOverlayLayer(dshInstall, profileDirectory, bundleNames);
1250
+ if (installOverlay !== null) {
1251
+ const overlayAfter = bundleLayers.findIndex(layer => layer.label === '@deepseek-ai/dsh-web-app');
1252
+ if (overlayAfter < 0)
1253
+ bundleLayers.push(installOverlay);
1254
+ else
1255
+ bundleLayers.splice(overlayAfter + 1, 0, installOverlay);
1256
+ }
1257
+ // --- 2. composed loader rows / duplicates / overrides / orphans ---
1258
+ const layers = [...bundleLayers];
1259
+ const userPatchPath = join(profileDirectory, 'cordis.patch.yml');
1260
+ if (existsSync(userPatchPath)) {
1261
+ const patches = parsePatchFile(userPatchPath);
1262
+ layers.push({ label: 'user-patch', kind: 'user', patches: patches ?? [], parseError: patches === null ? 'patch file is not a valid entry list' : null });
1263
+ }
1264
+ const homePatchPath = join(home, 'cordis.patch.yml');
1265
+ if (existsSync(homePatchPath)) {
1266
+ const patches = parsePatchFile(homePatchPath);
1267
+ layers.push({ label: 'home-patch', kind: 'home', patches: patches ?? [], parseError: patches === null ? 'patch file is not a valid entry list' : null });
1268
+ }
1269
+ const composed = composeLayers(layers);
1270
+ // --- 3. peer dependency mismatches (every declared peer, core or not) ---
1271
+ // NOTE (issue #98 division of labor): the core-package-as-ordinary-
1272
+ // dependency check (coreDeps / shadowing) belongs to @yzke's manifest PR;
1273
+ // PR-A keeps only the peer-resolution check here.
1274
+ const peerMismatches = [];
1275
+ const seenDeps = new Set();
1276
+ for (const plugin of installedPackageNames(profileDirectory)) {
1277
+ let pkg;
1278
+ try {
1279
+ pkg = JSON.parse(readFileSync(join(profileDirectory, 'node_modules', plugin, 'package.json'), 'utf8'));
1280
+ }
1281
+ catch {
1282
+ continue;
1283
+ }
1284
+ const pluginDir = join(profileDirectory, 'node_modules', plugin);
1285
+ const map = pkg.peerDependencies;
1286
+ if (map === null || typeof map !== 'object')
1287
+ continue;
1288
+ for (const [name, spec] of Object.entries(map)) {
1289
+ if (typeof spec !== 'string')
1290
+ continue;
1291
+ const key = `${plugin}\u0000${name}\u0000peer`;
1292
+ if (seenDeps.has(key))
1293
+ continue;
1294
+ seenDeps.add(key);
1295
+ // A HOST-PLANE peer never takes its version from the shared workspace
1296
+ // root: `<profiles>/node_modules` is shared by every profile, and on a
1297
+ // machine that also runs a second DSH installation — a global npm CLI
1298
+ // beside the Desktop app — that tree is the OTHER installation's
1299
+ // closure. Reading a host version from it reported a healthy install as
1300
+ // "introduced host-compatibility risks … vs 0.1.5-rc.2" and offered a
1301
+ // rollback, while the running host was 0.1.7-rc.2 (#726). What the
1302
+ // plugin itself resolves still counts (a nested copy, a profile-local
1303
+ // one), and the located installation is asked as `host` below; with
1304
+ // neither, the version is unknown rather than wrong — the rule #676
1305
+ // settled for bundles. Non-host peers keep the hoisted fallback.
1306
+ const hostPlane = name.startsWith('@deepseek-ai/');
1307
+ const hoisted = hostPlane
1308
+ ? readNodeModulesVersion(profileDirectory, name)
1309
+ : readProfileVisibleVersion(profileDirectory, name);
1310
+ const nested = readNodeModulesVersion(pluginDir, name);
1311
+ // The located installation is asked as `host` here — and `dshInstall` is
1312
+ // the PACKAGE directory `dshHostInfo()` answers (the CLI layout
1313
+ // `<prefix>/node_modules/@deepseek-ai/dsh`, and the #778 nested form
1314
+ // `<resources>/app.asar/dsh/node_modules/@deepseek-ai/dsh`), or a flat
1315
+ // Desktop deployment root. `readNodeModulesVersion` takes a package root
1316
+ // and appends `node_modules` itself, so passing a package directory read
1317
+ // `<package>/node_modules/<name>`: absent in most layouts, which silently
1318
+ // left the located installation unasked while the comment above promises
1319
+ // it is asked; and where the host package carries its own nested
1320
+ // `@deepseek-ai` scope (pnpm isolated trees) it answered from that
1321
+ // truncated subset instead — the opposite of the "unknown rather than
1322
+ // wrong" this rule promises. `hostNodeModulesRoot()` derives the shared
1323
+ // root from both shapes (#804's fix, same arithmetic).
1324
+ const host = dshInstall !== null
1325
+ ? readNodeModulesVersion(dirname(hostNodeModulesRoot(dshInstall)), name)
1326
+ : null;
1327
+ // Node resolves a plugin's peer from its OWN node_modules first
1328
+ // (nested), then the profile tree (hoisted), then the host install.
1329
+ const resolved = nested ?? hoisted ?? host;
1330
+ // Peer checks cover EVERY declared peer, not just host core packages:
1331
+ // plugin-to-plugin peer mismatches break runtime registration just as
1332
+ // hard (issue #98 optimization round).
1333
+ // #1000: the same prerelease admission the discovery and verify checks
1334
+ // already use. A peer range written for the host line (`>=0.2.0-rc.0
1335
+ // <0.3.0`) can only ever be satisfied by a prerelease host version, and
1336
+ // npm's default rule refuses it unless a comparator pins the exact
1337
+ // [major, minor, patch] tuple — so a healthy profile carried the same
1338
+ // six permanent warnings, with no way to clear them but pinning exact
1339
+ // rc versions. The flag widens admission only; `^`/`~` ceilings still
1340
+ // apply (exclusiveUpperBound), so a cross-minor host line stays out.
1341
+ const satisfied = resolved !== null ? satisfiesRange(resolved, spec, { includePrerelease: true }) : null;
1342
+ const optional = pkg.peerDependenciesMeta?.[name]?.optional === true;
1343
+ peerMismatches.push({
1344
+ plugin, name, range: spec, resolved,
1345
+ satisfied: satisfied === null ? null : satisfied,
1346
+ ...(optional ? { optional: true } : {}),
1347
+ });
1348
+ }
1349
+ }
1350
+ // --- 4. multi-version core packages from the lockfile ---
1351
+ const multiVersion = [];
1352
+ for (const [name, versions] of lockfileCoreVersions(profileDirectory)) {
1353
+ if (versions.length < 2)
1354
+ continue;
1355
+ multiVersion.push({ name, versions, hoisted: readProfileVisibleVersion(profileDirectory, name) });
1356
+ }
1357
+ multiVersion.sort((a, b) => a.name.localeCompare(b.name));
1358
+ // --- summary ---
1359
+ const errors = [];
1360
+ const warnings = [];
1361
+ for (const bundle of bundles) {
1362
+ if (bundle.error !== null)
1363
+ errors.push(`bundle ${bundle.name}: ${bundle.error}`);
1364
+ if (bundle.parseError !== null)
1365
+ errors.push(`bundle ${bundle.name}: ${bundle.parseError}`);
1366
+ }
1367
+ for (const layer of layers) {
1368
+ if (layer.parseError !== null && layer.kind !== 'bundle')
1369
+ errors.push(`${layer.label}: ${layer.parseError}`);
1370
+ }
1371
+ // User and home patches can insert packages independently of a bundle.
1372
+ // Only check rows that survived composition: an insert targeting a missing
1373
+ // group is skipped by the boot and therefore cannot cause module loading to
1374
+ // fail. Normalize package subpaths to their npm root and check the profile's
1375
+ // node_modules ancestry; exact exports/subpath validation and relative,
1376
+ // absolute, URL, builtin, package-import (#), or cordis: specifiers are
1377
+ // outside this check.
1378
+ const userLayerLabels = new Set(layers
1379
+ .filter(layer => layer.kind === 'user' || layer.kind === 'home')
1380
+ .map(layer => layer.label));
1381
+ const candidates = new Map();
1382
+ for (const row of composed.resolvableRows) {
1383
+ if (row.kind !== 'insert' || !userLayerLabels.has(row.layer))
1384
+ continue;
1385
+ if (row.name === undefined || row.name === '') {
1386
+ const message = `${row.layer}: loader entry ${JSON.stringify(row.id)} has no module name`;
1387
+ if (row.activation === 'required')
1388
+ errors.push(`${message} — the profile will fail to boot`);
1389
+ else
1390
+ warnings.push(`${message} — boot will fail if its disabled expression enables the entry`);
1391
+ continue;
1392
+ }
1393
+ if (!isBareLoaderSpecifier(row.name))
1394
+ continue;
1395
+ if (isBuiltin(row.name))
1396
+ continue;
1397
+ const packageName = packageRoot(row.name);
1398
+ if (packageName === null) {
1399
+ const message = `${row.layer}: loader specifier ${JSON.stringify(row.name)} is not a valid bare package name`;
1400
+ if (row.activation === 'required')
1401
+ errors.push(`${message} — the profile will fail to boot`);
1402
+ else
1403
+ warnings.push(`${message} — boot will fail if its disabled expression enables the entry`);
1404
+ continue;
1405
+ }
1406
+ const key = `${row.layer}\u0000${packageName}`;
1407
+ const previous = candidates.get(key);
1408
+ if (previous === undefined || previous.row.activation === 'conditional' && row.activation === 'required') {
1409
+ candidates.set(key, { row, packageName });
1410
+ }
1411
+ }
1412
+ for (const { row, packageName } of candidates.values()) {
1413
+ if (profilePackageInstalled(profileDirectory, packageName))
1414
+ continue;
1415
+ // Official Electron keeps built-in packages beside app.asar, not inside
1416
+ // the writable profile. The loader can resolve them from this anchor.
1417
+ if (dshInstall !== null && core.has(packageName)
1418
+ && resolvePackageDir(join(dshInstall, 'package.json'), packageName) !== null)
1419
+ continue;
1420
+ // Same rule as the bundle stack above: inside an archive the probe is
1421
+ // blind for EVERY `@deepseek-ai/` name, so the verdict depends on the
1422
+ // name being DeepSeek's and not on whether it appears on a list of the
1423
+ // ones we happen to have seen. `dsh-mcp-client` was that list's only
1424
+ // entry, and the next host-shipped loader would have been a fresh fatal
1425
+ // error (#676).
1426
+ if (isPackagedDesktopInstall(dshInstall) && packageName.startsWith('@deepseek-ai/')) {
1427
+ warnings.push(`${row.layer}: bundled Desktop loader ${packageName} could not be independently resolved from app.asar`);
1428
+ continue;
1429
+ }
1430
+ const message = `${row.layer}: loader package ${packageName} is not installed in the profile`;
1431
+ if (row.activation === 'required')
1432
+ errors.push(`${message} — the profile will fail to boot`);
1433
+ else
1434
+ warnings.push(`${message} — boot will fail if its disabled expression enables the entry`);
1435
+ }
1436
+ // Rows on one id: a boot failure on an old loader, a silent override on a
1437
+ // new one (see duplicateEntryIdsAreFatal). Refusing an operation over the
1438
+ // second shape rolled back every update for the reporter's profile.
1439
+ const duplicateFatal = duplicateEntryIdsAreFatal(profileDirectory, dshInstall);
1440
+ for (const dup of composed.duplicates) {
1441
+ if (duplicateFatal) {
1442
+ errors.push(`duplicate loader entry id ${JSON.stringify(dup.id)} (${dup.count} rows: ${dup.layers.join(', ')})`);
1443
+ continue;
1444
+ }
1445
+ warnings.push(`${dup.layers.join(' 与 ')}:同一个条目 id ${JSON.stringify(dup.id)} 各有 ${String(dup.count)} 行,当前宿主会让后一层覆盖前一层,启动不受影响,但前面那行会静默失效——删除其中一行即可消除歧义 / the layers ${dup.layers.join(' and ')} each declare entry id ${JSON.stringify(dup.id)} (${String(dup.count)} rows); this host lets the LATER row win, so the boot is fine but the earlier row is silently dropped — remove one of them to make the intent unambiguous`);
1446
+ }
1447
+ for (const orphan of composed.orphans) {
1448
+ warnings.push(`${orphan.layer}: ${orphan.id} — ${orphan.reason}`);
1449
+ }
1450
+ for (const mismatch of peerMismatches) {
1451
+ // Only CONFIRMED incompatibilities warn. Un-evaluable peers (sat=null —
1452
+ // the peer is supplied by the host, an optional accelerator, or simply
1453
+ // absent) stay in the peerMismatches list for the UI but are not noise
1454
+ // in the summary (issue #98 optimization round).
1455
+ // ...and an OPTIONAL peer is not a confirmed incompatibility either.
1456
+ // classifyPeer already downgrades those to non-risk (compatibility.ts),
1457
+ // and the summary disagreeing with it meant a plugin that declares "I
1458
+ // work without this" still produced a scary warning line — including
1459
+ // for the market's own optional peer, on every profile that installs us
1460
+ // (#275 by @tjxjxjx).
1461
+ if (mismatch.satisfied === false && mismatch.optional !== true) {
1462
+ warnings.push(`${mismatch.plugin} peer range ${mismatch.name}@${mismatch.range} does not match resolved ${String(mismatch.resolved)}`);
1463
+ }
1464
+ }
1465
+ for (const mv of multiVersion) {
1466
+ const line = `${mv.name}: ${mv.versions.join(' / ')}${mv.hoisted !== null ? ` (hoisted ${mv.hoisted})` : ''}`;
1467
+ if (core.has(mv.name))
1468
+ errors.push(`multiple versions of core package — ${line}`);
1469
+ else
1470
+ warnings.push(`multiple versions of ${line}`);
1471
+ }
1472
+ // Current-order before/after rule conflicts (issue #98 phase 2): these are
1473
+ // informative for the ordering UI; the author-declared rule breaking the
1474
+ // CURRENT stack is worth a warning but not a boot failure. Conflicts are
1475
+ // exposed both at the report top level and per bundle (order.conflicts) so
1476
+ // the ordering panel can render them next to the bundle rows.
1477
+ const orderConflicts = validateOrder(bundleNames, readBundleRules(profileDirectory));
1478
+ for (const conflict of orderConflicts) {
1479
+ warnings.push(`${conflict.name}: ${conflict.reason}`);
1480
+ }
1481
+ for (const bundle of bundles) {
1482
+ const own = orderConflicts.filter(conflict => conflict.name === bundle.name);
1483
+ if (own.length > 0)
1484
+ bundle.order = { ...bundle.order, conflicts: own };
1485
+ }
1486
+ // LOOT-style auto-fix: suggest a minimal-change order satisfying every
1487
+ // declared before/after rule. No rules → no suggestion (nothing to fix);
1488
+ // with rules the suggestion keeps unconstrained bundles in their current
1489
+ // relative order (issue #125 review — never silently rewrites a hand-picked
1490
+ // order into an arbitrary canonical one).
1491
+ const suggestedOrder = suggestOrder(bundleNames, readBundleRules(profileDirectory));
1492
+ if (suggestedOrder === null) {
1493
+ // No declared rules — nothing to suggest and nothing to warn about.
1494
+ }
1495
+ else if (!suggestedOrder.ok) {
1496
+ warnings.push(`ordering constraints contain a cycle: ${suggestedOrder.cycle.join(' -> ')} — no compliant order exists / 排序约束存在循环依赖,无法得出合规顺序`);
1497
+ }
1498
+ else {
1499
+ // Only warn when the CURRENT order actually breaks a declared rule. A
1500
+ // hand-picked order that satisfies every rule but merely differs from the
1501
+ // suggestion is valid — flagging it would be a false alert on a healthy
1502
+ // profile (issue #98 analysis).
1503
+ if (orderConflicts.length > 0) {
1504
+ warnings.push('current bundle order violates declared rules — a better order is suggested / 当前 bundle 顺序违反声明规则,已给出更优顺序');
1505
+ }
1506
+ }
1507
+ // Duplicate loader NAMES: the Loader registers plugins by name, so two rows
1508
+ // with the same name in DIFFERENT layers shadow each other at runtime (the
1509
+ // later layer wins). Rows sharing a name within ONE layer are routine — a
1510
+ // single bundle may define several entries under the same name — and are
1511
+ // skipped entirely: a same-layer "duplicate name" is a false positive, not
1512
+ // a conflict. The hard conflict is duplicate loader entry ids
1513
+ // (report.duplicates), which fail the boot outright and are unchanged.
1514
+ const nameCounts = new Map();
1515
+ for (const row of composed.rows) {
1516
+ if (row.name === undefined)
1517
+ continue;
1518
+ const layers = nameCounts.get(row.name) ?? [];
1519
+ if (!layers.includes(row.layer))
1520
+ layers.push(row.layer);
1521
+ nameCounts.set(row.name, layers);
1522
+ }
1523
+ const duplicateNames = [];
1524
+ for (const [name, layers] of nameCounts) {
1525
+ // Only cross-layer collisions are real shadowing candidates: all rows
1526
+ // with this name living in one layer is a normal multi-entry bundle.
1527
+ if (layers.length < 2)
1528
+ continue;
1529
+ const count = composed.rows.filter(row => row.name === name).length;
1530
+ duplicateNames.push({ name, layers, count });
1531
+ // Deliberately NOT pushed into summary.warnings: the report carries the
1532
+ // shadowing rows structurally (duplicateNames, rendered by the
1533
+ // diagnostics panel), and the cost of a false positive — a healthy
1534
+ // profile flagged with a warning — outweighs a false negative here.
1535
+ }
1536
+ duplicateNames.sort((a, b) => a.name.localeCompare(b.name));
1537
+ return {
1538
+ profile: profileDirectory,
1539
+ scannedAt: Date.now(),
1540
+ bundles,
1541
+ rows: composed.rows,
1542
+ duplicates: composed.duplicates,
1543
+ duplicateNames,
1544
+ overrides: composed.overrides,
1545
+ orphans: composed.orphans,
1546
+ peerMismatches,
1547
+ multiVersion,
1548
+ orderConflicts,
1549
+ suggestedOrder,
1550
+ residuals: findResidualDirectories(profileDirectory, declaredNames),
1551
+ summary: {
1552
+ ok: errors.length === 0,
1553
+ errors,
1554
+ warnings,
1555
+ },
1556
+ };
1557
+ }