@vini-ds/agent 0.0.0-stage → 0.1.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/updates.mjs ADDED
@@ -0,0 +1,361 @@
1
+ // Read-only public npm update discovery. No package code is downloaded or run.
2
+ import { constants } from 'node:fs';
3
+ import { lstat, open, realpath } from 'node:fs/promises';
4
+ import { execFile } from 'node:child_process';
5
+ import { createHash } from 'node:crypto';
6
+ import { isDeepStrictEqual, promisify } from 'node:util';
7
+ import path from 'node:path';
8
+ import { compareVersions, isExactVersion } from './version.mjs';
9
+
10
+ const registry = 'https://registry.npmjs.org';
11
+ const exactVersion = { test: isExactVersion };
12
+ const packageName = { test(value) { return typeof value === 'string' && value.length <= 214 && !/[\u0000-\u001f\u007f]/u.test(value) && /^@[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/u.test(value); } };
13
+ const keys = ['ui', 'tokens', 'agent'];
14
+ const hash = /^sha256:[a-f0-9]{64}$/u;
15
+ function validIntegrity(value) {
16
+ if (typeof value !== 'string' || !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(value)) return false;
17
+ const encoded = value.slice(7), bytes = Buffer.from(encoded, 'base64');
18
+ return bytes.length === 64 && bytes.toString('base64') === encoded;
19
+ }
20
+ const runFile = promisify(execFile);
21
+ const legacyNames = { ui: '@timelex/vini-ui', tokens: '@timelex/vini-tokens', agent: '@timelex/vini-agent' };
22
+ const viniNames = { ui: '@vini/ui', tokens: '@vini/tokens', agent: '@vini/agent' };
23
+ const directNames = { ui: '@vini-ds/ui', tokens: '@vini-ds/tokens', agent: '@vini-ds/agent' };
24
+ function sameNames(left, right) { return keys.every(key => left?.[key] === right?.[key]); }
25
+ function contextDistribution(metadata) {
26
+ return { version: metadata.version, ...Object.fromEntries(keys.map(key => [key, metadata.packages?.[key]?.name])) };
27
+ }
28
+ function contextIsConsistent(metadata) {
29
+ if (!exactVersion.test(metadata?.version ?? '') || !keys.every(key => typeof metadata.packages?.[key]?.name === 'string' && packageName.test(metadata.packages[key].name) && metadata.packages[key].version === metadata.version) ||
30
+ new Set(keys.map(key => metadata.packages[key].name)).size !== keys.length) return false;
31
+ try { compareVersions(metadata.version, metadata.version); return true; } catch { return false; }
32
+ }
33
+ function targetFamily(reference, target) {
34
+ if (!exactVersion.test(reference?.version ?? '') || !keys.every(key => packageName.test(reference[key] ?? ''))) throw new Error('installed or context package set cannot be verified');
35
+ if (sameNames(reference, target)) return 'same-family';
36
+ if (compareVersions(reference.version, target.version) < 0) {
37
+ if (sameNames(reference, legacyNames) && sameNames(target, viniNames)) return 'legacy-to-native';
38
+ if ((sameNames(reference, legacyNames) || sameNames(reference, viniNames)) && sameNames(target, directNames)) return 'manual-import-migration';
39
+ }
40
+ throw new Error('latest CLI does not describe a compatible exact package set');
41
+ }
42
+ function validateSelectedTarget(value) {
43
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
44
+ Object.keys(value).length !== 4 || !['version', ...keys].every(key => Object.hasOwn(value, key)) ||
45
+ typeof value.version !== 'string' || value.version.length > 100 || !exactVersion.test(value.version) || !keys.every(key => typeof value[key] === 'string' && value[key].length <= 214 && packageName.test(value[key])) ||
46
+ new Set(keys.map(key => value[key])).size !== keys.length) throw new Error('target must contain an exact version and three distinct scoped package names');
47
+ compareVersions(value.version, value.version);
48
+ return { version: value.version, ui: value.ui, tokens: value.tokens, agent: value.agent };
49
+ }
50
+ function equalsRelease(left, right) { return left?.version === right?.version && sameNames(left, right); }
51
+ function validRelease(value) {
52
+ try {
53
+ const url = new URL(value.atlas.url);
54
+ return url.protocol === 'https:' && !url.username && !url.password && !url.search && !url.hash &&
55
+ hash.test(value.atlas.archiveSha256) && /^[a-z0-9][a-z0-9.-]{0,99}$/u.test(value.atlas.siteRelease) &&
56
+ /^[a-f0-9]{40}$/u.test(value.atlas.commit) && /^candidate-[a-f0-9]{16}$/u.test(value.delivery.id) &&
57
+ hash.test(value.delivery.manifestSha256) && hash.test(value.delivery.packageManifestSha256) && exactVersion.test(value.changes.fromVersion) &&
58
+ typeof value.changes.summary === 'string' && !!value.changes.summary.trim() && value.changes.summary.length <= 1000 &&
59
+ Array.isArray(value.changes.components) && value.changes.components.length <= 200 &&
60
+ value.changes.components.every((name) => typeof name === 'string' && /^[A-Za-z][A-Za-z0-9-]{0,79}$/u.test(name)) &&
61
+ new Set(value.changes.components).size === value.changes.components.length;
62
+ } catch { return false; }
63
+ }
64
+
65
+ export async function boundedBytes(file) {
66
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
67
+ try {
68
+ const stat = await handle.stat({ bigint: true });
69
+ if (!stat.isFile() || stat.size > 4n * 1024n * 1024n) throw new Error('metadata must be a bounded regular file');
70
+ const data = Buffer.alloc(Number(stat.size) + 1);
71
+ let used = 0;
72
+ while (used < data.length) { const { bytesRead } = await handle.read(data, used, data.length - used, used); if (!bytesRead) break; used += bytesRead; }
73
+ const after = await handle.stat({ bigint: true });
74
+ if (used !== Number(stat.size) || stat.dev !== after.dev || stat.ino !== after.ino || stat.size !== after.size || stat.mtimeNs !== after.mtimeNs || stat.ctimeNs !== after.ctimeNs) throw new Error('metadata changed while reading');
75
+ return { bytes: data.subarray(0, used), stat: after };
76
+ } finally { await handle.close(); }
77
+ }
78
+ async function boundedJson(file) {
79
+ return JSON.parse((await boundedBytes(file)).bytes.toString('utf8'));
80
+ }
81
+
82
+ async function resolveEntries(app, importScope, signal) {
83
+ // Resolve in a fresh Node process so an already-connected MCP does not use
84
+ // cached pnpm realpaths after an upgrade. require.resolve reads package
85
+ // metadata and paths only; it never executes a package's entry point.
86
+ const code = `const {createRequire}=require('node:module');const r=createRequire(process.argv[1]);const scope=process.argv[2],out={};for(const k of ['ui','tokens','agent']){try{out[k]=r.resolve(scope+'/'+k+(k==='agent'?'/mcp':''));}catch{out[k]=null;}}process.stdout.write(JSON.stringify(out));`;
87
+ // Do not inherit Node preload options: discovery must not execute external code.
88
+ const env = Object.fromEntries(['PATH', 'SystemRoot', 'SYSTEMROOT'].filter(name => process.env[name] !== undefined).map(name => [name, process.env[name]]));
89
+ const { stdout } = await runFile(process.execPath, ['-e', code, path.join(app, 'package.json'), importScope], { timeout: 5000, maxBuffer: 1024 * 1024, env, signal });
90
+ return JSON.parse(stdout);
91
+ }
92
+
93
+ async function installedPackage(app, key, importScope, resolved) {
94
+ // Read the currently linked manifest directly rather than using Node's
95
+ // cached module resolution. pnpm can replace its version symlink while this
96
+ // MCP remains alive; a cached realpath would describe the old package.
97
+ const modules = await realpath(path.join(app, 'node_modules'));
98
+ const directory = await realpath(path.join(modules, importScope, key));
99
+ if (!directory.startsWith(`${modules}${path.sep}`)) throw new Error('package points outside project node_modules');
100
+ if (typeof resolved !== 'string') throw new Error(`cannot resolve ${key} package export`);
101
+ const entry = await realpath(resolved);
102
+ if (!entry.startsWith(`${directory}${path.sep}`)) throw new Error('package export points outside installed package');
103
+ const manifest = await boundedJson(path.join(directory, 'package.json'));
104
+ if (typeof manifest.name !== 'string' || typeof manifest.version !== 'string') throw new Error(`cannot find ${key} package manifest`);
105
+ return { name: manifest.name, version: manifest.version, manifest, directory };
106
+ }
107
+
108
+ function validInstalledManifest(manifest, key, expected, importScope) {
109
+ const direct = importScope === '@vini-ds';
110
+ if (direct && ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].some(section =>
111
+ Object.values(manifest[section] ?? {}).some(value => typeof value === 'string' && value.trim().startsWith('npm:')))) return false;
112
+ if (key !== 'ui') return true;
113
+ const token = `${importScope}/tokens`, dependency = manifest.dependencies?.[token], peer = manifest.peerDependencies?.[token];
114
+ if (direct && ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies', 'peerDependenciesMeta'].some(section => Object.hasOwn(manifest[section] ?? {}, '@vini/tokens'))) return false;
115
+ if (manifest.optionalDependencies?.[token] !== undefined || manifest.peerDependenciesMeta?.[token]?.optional === true) return false;
116
+ return expected.tokens === token
117
+ ? peer === expected.version && (dependency === undefined || dependency === expected.version)
118
+ : dependency === `npm:${expected.tokens}@${expected.version}` && (peer === undefined || peer === expected.version);
119
+ }
120
+
121
+ async function installedStatus(projectRoot, metadata, signal) {
122
+ let receipt;
123
+ try {
124
+ const dir = await lstat(path.join(projectRoot, '.vini-ds'));
125
+ if (!dir.isDirectory() || dir.isSymbolicLink()) throw new Error('unsafe receipt directory');
126
+ receipt = await boundedJson(path.join(projectRoot, '.vini-ds/npm-install.json'));
127
+ }
128
+ catch (error) {
129
+ if (error.code === 'ENOENT') return { status: 'not-configured', reason: 'VINi npm receipt not found' };
130
+ return { status: 'unknown', reason: 'VINi npm receipt could not be read' };
131
+ }
132
+ try {
133
+ if (receipt.installer !== 'vini-npm' || !receipt.distribution || typeof receipt.appRoot !== 'string') throw new Error('unsupported receipt');
134
+ const root = await realpath(projectRoot), app = await realpath(path.resolve(root, receipt.appRoot));
135
+ if (app !== root && !app.startsWith(`${root}${path.sep}`)) throw new Error('app root is outside project');
136
+ const expected = receipt.distribution;
137
+ if (!isExactVersion(expected.version) || !keys.every(key => packageName.test(expected[key]))) throw new Error('invalid receipt distribution');
138
+ // This implementation uses the receipt to select the installed paths. If
139
+ // its metadata is stale, it can distinguish that from a receipt mismatch.
140
+ // Previously published MCP implementations do not acquire this behavior.
141
+ const dsFamily = keys.every(key => expected[key] === `@vini-ds/${key}`);
142
+ if (!dsFamily && keys.some(key => expected[key] === `@vini-ds/${key}`)) throw new Error('mixed VINi package families');
143
+ const importScope = dsFamily ? '@vini-ds' : '@vini';
144
+ const projectManifest = await boundedJson(path.join(app, 'package.json'));
145
+ const dependencies = { ...projectManifest.optionalDependencies, ...projectManifest.devDependencies, ...projectManifest.dependencies };
146
+ const declarations = keys.every(key => dependencies[`${importScope}/${key}`] === (expected[key] === `${importScope}/${key}` ? expected.version : `npm:${expected[key]}@${expected.version}`));
147
+ if (typeof receipt.launcherSha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(receipt.launcherSha256)) throw new Error('launcher digest unavailable');
148
+ const launcherBytes = (await boundedBytes(path.join(root, '.vini-ds/npm-launcher.mjs'))).bytes;
149
+ const launcher = createHash('sha256').update(launcherBytes).digest('hex') === receipt.launcherSha256;
150
+ const resolved = await resolveEntries(app, importScope, signal);
151
+ const records = Object.fromEntries(await Promise.all(keys.map(async (key) => {
152
+ if (typeof resolved[key] !== 'string') return [key, null];
153
+ return [key, await installedPackage(app, key, importScope, resolved[key])];
154
+ })));
155
+ const packages = Object.fromEntries(keys.map(key => [key, records[key] ? {name: records[key].name, version: records[key].version} : {error: 'not-installed-or-unreadable'}]));
156
+ const packageMatches = keys.every(key => packages[key].name === expected[key] && packages[key].version === expected.version);
157
+ const manifestMatches = keys.every(key => records[key] && validInstalledManifest(records[key].manifest, key, expected, importScope));
158
+ let agentContext = false;
159
+ if (records.agent) {
160
+ const contextDirectory = await lstat(path.join(records.agent.directory, 'context'));
161
+ if (!contextDirectory.isDirectory() || contextDirectory.isSymbolicLink()) throw new Error('unsafe agent context directory');
162
+ const current = await boundedJson(path.join(records.agent.directory, 'context/current.json'));
163
+ agentContext = current.name === expected.agent && current.version === expected.version && keys.every(key => current.packages?.[key]?.name === expected[key] && current.packages[key].version === expected.version);
164
+ }
165
+ const checks = { declarations, packageManifests: manifestMatches, launcher, agentContext };
166
+ const matchesReceipt = packageMatches && Object.values(checks).every(Boolean);
167
+ const contextKnown = contextIsConsistent(metadata);
168
+ const matchesContext = contextKnown && keys.every((key) => packages[key].name === metadata.packages[key].name && packages[key].version === metadata.version);
169
+ return { status: matchesReceipt && matchesContext ? 'matched' : 'mismatch', packages,
170
+ receipt: { version: expected.version, ui: expected.ui, tokens: expected.tokens, agent: expected.agent },
171
+ context: { ...contextDistribution(metadata), metadataStatus: contextKnown ? 'consistent' : 'incomplete-or-inconsistent', baseline: metadata.baseline, ...(metadata.viniRelease ? { viniRelease: metadata.viniRelease } : {}) },
172
+ matchesReceipt, matchesContext, checks,
173
+ ...(matchesReceipt && matchesContext ? {} : { mismatchKind: !matchesReceipt ? 'package-receipt' : contextKnown ? 'mcp-context' : 'context-unverified' }) };
174
+ } catch { return { status: 'unknown', reason: 'Installed package manifests or receipt could not be verified' }; }
175
+ }
176
+
177
+ // The installer owns this existing project-local lock. Observe it at both ends
178
+ // of the read, and compare the receipt identity as well as its bytes: an entire
179
+ // install can finish between observations, including a repair of the same version.
180
+ async function installationObservation(projectRoot) {
181
+ const lock = path.join(projectRoot, '.vini-npm-install.lock');
182
+ const exists = async file => { try { return await lstat(file, { bigint: true }); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
183
+ try {
184
+ if (await exists(lock)) return { state: 'locked' };
185
+ const file = path.join(projectRoot, '.vini-ds/npm-install.json');
186
+ const before = await exists(file);
187
+ let bytes = null;
188
+ if (before) {
189
+ if (!before.isFile() || before.isSymbolicLink() || before.size > 4n * 1024n * 1024n) return { state: 'unknown' };
190
+ const opened = await boundedBytes(file);
191
+ if (before.dev !== opened.stat.dev || before.ino !== opened.stat.ino) return { state: 'changed' };
192
+ bytes = opened.bytes;
193
+ }
194
+ let app = projectRoot;
195
+ if (bytes) {
196
+ const receipt = JSON.parse(bytes.toString('utf8'));
197
+ if (typeof receipt.appRoot !== 'string') return { state: 'unknown' };
198
+ const root = await realpath(projectRoot);
199
+ app = await realpath(path.resolve(root, receipt.appRoot));
200
+ if (app !== root && !app.startsWith(`${root}${path.sep}`)) return { state: 'unknown' };
201
+ }
202
+ // Moving node_modules out and restoring it changes the containing directory,
203
+ // even when a failed cooperative install restores the same receipt bytes.
204
+ const appStat = await exists(app), modulesStat = await exists(path.join(app, 'node_modules'));
205
+ const after = await exists(file);
206
+ if (await exists(lock)) return { state: 'locked' };
207
+ const identity = value => value ? [value.dev, value.ino, value.size, value.mtimeNs, value.ctimeNs].map(String).join(':') : 'missing';
208
+ if (identity(before) !== identity(after)) return { state: 'changed' };
209
+ return { state: 'stable', identity: `${identity(after)}|${identity(appStat)}|${identity(modulesStat)}`, bytes: bytes?.toString('base64') ?? null };
210
+ } catch { return { state: 'unknown' }; }
211
+ }
212
+
213
+ async function registryJson(name, version, signal) {
214
+ const controller = new AbortController();
215
+ const abort = () => controller.abort(signal?.reason);
216
+ signal?.addEventListener('abort', abort, { once: true });
217
+ if (signal?.aborted) abort();
218
+ const timer = setTimeout(() => controller.abort(new Error('registry request timed out')), 5000);
219
+ try {
220
+ const response = await fetch(`${registry}/${encodeURIComponent(name)}/${encodeURIComponent(version)}`, {
221
+ headers: { accept: 'application/json' }, redirect: 'error', signal: controller.signal,
222
+ });
223
+ if (!response.ok) throw new Error(`registry returned ${response.status}`);
224
+ const length = Number(response.headers.get('content-length'));
225
+ if (Number.isFinite(length) && length > 2 * 1024 * 1024) throw new Error('registry metadata too large');
226
+ const reader = response.body.getReader(), chunks = []; let total = 0;
227
+ while (true) {
228
+ const { done, value } = await reader.read(); if (done) break;
229
+ total += value.length; if (total > 2 * 1024 * 1024) { await reader.cancel(); throw new Error('registry metadata too large'); }
230
+ chunks.push(value);
231
+ }
232
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
233
+ } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
234
+ }
235
+
236
+ // Optional fetchJson is a test seam; the installed server always uses npm HTTPS.
237
+ export async function checkUpdates(metadata, { projectRoot = process.cwd(), fetchJson = registryJson, target, signal } = {}) {
238
+ signal?.throwIfAborted();
239
+ const selected = target === undefined ? null : validateSelectedTarget(target);
240
+ const start = await installationObservation(projectRoot);
241
+ if (start.state === 'locked') return {
242
+ status: 'update-in-progress', statusScope: 'package-context-and-registry-latest',
243
+ installed: { status: 'update-in-progress', reason: 'VINi installation lock exists; package state is not verified' },
244
+ available: { status: 'not-checked', registry, reason: 'VINi installation is locked' },
245
+ target: selected ? { status: 'provided', ...selected, matchesInstalled: null, matchesReceipt: null, matchesContext: null, matchesLatest: null, verification: 'caller-supplied-not-independently-verified' } : { status: 'not-provided' },
246
+ nextStep: 'Wait if the VINi operation is still running. If it has stopped or its state is unknown, inspect the lock and recovery information before retrying; do not remove an ambiguous lock automatically.',
247
+ readOnly: true, installationChanged: false,
248
+ limitations: ['an installation lock may be left by an interrupted operation', 'client-session verification requires current, the affected component contract, and check_updates in the same client'],
249
+ };
250
+ let installed = start.state === 'stable' ? await installedStatus(projectRoot, metadata, signal) : { status: start.state === 'locked' ? 'update-in-progress' : 'unknown' };
251
+ signal?.throwIfAborted();
252
+ let available;
253
+ try {
254
+ const cli = await fetchJson('vini-ds', 'latest', signal), distribution = cli.viniDistribution;
255
+ signal?.throwIfAborted();
256
+ if (cli.name !== 'vini-ds' || !exactVersion.test(cli.version ?? '') || !validIntegrity(cli.dist?.integrity) || !distribution || distribution.version !== cli.version ||
257
+ !keys.every((key) => packageName.test(distribution[key] ?? ''))) {
258
+ throw new Error('latest CLI does not describe a compatible exact package set');
259
+ }
260
+ // A consistent installation and receipt identify the project even when
261
+ // this server's context is stale. Otherwise use only this server's context
262
+ // as the family reference; never treat a broken receipt as authoritative.
263
+ const reference = installed.matchesReceipt ? installed.receipt : contextDistribution(metadata);
264
+ const familyTransition = targetFamily(reference, distribution);
265
+ const manifests = Object.fromEntries(await Promise.all(keys.map(async (key) => [key, await fetchJson(distribution[key], distribution.version, signal)])));
266
+ signal?.throwIfAborted();
267
+ const dsFamily = keys.every(key => distribution[key] === `@vini-ds/${key}`);
268
+ if (!dsFamily && keys.some(key => distribution[key] === `@vini-ds/${key}`)) throw new Error('mixed VINi package families');
269
+ for (const key of keys) {
270
+ const manifest = manifests[key];
271
+ if (manifest.name !== distribution[key] || manifest.version !== distribution.version || !validIntegrity(manifest.dist?.integrity)) {
272
+ throw new Error(`registry metadata for ${key} does not match the selected release`);
273
+ }
274
+ if (dsFamily && ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].some(section =>
275
+ Object.values(manifest[section] ?? {}).some(value => typeof value === 'string' && value.trim().startsWith('npm:')))) {
276
+ throw new Error('native VINi DS package metadata contains an npm alias');
277
+ }
278
+ }
279
+ if (!isDeepStrictEqual(cli.viniRelease ?? null, manifests.agent.viniRelease ?? null)) {
280
+ throw new Error('agent and CLI release metadata differ');
281
+ }
282
+ if (cli.viniRelease !== undefined && !validRelease(cli.viniRelease)) throw new Error('invalid release metadata');
283
+ const tokenImport = dsFamily ? '@vini-ds/tokens' : '@vini/tokens';
284
+ if (dsFamily && ['dependencies', 'peerDependencies', 'optionalDependencies'].some(section => Object.hasOwn(manifests.ui[section] ?? {}, '@vini/tokens'))) {
285
+ throw new Error('UI package does not select the matching token package');
286
+ }
287
+ const tokenDependency = manifests.ui.dependencies?.[tokenImport];
288
+ const tokenPeer = manifests.ui.peerDependencies?.[tokenImport];
289
+ const tokenOptional = manifests.ui.optionalDependencies?.[tokenImport];
290
+ const nativeTokens = distribution.tokens === tokenImport;
291
+ if (tokenOptional !== undefined || manifests.ui.peerDependenciesMeta?.[tokenImport]?.optional === true || (nativeTokens
292
+ ? tokenPeer !== distribution.version || (tokenDependency !== undefined && tokenDependency !== distribution.version)
293
+ : tokenDependency !== `npm:${distribution.tokens}@${distribution.version}` || (tokenPeer !== undefined && tokenPeer !== distribution.version))) {
294
+ throw new Error('UI package does not select the matching token package');
295
+ }
296
+ const fromVersion = installed.matchesReceipt ? installed.receipt.version : null;
297
+ const changes = cli.viniRelease?.changes;
298
+ const comparison = fromVersion === null ? null : compareVersions(fromVersion, distribution.version);
299
+ available = { status: 'verified-metadata', registry, version: distribution.version, packages: distribution, cliIntegrity: cli.dist.integrity,
300
+ integrity: Object.fromEntries(keys.map((key) => [key, manifests[key].dist.integrity])),
301
+ familyTransition,
302
+ matchesInstalled: installed.matchesReceipt ? comparison === 0 && sameNames(installed.receipt, distribution) : null,
303
+ matchesContext: contextIsConsistent(metadata) ? equalsRelease(contextDistribution(metadata), distribution) : null,
304
+ ...(cli.viniRelease ? { viniRelease: cli.viniRelease } : {}),
305
+ changes: changes?.fromVersion === fromVersion ? changes : { status: 'not-available-for-installed-version' },
306
+ relation: comparison === null ? 'unknown' : comparison === 0 ? 'same' : comparison < 0 ? 'newer' : 'older' };
307
+ } catch (error) { signal?.throwIfAborted(); available = { status: 'unavailable-or-unverified', registry, reason: error.message }; }
308
+ const end = await installationObservation(projectRoot);
309
+ let changed = start.state !== 'stable' || end.state !== 'stable' || start.identity !== end.identity || start.bytes !== end.bytes;
310
+ if (!changed && installed.status !== 'not-configured') {
311
+ const repeated = await installedStatus(projectRoot, metadata, signal);
312
+ signal?.throwIfAborted();
313
+ const final = await installationObservation(projectRoot);
314
+ changed = !isDeepStrictEqual(installed, repeated) || final.state !== 'stable' || start.identity !== final.identity || start.bytes !== final.bytes;
315
+ }
316
+ if (changed) {
317
+ const locked = start.state === 'locked' || end.state === 'locked';
318
+ installed = { status: locked ? 'update-in-progress' : 'unknown', reason: locked ? 'VINi installation is locked; package state is not verified' : 'VINi installation changed or could not be observed consistently' };
319
+ if (available.status === 'verified-metadata') available = { ...available, relation: 'unknown', familyTransition: 'unknown', matchesInstalled: null, changes: { status: 'not-available-for-installed-version' } };
320
+ }
321
+ let legacyGeneration = false;
322
+ if (!changed && start.bytes) {
323
+ try {
324
+ const generation = JSON.parse(Buffer.from(start.bytes, 'base64').toString('utf8')).generation;
325
+ legacyGeneration = typeof generation !== 'string' || generation.length !== 36 || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(generation);
326
+ } catch { legacyGeneration = true; }
327
+ if (legacyGeneration) {
328
+ installed = { ...installed, status: 'unverified', observedMatchesReceipt: installed.matchesReceipt ?? null, observedMatchesContext: installed.matchesContext ?? null, matchesReceipt: null, matchesContext: null, reason: 'Legacy or invalid receipt generation; package observations cannot establish a stable installation' };
329
+ if (available.status === 'verified-metadata') available = { ...available, relation: 'unknown', familyTransition: 'unknown', matchesInstalled: null, changes: { status: 'not-available-for-installed-version' } };
330
+ }
331
+ }
332
+ const installedKnown = installed.packages && keys.every(key => typeof installed.packages[key]?.name === 'string' && typeof installed.packages[key]?.version === 'string');
333
+ const selectedTarget = selected ? { status: 'provided', ...selected,
334
+ matchesInstalled: installedKnown && !legacyGeneration ? keys.every(key => installed.packages[key].name === selected[key] && installed.packages[key].version === selected.version) : null,
335
+ matchesReceipt: installed.receipt && !legacyGeneration ? equalsRelease(installed.receipt, selected) : null,
336
+ matchesContext: contextIsConsistent(metadata) ? equalsRelease(contextDistribution(metadata), selected) : null,
337
+ matchesLatest: available.status === 'verified-metadata' ? equalsRelease(available.packages, selected) : null,
338
+ verification: 'caller-supplied-not-independently-verified' } : { status: 'not-provided' };
339
+ const nextStep = installed.status === 'update-in-progress' ? 'Wait if the VINi operation is still running. If it has stopped or its state is unknown, inspect the lock and recovery information before retrying; do not remove an ambiguous lock automatically.' :
340
+ changed ? 'The VINi installation changed or could not be read consistently. Repeat this read after the operation finishes; inspect recovery if the lock remains.' :
341
+ legacyGeneration ? 'This receipt predates installation generations or has an invalid generation. Review the actual packages and the selected update plan; do not reinstall the same release just to clear this status. Verify the connection in the client.' :
342
+ installed.mismatchKind === 'mcp-context' ?
343
+ 'Installed packages match the receipt, but this MCP context does not match them. Reconnect the project VINi MCP once in this client. If reconnect is unavailable or was already attempted and the context remains stale, fully quit and reopen this specific client. Then read vini://system/current and the affected component contract and run check_updates again through the same client. Do not repair packages based on the old context alone.' :
344
+ installed.mismatchKind === 'context-unverified' ?
345
+ 'Installed packages match the receipt, but this MCP context metadata is incomplete or inconsistent. Reconnect the project VINi MCP once in this client. If reconnect is unavailable or was already attempted and the context remains unverified, fully quit and reopen this specific client. Then read vini://system/current and the affected component contract and run check_updates again through the same client. Do not repair packages based on this context alone.' :
346
+ installed.status === 'mismatch' ? 'Inspect the installed package names, versions and receipt, declarations, launcher and agent context before changing the setup; the mismatch alone does not establish which is wrong.' :
347
+ selected && installed.status === 'matched' && selectedTarget.matchesInstalled && selectedTarget.matchesContext ?
348
+ 'Installed package manifests and this MCP context match the caller-selected target. Verify vini://system/current, the affected component contract and check_updates through the same client; a standalone STDIO check does not establish client verification. Registry latest is a separate result, and an unavailable registry does not mean there is no update.' :
349
+ selected && installed.status === 'matched' && !selectedTarget.matchesInstalled ?
350
+ 'The caller-selected target differs from the installed package set. Verify the exact target and review the applicable update plan before any change; registry latest is a separate result.' :
351
+ available.status !== 'verified-metadata' ? 'Registry metadata could not be verified; retry later. This does not mean there is no update.' :
352
+ installed.status !== 'matched' ? 'Check the project npm setup before selecting an update.' :
353
+ available.relation === 'same' ? 'The installed package set matches this CLI release.' :
354
+ available.relation === 'older' ? 'The installed package set is newer than the latest CLI release; no downgrade is proposed.' :
355
+ available.familyTransition === 'manual-import-migration' ? `Review npx vini-ds@${available.version} update --plan and migrate the project imports and configuration before explicitly updating; then reconnect the project MCP in the current client.` :
356
+ `Review npx vini-ds@${available.version} update --plan, then run the exact update and reconnect the project MCP in the current client.`;
357
+ const status = installed.status === 'update-in-progress' ? 'update-in-progress' : installed.status === 'not-configured' ? 'not-installed' : installed.status === 'mismatch' ? 'mismatch' :
358
+ installed.status !== 'matched' || available.status !== 'verified-metadata' ? 'unknown' : available.relation === 'same' ? 'current' : available.relation === 'older' ? 'ahead-of-latest' : 'update-available';
359
+ return { status, statusScope: 'package-context-and-registry-latest', installed, available, target: selectedTarget, nextStep, readOnly: true, installationChanged: false,
360
+ limitations: ['installation observations are not a transactional snapshot and cannot rule out concurrent external changes', 'npm metadata discovery does not verify tarball bytes or product behavior', 'client-session verification requires current, the affected component contract, and check_updates in that same client; standalone STDIO does not verify it'] };
361
+ }
package/version.mjs ADDED
@@ -0,0 +1,34 @@
1
+ // Exact versions supported by the public VINi release builders: lowercase
2
+ // prerelease identifiers, no build metadata, with bounded input size.
3
+ const maxVersionLength = 100;
4
+ const pattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([a-z0-9]+(?:\.[a-z0-9]+)*))?$/u;
5
+
6
+ function parse(version) {
7
+ if (typeof version !== 'string' || version.length > maxVersionLength) throw new Error('invalid exact version');
8
+ const match = pattern.exec(version);
9
+ if (!match || match[0] !== version) throw new Error('invalid exact version');
10
+ const prerelease = match[4]?.split('.') ?? null;
11
+ if (prerelease?.some(part => /^\d+$/u.test(part) && part.length > 1 && part.startsWith('0'))) throw new Error('invalid exact version');
12
+ return { core: match.slice(1, 4).map(BigInt), prerelease };
13
+ }
14
+
15
+ export function isExactVersion(version) {
16
+ try { parse(version); return true; } catch { return false; }
17
+ }
18
+
19
+ // Numeric fields use arbitrary precision, not JS Number. Results are -1/0/1.
20
+ export function compareVersions(left, right) {
21
+ const x = parse(left), y = parse(right);
22
+ for (let i = 0; i < 3; i++) if (x.core[i] !== y.core[i]) return x.core[i] < y.core[i] ? -1 : 1;
23
+ if (!x.prerelease || !y.prerelease) return x.prerelease === y.prerelease ? 0 : x.prerelease ? -1 : 1;
24
+ for (let i = 0; i < Math.max(x.prerelease.length, y.prerelease.length); i++) {
25
+ const a = x.prerelease[i], b = y.prerelease[i];
26
+ if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1;
27
+ if (a === b) continue;
28
+ const aNumeric = /^\d+$/u.test(a), bNumeric = /^\d+$/u.test(b);
29
+ if (aNumeric && bNumeric) return BigInt(a) < BigInt(b) ? -1 : 1;
30
+ if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
31
+ return a < b ? -1 : 1;
32
+ }
33
+ return 0;
34
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.