vini-ds 0.1.0-alpha.1 → 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/README.md +9 -3
- package/cli.mjs +315 -76
- package/package.json +6 -28
- package/version.mjs +34 -0
package/README.md
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
# VINi CLI
|
|
2
2
|
|
|
3
|
-
Connect with `npx vini-ds init`. This is a public alpha, 0.1.0-alpha.
|
|
3
|
+
Connect with `npx vini-ds init`. This is a public alpha, 0.1.0-alpha.11; it supports the bounded setup described below. For a reproducible installation, use the exact version.
|
|
4
4
|
|
|
5
|
-
Preview: `npx vini-ds@0.1.0-alpha.
|
|
5
|
+
Preview: `npx vini-ds@0.1.0-alpha.11 init --plan`. Connect: `npx vini-ds@0.1.0-alpha.11 init`.
|
|
6
6
|
|
|
7
7
|
Requires an existing React 18/Vite project and Node 20+. Detects npm or pnpm; configures CSS, ThemeBrandProvider and project-local Codex MCP/Skill. Does not change global Codex settings or project trust. This alpha supports the direct createRoot(...).render(JSX) entry form; use --entry for an explicit supported entry. New desktop Codex session discovery is a separate check.
|
|
8
8
|
|
|
9
|
-
Check an existing project with `npx vini-ds@latest status` (or `status --json`). A registry error means the available version is unknown. Review the suggested exact version with `npx vini-ds@0.1.0-alpha.
|
|
9
|
+
Check an existing project with `npx vini-ds@latest status` (or `status --json`). A registry error means the available version is unknown. A package status of current does not verify the open application page or the MCP connection in the current client. Review the suggested exact version with `npx vini-ds@0.1.0-alpha.11 update --plan`. For the name migration, complete the manual review below and use --imports-migrated; other updates use the same command without --plan. Identify the dev or preview server serving the original application URL. If it still serves old assets, update or restart only that server when its ownership and authorization are clear; otherwise ask its owner. Reload the same URL and exercise the affected component; never terminate an unidentified process. In the current project and client, call the connection's `refresh_connection` with the exact selected target when available. For a legacy connection or incompatible interface reconnect the project MCP once; restart the client only if reconnect is unavailable or already failed. In the same project and client read `vini://system/current`, the affected component contract, and `check_updates`; compare their versions with the target, installed packages and receipt. If the context is stale, follow the refresh or reconnect steps and repeat the checks instead of reinstalling packages just to refresh it. A separate STDIO process does not verify the current client. Treat package installation, the application page, and the current MCP client as separate results; if a check cannot be performed, report it as not verified. Update creates a recovery backup; if installation fails, inspect the reported recovery path before retrying. Previously installed private-GitHub Kits need an explicit migration and are not overwritten.
|
|
10
|
+
|
|
11
|
+
## Migrating existing projects to @vini-ds
|
|
12
|
+
|
|
13
|
+
Confirm the exact new CLI and all three packages are actually published before migrating. For a CLI-managed installation, run `npx vini-ds@0.1.0-alpha.11 update --plan` and review the existing receipt and planned dependency changes. Save the project state and manually review and replace every old `@vini/*` or `@timelex/vini-*` import, CSS path, configuration and other reference with the appropriate `@vini-ds/*` name. The CLI does not rewrite arbitrary project sources. Once that review is complete, run `npx vini-ds@0.1.0-alpha.11 update --imports-migrated`; the flag records your review, not proof of it. The CLI validates the entry, avoids an extra provider and replaces the managed dependencies without aliases. Check the build, lockfile and affected application scenario, then reconnect and verify the actual MCP client.
|
|
14
|
+
|
|
15
|
+
Older CLI or MCP instances may report the changed release as unknown after a future latest change; unknown is not proof that no update exists. Use the exact new CLI and reconnect the existing client. Direct unmanaged dependencies require a separate reviewed manual migration: remove old declarations after reviewing the project, then inspect `init --plan` before installing. No automatic edits to arbitrary project files are performed.
|
package/cli.mjs
CHANGED
|
@@ -1,20 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { promises as fs } from 'node:fs';
|
|
2
|
+
import { promises as fs, constants as fsConstants } from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { createHash, randomUUID } from 'node:crypto';
|
|
5
|
-
import { createRequire } from 'node:module';
|
|
6
5
|
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
8
|
-
import { spawn } from 'node:child_process';
|
|
6
|
+
import { isDeepStrictEqual, promisify } from 'node:util';
|
|
7
|
+
import { execFile, spawn } from 'node:child_process';
|
|
9
8
|
import ts from 'typescript';
|
|
9
|
+
import { compareVersions, isExactVersion } from './version.mjs';
|
|
10
10
|
|
|
11
11
|
const self=fileURLToPath(import.meta.url);
|
|
12
|
+
const execFileAsync=promisify(execFile);
|
|
12
13
|
const digest=value=>createHash('sha256').update(value).digest('hex');
|
|
13
14
|
const fail=message=>{throw new Error(`VINi: ${message}`);};
|
|
14
15
|
const exists=async file=>fs.lstat(file).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
15
|
-
const
|
|
16
|
+
const legacyPackages={ui:'@timelex/vini-ui',tokens:'@timelex/vini-tokens',agent:'@timelex/vini-agent'};
|
|
17
|
+
const nativeDsPackages={ui:'@vini-ds/ui',tokens:'@vini-ds/tokens',agent:'@vini-ds/agent'};
|
|
18
|
+
const packageKeys=['ui','tokens','agent'];
|
|
19
|
+
const isNativeDs=distribution=>!!distribution&&packageKeys.every(key=>distribution[key]===nativeDsPackages[key]);
|
|
20
|
+
const localNames=distribution=>Object.fromEntries(packageKeys.map(key=>[key,isNativeDs(distribution)?nativeDsPackages[key]:`@vini/${key}`]));
|
|
21
|
+
const packageSpec=(distribution,key)=>distribution[key]===localNames(distribution)[key]?distribution.version:`npm:${distribution[key]}@${distribution.version}`;
|
|
22
|
+
const pageCheck='Identify the dev or preview server serving the original application URL. If it still serves old assets, update or restart only that server when its ownership and authorization are clear; otherwise ask its owner. Reload the same URL and exercise the affected component. Do not terminate an unidentified process.';
|
|
23
|
+
const clientCheck='In the current project and client, use this connection’s refresh_connection with the exact selected target when available; then read vini://system/current, the affected component contract and check_updates through that connection and compare them with the target and installed packages. For a legacy connection or incompatible interface, reconnect the project MCP once; restart the client only if reconnect is unavailable or already failed. Do not reinstall packages only to refresh the connection. A separate STDIO process does not verify the current client; report unavailable checks as not verified.';
|
|
24
|
+
const generationPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
25
|
+
const isGeneration=value=>typeof value==='string'&&value.length===36&&generationPattern.test(value);
|
|
26
|
+
function validateNativeManifest(info,key,distribution){
|
|
27
|
+
if(!isNativeDs(distribution))return;
|
|
28
|
+
if(['dependencies','devDependencies','peerDependencies','optionalDependencies'].some(section=>Object.values(info[section]??{}).some(value=>typeof value==='string'&&/^npm:/u.test(value.trim()))))throw new Error(`${key} native package metadata contains an npm alias`);
|
|
29
|
+
if(key==='ui'){
|
|
30
|
+
const name=distribution.tokens,dep=info.dependencies?.[name],peer=info.peerDependencies?.[name];
|
|
31
|
+
if(['dependencies','devDependencies','peerDependencies','optionalDependencies','peerDependenciesMeta'].some(section=>Object.hasOwn(info[section]??{},'@vini/tokens'))||peer!==distribution.version||(dep!==undefined&&dep!==distribution.version)||Object.hasOwn(info.optionalDependencies??{},name)||info.peerDependenciesMeta?.[name]?.optional===true)throw new Error('native UI token dependency does not match the release');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
16
34
|
const pointer='<!-- BEGIN:vini-npm -->\nFor VINi interface work, use `.agents/skills/vini-ds/SKILL.md` and the project-local `vini-ds` MCP server.\n<!-- END:vini-npm -->';
|
|
17
|
-
const usage='vini init|update [--plan] | status [--json] [--cwd PROJECT] [--app-root APP] [--entry src/main.tsx] [--package-manager npm|pnpm] [--registry HTTPS_URL]';
|
|
35
|
+
const usage='vini init|update [--plan] [--imports-migrated] | status [--json] [--cwd PROJECT] [--app-root APP] [--entry src/main.tsx] [--package-manager npm|pnpm] [--registry HTTPS_URL]';
|
|
18
36
|
|
|
19
37
|
export function parseArgs(args) {
|
|
20
38
|
if(args.length===1&&['--help','-h'].includes(args[0]))return {help:true};
|
|
@@ -24,18 +42,31 @@ export function parseArgs(args) {
|
|
|
24
42
|
for(let i=1;i<args.length;i++) {
|
|
25
43
|
if(args[i]==='--plan'){if(options.plan)fail('duplicate --plan');options.plan=true;continue;}
|
|
26
44
|
if(args[i]==='--json'){if(options.json)fail('duplicate --json');options.json=true;continue;}
|
|
45
|
+
if(args[i]==='--imports-migrated'){if(options.importsMigrated)fail('duplicate --imports-migrated');options.importsMigrated=true;continue;}
|
|
27
46
|
const key=names[args[i]];if(!key||options[key]||!args[i+1]||args[i+1].startsWith('--'))fail(usage);options[key]=args[++i];
|
|
28
47
|
}
|
|
29
48
|
if(options.packageManager&&!['npm','pnpm'].includes(options.packageManager))fail('only npm and pnpm are supported');
|
|
30
49
|
if(options.json&&options.command!=='status')fail('--json is supported by status');
|
|
50
|
+
if(options.importsMigrated&&options.command!=='update')fail('--imports-migrated is supported by update');
|
|
31
51
|
if(options.command==='status'&&(options.plan||options.entry||options.packageManager))fail(usage);
|
|
32
52
|
if(options.registry){const url=new URL(options.registry);if(url.username||url.password||url.search||url.hash||(url.protocol!=='https:'&&!(url.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(url.hostname))))fail('registry must use HTTPS (HTTP localhost is allowed for testing)');}
|
|
33
53
|
return options;
|
|
34
54
|
}
|
|
35
55
|
async function fileBytes(file,optional=false) {
|
|
36
|
-
const
|
|
37
|
-
if(
|
|
38
|
-
|
|
56
|
+
const limit=4*1024*1024;
|
|
57
|
+
if(typeof fsConstants.O_NOFOLLOW!=='number'||typeof fsConstants.O_NONBLOCK!=='number')fail('safe regular-file reads are not supported on this platform');
|
|
58
|
+
let handle;
|
|
59
|
+
try{handle=await fs.open(file,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK);}
|
|
60
|
+
catch(error){if(error.code==='ENOENT'){if(optional)return null;fail(`missing ${file}`);}if(['ELOOP','EMLINK'].includes(error.code))fail(`expected bounded regular file: ${file}`);throw error;}
|
|
61
|
+
try{
|
|
62
|
+
const before=await handle.stat({bigint:true});
|
|
63
|
+
if(!before.isFile()||before.size>BigInt(limit))fail(`expected bounded regular file: ${file}`);
|
|
64
|
+
const chunks=[];let total=0;
|
|
65
|
+
while(true){const buffer=Buffer.allocUnsafe(Math.min(65536,limit+1-total));const {bytesRead}=await handle.read(buffer,0,buffer.length,null);if(!bytesRead)break;total+=bytesRead;if(total>limit)fail(`expected bounded regular file: ${file}`);chunks.push(buffer.subarray(0,bytesRead));}
|
|
66
|
+
const after=await handle.stat({bigint:true}),atPath=await fs.lstat(file,{bigint:true}).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
67
|
+
if(!atPath||!atPath.isFile()||atPath.isSymbolicLink()||before.dev!==atPath.dev||before.ino!==atPath.ino||after.size!==atPath.size||after.mtimeNs!==atPath.mtimeNs||after.ctimeNs!==atPath.ctimeNs||before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||before.mtimeNs!==after.mtimeNs||before.ctimeNs!==after.ctimeNs||BigInt(total)!==after.size)fail(`file changed during read: ${file}`);
|
|
68
|
+
return Buffer.concat(chunks,total);
|
|
69
|
+
}finally{await handle.close();}
|
|
39
70
|
}
|
|
40
71
|
async function safeParents(root,file) {
|
|
41
72
|
const rel=path.relative(root,file);if(rel.startsWith('..'+path.sep)||path.isAbsolute(rel)||rel==='..')fail('file escapes project');
|
|
@@ -45,26 +76,34 @@ async function safeParents(root,file) {
|
|
|
45
76
|
function text(bytes,label) {const value=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);if(value.charCodeAt(0)===0xfeff)fail(`${label}: BOM requires manual review`);return value;}
|
|
46
77
|
function json(bytes,label){try{return JSON.parse(text(bytes,label));}catch{fail(`invalid JSON: ${label}`);}}
|
|
47
78
|
function distributionCheck(value) {
|
|
48
|
-
if(!value
|
|
49
|
-
for(const key of ['ui','tokens','agent'])
|
|
79
|
+
if(!value||!isExactVersion(value.version))fail('CLI distribution has no exact version');
|
|
80
|
+
for(const key of ['ui','tokens','agent']){const name=value[key],match=typeof name==='string'&&name.length<=214?/^@[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.exec(name):null;if(!match||match[0]!==name)fail(`invalid distribution ${key}`);}
|
|
50
81
|
return value;
|
|
51
82
|
}
|
|
83
|
+
function familyTransition(from,to) {
|
|
84
|
+
const keys=['ui','tokens','agent'];
|
|
85
|
+
if(keys.every(key=>from[key]===to[key]))return 'same';
|
|
86
|
+
if(keys.every(key=>from[key]===legacyPackages[key]&&to[key]===`@vini/${key}`)&&compareVersions(to.version,from.version)>0)return 'legacy-to-native';
|
|
87
|
+
if(isNativeDs(to)&&(keys.every(key=>from[key]===legacyPackages[key])||keys.every(key=>from[key]===`@vini/${key}`))&&compareVersions(to.version,from.version)>0)return 'manual-import-migration';
|
|
88
|
+
return 'unsupported';
|
|
89
|
+
}
|
|
52
90
|
export function transformEntry(source,file='main.tsx',distribution) {
|
|
53
91
|
if(source.startsWith('\uFEFF'))fail('entry has a BOM; review it manually');
|
|
54
92
|
const ast=ts.createSourceFile(file,source,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
|
|
55
93
|
if(ast.parseDiagnostics.length)fail('entry has syntax errors');
|
|
94
|
+
const local=localNames(distribution),css=[`${local.tokens}/fonts.css`,`${local.tokens}/themes.css`,`${local.tokens}/typography.css`,`${local.ui}/styles.css`];
|
|
56
95
|
const rootNames=new Set(),rootNamespaces=new Set(),providers=new Set(),imports=new Set();
|
|
57
96
|
for(const statement of ast.statements)if(ts.isImportDeclaration(statement)&&ts.isStringLiteral(statement.moduleSpecifier)) {
|
|
58
97
|
const module=statement.moduleSpecifier.text;imports.add(module);
|
|
59
|
-
if(distribution)for(const key of
|
|
98
|
+
if(distribution)for(const key of packageKeys)for(const published of new Set([distribution[key],legacyPackages[key],`@vini/${key}`,nativeDsPackages[key]])){if(published!==local[key]&&(module===published||module.startsWith(published+'/')))fail(`direct ${published} import requires an explicit manual-to-CLI migration; use one package identity`);}
|
|
60
99
|
const clause=statement.importClause,bindings=clause?.namedBindings;
|
|
61
100
|
if(module==='react-dom/client') {
|
|
62
101
|
if(clause?.name)rootNamespaces.add(clause.name.text);
|
|
63
102
|
if(bindings&&ts.isNamespaceImport(bindings))rootNamespaces.add(bindings.name.text);
|
|
64
103
|
if(bindings&&ts.isNamedImports(bindings))for(const item of bindings.elements)if((item.propertyName?.text??item.name.text)==='createRoot')rootNames.add(item.name.text);
|
|
65
104
|
}
|
|
66
|
-
if(module===
|
|
67
|
-
if(module===
|
|
105
|
+
if(module===local.ui&&bindings&&ts.isNamedImports(bindings))for(const item of bindings.elements)if((item.propertyName?.text??item.name.text)==='ThemeBrandProvider')providers.add(item.name.text);
|
|
106
|
+
if(module===local.ui&&bindings&&ts.isNamespaceImport(bindings))providers.add(`${bindings.name.text}.ThemeBrandProvider`);
|
|
68
107
|
}
|
|
69
108
|
const renders=[];
|
|
70
109
|
const isCreate=expression=>ts.isCallExpression(expression)&&(ts.isIdentifier(expression.expression)?rootNames.has(expression.expression.text):ts.isPropertyAccessExpression(expression.expression)&&ts.isIdentifier(expression.expression.expression)&&rootNamespaces.has(expression.expression.expression.text)&&expression.expression.name.text==='createRoot');
|
|
@@ -76,7 +115,7 @@ export function transformEntry(source,file='main.tsx',distribution) {
|
|
|
76
115
|
const found=[];function findProvider(node){if(ts.isJsxElement(node)&&providers.has(node.openingElement.tagName.getText(ast)))found.push(node);ts.forEachChild(node,findProvider);}findProvider(jsx);
|
|
77
116
|
let result=source;const prepend=css.filter(item=>!imports.has(item)).map(item=>`import ${JSON.stringify(item)};`);
|
|
78
117
|
if(found.length>1)fail('multiple ThemeBrandProvider scopes require manual setup');
|
|
79
|
-
if(!found.length){let alias='ViniThemeBrandProvider';while(new RegExp(`\\b${alias}\\b`).test(source))alias+='Root';prepend.push(`import { ThemeBrandProvider as ${alias} } from "
|
|
118
|
+
if(!found.length){let alias='ViniThemeBrandProvider';while(new RegExp(`\\b${alias}\\b`).test(source))alias+='Root';prepend.push(`import { ThemeBrandProvider as ${alias} } from "${local.ui}";`);const wrapped=`<${alias} theme="light" brand="vini" colorway="blue" typographyScope="desktop">{${argument.getText(ast)}}</${alias}>`;result=source.slice(0,argument.getStart(ast))+wrapped+source.slice(argument.end);}
|
|
80
119
|
else if(found[0]!==jsx){
|
|
81
120
|
// A provider directly inside StrictMode/Fragment still covers the whole app.
|
|
82
121
|
const outer=ts.isJsxElement(jsx)?jsx.children:ts.isJsxFragment(jsx)?jsx.children:[];
|
|
@@ -101,21 +140,41 @@ function agentsMerge(source) {
|
|
|
101
140
|
if(source.includes('<!-- BEGIN:vini-npm -->')||source.includes('<!-- END:vini-npm -->')){if(source.split('<!-- BEGIN:vini-npm -->').length!==2||source.split('<!-- END:vini-npm -->').length!==2||!source.includes(pointer))fail('modified VINi npm instructions need manual merge');return source;}
|
|
102
141
|
return source+(source&&!source.endsWith('\n')?'\n':'')+(source?'\n':'')+pointer+'\n';
|
|
103
142
|
}
|
|
104
|
-
export async function run(executable,args,{cwd,timeout=600000,env=process.env}={}) {
|
|
143
|
+
export async function run(executable,args,{cwd,timeout=600000,env=process.env,stdoutOnly=false}={}) {
|
|
105
144
|
return new Promise((resolve,reject)=>{
|
|
106
|
-
const child=spawn(executable,args,{cwd,env,shell:false,stdio:['ignore','pipe','pipe'],detached:process.platform!=='win32'});let output='',done=false,timed=false,killTimer;
|
|
107
|
-
const finish=error=>{if(done)return;done=true;clearTimeout(timer);clearTimeout(killTimer);error?reject(error):resolve(output);};
|
|
145
|
+
const child=spawn(executable,args,{cwd,env,shell:false,stdio:['ignore','pipe','pipe'],detached:process.platform!=='win32'});let output='',stdout='',done=false,timed=false,killTimer;
|
|
146
|
+
const finish=error=>{if(done)return;done=true;clearTimeout(timer);clearTimeout(killTimer);error?reject(error):resolve(stdoutOnly?stdout:output);};
|
|
108
147
|
const timer=setTimeout(()=>{timed=true;try{if(process.platform!=='win32')process.kill(-child.pid,'SIGTERM');else child.kill('SIGTERM');}catch{}killTimer=setTimeout(()=>{try{if(process.platform!=='win32')process.kill(-child.pid,'SIGKILL');else child.kill('SIGKILL');}catch{}const error=new Error(`${executable} timed out; preserve recovery before retrying`);error.uncertainChildren=true;finish(error);},1000);},timeout);
|
|
109
|
-
|
|
148
|
+
child.stdout.on('data',buf=>{const value=buf.toString();stdout=(stdout+value).slice(-16000);output=(output+value).slice(-16000);});
|
|
149
|
+
child.stderr.on('data',buf=>{output=(output+buf.toString()).slice(-16000);});
|
|
110
150
|
child.on('error',error=>finish(error));child.on('close',code=>{if(timed)return;finish(code===0?null:new Error(`${executable} exited ${code}:\n${output}`));});
|
|
111
151
|
});
|
|
112
152
|
}
|
|
113
|
-
async function
|
|
114
|
-
const
|
|
153
|
+
async function projectModuleEntry(app,entry) {
|
|
154
|
+
const modules=path.join(app,'node_modules'),stat=await exists(modules);
|
|
155
|
+
if(!stat||stat.isSymbolicLink()||!stat.isDirectory())fail('node_modules must be a real project directory');
|
|
156
|
+
const root=await fs.realpath(modules),resolved=await fs.realpath(entry);
|
|
157
|
+
if(!resolved.startsWith(root+path.sep))fail('installed package resolves outside project node_modules');
|
|
158
|
+
return resolved;
|
|
159
|
+
}
|
|
160
|
+
async function manifestForEntry(resolved,name,app) {
|
|
161
|
+
resolved=await projectModuleEntry(app,resolved);let dir=path.dirname(resolved);
|
|
115
162
|
while(true){const file=path.join(dir,'package.json');if(await exists(file)){const value=json(await fileBytes(file),file);if(value.name&&value.version)return {root:dir,manifest:value,entry:resolved};}const parent=path.dirname(dir);if(parent===dir)fail(`cannot find package metadata: ${name}`);dir=parent;}
|
|
116
163
|
}
|
|
164
|
+
// Node caches resolved pnpm symlink targets in-process. A completed install may
|
|
165
|
+
// replace those symlinks, so inspect the new installation in a fresh process.
|
|
166
|
+
async function freshResolveMaybe(manifest,names,cwd) {
|
|
167
|
+
const script='const {createRequire}=require("node:module");const req=createRequire(process.argv[1]);process.stdout.write(JSON.stringify(JSON.parse(process.argv[2]).map(name=>{try{return {path:req.resolve(name)}}catch(error){return {error:error.code||"unknown"}}})));';
|
|
168
|
+
let output;try{({stdout:output}=await execFileAsync(process.execPath,['-e',script,manifest,JSON.stringify(names)],{cwd,timeout:10000,maxBuffer:1024*1024,encoding:'utf8'}));}catch(error){fail(`fresh package resolution failed (${error.code??'unknown'})`);}
|
|
169
|
+
const entries=JSON.parse(output);if(!Array.isArray(entries)||entries.length!==names.length||!entries.every(value=>value&&((typeof value.path==='string'&&path.isAbsolute(value.path)&&value.error===undefined)||(typeof value.error==='string'&&value.path===undefined))))fail('fresh package resolution returned invalid paths');return entries;
|
|
170
|
+
}
|
|
171
|
+
async function freshResolve(manifest,names,cwd) {
|
|
172
|
+
const entries=await freshResolveMaybe(manifest,names,cwd);
|
|
173
|
+
for(let i=0;i<names.length;i++)if(entries[i].error)fail(`cannot resolve ${names[i]} after install (${entries[i].error})`);
|
|
174
|
+
return entries.map(entry=>entry.path);
|
|
175
|
+
}
|
|
117
176
|
async function verifyAgentContext(runner,entry,distribution,cwd) {
|
|
118
|
-
const result=JSON.parse(await runner(process.execPath,[entry,'--check'],{cwd,timeout:10000}));
|
|
177
|
+
const result=JSON.parse(await runner(process.execPath,[entry,'--check'],{cwd,timeout:10000,stdoutOnly:true}));
|
|
119
178
|
if(result.ok!==true||result.name!==distribution.agent||result.version!==distribution.version)fail('installed agent selfcheck does not match the CLI distribution');
|
|
120
179
|
for(const key of ['ui','tokens','agent'])if(result.packages?.[key]?.name!==distribution[key]||result.packages[key].version!==distribution.version)fail('agent contract and installed npm package pair differ');
|
|
121
180
|
return result;
|
|
@@ -132,23 +191,79 @@ async function readInstallation(root,requestedApp,expected) {
|
|
|
132
191
|
if(raw){receipt=json(raw,receiptPath);if(receipt.installer!=='vini-npm'||!receipt.distribution||typeof receipt.configTable!=='string')fail('unrecognized npm setup receipt');distributionCheck(receipt.distribution);}
|
|
133
192
|
const relative=requestedApp??receipt?.appRoot??'.';const app=await fs.realpath(path.resolve(root,relative));
|
|
134
193
|
if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
|
|
194
|
+
let appRootMatchesReceipt=null;
|
|
195
|
+
if(receipt){
|
|
196
|
+
const recorded=typeof receipt.appRoot==='string'?await fs.realpath(path.resolve(root,receipt.appRoot)).catch(()=>null):null;
|
|
197
|
+
appRootMatchesReceipt=!!recorded&&(recorded===root||recorded.startsWith(root+path.sep))&&recorded===app;
|
|
198
|
+
}
|
|
135
199
|
const manifestPath=path.join(app,'package.json');await safeParents(root,manifestPath);
|
|
136
|
-
const
|
|
200
|
+
const manifestBytes=await fileBytes(manifestPath),manifest=json(manifestBytes,manifestPath);
|
|
137
201
|
const dependencies={...manifest.optionalDependencies,...manifest.devDependencies,...manifest.dependencies};
|
|
138
202
|
const lockfiles=[];for(const name of ['package-lock.json','pnpm-lock.yaml']){const bytes=await fileBytes(path.join(app,name),true);if(bytes)lockfiles.push({name,sha256:`sha256:${digest(bytes)}`});}
|
|
139
203
|
const installed={};let installedAgent;
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
204
|
+
const keys=['ui','tokens','agent'],local=localNames(receipt?.distribution??expected),resolved=await freshResolveMaybe(manifestPath,keys.map(key=>`${local[key]}${key==='agent'?'/mcp':''}`),app);
|
|
205
|
+
for(const [index,key] of keys.entries()) {
|
|
206
|
+
const alias=local[key];let actual=null,error=null,manifestSha256=null;
|
|
207
|
+
try{if(resolved[index].error){const problem=new Error('not resolvable');problem.code=resolved[index].error;throw problem;}const pkg=await manifestForEntry(resolved[index].path,alias,app);validateNativeManifest(pkg.manifest,key,receipt?.distribution??expected);actual={name:pkg.manifest.name,version:pkg.manifest.version};manifestSha256=`sha256:${digest(JSON.stringify(pkg.manifest))}`;if(key==='agent')installedAgent=pkg;}
|
|
143
208
|
catch(problem){if(problem.code==='MODULE_NOT_FOUND'||problem.code==='ERR_PACKAGE_PATH_NOT_EXPORTED')error='not-resolvable';else error='metadata-unavailable';}
|
|
144
|
-
const declared=dependencies[alias]??null,recorded=receipt?(receipt.distribution
|
|
145
|
-
installed[key]={declared,actual,error,matchesLauncher:!!actual&&actual.name===expected[key]&&actual.version===expected.version,matchesReceipt:!!actual&&!!receipt&&actual.name===receipt.distribution[key]&&actual.version===receipt.distribution.version&&declared===recorded};
|
|
209
|
+
const declared=dependencies[alias]??null,recorded=receipt?packageSpec(receipt.distribution,key):null;
|
|
210
|
+
installed[key]={declared,actual,error,manifestSha256,matchesLauncher:!!actual&&actual.name===expected[key]&&actual.version===expected.version,matchesReceipt:!!actual&&!!receipt&&actual.name===receipt.distribution[key]&&actual.version===receipt.distribution.version&&declared===recorded};
|
|
146
211
|
}
|
|
147
212
|
let launcher='not-installed';
|
|
148
213
|
if(receipt){const file=path.join(root,'.vini-ds/npm-launcher.mjs');await safeParents(root,file);const bytes=await fileBytes(file,true);launcher=bytes&&digest(bytes)===receipt.launcherSha256?'matches-receipt':'missing-or-modified';}
|
|
149
214
|
let agentContext=null;
|
|
150
|
-
if(installedAgent){const file=path.join(installedAgent.root,'context/current.json');const bytes=await fileBytes(file,true);if(bytes){const current=json(bytes,file);agentContext={version:current.version??null,baseline:current.baseline??null,release:current.viniRelease??null};}}
|
|
151
|
-
return {projectRoot:root,appRoot:app,receipt:receipt?{distribution:receipt.distribution,appRoot:receipt.appRoot}:null,launcher:{status:launcher,expected:receipt?.distribution??null},installed,lockfiles,agentContext};
|
|
215
|
+
if(installedAgent)try{const file=path.join(installedAgent.root,'context/current.json');const bytes=await fileBytes(file,true);if(bytes){const current=json(bytes,file);agentContext={name:current.name??null,version:current.version??null,packages:current.packages??null,sha256:`sha256:${digest(bytes)}`,baseline:current.baseline??null,release:current.viniRelease??null};}}catch{}
|
|
216
|
+
return {projectRoot:root,appRoot:app,appRootMatchesReceipt,receipt:receipt?{distribution:receipt.distribution,appRoot:receipt.appRoot,...(typeof receipt.generation==='string'?{generation:receipt.generation}:{})}:null,launcher:{status:launcher,expected:receipt?.distribution??null},installed,appManifestSha256:`sha256:${digest(manifestBytes)}`,lockfiles,agentContext};
|
|
217
|
+
}
|
|
218
|
+
function contextMatchesReceipt(state) {
|
|
219
|
+
const d=state.receipt?.distribution,c=state.agentContext;
|
|
220
|
+
return !!d&&!!c&&c.name===d.agent&&c.version===d.version&&packageKeys.every(key=>c.packages?.[key]?.name===d[key]&&c.packages[key].version===d.version);
|
|
221
|
+
}
|
|
222
|
+
// Directory changes provide an additional conservative signal if a whole
|
|
223
|
+
// lock lifetime falls between two reads; generation catches successful
|
|
224
|
+
// replacements. External installers and filesystems with coarse timestamp
|
|
225
|
+
// resolution remain outside a claim of transactional filesystem snapshots.
|
|
226
|
+
async function readCheckpoint(root,requestedApp) {
|
|
227
|
+
const lock=path.join(root,'.vini-npm-install.lock');
|
|
228
|
+
if(await exists(lock))return null;
|
|
229
|
+
const before=await fs.stat(root,{bigint:true});
|
|
230
|
+
const receiptPath=path.join(root,'.vini-ds/npm-install.json');await safeParents(root,receiptPath);
|
|
231
|
+
const receipt=await fileBytes(receiptPath,true);
|
|
232
|
+
let generation=null,relative=requestedApp??'.';if(receipt)try{const data=JSON.parse(receipt.toString('utf8'));generation=data.generation??null;relative=requestedApp??(typeof data.appRoot==='string'?data.appRoot:'.');}catch{}
|
|
233
|
+
const app=await fs.realpath(path.resolve(root,relative)).catch(()=>null);
|
|
234
|
+
if(!app||(app!==root&&!app.startsWith(root+path.sep)))return null;
|
|
235
|
+
const appStat=await fs.stat(app,{bigint:true});
|
|
236
|
+
const modules=await fs.lstat(path.join(app,'node_modules'),{bigint:true}).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
237
|
+
const after=await fs.stat(root,{bigint:true});
|
|
238
|
+
const appAfter=await fs.stat(app,{bigint:true});
|
|
239
|
+
const modulesAfter=await fs.lstat(path.join(app,'node_modules'),{bigint:true}).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
240
|
+
const fingerprint=stat=>stat?{dev:stat.dev,ino:stat.ino,mtime:stat.mtimeNs,ctime:stat.ctimeNs,mode:stat.mode}:null;
|
|
241
|
+
const same=(a,b)=>a===null?b===null:b!==null&&a.dev===b.dev&&a.ino===b.ino&&a.mtime===b.mtime&&a.ctime===b.ctime&&a.mode===b.mode;
|
|
242
|
+
if(await exists(lock)||!same(fingerprint(before),fingerprint(after))||!same(fingerprint(appStat),fingerprint(appAfter))||!same(fingerprint(modules),fingerprint(modulesAfter)))return null;
|
|
243
|
+
return {receipt,root:fingerprint(after),app,appStat:fingerprint(appAfter),modules:fingerprint(modulesAfter),generation};
|
|
244
|
+
}
|
|
245
|
+
function checkpointMatches(first,last) {
|
|
246
|
+
const same=(a,b)=>a===null?b===null:b!==null&&a.dev===b.dev&&a.ino===b.ino&&a.mtime===b.mtime&&a.ctime===b.ctime&&a.mode===b.mode;
|
|
247
|
+
return !!first&&!!last&&same(first.root,last.root)&&first.app===last.app&&same(first.appStat,last.appStat)&&same(first.modules,last.modules)&&
|
|
248
|
+
(first.receipt===null?last.receipt===null:last.receipt!==null&&first.receipt.equals(last.receipt));
|
|
249
|
+
}
|
|
250
|
+
function unverifiedStatus(root,target,reason) {
|
|
251
|
+
const installed=Object.fromEntries(packageKeys.map(key=>[key,{declared:null,actual:null,error:'not-verified',matchesLauncher:false,matchesReceipt:false}]));
|
|
252
|
+
const state={projectRoot:root,appRoot:null,appRootMatchesReceipt:null,receipt:null,launcher:{status:'not-verified',expected:null},installed,lockfiles:[],agentContext:null};
|
|
253
|
+
const verification=verificationState(target,state);verification.installation={...verification.installation,status:'not-verified',matchesTarget:null};
|
|
254
|
+
return {status:'unknown',statusScope:'package-installation-and-registry',...state,launcherVersion:target.version,launcherMatchesInstalled:false,available:{status:'not-checked',reason},familyTransition:null,changes:{status:'unknown'},nextStep:reason,verification,mutated:false};
|
|
255
|
+
}
|
|
256
|
+
// These observations are returned with the command, not persisted as a new receipt.
|
|
257
|
+
// A package/launcher check cannot establish what a running application or MCP client sees.
|
|
258
|
+
function verificationState(target,state) {
|
|
259
|
+
const receipt=state.receipt?.distribution??null;
|
|
260
|
+
const matched=!!receipt&&state.appRootMatchesReceipt===true&&state.launcher.status==='matches-receipt'&&contextMatchesReceipt(state)&&packageKeys.every(key=>state.installed[key].matchesReceipt);
|
|
261
|
+
const matchesTarget=matched&&receipt.version===target.version&&packageKeys.every(key=>receipt[key]===target[key]&&state.installed[key].actual?.name===target[key]&&state.installed[key].actual?.version===target.version);
|
|
262
|
+
return {target:{version:target.version,packages:Object.fromEntries(packageKeys.map(key=>[key,target[key]]))},
|
|
263
|
+
installation:{status:!receipt?'not-installed':matched?'matched':'mismatch',matchesTarget,receipt,packages:state.installed},
|
|
264
|
+
applicationPage:{status:'not-verified',nextStep:pageCheck},
|
|
265
|
+
clientMcp:{status:'not-verified',nextStep:clientCheck},
|
|
266
|
+
completion:{status:'not-verified',reason:'Installation, the application page and the current client MCP are separate checks; the CLI cannot verify the running page or client session.'}};
|
|
152
267
|
}
|
|
153
268
|
const validIntegrity=value=>{if(typeof value!=='string'||!/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(value))return false;const encoded=value.slice(7),bytes=Buffer.from(encoded,'base64');return bytes.length===64&&bytes.toString('base64')===encoded;};
|
|
154
269
|
function validRelease(value) {
|
|
@@ -156,12 +271,6 @@ function validRelease(value) {
|
|
|
156
271
|
const web=x=>{if(!safe(x))return false;try{const u=new URL(x);return u.protocol==='https:'&&!u.username&&!u.password&&!u.search&&!u.hash;}catch{return false;}};
|
|
157
272
|
return value===null||!!value&&web(value.atlas?.url)&&/^sha256:[0-9a-f]{64}$/u.test(value.atlas.archiveSha256??'')&&safe(value.atlas.siteRelease)&&/^[0-9a-f]{40}$/u.test(value.atlas.commit??'')&&safe(value.delivery?.id)&&/^sha256:[0-9a-f]{64}$/u.test(value.delivery.manifestSha256??'')&&/^sha256:[0-9a-f]{64}$/u.test(value.delivery.packageManifestSha256??'')&&safe(value.changes?.fromVersion)&&safe(value.changes?.summary)&&Array.isArray(value.changes?.components)&&value.changes.components.length<=500&&value.changes.components.every(x=>safe(x)&&x.length<=100);
|
|
158
273
|
}
|
|
159
|
-
function compareVersions(a,b) {
|
|
160
|
-
const parse=x=>{const m=/^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?$/u.exec(x??'');if(!m)throw new Error('invalid published version');return {core:m.slice(1,4).map(Number),pre:m[4]?.split('.')??null};};
|
|
161
|
-
const x=parse(a),y=parse(b);for(let i=0;i<3;i++)if(x.core[i]!==y.core[i])return Math.sign(x.core[i]-y.core[i]);
|
|
162
|
-
if(!x.pre||!y.pre)return x.pre? -1:y.pre?1:0;
|
|
163
|
-
for(let i=0;i<Math.max(x.pre.length,y.pre.length);i++){const l=x.pre[i],r=y.pre[i];if(l===undefined||r===undefined)return l===undefined?-1:1;if(l===r)continue;const ln=/^\d+$/u.test(l),rn=/^\d+$/u.test(r);if(ln&&rn)return Math.sign(Number(l)-Number(r));if(ln!==rn)return ln?-1:1;return l<r?-1:1;}return 0;
|
|
164
|
-
}
|
|
165
274
|
function registryUrl(raw) {
|
|
166
275
|
const url=new URL(raw);if(url.username||url.password||url.search||url.hash||(url.protocol!=='https:'&&!(url.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(url.hostname))))fail('registry must use HTTPS (HTTP localhost is allowed for testing)');
|
|
167
276
|
if(!url.pathname.endsWith('/'))url.pathname+='/';return url;
|
|
@@ -185,7 +294,15 @@ async function availableRelease(registry,cliName,expected,request=requestMetadat
|
|
|
185
294
|
const entries=await Promise.all(['ui','tokens','agent'].map(async key=>{
|
|
186
295
|
const info=await request(endpoint(distribution[key],distribution.version));
|
|
187
296
|
if(info?.name!==distribution[key]||info.version!==distribution.version||!validIntegrity(info?.dist?.integrity))throw new Error(`${key} exact-version metadata is unavailable or invalid`);
|
|
188
|
-
|
|
297
|
+
validateNativeManifest(info,key,distribution);
|
|
298
|
+
if(key==='ui'){
|
|
299
|
+
const token=localNames(distribution).tokens,native=distribution.tokens===token;
|
|
300
|
+
const dependency=info.dependencies?.[token];
|
|
301
|
+
const peer=info.peerDependencies?.[token];
|
|
302
|
+
const optional=Object.hasOwn(info.optionalDependencies??{},token)||info.peerDependenciesMeta?.[token]?.optional===true;
|
|
303
|
+
if(isNativeDs(distribution)&&['dependencies','peerDependencies','optionalDependencies','peerDependenciesMeta'].some(section=>Object.hasOwn(info[section]??{},'@vini/tokens')))throw new Error('native UI metadata includes old token identity');
|
|
304
|
+
if(optional||(native ? peer!==distribution.version || (dependency!==undefined&&dependency!==distribution.version) : dependency!==`npm:${distribution.tokens}@${distribution.version}` || (peer!==undefined&&peer!==distribution.version)))throw new Error('published UI token dependency does not match the release');
|
|
305
|
+
}
|
|
189
306
|
if(key==='agent'&&!isDeepStrictEqual(info.viniRelease??null,latest.viniRelease??null))throw new Error('CLI and agent release metadata differ');
|
|
190
307
|
return [key,{name:info.name,version:info.version,integrity:info.dist.integrity}];
|
|
191
308
|
}));const packages=Object.fromEntries(entries);
|
|
@@ -195,17 +312,31 @@ async function availableRelease(registry,cliName,expected,request=requestMetadat
|
|
|
195
312
|
export async function status(options={},suppliedDistribution,{request=requestMetadata,cliName,release}={}) {
|
|
196
313
|
const cli=suppliedDistribution?{name:cliName??'vini-ds',viniDistribution:suppliedDistribution,viniRelease:release}:json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package');
|
|
197
314
|
const expected=distributionCheck(cli.viniDistribution),root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
|
|
198
|
-
const
|
|
315
|
+
const lockReason='A VINi setup is active, was interrupted, or the project changed while reading. Wait for the owner or inspect .vini-npm-install.lock and the recorded recovery before retrying; do not remove a lock just because it is old.';
|
|
316
|
+
const checkpoint=await readCheckpoint(root,options.appRoot);
|
|
317
|
+
if(!checkpoint)return unverifiedStatus(root,expected,lockReason);
|
|
318
|
+
let state;
|
|
319
|
+
try{state=await readInstallation(root,options.appRoot,expected);}
|
|
320
|
+
catch(error){if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))return unverifiedStatus(root,expected,lockReason);throw error;}
|
|
199
321
|
const registry=options.registry??process.env.npm_config_registry??'https://registry.npmjs.org/';
|
|
200
322
|
const published=await availableRelease(registry,cli.name,expected,request);
|
|
201
|
-
|
|
323
|
+
if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))return unverifiedStatus(root,expected,lockReason);
|
|
324
|
+
let repeated;try{repeated=await readInstallation(root,options.appRoot,expected);}catch{return unverifiedStatus(root,expected,lockReason);}
|
|
325
|
+
if(!isDeepStrictEqual(state,repeated)||!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))return unverifiedStatus(root,expected,lockReason);
|
|
326
|
+
if(checkpoint.receipt&&!isGeneration(checkpoint.generation)) {
|
|
327
|
+
const result=unverifiedStatus(root,expected,'This legacy receipt has no valid installation generation; installed observations cannot prove a stable snapshot. Review the selected update plan and verify the actual client; do not reinstall only to clear this status.');
|
|
328
|
+
result.available=published;result.installed=state.installed;result.receipt=state.receipt;result.appRoot=state.appRoot;result.appRootMatchesReceipt=state.appRootMatchesReceipt;result.launcher=state.launcher;result.lockfiles=state.lockfiles;result.agentContext=state.agentContext;
|
|
329
|
+
result.verification.installation={...result.verification.installation,receipt:state.receipt?.distribution??null,packages:state.installed};return result;
|
|
330
|
+
}
|
|
331
|
+
const aligned=!!state.receipt&&state.appRootMatchesReceipt&&state.launcher.status==='matches-receipt'&&contextMatchesReceipt(state)&&['ui','tokens','agent'].every(key=>state.installed[key].matchesReceipt);
|
|
202
332
|
const installedVersion=aligned?state.receipt.distribution.version:null;
|
|
203
333
|
const installedToLauncher=aligned&&['ui','tokens','agent'].every(key=>state.installed[key].matchesLauncher);
|
|
204
334
|
const latest=published.status==='available'?published.distribution.version:null;
|
|
335
|
+
const family=aligned&&published.status==='available'?familyTransition(state.receipt.distribution,published.distribution):null;
|
|
205
336
|
const ordering=aligned&&latest?compareVersions(installedVersion,latest):null;
|
|
206
|
-
const relation=!state.receipt?'not-installed':!aligned?'mismatch':published.status!=='available'?'unknown':ordering===0?'current':ordering<0?'update-available':'ahead-of-latest';
|
|
207
|
-
const next=relation==='not-installed'?`npx ${cli.name}@${expected.version} init --plan`:relation==='mismatch'?'Installed packages or launcher differ from the receipt; resolve the mismatch before updating.':relation==='unknown'?'Registry unavailable; retry status before deciding about updates.':relation==='update-available'?`npx ${cli.name}@${latest} update --plan`:relation==='ahead-of-latest'?'Installed release is newer than the registry latest tag; no downgrade is selected.':'Installed package versions match the latest available release.';
|
|
208
|
-
return {status:relation,...state,launcherVersion:expected.version,launcherMatchesInstalled:installedToLauncher,available:published,changes:published.status==='available'?transition(published.release,installedVersion,latest):{status:'unknown'},nextStep:next,mutated:false};
|
|
337
|
+
const relation=!state.receipt?'not-installed':!aligned?'mismatch':published.status!=='available'||family==='unsupported'?'unknown':ordering===0?'current':ordering<0?'update-available':'ahead-of-latest';
|
|
338
|
+
const next=relation==='not-installed'?`npx ${cli.name}@${expected.version} init --plan`:relation==='mismatch'?(state.appRootMatchesReceipt===false?'Selected app root differs from the recorded npm setup; review the receipt before updating.':!contextMatchesReceipt(state)?'The installed agent context is missing or differs from the recorded package set; inspect the agent and receipt before changing the setup.':'Installed packages or launcher differ from the receipt; resolve the mismatch before updating.'):relation==='unknown'?(family==='unsupported'?'Installed and available package families do not have a supported automatic transition; review the distribution before migration.':'Registry unavailable; retry status before deciding about updates.'):relation==='update-available'?`npx ${cli.name}@${latest} update --plan`:relation==='ahead-of-latest'?'Installed release is newer than the registry latest tag; no downgrade is selected.':'Installed package versions match the latest available release.';
|
|
339
|
+
return {status:relation,statusScope:'package-installation-and-registry',...state,launcherVersion:expected.version,launcherMatchesInstalled:installedToLauncher,available:published,familyTransition:family,changes:published.status==='available'&&family!=='unsupported'?transition(published.release,installedVersion,latest):{status:'unknown'},nextStep:next,verification:verificationState(expected,state),mutated:false};
|
|
209
340
|
}
|
|
210
341
|
export function formatStatus(result) {
|
|
211
342
|
const installed=['ui','tokens','agent'].map(key=>{const p=result.installed[key];return `${key}: ${p.actual?`${p.actual.name}@${p.actual.version}`:'not installed'}${p.error?` (${p.error})`:''}`;}).join('\n');
|
|
@@ -213,10 +344,10 @@ export function formatStatus(result) {
|
|
|
213
344
|
const changes=result.changes.status==='available'?`\nChanges: ${result.changes.summary}\nComponents: ${result.changes.components.join(', ')||'none listed'}`:'';
|
|
214
345
|
const release=result.available.release;
|
|
215
346
|
const site=release?`\nAtlas: ${release.atlas.url} (${release.atlas.siteRelease}, commit ${release.atlas.commit})\nAtlas archive: ${release.atlas.archiveSha256}\nDelivery: ${release.delivery.id}; package manifest: ${release.delivery.packageManifestSha256}; gateway manifest: ${release.delivery.manifestSha256}`:'';
|
|
216
|
-
return `VINi status: ${result.status}\n${installed}\nLauncher expects: ${result.launcherVersion}\nReceipt: ${result.receipt?.distribution.version??'not installed'}; launcher: ${result.launcher.status}\nAvailable published release: ${available}${site}${changes}\n${result.nextStep}`;
|
|
347
|
+
return `VINi package status: ${result.status}\nSelected CLI target: ${result.verification.target.version}\n${installed}\nLauncher expects: ${result.launcherVersion}\nReceipt: ${result.receipt?.distribution.version??'not installed'}; launcher: ${result.launcher.status}\nAvailable published release: ${available}${site}${changes}\n${result.nextStep}\nUpdate completion: not verified\nApplication page: not verified\n${result.verification.applicationPage.nextStep}\nCurrent client MCP: not verified\n${result.verification.clientMcp.nextStep}`;
|
|
217
348
|
}
|
|
218
349
|
function launcher(distribution,appRelative) {
|
|
219
|
-
return `// Generated by VINi npm CLI; resolves persistent project packages, never npx cache.\nimport { createRequire } from 'node:module';\nimport { readFileSync, existsSync } from 'node:fs';\nimport { spawn } from 'node:child_process';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst project=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');\nconst req=createRequire(path.join(project
|
|
350
|
+
return `// Generated by VINi npm CLI; resolves persistent project packages, never npx cache.\nimport { createRequire } from 'node:module';\nimport { readFileSync, existsSync, realpathSync } from 'node:fs';\nimport { spawn } from 'node:child_process';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst project=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');\nconst appRelative=${JSON.stringify(appRelative)};\nconst req=createRequire(path.join(project,appRelative,'package.json'));\nconst expected=${JSON.stringify(distribution)};\nconst local=${JSON.stringify(localNames(distribution))};\nlet agentRoot;\nfor(const key of ['tokens','ui','agent']) { const entry=req.resolve(local[key]+(key==='agent'?'/mcp':'')); let dir=path.dirname(entry), meta; while(true){const file=path.join(dir,'package.json');if(existsSync(file)){meta=JSON.parse(readFileSync(file,'utf8'));if(meta.name&&meta.version)break;} const parent=path.dirname(dir);if(parent===dir)throw Error('VINi package metadata missing');dir=parent;} if(meta.name!==expected[key]||meta.version!==expected.version)throw Error('VINi installed package/agent versions differ; inspect the receipt and installed packages');if(key==='agent')agentRoot=realpathSync(dir);}\nlet supervisor;try{supervisor=realpathSync(req.resolve(local.agent+'/supervisor'));}catch{throw Error('Installed VINi agent does not provide a managed connection; review the selected release and reconnect the project MCP');}\nif(!supervisor.startsWith(agentRoot+path.sep))throw Error('VINi supervisor is outside the selected agent package');\nconst child=spawn(process.execPath,[supervisor,'--project-root',project,'--app-root',appRelative],{stdio:'inherit',cwd:project});\nfor(const sig of ['SIGINT','SIGTERM'])process.on(sig,()=>child.kill(sig));\nchild.on('error',error=>{console.error(error.message);process.exitCode=1;});\nchild.on('exit',(code,signal)=>{process.exitCode=code??1;});\n`;
|
|
220
351
|
}
|
|
221
352
|
async function managerFor(root,app,options,manifest) {
|
|
222
353
|
const dirs=[];let dir=app;while(true){dirs.push(dir);if(dir===root)break;dir=path.dirname(dir);}
|
|
@@ -231,33 +362,112 @@ async function managerFor(root,app,options,manifest) {
|
|
|
231
362
|
if(manifest.workspaces)fail('workspace root is not supported by this alpha; choose a standalone Vite app');
|
|
232
363
|
return manager??'npm';
|
|
233
364
|
}
|
|
234
|
-
|
|
365
|
+
// The lock is taken before reading the installation or making any mutation
|
|
366
|
+
// decision. Its metadata is diagnostic only: a PID or timestamp does not prove
|
|
367
|
+
// that a former owner (or its package-manager children) has stopped.
|
|
368
|
+
async function acquireInstallLock(root,command) {
|
|
369
|
+
const directory=path.join(root,'.vini-npm-install.lock'),ownerFile=path.join(directory,'owner.json');
|
|
370
|
+
try{await fs.mkdir(directory,{mode:0o700});}catch(error){if(error.code==='EEXIST')fail('another VINi setup is active or previous recovery needs review; inspect .vini-npm-install.lock and .vini-ds-recovery before retrying');throw error;}
|
|
371
|
+
const identity=await fs.lstat(directory), owner={version:1,nonce:randomUUID(),pid:process.pid,startedAt:new Date().toISOString(),command:command??'init',recovery:null};
|
|
372
|
+
let expected=Buffer.from(JSON.stringify(owner,null,2)+'\n');
|
|
373
|
+
try{await fs.writeFile(ownerFile,expected,{flag:'wx',mode:0o600});}catch(error){await fs.rmdir(directory).catch(()=>{});throw error;}
|
|
374
|
+
async function owns() {
|
|
375
|
+
const current=await fs.lstat(directory).catch(()=>null);
|
|
376
|
+
if(!current||!current.isDirectory()||current.isSymbolicLink()||current.dev!==identity.dev||current.ino!==identity.ino)return false;
|
|
377
|
+
const names=await fs.readdir(directory);
|
|
378
|
+
if(names.length!==1||names[0]!=='owner.json')return false;
|
|
379
|
+
const contents=await fileBytes(ownerFile,true);
|
|
380
|
+
return !!contents&&contents.equals(expected);
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
async recordRecovery(recovery) {
|
|
384
|
+
if(!await owns())fail('VINi setup lock changed; preserve it and inspect recovery before retrying');
|
|
385
|
+
owner.recovery=recovery;const next=Buffer.from(JSON.stringify(owner,null,2)+'\n');
|
|
386
|
+
await fs.writeFile(ownerFile,next,{mode:0o600});expected=next;
|
|
387
|
+
},
|
|
388
|
+
async release() {
|
|
389
|
+
if(!await owns())fail('VINi setup lock changed; preserve it and inspect recovery before retrying');
|
|
390
|
+
await fs.unlink(ownerFile);await fs.rmdir(directory);
|
|
391
|
+
},
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export async function init(options={},suppliedDistribution,dependencies={}) {
|
|
396
|
+
const root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
|
|
397
|
+
if(options.plan){
|
|
398
|
+
const checkpoint=await readCheckpoint(root,options.appRoot),reason='another VINi setup is active or previous recovery needs review; inspect .vini-npm-install.lock before planning';
|
|
399
|
+
if(!checkpoint)fail(reason);
|
|
400
|
+
let plan;try{plan=await initWithLock({...options,cwd:root},suppliedDistribution,dependencies);}catch(error){if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))fail('VINi setup changed while planning; inspect the lock and recovery before retrying');throw error;}
|
|
401
|
+
if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))fail('VINi setup changed while planning; inspect the lock and recovery before retrying');
|
|
402
|
+
if(checkpoint.receipt&&!isGeneration(checkpoint.generation)){
|
|
403
|
+
plan.installedStatus='unverified';plan.changes={status:'not-available'};
|
|
404
|
+
plan.verification.installation={...plan.verification.installation,status:'not-verified',matchesTarget:null};
|
|
405
|
+
plan.snapshotNote='Legacy receipt has no valid generation; observations cannot prove a stable installation snapshot. The actual update rechecks under its lock.';
|
|
406
|
+
}
|
|
407
|
+
return plan;
|
|
408
|
+
}
|
|
409
|
+
const lock=await acquireInstallLock(root,options.command);let retain=false,primary,result;
|
|
410
|
+
try{result=await initWithLock({...options,cwd:root},suppliedDistribution,{...dependencies,recordRecovery:lock.recordRecovery});return result;}
|
|
411
|
+
catch(error){primary=error;retain=error.retainInstallLock===true;throw error;}
|
|
412
|
+
finally{if(!retain)try{await lock.release();}catch(cleanupError){if(primary){const combined=new Error(`${primary.message}; lock cleanup also failed: ${cleanupError.message}`);combined.cause=primary;throw combined;}throw new Error(`VINi operation may have completed (${result?.status??'unknown'}); saved originals: ${result?.recovery??'none for a no-op'}; lock cleanup failed: ${cleanupError.message}`);}}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function initWithLock(options={},suppliedDistribution,{runner=run,releaseMetadata,recordRecovery}={}) {
|
|
235
416
|
const cli=suppliedDistribution?null:json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package');
|
|
236
417
|
const distribution=distributionCheck(suppliedDistribution??cli.viniDistribution);
|
|
237
418
|
const release=releaseMetadata??cli?.viniRelease;
|
|
238
419
|
if(release&&!validRelease(release))fail('invalid CLI release metadata');
|
|
239
420
|
const root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
|
|
240
|
-
const
|
|
421
|
+
const kit=path.join(root,'.vini-ds'),receiptPath=path.join(kit,'npm-install.json');await safeParents(root,receiptPath);
|
|
422
|
+
const kitStat=await exists(kit),receiptBytes=await fileBytes(receiptPath,true);let previous=null;
|
|
423
|
+
if(kitStat&&!receiptBytes)fail('existing .vini-ds belongs to another setup; migrate the private-GitHub Kit explicitly before npm init');
|
|
424
|
+
if(receiptBytes){previous=json(receiptBytes,receiptPath);if(previous.installer!=='vini-npm'||!previous.distribution||typeof previous.configTable!=='string')fail('unrecognized npm setup receipt');distributionCheck(previous.distribution);}
|
|
425
|
+
if(options.command==='update'&&!previous)fail('no npm VINi setup to update; use init');
|
|
426
|
+
if(previous&&typeof previous.appRoot!=='string')fail('npm setup receipt has no valid app root');
|
|
427
|
+
const app=await fs.realpath(path.resolve(root,options.appRoot??previous?.appRoot??'.'));
|
|
241
428
|
if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
|
|
242
429
|
const manifestFile=path.join(app,'package.json'),manifest=json(await fileBytes(manifestFile),manifestFile);
|
|
243
430
|
const deps={...manifest.devDependencies,...manifest.dependencies};
|
|
244
|
-
const allDependencies={...manifest.peerDependencies,...manifest.optionalDependencies,...deps};
|
|
245
|
-
for(const key of ['ui','tokens','agent'])if(distribution[key]!==`@vini/${key}`&&allDependencies[distribution[key]])fail(`direct ${distribution[key]} dependency requires an explicit manual-to-CLI migration; this installer uses @vini/${key} aliases and will not add a second package identity`);
|
|
246
431
|
if(!deps.react||!deps['react-dom']||![deps.react,deps['react-dom']].every(value=>typeof value==='string'&&/^(?:\^|~)?18(?:\.|$)/.test(value)))fail('this alpha requires existing React and React DOM 18 dependencies; their versions will not be replaced');
|
|
247
432
|
const manager=await managerFor(root,app,options,manifest);
|
|
248
433
|
let entry;
|
|
249
434
|
if(options.entry)entry=path.resolve(app,options.entry);
|
|
250
435
|
else {const candidates=[];for(const name of ['src/main.tsx','src/main.jsx','src/main.ts','src/main.js'])if(await exists(path.join(app,name)))candidates.push(path.join(app,name));if(candidates.length!==1)fail('cannot identify one Vite React entry; pass --entry src/main.tsx');entry=candidates[0];}
|
|
251
436
|
await safeParents(root,entry);if(entry!==app&&!entry.startsWith(app+path.sep))fail('entry must be inside app');
|
|
252
|
-
const entryBefore=await fileBytes(entry),
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
if(
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
437
|
+
const entryBefore=await fileBytes(entry);let entryAfter,entryPreparation='ready';
|
|
438
|
+
try {entryAfter=Buffer.from(transformEntry(text(entryBefore,entry),entry,distribution));}
|
|
439
|
+
catch(error){if(options.plan&&previous&&isNativeDs(distribution)&&/direct .* import requires an explicit manual-to-CLI migration/.test(error.message)){entryAfter=null;entryPreparation='manual-import-migration-required';}else throw error;}
|
|
440
|
+
if(previous){
|
|
441
|
+
let recordedApp;try{recordedApp=await fs.realpath(path.resolve(root,previous.appRoot));}catch{fail('recorded npm app root is unavailable; review the setup before updating');}
|
|
442
|
+
if(recordedApp!==root&&!recordedApp.startsWith(root+path.sep))fail('recorded npm app root is outside project');
|
|
443
|
+
if(recordedApp!==app)fail('selected app root differs from the recorded npm setup');
|
|
444
|
+
}
|
|
445
|
+
const targetLocal=localNames(distribution),priorLocal=previous?localNames(previous.distribution):null;
|
|
446
|
+
for(const section of ['dependencies','devDependencies','peerDependencies','optionalDependencies'])for(const [name,spec] of Object.entries(manifest[section]??{})){
|
|
447
|
+
for(const key of ['ui','tokens','agent'])for(const published of new Set([distribution[key],legacyPackages[key],`@vini/${key}`,nativeDsPackages[key]])){
|
|
448
|
+
const canonical=priorLocal?.[key]??targetLocal[key];
|
|
449
|
+
if(name===canonical){
|
|
450
|
+
if(!previous)fail(`existing ${canonical} dependency is not managed by this npm setup; migrate explicitly`);
|
|
451
|
+
if(section!==(key==='agent'?'devDependencies':'dependencies'))fail(`${canonical} appears in an unexpected dependency section; review the npm setup`);
|
|
452
|
+
}
|
|
453
|
+
if(name===targetLocal[key]&&targetLocal[key]!==canonical)fail(`existing ${name} dependency is not managed by this npm setup; migrate explicitly`);
|
|
454
|
+
if(name===published&&name!==canonical)fail(`direct ${published} dependency requires an explicit manual-to-CLI migration; this installer uses ${canonical} and will not add a second package identity`);
|
|
455
|
+
const value=typeof spec==='string'?spec.trim():'';
|
|
456
|
+
if(value===`npm:${published}`||value.startsWith(`npm:${published}@`)){
|
|
457
|
+
const recorded=previous&&name===canonical&§ion===(key==='agent'?'devDependencies':'dependencies')&&previous.distribution[key]===published&&spec===`npm:${published}@${previous.distribution.version}`;
|
|
458
|
+
if(!recorded)fail(`unmanaged alias ${name} for ${published} requires an explicit manual-to-CLI migration; use one package identity`);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
if(previous){
|
|
463
|
+
const sameNames=packageKeys.every(key=>previous.distribution[key]===distribution[key]);
|
|
464
|
+
const supportedFamilyChange=(packageKeys.every(key=>previous.distribution[key]===legacyPackages[key])&&(packageKeys.every(key=>distribution[key]===`@vini/${key}`)||isNativeDs(distribution)))||(packageKeys.every(key=>previous.distribution[key]===`@vini/${key}`)&&isNativeDs(distribution));
|
|
465
|
+
if(!sameNames&&supportedFamilyChange&&compareVersions(distribution.version,previous.distribution.version)<=0)fail('package family migration requires a newer release; no downgrade is selected');
|
|
466
|
+
if(familyTransition(previous.distribution,distribution)==='unsupported')fail('package family transition is not supported; review the installed distribution before migration');
|
|
467
|
+
if(compareVersions(distribution.version,previous.distribution.version)<0)fail('installed release is newer than the requested release; no downgrade is selected');
|
|
468
|
+
}
|
|
469
|
+
const alias=(key)=>packageSpec(distribution,key);
|
|
470
|
+
if(previous)for(const key of ['ui','tokens','agent']){const prior=packageSpec(previous.distribution,key);if(deps[priorLocal[key]]!==prior&&!(priorLocal[key]===targetLocal[key]&&deps[priorLocal[key]]===alias(key)))fail(`${priorLocal[key]} differs from the recorded npm setup`);}
|
|
261
471
|
const lockfile=path.join(app,manager==='npm'?'package-lock.json':'pnpm-lock.yaml');
|
|
262
472
|
const configFile=path.join(root,'.codex/config.toml'),agentsFile=path.join(root,'AGENTS.md'),skillFile=path.join(root,'.agents/skills/vini-ds/SKILL.md'),launchFile=path.join(kit,'npm-launcher.mjs'),setupFile=path.join(kit,'QUICKSTART.md');
|
|
263
473
|
const files=[manifestFile,lockfile,entry,configFile,agentsFile,skillFile,launchFile,setupFile,receiptPath];
|
|
@@ -268,48 +478,75 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
|
|
|
268
478
|
const config=Buffer.from(configMerge(before.get(configFile)?text(before.get(configFile),configFile):'',configTable,previous?.configTable));
|
|
269
479
|
const agents=Buffer.from(agentsMerge(before.get(agentsFile)?text(before.get(agentsFile),agentsFile):''));
|
|
270
480
|
const current=await readInstallation(root,path.relative(root,app)||'.',distribution);
|
|
271
|
-
const installedAligned=!!previous&¤t.launcher.status==='matches-receipt'&&['ui','tokens','agent'].every(key=>current.installed[key].matchesReceipt);
|
|
272
|
-
const
|
|
481
|
+
const installedAligned=!!previous&¤t.launcher.status==='matches-receipt'&&contextMatchesReceipt(current)&&['ui','tokens','agent'].every(key=>current.installed[key].matchesReceipt);
|
|
482
|
+
const migration=!!previous&&familyTransition(previous.distribution,distribution)==='manual-import-migration';
|
|
483
|
+
const plan={status:'plan-only',command:options.command??'init',projectRoot:root,appRoot:app,entry:path.relative(app,entry),entryPreparation,packageManager:manager,installed:current.installed,installedStatus:previous?(installedAligned?'matches-receipt':'mismatch'):'not-installed',from:previous?.distribution??null,to:distribution,distribution,changes:transition(release,installedAligned?previous.distribution.version:null,distribution.version),release:release??null,restart:clientCheck,dependencies:{[targetLocal.ui]:alias('ui'),[targetLocal.tokens]:alias('tokens')},devDependencies:{[targetLocal.agent]:alias('agent')},...(migration?{removeDependencies:Object.values(priorLocal),manualMigration:'Review and replace all old imports and configuration in the project before update; pass --imports-migrated only after review. The CLI checks the entry and build but cannot verify every source file.'}:{}),agent:'project-local Codex MCP + Skill',applicationPage:'not-verified',nativeClient:'not-verified',verification:verificationState(distribution,current),postUpdateSteps:[pageCheck,clientCheck],globalConfig:'unchanged',supported:'React 18, Vite direct createRoot(...).render(JSX), standalone npm/pnpm app'};
|
|
273
484
|
if(options.plan)return plan;
|
|
485
|
+
if(migration&&!options.importsMigrated)fail('review and migrate all project imports and configuration before update; then pass --imports-migrated');
|
|
486
|
+
if(previous&&!installedAligned)fail('installed packages, agent context or launcher differ from the receipt; resolve the mismatch before updating');
|
|
274
487
|
const recoveryRoot=path.join(root,'.vini-ds-recovery');await safeParents(root,path.join(recoveryRoot,'placeholder'));
|
|
275
488
|
const recoveryRootExisted=!!await exists(recoveryRoot);
|
|
276
489
|
const modules=path.join(app,'node_modules');
|
|
277
490
|
const moduleStat=await exists(modules);if(moduleStat&&(moduleStat.isSymbolicLink()||!moduleStat.isDirectory()))fail('node_modules must be a real directory');
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
const expected=new Map(before);let modulesMoved=false,projectMutationStarted=false,installFailed=false,buildAttempted=false,uncertain=false;
|
|
491
|
+
let backup;await fs.mkdir(recoveryRoot,{recursive:true,mode:0o700});backup=await fs.mkdtemp(path.join(recoveryRoot,'npm-'));await recordRecovery(backup);
|
|
492
|
+
const expected=new Map(before);let modulesMoved=false,modulesMayHaveChanged=false,projectMutationStarted=false,installFailed=false,buildAttempted=false;
|
|
281
493
|
const write=async(file,bytes)=>{await safeParents(root,file);const current=await fileBytes(file,true),expectedBytes=expected.get(file);if(current===null?expectedBytes!==null:expectedBytes===null||!current.equals(expectedBytes))fail(`concurrent change: ${file}`);await fs.mkdir(path.dirname(file),{recursive:true});const temporary=path.join(path.dirname(file),`.vini-${randomUUID()}`);await fs.writeFile(temporary,bytes,{flag:'wx',mode:(await exists(file))?.mode&0o777||0o600});await fs.rename(temporary,file);expected.set(file,bytes);};
|
|
282
494
|
const pm=async(args)=>runner(manager==='npm'?'npm':'corepack',manager==='npm'?args:['pnpm',...args],{cwd:app});
|
|
283
495
|
const registry=options.registry?[`--registry=${options.registry}`]:[];
|
|
284
496
|
try {
|
|
285
|
-
const next=structuredClone(manifest);next.dependencies={...next.dependencies
|
|
497
|
+
const next=structuredClone(manifest);next.dependencies={...next.dependencies};next.devDependencies={...next.devDependencies};
|
|
498
|
+
if(migration)for(const key of packageKeys){delete next.dependencies[priorLocal[key]];delete next.devDependencies[priorLocal[key]];}
|
|
499
|
+
next.dependencies[targetLocal.tokens]=alias('tokens');next.dependencies[targetLocal.ui]=alias('ui');next.devDependencies[targetLocal.agent]=alias('agent');delete next.dependencies[targetLocal.agent];delete next.devDependencies[targetLocal.ui];delete next.devDependencies[targetLocal.tokens];
|
|
286
500
|
const manifestAfter=Buffer.from(JSON.stringify(next,null,2)+'\n');
|
|
287
501
|
const unchanged=previous&&JSON.stringify(previous.distribution)===JSON.stringify(distribution)&&before.get(manifestFile).equals(manifestAfter)&&entryBefore.equals(entryAfter)&&before.get(configFile)?.equals(config)&&before.get(agentsFile)?.equals(agents)&&before.get(skillFile)!==null&&before.get(setupFile)!==null;
|
|
288
502
|
let verified=false;
|
|
289
|
-
if(unchanged){try{const
|
|
290
|
-
if(verified){
|
|
503
|
+
if(unchanged){try{const keys=['tokens','ui','agent'],entries=await freshResolve(manifestFile,keys.map(key=>`${targetLocal[key]}${key==='agent'?'/mcp':''}`),app);for(const [index,key]of keys.entries()){const pkg=await manifestForEntry(entries[index],targetLocal[key],app);if(pkg.manifest.name!==distribution[key]||pkg.manifest.version!==distribution.version)throw new Error('mismatch');validateNativeManifest(pkg.manifest,key,distribution);if(key==='agent')await verifyAgentContext(runner,pkg.entry,distribution,app);}verified=true;}catch{}}
|
|
504
|
+
if(verified){
|
|
505
|
+
let supervisor;
|
|
506
|
+
try{const [agentEntry,supervisorEntry]=await freshResolve(manifestFile,[`${targetLocal.agent}/mcp`,`${targetLocal.agent}/supervisor`],app);const agent=await manifestForEntry(agentEntry,targetLocal.agent,app);supervisor=await projectModuleEntry(app,supervisorEntry);if(!supervisor.startsWith((await fs.realpath(agent.root))+path.sep))throw new Error('outside agent');}
|
|
507
|
+
catch{fail('installed agent supervisor is missing or invalid; inspect the installed agent and receipt before retrying; no reinstall was started');}
|
|
508
|
+
const launch=Buffer.from(launcher(distribution,path.relative(root,app)||'.'));
|
|
509
|
+
if(before.get(launchFile)?.equals(launch)&&isGeneration(previous.generation)){await fs.rmdir(backup);if(!recoveryRootExisted)await fs.rmdir(recoveryRoot).catch(error=>{if(error.code!=='ENOTEMPTY'&&error.code!=='ENOENT')throw error;});return {...plan,status:'already-installed',build:'not-rerun'};}
|
|
510
|
+
// The installed set is already correct, but its recorded launcher is an
|
|
511
|
+
// older format. Repair only the launcher and receipt under this lock;
|
|
512
|
+
// do not reinstall packages or touch build output.
|
|
513
|
+
for(const [file,bytes]of before)if(bytes!==null){const target=path.join(backup,'files',path.relative(root,file));await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,bytes);}
|
|
514
|
+
projectMutationStarted=true;await write(launchFile,launch);
|
|
515
|
+
const receipt={...previous,generation:randomUUID(),launcherSha256:digest(launch)};
|
|
516
|
+
await write(receiptPath,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
|
|
517
|
+
const finalState=await readInstallation(root,path.relative(root,app)||'.',distribution),verification=verificationState(distribution,finalState);
|
|
518
|
+
if(!verification.installation.matchesTarget)fail('installed packages or launcher do not match the repaired receipt');
|
|
519
|
+
return {...plan,status:'connection-repaired',installed:finalState.installed,installedStatus:'matches-receipt',verification,build:'not-rerun',recovery:backup};
|
|
520
|
+
}
|
|
291
521
|
for(const [file,bytes]of before)if(bytes!==null){const target=path.join(backup,'files',path.relative(root,file));await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,bytes);}
|
|
292
522
|
if(moduleStat){await fs.rename(modules,path.join(backup,'node_modules'));modulesMoved=true;}
|
|
293
523
|
projectMutationStarted=true;
|
|
294
524
|
await write(manifestFile,manifestAfter);
|
|
295
|
-
try {await pm(manager==='npm'?['install','--ignore-scripts','--strict-peer-deps','--no-audit','--no-fund',...registry]:['install','--ignore-scripts','--config.strict-peer-dependencies=true','--no-frozen-lockfile',...registry]);}
|
|
525
|
+
try {modulesMayHaveChanged=true;await pm(manager==='npm'?['install','--ignore-scripts','--strict-peer-deps','--no-audit','--no-fund',...registry]:['install','--ignore-scripts','--config.strict-peer-dependencies=true','--no-frozen-lockfile',...registry]);}
|
|
296
526
|
catch(error){installFailed=true;throw error;}
|
|
297
527
|
expected.set(manifestFile,await fileBytes(manifestFile));expected.set(lockfile,await fileBytes(lockfile));
|
|
298
|
-
const
|
|
299
|
-
|
|
528
|
+
const packageRoots={};
|
|
529
|
+
const [tokensEntry,uiEntry,agentEntry,supervisorEntry,skillEntry,setupEntry,reactEntry,reactDomEntry]=await freshResolve(manifestFile,[targetLocal.tokens,targetLocal.ui,`${targetLocal.agent}/mcp`,`${targetLocal.agent}/supervisor`,`${targetLocal.agent}/skill`,`${targetLocal.agent}/setup`,'react','react-dom'],app);
|
|
530
|
+
for(const [key,entry]of [['tokens',tokensEntry],['ui',uiEntry],['agent',agentEntry]]){const pkg=await manifestForEntry(entry,targetLocal[key],app);if(pkg.manifest.name!==distribution[key]||pkg.manifest.version!==distribution.version)fail(`${key} npm version mismatch`);validateNativeManifest(pkg.manifest,key,distribution);packageRoots[key]=pkg;}
|
|
300
531
|
await verifyAgentContext(runner,packageRoots.agent.entry,distribution,app);
|
|
301
|
-
const
|
|
302
|
-
|
|
532
|
+
const supervisor=await projectModuleEntry(app,supervisorEntry),agentRoot=await fs.realpath(packageRoots.agent.root);
|
|
533
|
+
if(!supervisor.startsWith(agentRoot+path.sep))fail('agent supervisor must belong to the installed agent package');
|
|
534
|
+
const uiPeers=await freshResolve(path.join(packageRoots.ui.root,'package.json'),['react','react-dom'],app);
|
|
535
|
+
for(const [i,name]of ['react','react-dom'].entries())if(await projectModuleEntry(app,[reactEntry,reactDomEntry][i])!==await projectModuleEntry(app,uiPeers[i]))fail(`multiple ${name} instances after install`);
|
|
536
|
+
const skill=await fileBytes(await projectModuleEntry(app,skillEntry)),setup=await fileBytes(await projectModuleEntry(app,setupEntry));
|
|
303
537
|
const launch=Buffer.from(launcher(distribution,path.relative(root,app)||'.'));
|
|
304
538
|
await write(entry,entryAfter);
|
|
305
539
|
if(manifest.scripts?.build){buildAttempted=true;await pm(['run','build']);}
|
|
306
540
|
for(const file of [manifestFile,lockfile,entry]){const bytes=await fileBytes(file);if(!bytes.equals(expected.get(file)))fail(`project files changed during build: ${file}`);}
|
|
307
541
|
for(const [file,bytes]of [[launchFile,launch],[setupFile,setup],[configFile,config],[skillFile,skill],[agentsFile,agents]])await write(file,bytes);
|
|
308
|
-
const receipt={installer:'vini-npm',distribution,appRoot:path.relative(root,app)||'.',entry:path.relative(app,entry),configTable,skillSha256:digest(skill),launcherSha256:digest(launch)};
|
|
542
|
+
const receipt={installer:'vini-npm',generation:randomUUID(),distribution,appRoot:path.relative(root,app)||'.',entry:path.relative(app,entry),configTable,skillSha256:digest(skill),launcherSha256:digest(launch)};
|
|
309
543
|
await write(receiptPath,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
|
|
310
|
-
|
|
544
|
+
const finalState=await readInstallation(root,path.relative(root,app)||'.',distribution);
|
|
545
|
+
const verification=verificationState(distribution,finalState);
|
|
546
|
+
if(!verification.installation.matchesTarget)fail('installed packages or launcher do not match the newly written receipt');
|
|
547
|
+
return {...plan,status:'installed',installed:finalState.installed,installedStatus:'matches-receipt',verification,build:buildAttempted?'passed':'not-configured',recovery:backup};
|
|
311
548
|
} catch(error) {
|
|
312
|
-
if(error.uncertainChildren){
|
|
549
|
+
if(error.uncertainChildren){const retained=new Error(`${error.message}; retained lock and recovery: ${backup}`);retained.retainInstallLock=true;throw retained;}
|
|
313
550
|
if(!projectMutationStarted&&!modulesMoved)throw new Error(`${error.message}; no project files or dependencies changed; recovery retained: ${backup}`);
|
|
314
551
|
const issues=[];
|
|
315
552
|
let mayRecover=!installFailed;
|
|
@@ -331,10 +568,12 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
|
|
|
331
568
|
}catch(recoveryError){issues.push(`package-manager recovery requires review: ${recoveryError.message}`);}
|
|
332
569
|
if(mayRecover) {
|
|
333
570
|
for(const [file,bytes]of before){try{const current=await fileBytes(file,true),exp=expected.get(file);if(current===null?exp!==null:exp===null||!current.equals(exp))throw new Error('changed after last completed step');if(bytes===null){if(current)await fs.unlink(file);}else await write(file,bytes);}catch(e){issues.push(`${path.relative(root,file)}: ${e.message}`);}}
|
|
334
|
-
try{const failed=await exists(modules);if(failed){if(failed.isSymbolicLink()||!failed.isDirectory())throw new Error('node_modules changed type');await fs.rename(modules,path.join(backup,'node_modules-failed'));}if(modulesMoved)await fs.rename(path.join(backup,'node_modules'),modules);}catch(e){issues.push(`node_modules: ${e.message}`);}
|
|
571
|
+
if(modulesMoved||modulesMayHaveChanged)try{const failed=await exists(modules);if(failed){if(failed.isSymbolicLink()||!failed.isDirectory())throw new Error('node_modules changed type');await fs.rename(modules,path.join(backup,'node_modules-failed'));}if(modulesMoved)await fs.rename(path.join(backup,'node_modules'),modules);}catch(e){issues.push(`node_modules: ${e.message}`);}
|
|
335
572
|
if(!kitStat)await fs.rmdir(kit).catch(()=>{});
|
|
336
573
|
}
|
|
337
|
-
|
|
338
|
-
|
|
574
|
+
const failure=new Error(`${error.message}; ${issues.length?'recovery incomplete: '+issues.join('; '):'original files and dependencies restored'}; saved originals: ${backup}${migration?'; manually migrated source imports were present before update and are not reverted; they may require the new packages, so review and restore the previous source or retry the migration before running the project':''}${buildAttempted?'; build outputs are not automatically restored':''}${issues.length?'; retained lock requires recovery review':''}`);
|
|
575
|
+
if(issues.length)failure.retainInstallLock=true;
|
|
576
|
+
throw failure;
|
|
577
|
+
}
|
|
339
578
|
}
|
|
340
579
|
if(process.argv[1]&&await fs.realpath(process.argv[1]).catch(()=>null)===self){try{const options=parseArgs(process.argv.slice(2));if(options.help)console.log(usage);else if(options.command==='status'){const result=await status(options);console.log(options.json?JSON.stringify(result,null,2):formatStatus(result));}else console.log(JSON.stringify(await init(options),null,2));}catch(error){console.error(error.message);process.exitCode=1;}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vini-ds",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.11",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "VINi React project and local agent setup",
|
|
6
6
|
"bin": {
|
|
@@ -14,38 +14,16 @@
|
|
|
14
14
|
},
|
|
15
15
|
"files": [
|
|
16
16
|
"cli.mjs",
|
|
17
|
+
"version.mjs",
|
|
17
18
|
"README.md"
|
|
18
19
|
],
|
|
19
20
|
"dependencies": {
|
|
20
21
|
"typescript": "5.5.4"
|
|
21
22
|
},
|
|
22
23
|
"viniDistribution": {
|
|
23
|
-
"version": "0.1.0-alpha.
|
|
24
|
-
"ui": "@
|
|
25
|
-
"tokens": "@
|
|
26
|
-
"agent": "@
|
|
27
|
-
},
|
|
28
|
-
"viniRelease": {
|
|
29
|
-
"atlas": {
|
|
30
|
-
"url": "https://vini-atlas-pilot.layero.app/",
|
|
31
|
-
"archiveSha256": "sha256:d34523af2875a85b00fb41177ec4e3d539d6281cef23523b6253156781503647",
|
|
32
|
-
"siteRelease": "public-atlas-20261103-final",
|
|
33
|
-
"commit": "5b77933f6f7c37bea346e8e2276fc4952086be1d"
|
|
34
|
-
},
|
|
35
|
-
"delivery": {
|
|
36
|
-
"id": "candidate-33650c3731824b54",
|
|
37
|
-
"manifestSha256": "sha256:2d5f20b571a1ca5d330e46641c044afa5c97b14477ad83bfe1670df9b464893a",
|
|
38
|
-
"packageManifestSha256": "sha256:e937711fe54769b392b1cffc2982b4801e1339eee87ddbc1e6f726916bc06d8e"
|
|
39
|
-
},
|
|
40
|
-
"changes": {
|
|
41
|
-
"fromVersion": "0.1.0-alpha.0",
|
|
42
|
-
"summary": "Среди изменений — компоненты компоновки Container, Grid, Inline и Stack. Пакеты UI и токенов обновлены до сборки Atlas от 03.11.2026; в CLI добавлены проверка версии и план обновления, в MCP — проверка обновлений. Перечень изменений компонентов не является полным.",
|
|
43
|
-
"components": [
|
|
44
|
-
"Container",
|
|
45
|
-
"Grid",
|
|
46
|
-
"Inline",
|
|
47
|
-
"Stack"
|
|
48
|
-
]
|
|
49
|
-
}
|
|
24
|
+
"version": "0.1.0-alpha.11",
|
|
25
|
+
"ui": "@vini-ds/ui",
|
|
26
|
+
"tokens": "@vini-ds/tokens",
|
|
27
|
+
"agent": "@vini-ds/agent"
|
|
50
28
|
}
|
|
51
29
|
}
|
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
|
+
}
|