@ran-sh/dsh-crew 1.0.2 → 1.1.0

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 (40) hide show
  1. package/README.md +4 -0
  2. package/README.zh.md +4 -0
  3. package/codex/AGENTS.md +101 -92
  4. package/docs/ui-surfaces.md +48 -21
  5. package/lib/client.js +235 -34
  6. package/official-web-bridge/lib/client.js +368 -4532
  7. package/official-web-bridge/package.json +1 -2
  8. package/package.json +130 -67
  9. package/scripts/build-client.mjs +30 -15
  10. package/scripts/remove-legacy-official-bridge.ps1 +89 -0
  11. package/scripts/setup.mjs +152 -140
  12. package/scripts/verify-npm-install.mjs +311 -310
  13. package/scripts/verify-official-bridge-e2e.mjs +12 -1
  14. package/src/client/host-readiness.mjs +62 -59
  15. package/src/client/index.tsx +117 -24
  16. package/src/client/quick-entry.tsx +10 -0
  17. package/src/client/quick-panel.tsx +295 -0
  18. package/src/client/surface-detection.mjs +43 -30
  19. package/src/credential-reference.mjs +38 -0
  20. package/src/dsh-cli-runtime.mjs +500 -40
  21. package/src/dsh-cohort.mjs +20 -0
  22. package/src/hub/index.mjs +1602 -1016
  23. package/src/install/npx-lifecycle.mjs +1983 -468
  24. package/src/install/official-web.mjs +36 -73
  25. package/src/jobs.mjs +20 -24
  26. package/src/model-catalog.mjs +8 -1
  27. package/src/official-web-bridge.mjs +329 -249
  28. package/src/provider-delete-adapters.mjs +165 -17
  29. package/src/provider-inventory.mjs +17 -3
  30. package/src/provider-layer-migration-adapters.mjs +759 -0
  31. package/src/provider-layer-migration.mjs +198 -0
  32. package/src/provider-lifecycle-state.mjs +4 -1
  33. package/src/provider-profile-store.mjs +193 -4
  34. package/src/provider-settings-store.mjs +82 -6
  35. package/src/provider-store-lock.mjs +67 -0
  36. package/src/runtime-identity.mjs +24 -1
  37. package/src/supervisor/restart-request.mjs +202 -0
  38. package/windows/start-dsh-crew.ps1 +783 -370
  39. package/worker.cordis.yml +32 -46
  40. package/zcode/AGENTS.md +35 -26
@@ -1,310 +1,311 @@
1
- #!/usr/bin/env node
2
-
3
- // Regression gate for the published-package peer contract.
4
- // This intentionally uses npm's default resolver for the candidate install:
5
- // no peer-resolution bypass or equivalent override is permitted here.
6
- //
7
- // The official DSH check is deliberately bounded. It audits authoritative
8
- // public registry manifests and cross-cohort ranges instead of materializing
9
- // or fully resolving the very large official DSH dependency graph.
10
-
11
- import { mkdtemp, readFile, rm } from 'node:fs/promises';
12
- import { existsSync } from 'node:fs';
13
- import os from 'node:os';
14
- import path from 'node:path';
15
- import { spawnSync } from 'node:child_process';
16
- import { fileURLToPath } from 'node:url';
17
-
18
- const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
19
- const registry = process.env.NPM_REGISTRY ?? 'https://registry.npmjs.org/';
20
- export const supportedDshVersion = '0.1.1-rc.2';
21
- const verifyOfficialDsh = process.argv.includes('--with-official-dsh');
22
- const DSH_PACKAGE = '@deepseek-ai/dsh';
23
- const DSH_PREFIX = '@deepseek-ai/dsh-';
24
- const MAX_DIRECT_PEERS = 64;
25
-
26
- export function resolveNpmInvocation({
27
- platform = process.platform,
28
- nodePath = process.execPath,
29
- fileExists = existsSync,
30
- } = {}) {
31
- if (platform !== 'win32') return { command: 'npm', argsPrefix: [] };
32
- const npmCli = path.join(path.dirname(nodePath), 'node_modules', 'npm', 'bin', 'npm-cli.js');
33
- if (!fileExists(npmCli)) throw new Error(`npm CLI was not found beside Node.js: ${npmCli}`);
34
- return { command: nodePath, argsPrefix: [npmCli] };
35
- }
36
-
37
- const npmInvocation = resolveNpmInvocation();
38
-
39
- /**
40
- * The candidate version is derived from the candidate package manifest at the
41
- * checkout root instead of a hard-coded release literal, so the verifier never
42
- * needs a source edit for the next candidate version. The audit guard still
43
- * requires the passed-in manifest to match this authoritative value.
44
- */
45
- export async function readCandidateVersion({ rootDir = root, readFileImpl = readFile } = {}) {
46
- const packageJson = await readFileImpl(path.join(rootDir, 'package.json'), 'utf8');
47
- return JSON.parse(packageJson).version;
48
- }
49
-
50
- function isDshPackage(name) {
51
- return name === DSH_PACKAGE || name.startsWith(DSH_PREFIX);
52
- }
53
-
54
- function parseVersion(value) {
55
- const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
56
- if (!match) return null;
57
- return {
58
- major: Number(match[1]),
59
- minor: Number(match[2]),
60
- patch: Number(match[3]),
61
- prerelease: match[4] ? match[4].split('.') : [],
62
- };
63
- }
64
-
65
- function compareVersions(left, right) {
66
- for (const key of ['major', 'minor', 'patch']) {
67
- if (left[key] !== right[key]) return left[key] > right[key] ? 1 : -1;
68
- }
69
- if (left.prerelease.length === 0 && right.prerelease.length === 0) return 0;
70
- if (left.prerelease.length === 0) return 1;
71
- if (right.prerelease.length === 0) return -1;
72
- const length = Math.max(left.prerelease.length, right.prerelease.length);
73
- for (let index = 0; index < length; index += 1) {
74
- const a = left.prerelease[index];
75
- const b = right.prerelease[index];
76
- if (a === undefined) return -1;
77
- if (b === undefined) return 1;
78
- if (a === b) continue;
79
- const aNumber = /^\d+$/.test(a);
80
- const bNumber = /^\d+$/.test(b);
81
- if (aNumber && bNumber) return Number(a) > Number(b) ? 1 : -1;
82
- if (aNumber !== bNumber) return aNumber ? -1 : 1;
83
- return a > b ? 1 : -1;
84
- }
85
- return 0;
86
- }
87
-
88
- function upperBoundForCaret(version) {
89
- if (version.major > 0) return { major: version.major + 1, minor: 0, patch: 0, prerelease: [] };
90
- if (version.minor > 0) return { major: 0, minor: version.minor + 1, patch: 0, prerelease: [] };
91
- return { major: 0, minor: 0, patch: version.patch + 1, prerelease: [] };
92
- }
93
-
94
- function upperBoundForTilde(version) {
95
- return { major: version.major, minor: version.minor + 1, patch: 0, prerelease: [] };
96
- }
97
-
98
- function satisfiesComparator(version, operator, expected) {
99
- const comparison = compareVersions(version, expected);
100
- if (operator === '>') return comparison > 0;
101
- if (operator === '>=') return comparison >= 0;
102
- if (operator === '<') return comparison < 0;
103
- if (operator === '<=') return comparison <= 0;
104
- return comparison === 0;
105
- }
106
-
107
- function satisfiesAlternative(version, alternative) {
108
- const normalized = alternative.trim();
109
- if (!normalized || /[*xX]|workspace:|^npm:|^file:|^git:/.test(normalized)) return false;
110
- const tokens = normalized.replace(/,/g, ' ').split(/\s+/).filter(Boolean);
111
- return tokens.every((token) => {
112
- const prefix = /^(\^|~|>=|<=|>|<|=)/.exec(token)?.[1] ?? '';
113
- const raw = prefix ? token.slice(prefix.length) : token;
114
- const expected = parseVersion(raw);
115
- if (!expected) return false;
116
- if (prefix === '^') {
117
- return compareVersions(version, expected) >= 0 && compareVersions(version, upperBoundForCaret(expected)) < 0;
118
- }
119
- if (prefix === '~') {
120
- return compareVersions(version, expected) >= 0 && compareVersions(version, upperBoundForTilde(expected)) < 0;
121
- }
122
- return satisfiesComparator(version, prefix, expected);
123
- });
124
- }
125
-
126
- export function satisfiesCohortRange(versionString, range) {
127
- const version = parseVersion(versionString);
128
- if (!version || typeof range !== 'string') return false;
129
- return range.split(/\s*\|\|\s*/).some((alternative) => satisfiesAlternative(version, alternative));
130
- }
131
-
132
- function assertManifest(manifest, expectedName, expectedVersion) {
133
- if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
134
- throw new Error(`invalid registry manifest for ${expectedName}@${expectedVersion}`);
135
- }
136
- if (manifest.name !== expectedName || manifest.version !== expectedVersion) {
137
- throw new Error(`registry manifest identity mismatch for ${expectedName}@${expectedVersion}`);
138
- }
139
- return manifest;
140
- }
141
-
142
- function manifestUrl(registryUrl, name, version) {
143
- const encodedName = name.startsWith('@') ? name.replace('/', '%2f') : encodeURIComponent(name);
144
- return `${registryUrl.replace(/\/+$/, '')}/${encodedName}/${encodeURIComponent(version)}`;
145
- }
146
-
147
- export async function fetchPublicManifest(name, version, {
148
- registryUrl = registry,
149
- fetchImpl = globalThis.fetch,
150
- } = {}) {
151
- if (typeof fetchImpl !== 'function') throw new Error('global fetch is unavailable');
152
- const response = await fetchImpl(manifestUrl(registryUrl, name, version), {
153
- headers: { accept: 'application/json', 'user-agent': 'dsh-crew-cohort-audit' },
154
- });
155
- if (!response?.ok) throw new Error(`public manifest unavailable for ${name}@${version} (HTTP ${response?.status ?? 'unknown'})`);
156
- let manifest;
157
- try {
158
- manifest = await response.json();
159
- } catch {
160
- throw new Error(`public manifest was not valid JSON for ${name}@${version}`);
161
- }
162
- return assertManifest(manifest, name, version);
163
- }
164
-
165
- function dshReferences(manifest) {
166
- return [
167
- ...Object.entries(manifest.dependencies ?? {}),
168
- ...Object.entries(manifest.optionalDependencies ?? {}),
169
- ...Object.entries(manifest.peerDependencies ?? {}),
170
- ].filter(([name]) => isDshPackage(name));
171
- }
172
-
173
- function assertCrossCohortRanges(manifest, label) {
174
- const references = dshReferences(manifest);
175
- for (const [name, range] of references) {
176
- if (!satisfiesCohortRange(supportedDshVersion, range)) {
177
- throw new Error(`${label} has incompatible ${name} range ${JSON.stringify(range)} for ${supportedDshVersion}`);
178
- }
179
- }
180
- return references.length;
181
- }
182
-
183
- export async function auditOfficialDshCohort({
184
- candidateManifest,
185
- expectedCandidateVersion,
186
- registryUrl = registry,
187
- fetchManifest = (name, version) => fetchPublicManifest(name, version, { registryUrl }),
188
- } = {}) {
189
- if (!candidateManifest || typeof candidateManifest !== 'object') throw new Error('candidate package manifest is missing');
190
- if (typeof expectedCandidateVersion !== 'string' || expectedCandidateVersion.length === 0) {
191
- throw new Error('expectedCandidateVersion is required (derive it with readCandidateVersion)');
192
- }
193
- if (candidateManifest.version !== expectedCandidateVersion) {
194
- throw new Error(`package.json must be ${expectedCandidateVersion}`);
195
- }
196
-
197
- const directPeers = Object.entries(candidateManifest.peerDependencies ?? {})
198
- .filter(([name]) => isDshPackage(name));
199
- if (directPeers.length === 0 || directPeers.length > MAX_DIRECT_PEERS) {
200
- throw new Error(`candidate DSH peer count is outside the bounded audit limit: ${directPeers.length}`);
201
- }
202
- for (const [name, range] of directPeers) {
203
- if (range !== supportedDshVersion) {
204
- throw new Error(`candidate peer ${name} must pin exact cohort ${supportedDshVersion}, got ${JSON.stringify(range)}`);
205
- }
206
- }
207
-
208
- const officialManifest = assertManifest(
209
- await fetchManifest(DSH_PACKAGE, supportedDshVersion),
210
- DSH_PACKAGE,
211
- supportedDshVersion,
212
- );
213
- const manifests = [officialManifest];
214
- let crossCohortChecks = assertCrossCohortRanges(officialManifest, `${DSH_PACKAGE}@${supportedDshVersion}`);
215
-
216
- for (const [name] of directPeers) {
217
- const manifest = assertManifest(await fetchManifest(name, supportedDshVersion), name, supportedDshVersion);
218
- manifests.push(manifest);
219
- crossCohortChecks += assertCrossCohortRanges(manifest, `${name}@${supportedDshVersion}`);
220
- }
221
-
222
- return {
223
- marker: 'PASS',
224
- candidate: expectedCandidateVersion,
225
- officialDsh: supportedDshVersion,
226
- directPeerCount: directPeers.length,
227
- manifestCount: manifests.length,
228
- crossCohortChecks,
229
- };
230
- }
231
-
232
- function run(args, cwd = root) {
233
- const result = spawnSync(npmInvocation.command, [...npmInvocation.argsPrefix, ...args], {
234
- cwd,
235
- encoding: 'utf8',
236
- shell: false,
237
- windowsHide: true,
238
- });
239
- if (result.error) throw result.error;
240
- return {
241
- status: result.status ?? 1,
242
- stdout: result.stdout ?? '',
243
- stderr: result.stderr ?? '',
244
- };
245
- }
246
-
247
- function fail(label, result) {
248
- const detail = `${result.stdout}\n${result.stderr}`.trim().replace(/\s+/g, ' ').slice(0, 800);
249
- throw new Error(`${label} failed (exit ${result.status}): ${detail}`);
250
- }
251
-
252
- export async function assertInstalled(prefix, label, expectedVersion) {
253
- const packageRoot = path.join(prefix, 'node_modules', '@ran-sh', 'dsh-crew');
254
- const packageJson = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
255
- const runtimeSource = await readFile(path.join(packageRoot, 'src', 'runtime-identity.mjs'), 'utf8');
256
- const runtimeVersion = runtimeSource.match(/RUNTIME_VERSION\s*=\s*'([^']+)'/)?.[1];
257
- const entryExists = await readFile(path.join(packageRoot, 'src', 'hub', 'entry.mjs')).then(() => true, () => false);
258
- const clientExists = await readFile(path.join(packageRoot, 'lib', 'client.js')).then(() => true, () => false);
259
- if (packageJson.version !== expectedVersion || runtimeVersion !== expectedVersion || !entryExists || !clientExists) {
260
- throw new Error(`${label} did not install the expected ${expectedVersion} package/runtime entries`);
261
- }
262
- }
263
-
264
- async function main() {
265
- const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'dsh-crew-install-verify-'));
266
- const paths = {
267
- pack: await mkdtemp(path.join(tempRoot, 'pack-')),
268
- standalone: await mkdtemp(path.join(tempRoot, 'standalone-')),
269
- };
270
-
271
- try {
272
- const packageJson = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));
273
- const candidateVersion = await readCandidateVersion();
274
- if (packageJson.version !== candidateVersion) throw new Error(`package.json must be ${candidateVersion}`);
275
-
276
- const packed = run(['pack', '--json', '--pack-destination', paths.pack]);
277
- if (packed.status !== 0) fail('npm pack', packed);
278
- const packInfo = JSON.parse(packed.stdout)[0];
279
- const tarball = path.join(paths.pack, packInfo.filename);
280
-
281
- const standalone = run([
282
- 'install', '--prefix', paths.standalone, '--no-save', '--package-lock=false', '--ignore-scripts', '--no-audit', '--no-fund',
283
- '--registry', registry, tarball,
284
- ]);
285
- if (standalone.status !== 0) fail('plain npm candidate install', standalone);
286
- await assertInstalled(paths.standalone, 'standalone candidate', candidateVersion);
287
-
288
- let officialMarker = 'not-run';
289
- if (verifyOfficialDsh) {
290
- const audit = await auditOfficialDshCohort({
291
- candidateManifest: packageJson,
292
- expectedCandidateVersion: candidateVersion,
293
- registryUrl: registry,
294
- });
295
- officialMarker = `${supportedDshVersion}:manifest-audit`;
296
- console.log(`DSH_COHORT_AUDIT=PASS official_dsh=${audit.officialDsh} direct_peers=${audit.directPeerCount} manifests=${audit.manifestCount} cross_cohort_checks=${audit.crossCohortChecks}`);
297
- }
298
-
299
- console.log(`NPM_INSTALL_CONTRACT=PASS candidate=${candidateVersion} official_dsh=${officialMarker}`);
300
- } finally {
301
- await rm(tempRoot, { recursive: true, force: true });
302
- }
303
- }
304
-
305
- if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
306
- main().catch((error) => {
307
- console.error(error instanceof Error ? error.message : String(error));
308
- process.exitCode = 1;
309
- });
310
- }
1
+ #!/usr/bin/env node
2
+
3
+ // Regression gate for the published-package peer contract.
4
+ // This intentionally uses npm's default resolver for the candidate install:
5
+ // no peer-resolution bypass or equivalent override is permitted here.
6
+ //
7
+ // The official DSH check is deliberately bounded. It audits authoritative
8
+ // public registry manifests and cross-cohort ranges instead of materializing
9
+ // or fully resolving the very large official DSH dependency graph.
10
+
11
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
12
+ import { existsSync } from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { spawnSync } from 'node:child_process';
16
+ import { fileURLToPath } from 'node:url';
17
+ import { TARGET_DSH_VERSION } from '../src/dsh-cohort.mjs';
18
+
19
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
20
+ const registry = process.env.NPM_REGISTRY ?? 'https://registry.npmjs.org/';
21
+ export const supportedDshVersion = TARGET_DSH_VERSION;
22
+ const verifyOfficialDsh = process.argv.includes('--with-official-dsh');
23
+ const DSH_PACKAGE = '@deepseek-ai/dsh';
24
+ const DSH_PREFIX = '@deepseek-ai/dsh-';
25
+ const MAX_DIRECT_PEERS = 64;
26
+
27
+ export function resolveNpmInvocation({
28
+ platform = process.platform,
29
+ nodePath = process.execPath,
30
+ fileExists = existsSync,
31
+ } = {}) {
32
+ if (platform !== 'win32') return { command: 'npm', argsPrefix: [] };
33
+ const npmCli = path.join(path.dirname(nodePath), 'node_modules', 'npm', 'bin', 'npm-cli.js');
34
+ if (!fileExists(npmCli)) throw new Error(`npm CLI was not found beside Node.js: ${npmCli}`);
35
+ return { command: nodePath, argsPrefix: [npmCli] };
36
+ }
37
+
38
+ const npmInvocation = resolveNpmInvocation();
39
+
40
+ /**
41
+ * The candidate version is derived from the candidate package manifest at the
42
+ * checkout root instead of a hard-coded release literal, so the verifier never
43
+ * needs a source edit for the next candidate version. The audit guard still
44
+ * requires the passed-in manifest to match this authoritative value.
45
+ */
46
+ export async function readCandidateVersion({ rootDir = root, readFileImpl = readFile } = {}) {
47
+ const packageJson = await readFileImpl(path.join(rootDir, 'package.json'), 'utf8');
48
+ return JSON.parse(packageJson).version;
49
+ }
50
+
51
+ function isDshPackage(name) {
52
+ return name === DSH_PACKAGE || name.startsWith(DSH_PREFIX);
53
+ }
54
+
55
+ function parseVersion(value) {
56
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
57
+ if (!match) return null;
58
+ return {
59
+ major: Number(match[1]),
60
+ minor: Number(match[2]),
61
+ patch: Number(match[3]),
62
+ prerelease: match[4] ? match[4].split('.') : [],
63
+ };
64
+ }
65
+
66
+ function compareVersions(left, right) {
67
+ for (const key of ['major', 'minor', 'patch']) {
68
+ if (left[key] !== right[key]) return left[key] > right[key] ? 1 : -1;
69
+ }
70
+ if (left.prerelease.length === 0 && right.prerelease.length === 0) return 0;
71
+ if (left.prerelease.length === 0) return 1;
72
+ if (right.prerelease.length === 0) return -1;
73
+ const length = Math.max(left.prerelease.length, right.prerelease.length);
74
+ for (let index = 0; index < length; index += 1) {
75
+ const a = left.prerelease[index];
76
+ const b = right.prerelease[index];
77
+ if (a === undefined) return -1;
78
+ if (b === undefined) return 1;
79
+ if (a === b) continue;
80
+ const aNumber = /^\d+$/.test(a);
81
+ const bNumber = /^\d+$/.test(b);
82
+ if (aNumber && bNumber) return Number(a) > Number(b) ? 1 : -1;
83
+ if (aNumber !== bNumber) return aNumber ? -1 : 1;
84
+ return a > b ? 1 : -1;
85
+ }
86
+ return 0;
87
+ }
88
+
89
+ function upperBoundForCaret(version) {
90
+ if (version.major > 0) return { major: version.major + 1, minor: 0, patch: 0, prerelease: [] };
91
+ if (version.minor > 0) return { major: 0, minor: version.minor + 1, patch: 0, prerelease: [] };
92
+ return { major: 0, minor: 0, patch: version.patch + 1, prerelease: [] };
93
+ }
94
+
95
+ function upperBoundForTilde(version) {
96
+ return { major: version.major, minor: version.minor + 1, patch: 0, prerelease: [] };
97
+ }
98
+
99
+ function satisfiesComparator(version, operator, expected) {
100
+ const comparison = compareVersions(version, expected);
101
+ if (operator === '>') return comparison > 0;
102
+ if (operator === '>=') return comparison >= 0;
103
+ if (operator === '<') return comparison < 0;
104
+ if (operator === '<=') return comparison <= 0;
105
+ return comparison === 0;
106
+ }
107
+
108
+ function satisfiesAlternative(version, alternative) {
109
+ const normalized = alternative.trim();
110
+ if (!normalized || /[*xX]|workspace:|^npm:|^file:|^git:/.test(normalized)) return false;
111
+ const tokens = normalized.replace(/,/g, ' ').split(/\s+/).filter(Boolean);
112
+ return tokens.every((token) => {
113
+ const prefix = /^(\^|~|>=|<=|>|<|=)/.exec(token)?.[1] ?? '';
114
+ const raw = prefix ? token.slice(prefix.length) : token;
115
+ const expected = parseVersion(raw);
116
+ if (!expected) return false;
117
+ if (prefix === '^') {
118
+ return compareVersions(version, expected) >= 0 && compareVersions(version, upperBoundForCaret(expected)) < 0;
119
+ }
120
+ if (prefix === '~') {
121
+ return compareVersions(version, expected) >= 0 && compareVersions(version, upperBoundForTilde(expected)) < 0;
122
+ }
123
+ return satisfiesComparator(version, prefix, expected);
124
+ });
125
+ }
126
+
127
+ export function satisfiesCohortRange(versionString, range) {
128
+ const version = parseVersion(versionString);
129
+ if (!version || typeof range !== 'string') return false;
130
+ return range.split(/\s*\|\|\s*/).some((alternative) => satisfiesAlternative(version, alternative));
131
+ }
132
+
133
+ function assertManifest(manifest, expectedName, expectedVersion) {
134
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
135
+ throw new Error(`invalid registry manifest for ${expectedName}@${expectedVersion}`);
136
+ }
137
+ if (manifest.name !== expectedName || manifest.version !== expectedVersion) {
138
+ throw new Error(`registry manifest identity mismatch for ${expectedName}@${expectedVersion}`);
139
+ }
140
+ return manifest;
141
+ }
142
+
143
+ function manifestUrl(registryUrl, name, version) {
144
+ const encodedName = name.startsWith('@') ? name.replace('/', '%2f') : encodeURIComponent(name);
145
+ return `${registryUrl.replace(/\/+$/, '')}/${encodedName}/${encodeURIComponent(version)}`;
146
+ }
147
+
148
+ export async function fetchPublicManifest(name, version, {
149
+ registryUrl = registry,
150
+ fetchImpl = globalThis.fetch,
151
+ } = {}) {
152
+ if (typeof fetchImpl !== 'function') throw new Error('global fetch is unavailable');
153
+ const response = await fetchImpl(manifestUrl(registryUrl, name, version), {
154
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crew-cohort-audit' },
155
+ });
156
+ if (!response?.ok) throw new Error(`public manifest unavailable for ${name}@${version} (HTTP ${response?.status ?? 'unknown'})`);
157
+ let manifest;
158
+ try {
159
+ manifest = await response.json();
160
+ } catch {
161
+ throw new Error(`public manifest was not valid JSON for ${name}@${version}`);
162
+ }
163
+ return assertManifest(manifest, name, version);
164
+ }
165
+
166
+ function dshReferences(manifest) {
167
+ return [
168
+ ...Object.entries(manifest.dependencies ?? {}),
169
+ ...Object.entries(manifest.optionalDependencies ?? {}),
170
+ ...Object.entries(manifest.peerDependencies ?? {}),
171
+ ].filter(([name]) => isDshPackage(name));
172
+ }
173
+
174
+ function assertCrossCohortRanges(manifest, label) {
175
+ const references = dshReferences(manifest);
176
+ for (const [name, range] of references) {
177
+ if (!satisfiesCohortRange(supportedDshVersion, range)) {
178
+ throw new Error(`${label} has incompatible ${name} range ${JSON.stringify(range)} for ${supportedDshVersion}`);
179
+ }
180
+ }
181
+ return references.length;
182
+ }
183
+
184
+ export async function auditOfficialDshCohort({
185
+ candidateManifest,
186
+ expectedCandidateVersion,
187
+ registryUrl = registry,
188
+ fetchManifest = (name, version) => fetchPublicManifest(name, version, { registryUrl }),
189
+ } = {}) {
190
+ if (!candidateManifest || typeof candidateManifest !== 'object') throw new Error('candidate package manifest is missing');
191
+ if (typeof expectedCandidateVersion !== 'string' || expectedCandidateVersion.length === 0) {
192
+ throw new Error('expectedCandidateVersion is required (derive it with readCandidateVersion)');
193
+ }
194
+ if (candidateManifest.version !== expectedCandidateVersion) {
195
+ throw new Error(`package.json must be ${expectedCandidateVersion}`);
196
+ }
197
+
198
+ const directPeers = Object.entries(candidateManifest.peerDependencies ?? {})
199
+ .filter(([name]) => isDshPackage(name));
200
+ if (directPeers.length === 0 || directPeers.length > MAX_DIRECT_PEERS) {
201
+ throw new Error(`candidate DSH peer count is outside the bounded audit limit: ${directPeers.length}`);
202
+ }
203
+ for (const [name, range] of directPeers) {
204
+ if (range !== supportedDshVersion) {
205
+ throw new Error(`candidate peer ${name} must pin exact cohort ${supportedDshVersion}, got ${JSON.stringify(range)}`);
206
+ }
207
+ }
208
+
209
+ const officialManifest = assertManifest(
210
+ await fetchManifest(DSH_PACKAGE, supportedDshVersion),
211
+ DSH_PACKAGE,
212
+ supportedDshVersion,
213
+ );
214
+ const manifests = [officialManifest];
215
+ let crossCohortChecks = assertCrossCohortRanges(officialManifest, `${DSH_PACKAGE}@${supportedDshVersion}`);
216
+
217
+ for (const [name] of directPeers) {
218
+ const manifest = assertManifest(await fetchManifest(name, supportedDshVersion), name, supportedDshVersion);
219
+ manifests.push(manifest);
220
+ crossCohortChecks += assertCrossCohortRanges(manifest, `${name}@${supportedDshVersion}`);
221
+ }
222
+
223
+ return {
224
+ marker: 'PASS',
225
+ candidate: expectedCandidateVersion,
226
+ officialDsh: supportedDshVersion,
227
+ directPeerCount: directPeers.length,
228
+ manifestCount: manifests.length,
229
+ crossCohortChecks,
230
+ };
231
+ }
232
+
233
+ function run(args, cwd = root) {
234
+ const result = spawnSync(npmInvocation.command, [...npmInvocation.argsPrefix, ...args], {
235
+ cwd,
236
+ encoding: 'utf8',
237
+ shell: false,
238
+ windowsHide: true,
239
+ });
240
+ if (result.error) throw result.error;
241
+ return {
242
+ status: result.status ?? 1,
243
+ stdout: result.stdout ?? '',
244
+ stderr: result.stderr ?? '',
245
+ };
246
+ }
247
+
248
+ function fail(label, result) {
249
+ const detail = `${result.stdout}\n${result.stderr}`.trim().replace(/\s+/g, ' ').slice(0, 800);
250
+ throw new Error(`${label} failed (exit ${result.status}): ${detail}`);
251
+ }
252
+
253
+ export async function assertInstalled(prefix, label, expectedVersion) {
254
+ const packageRoot = path.join(prefix, 'node_modules', '@ran-sh', 'dsh-crew');
255
+ const packageJson = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
256
+ const runtimeSource = await readFile(path.join(packageRoot, 'src', 'runtime-identity.mjs'), 'utf8');
257
+ const runtimeVersion = runtimeSource.match(/RUNTIME_VERSION\s*=\s*'([^']+)'/)?.[1];
258
+ const entryExists = await readFile(path.join(packageRoot, 'src', 'hub', 'entry.mjs')).then(() => true, () => false);
259
+ const clientExists = await readFile(path.join(packageRoot, 'lib', 'client.js')).then(() => true, () => false);
260
+ if (packageJson.version !== expectedVersion || runtimeVersion !== expectedVersion || !entryExists || !clientExists) {
261
+ throw new Error(`${label} did not install the expected ${expectedVersion} package/runtime entries`);
262
+ }
263
+ }
264
+
265
+ async function main() {
266
+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'dsh-crew-install-verify-'));
267
+ const paths = {
268
+ pack: await mkdtemp(path.join(tempRoot, 'pack-')),
269
+ standalone: await mkdtemp(path.join(tempRoot, 'standalone-')),
270
+ };
271
+
272
+ try {
273
+ const packageJson = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));
274
+ const candidateVersion = await readCandidateVersion();
275
+ if (packageJson.version !== candidateVersion) throw new Error(`package.json must be ${candidateVersion}`);
276
+
277
+ const packed = run(['pack', '--json', '--pack-destination', paths.pack]);
278
+ if (packed.status !== 0) fail('npm pack', packed);
279
+ const packInfo = JSON.parse(packed.stdout)[0];
280
+ const tarball = path.join(paths.pack, packInfo.filename);
281
+
282
+ const standalone = run([
283
+ 'install', '--prefix', paths.standalone, '--no-save', '--package-lock=false', '--ignore-scripts', '--no-audit', '--no-fund',
284
+ '--registry', registry, tarball,
285
+ ]);
286
+ if (standalone.status !== 0) fail('plain npm candidate install', standalone);
287
+ await assertInstalled(paths.standalone, 'standalone candidate', candidateVersion);
288
+
289
+ let officialMarker = 'not-run';
290
+ if (verifyOfficialDsh) {
291
+ const audit = await auditOfficialDshCohort({
292
+ candidateManifest: packageJson,
293
+ expectedCandidateVersion: candidateVersion,
294
+ registryUrl: registry,
295
+ });
296
+ officialMarker = `${supportedDshVersion}:manifest-audit`;
297
+ console.log(`DSH_COHORT_AUDIT=PASS official_dsh=${audit.officialDsh} direct_peers=${audit.directPeerCount} manifests=${audit.manifestCount} cross_cohort_checks=${audit.crossCohortChecks}`);
298
+ }
299
+
300
+ console.log(`NPM_INSTALL_CONTRACT=PASS candidate=${candidateVersion} official_dsh=${officialMarker}`);
301
+ } finally {
302
+ await rm(tempRoot, { recursive: true, force: true });
303
+ }
304
+ }
305
+
306
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
307
+ main().catch((error) => {
308
+ console.error(error instanceof Error ? error.message : String(error));
309
+ process.exitCode = 1;
310
+ });
311
+ }