vini-ds 0.1.0-alpha.0 → 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.
Files changed (4) hide show
  1. package/README.md +9 -3
  2. package/cli.mjs +403 -57
  3. package/package.json +6 -5
  4. 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 the first public alpha, 0.1.0-alpha.0; it supports the bounded setup described below. For a reproducible installation, use the exact version.
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.0 init --plan`. Connect: `npx vini-ds@0.1.0-alpha.0 init`.
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
- Use a newer exact CLI version with `update` to select its matching package pair and agent. Previously installed private-GitHub Kits need an explicit migration and are not overwritten.
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,37 +1,72 @@
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 { spawn } from 'node:child_process';
6
+ import { isDeepStrictEqual, promisify } from 'node:util';
7
+ import { execFile, spawn } from 'node:child_process';
8
8
  import ts from 'typescript';
9
+ import { compareVersions, isExactVersion } from './version.mjs';
9
10
 
10
11
  const self=fileURLToPath(import.meta.url);
12
+ const execFileAsync=promisify(execFile);
11
13
  const digest=value=>createHash('sha256').update(value).digest('hex');
12
14
  const fail=message=>{throw new Error(`VINi: ${message}`);};
13
15
  const exists=async file=>fs.lstat(file).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
14
- const css=['@vini/tokens/fonts.css','@vini/tokens/themes.css','@vini/tokens/typography.css','@vini/ui/styles.css'];
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
+ }
15
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 -->';
16
- const usage='vini init|update [--plan] [--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]';
17
36
 
18
37
  export function parseArgs(args) {
19
38
  if(args.length===1&&['--help','-h'].includes(args[0]))return {help:true};
20
39
  const options={command:args[0]??'init',plan:false};
21
- if(!['init','update'].includes(options.command))fail(usage);
40
+ if(!['init','update','status'].includes(options.command))fail(usage);
22
41
  const names={'--cwd':'cwd','--app-root':'appRoot','--entry':'entry','--package-manager':'packageManager','--registry':'registry'};
23
42
  for(let i=1;i<args.length;i++) {
24
43
  if(args[i]==='--plan'){if(options.plan)fail('duplicate --plan');options.plan=true;continue;}
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;}
25
46
  const key=names[args[i]];if(!key||options[key]||!args[i+1]||args[i+1].startsWith('--'))fail(usage);options[key]=args[++i];
26
47
  }
27
48
  if(options.packageManager&&!['npm','pnpm'].includes(options.packageManager))fail('only npm and pnpm are supported');
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');
51
+ if(options.command==='status'&&(options.plan||options.entry||options.packageManager))fail(usage);
28
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)');}
29
53
  return options;
30
54
  }
31
55
  async function fileBytes(file,optional=false) {
32
- const stat=await exists(file);if(!stat){if(optional)return null;fail(`missing ${file}`);}
33
- if(!stat.isFile()||stat.isSymbolicLink()||stat.size>4*1024*1024)fail(`expected bounded regular file: ${file}`);
34
- return fs.readFile(file);
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();}
35
70
  }
36
71
  async function safeParents(root,file) {
37
72
  const rel=path.relative(root,file);if(rel.startsWith('..'+path.sep)||path.isAbsolute(rel)||rel==='..')fail('file escapes project');
@@ -41,26 +76,34 @@ async function safeParents(root,file) {
41
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;}
42
77
  function json(bytes,label){try{return JSON.parse(text(bytes,label));}catch{fail(`invalid JSON: ${label}`);}}
43
78
  function distributionCheck(value) {
44
- if(!value||!/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/.test(value.version??''))fail('CLI distribution has no exact version');
45
- for(const key of ['ui','tokens','agent'])if(!/^@[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(value[key]??''))fail(`invalid distribution ${key}`);
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}`);}
46
81
  return value;
47
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
+ }
48
90
  export function transformEntry(source,file='main.tsx',distribution) {
49
91
  if(source.startsWith('\uFEFF'))fail('entry has a BOM; review it manually');
50
92
  const ast=ts.createSourceFile(file,source,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
51
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`];
52
95
  const rootNames=new Set(),rootNamespaces=new Set(),providers=new Set(),imports=new Set();
53
96
  for(const statement of ast.statements)if(ts.isImportDeclaration(statement)&&ts.isStringLiteral(statement.moduleSpecifier)) {
54
97
  const module=statement.moduleSpecifier.text;imports.add(module);
55
- if(distribution)for(const key of ['ui','tokens','agent']){const published=distribution[key];if(published!==`@vini/${key}`&&(module===published||module.startsWith(published+'/')))fail(`direct ${published} import requires an explicit manual-to-CLI migration; use one package identity`);}
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`);}
56
99
  const clause=statement.importClause,bindings=clause?.namedBindings;
57
100
  if(module==='react-dom/client') {
58
101
  if(clause?.name)rootNamespaces.add(clause.name.text);
59
102
  if(bindings&&ts.isNamespaceImport(bindings))rootNamespaces.add(bindings.name.text);
60
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);
61
104
  }
62
- if(module==='@vini/ui'&&bindings&&ts.isNamedImports(bindings))for(const item of bindings.elements)if((item.propertyName?.text??item.name.text)==='ThemeBrandProvider')providers.add(item.name.text);
63
- if(module==='@vini/ui'&&bindings&&ts.isNamespaceImport(bindings))providers.add(`${bindings.name.text}.ThemeBrandProvider`);
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`);
64
107
  }
65
108
  const renders=[];
66
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');
@@ -72,7 +115,7 @@ export function transformEntry(source,file='main.tsx',distribution) {
72
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);
73
116
  let result=source;const prepend=css.filter(item=>!imports.has(item)).map(item=>`import ${JSON.stringify(item)};`);
74
117
  if(found.length>1)fail('multiple ThemeBrandProvider scopes require manual setup');
75
- if(!found.length){let alias='ViniThemeBrandProvider';while(new RegExp(`\\b${alias}\\b`).test(source))alias+='Root';prepend.push(`import { ThemeBrandProvider as ${alias} } from "@vini/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);}
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);}
76
119
  else if(found[0]!==jsx){
77
120
  // A provider directly inside StrictMode/Fragment still covers the whole app.
78
121
  const outer=ts.isJsxElement(jsx)?jsx.children:ts.isJsxFragment(jsx)?jsx.children:[];
@@ -97,27 +140,214 @@ function agentsMerge(source) {
97
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;}
98
141
  return source+(source&&!source.endsWith('\n')?'\n':'')+(source?'\n':'')+pointer+'\n';
99
142
  }
100
- 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}={}) {
101
144
  return new Promise((resolve,reject)=>{
102
- const child=spawn(executable,args,{cwd,env,shell:false,stdio:['ignore','pipe','pipe'],detached:process.platform!=='win32'});let output='',done=false,timed=false,killTimer;
103
- 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);};
104
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);
105
- for(const stream of [child.stdout,child.stderr])stream.on('data',buf=>{output=(output+buf.toString()).slice(-16000);});
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);});
106
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}`));});
107
151
  });
108
152
  }
109
- async function resolveManifest(req,name,subpath='') {
110
- const resolved=req.resolve(name+subpath);let dir=path.dirname(resolved);
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);
111
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;}
112
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
+ }
113
176
  async function verifyAgentContext(runner,entry,distribution,cwd) {
114
- 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}));
115
178
  if(result.ok!==true||result.name!==distribution.agent||result.version!==distribution.version)fail('installed agent selfcheck does not match the CLI distribution');
116
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');
117
180
  return result;
118
181
  }
182
+ // This is a description of one published transition, never a universal changelog.
183
+ function transition(release,fromVersion,toVersion) {
184
+ const changes=release?.changes;
185
+ if(!changes||changes.fromVersion!==fromVersion||!Array.isArray(changes.components)||!changes.components.every(x=>typeof x==='string'&&x.length<100)||typeof changes.summary!=='string'||changes.summary.length>2000)return {status:'not-available',from:fromVersion??null,to:toVersion};
186
+ return {status:'available',from:fromVersion,to:toVersion,summary:changes.summary,components:changes.components};
187
+ }
188
+ async function readInstallation(root,requestedApp,expected) {
189
+ const receiptPath=path.join(root,'.vini-ds/npm-install.json');await safeParents(root,receiptPath);
190
+ const raw=await fileBytes(receiptPath,true);let receipt=null;
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);}
192
+ const relative=requestedApp??receipt?.appRoot??'.';const app=await fs.realpath(path.resolve(root,relative));
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
+ }
199
+ const manifestPath=path.join(app,'package.json');await safeParents(root,manifestPath);
200
+ const manifestBytes=await fileBytes(manifestPath),manifest=json(manifestBytes,manifestPath);
201
+ const dependencies={...manifest.optionalDependencies,...manifest.devDependencies,...manifest.dependencies};
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)}`});}
203
+ const installed={};let installedAgent;
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;}
208
+ catch(problem){if(problem.code==='MODULE_NOT_FOUND'||problem.code==='ERR_PACKAGE_PATH_NOT_EXPORTED')error='not-resolvable';else error='metadata-unavailable';}
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};
211
+ }
212
+ let launcher='not-installed';
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';}
214
+ let agentContext=null;
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.'}};
267
+ }
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;};
269
+ function validRelease(value) {
270
+ const safe=x=>typeof x==='string'&&x.length>0&&x.length<=2000&&!/[\u0000-\u001f\u007f]/u.test(x);
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;}};
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);
273
+ }
274
+ function registryUrl(raw) {
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)');
276
+ if(!url.pathname.endsWith('/'))url.pathname+='/';return url;
277
+ }
278
+ async function requestMetadata(url) {
279
+ const response=await fetch(url,{headers:{accept:'application/vnd.npm.install-v1+json, application/json'},redirect:'error',signal:AbortSignal.timeout(8000)});
280
+ if(!response.ok)throw new Error(`registry HTTP ${response.status}`);
281
+ const length=Number(response.headers.get('content-length')??0);if(length>2*1024*1024)throw new Error('registry metadata too large');
282
+ const reader=response.body?.getReader();if(!reader)throw new Error('registry metadata body missing');let total=0,chunks=[];
283
+ try{while(true){const {done,value}=await reader.read();if(done)break;total+=value.length;if(total>2*1024*1024)throw new Error('registry metadata too large');chunks.push(value);}}finally{reader.releaseLock();}
284
+ return JSON.parse(Buffer.concat(chunks.map(x=>Buffer.from(x))).toString('utf8'));
285
+ }
286
+ async function availableRelease(registry,cliName,expected,request=requestMetadata) {
287
+ try {
288
+ const root=registryUrl(registry),endpoint=(name,version)=>new URL(`${encodeURIComponent(name)}/${encodeURIComponent(version)}`,root).href;
289
+ const latest=await request(endpoint(cliName,'latest'));
290
+ if(latest?.name!==cliName||!validIntegrity(latest?.dist?.integrity)||latest.version!==latest.viniDistribution?.version)throw new Error('invalid latest CLI identity or integrity');
291
+ const distribution=distributionCheck(latest.viniDistribution);
292
+ if(!validRelease(latest.viniRelease??null))throw new Error('invalid release metadata');
293
+ if(['ui','tokens','agent'].some(key=>distribution[key]!==expected[key]))throw new Error('latest CLI publishes a different package family');
294
+ const entries=await Promise.all(['ui','tokens','agent'].map(async key=>{
295
+ const info=await request(endpoint(distribution[key],distribution.version));
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`);
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
+ }
306
+ if(key==='agent'&&!isDeepStrictEqual(info.viniRelease??null,latest.viniRelease??null))throw new Error('CLI and agent release metadata differ');
307
+ return [key,{name:info.name,version:info.version,integrity:info.dist.integrity}];
308
+ }));const packages=Object.fromEntries(entries);
309
+ return {status:'available',distribution,cli:{name:latest.name,version:latest.version,integrity:latest.dist.integrity},packages,release:latest.viniRelease??null};
310
+ } catch(error) {return {status:'unavailable',reason:String(error.message??error)};}
311
+ }
312
+ export async function status(options={},suppliedDistribution,{request=requestMetadata,cliName,release}={}) {
313
+ const cli=suppliedDistribution?{name:cliName??'vini-ds',viniDistribution:suppliedDistribution,viniRelease:release}:json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package');
314
+ const expected=distributionCheck(cli.viniDistribution),root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
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;}
321
+ const registry=options.registry??process.env.npm_config_registry??'https://registry.npmjs.org/';
322
+ const published=await availableRelease(registry,cli.name,expected,request);
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);
332
+ const installedVersion=aligned?state.receipt.distribution.version:null;
333
+ const installedToLauncher=aligned&&['ui','tokens','agent'].every(key=>state.installed[key].matchesLauncher);
334
+ const latest=published.status==='available'?published.distribution.version:null;
335
+ const family=aligned&&published.status==='available'?familyTransition(state.receipt.distribution,published.distribution):null;
336
+ const ordering=aligned&&latest?compareVersions(installedVersion,latest):null;
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};
340
+ }
341
+ export function formatStatus(result) {
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');
343
+ const available=result.available.status==='available'?result.available.distribution.version:`unknown (${result.available.reason})`;
344
+ const changes=result.changes.status==='available'?`\nChanges: ${result.changes.summary}\nComponents: ${result.changes.components.join(', ')||'none listed'}`:'';
345
+ const release=result.available.release;
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}`:'';
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}`;
348
+ }
119
349
  function launcher(distribution,appRelative) {
120
- 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,${JSON.stringify(appRelative)},'package.json'));\nconst expected=${JSON.stringify(distribution)};\nlet server;\nfor(const key of ['tokens','ui','agent']) { const entry=req.resolve('@vini/'+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; run matching VINi CLI update');if(key==='agent')server=entry;}\nconst child=spawn(process.execPath,[server],{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`;
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`;
121
351
  }
122
352
  async function managerFor(root,app,options,manifest) {
123
353
  const dirs=[];let dir=app;while(true){dirs.push(dir);if(dir===root)break;dir=path.dirname(dir);}
@@ -132,30 +362,112 @@ async function managerFor(root,app,options,manifest) {
132
362
  if(manifest.workspaces)fail('workspace root is not supported by this alpha; choose a standalone Vite app');
133
363
  return manager??'npm';
134
364
  }
135
- export async function init(options={},suppliedDistribution,{runner=run}={}) {
136
- const distribution=distributionCheck(suppliedDistribution??json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package').viniDistribution);
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={}) {
137
396
  const root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
138
- const app=await fs.realpath(path.resolve(root,options.appRoot??'.'));
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}={}) {
416
+ const cli=suppliedDistribution?null:json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package');
417
+ const distribution=distributionCheck(suppliedDistribution??cli.viniDistribution);
418
+ const release=releaseMetadata??cli?.viniRelease;
419
+ if(release&&!validRelease(release))fail('invalid CLI release metadata');
420
+ const root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
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??'.'));
139
428
  if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
140
429
  const manifestFile=path.join(app,'package.json'),manifest=json(await fileBytes(manifestFile),manifestFile);
141
430
  const deps={...manifest.devDependencies,...manifest.dependencies};
142
- const allDependencies={...manifest.peerDependencies,...manifest.optionalDependencies,...deps};
143
- 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`);
144
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');
145
432
  const manager=await managerFor(root,app,options,manifest);
146
433
  let entry;
147
434
  if(options.entry)entry=path.resolve(app,options.entry);
148
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];}
149
436
  await safeParents(root,entry);if(entry!==app&&!entry.startsWith(app+path.sep))fail('entry must be inside app');
150
- const entryBefore=await fileBytes(entry),entryAfter=Buffer.from(transformEntry(text(entryBefore,entry),entry,distribution));
151
- const kit=path.join(root,'.vini-ds'),receiptPath=path.join(kit,'npm-install.json');await safeParents(root,receiptPath);
152
- const kitStat=await exists(kit),receiptBytes=await fileBytes(receiptPath,true);let previous=null;
153
- if(kitStat&&!receiptBytes)fail('existing .vini-ds belongs to another setup; migrate the private-GitHub Kit explicitly before npm init');
154
- 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);}
155
- if(options.command==='update'&&!previous)fail('no npm VINi setup to update; use init');
156
- const alias=(key)=>distribution[key]===`@vini/${key}`?distribution.version:`npm:${distribution[key]}@${distribution.version}`;
157
- for(const key of ['ui','tokens','agent'])if(deps[`@vini/${key}`]&&!previous)fail('existing VINi dependency is not managed by this npm setup; migrate explicitly');
158
- if(previous)for(const key of ['ui','tokens','agent']){const prior=previous.distribution[key]===`@vini/${key}`?previous.distribution.version:`npm:${previous.distribution[key]}@${previous.distribution.version}`;if(deps[`@vini/${key}`]!==prior&&deps[`@vini/${key}`]!==alias(key))fail(`@vini/${key} differs from the recorded npm setup`);}
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&&section===(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`);}
159
471
  const lockfile=path.join(app,manager==='npm'?'package-lock.json':'pnpm-lock.yaml');
160
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');
161
473
  const files=[manifestFile,lockfile,entry,configFile,agentsFile,skillFile,launchFile,setupFile,receiptPath];
@@ -165,45 +477,77 @@ export async function init(options={},suppliedDistribution,{runner=run}={}) {
165
477
  const configTable=`[mcp_servers.vini-ds]\ncommand = "node"\nargs = [${JSON.stringify(launchFile)}]\nenabled = true\nstartup_timeout_sec = 10`;
166
478
  const config=Buffer.from(configMerge(before.get(configFile)?text(before.get(configFile),configFile):'',configTable,previous?.configTable));
167
479
  const agents=Buffer.from(agentsMerge(before.get(agentsFile)?text(before.get(agentsFile),agentsFile):''));
168
- const plan={status:'plan-only',command:options.command??'init',projectRoot:root,appRoot:app,entry:path.relative(app,entry),packageManager:manager,distribution,dependencies:{'@vini/ui':alias('ui'),'@vini/tokens':alias('tokens')},devDependencies:{'@vini/agent':alias('agent')},agent:'project-local Codex MCP + Skill',nativeClient:'not-verified',globalConfig:'unchanged',supported:'React 18, Vite direct createRoot(...).render(JSX), standalone npm/pnpm app'};
480
+ const current=await readInstallation(root,path.relative(root,app)||'.',distribution);
481
+ const installedAligned=!!previous&&current.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'};
169
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');
170
487
  const recoveryRoot=path.join(root,'.vini-ds-recovery');await safeParents(root,path.join(recoveryRoot,'placeholder'));
488
+ const recoveryRootExisted=!!await exists(recoveryRoot);
171
489
  const modules=path.join(app,'node_modules');
172
490
  const moduleStat=await exists(modules);if(moduleStat&&(moduleStat.isSymbolicLink()||!moduleStat.isDirectory()))fail('node_modules must be a real directory');
173
- const operationLock=path.join(root,'.vini-npm-install.lock');try{await fs.mkdir(operationLock,{mode:0o700});}catch(error){if(error.code==='EEXIST')fail('another VINi setup is active or previous recovery needs review');throw error;}
174
- let backup;try{await fs.mkdir(recoveryRoot,{recursive:true,mode:0o700});backup=await fs.mkdtemp(path.join(recoveryRoot,'npm-'));}catch(error){await fs.rmdir(operationLock);throw error;}
175
- const expected=new Map(before);let modulesMoved=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;
176
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);};
177
494
  const pm=async(args)=>runner(manager==='npm'?'npm':'corepack',manager==='npm'?args:['pnpm',...args],{cwd:app});
178
495
  const registry=options.registry?[`--registry=${options.registry}`]:[];
179
496
  try {
180
- 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);}
181
- const next=structuredClone(manifest);next.dependencies={...next.dependencies,'@vini/tokens':alias('tokens'),'@vini/ui':alias('ui')};next.devDependencies={...next.devDependencies,'@vini/agent':alias('agent')};delete next.dependencies['@vini/agent'];delete next.devDependencies['@vini/ui'];delete next.devDependencies['@vini/tokens'];
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];
182
500
  const manifestAfter=Buffer.from(JSON.stringify(next,null,2)+'\n');
183
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;
184
502
  let verified=false;
185
- if(unchanged){try{const req=createRequire(manifestFile);for(const key of ['tokens','ui','agent']){const pkg=await resolveManifest(req,`@vini/${key}`,key==='agent'?'/mcp':'');if(pkg.manifest.name!==distribution[key]||pkg.manifest.version!==distribution.version)throw new Error('mismatch');if(key==='agent')await verifyAgentContext(runner,pkg.entry,distribution,app);}verified=true;}catch{}}
186
- if(verified)return {...plan,status:'already-installed',build:'not-rerun'};
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
+ }
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);}
187
522
  if(moduleStat){await fs.rename(modules,path.join(backup,'node_modules'));modulesMoved=true;}
523
+ projectMutationStarted=true;
188
524
  await write(manifestFile,manifestAfter);
189
- 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]);}
190
526
  catch(error){installFailed=true;throw error;}
191
527
  expected.set(manifestFile,await fileBytes(manifestFile));expected.set(lockfile,await fileBytes(lockfile));
192
- const req=createRequire(manifestFile),packageRoots={};
193
- for(const key of ['tokens','ui','agent']){const pkg=await resolveManifest(req,`@vini/${key}`,key==='agent'?'/mcp':'');if(pkg.manifest.name!==distribution[key]||pkg.manifest.version!==distribution.version)fail(`${key} npm version mismatch`);packageRoots[key]=pkg;}
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;}
194
531
  await verifyAgentContext(runner,packageRoots.agent.entry,distribution,app);
195
- const uiRequire=createRequire(path.join(packageRoots.ui.root,'package.json'));for(const name of ['react','react-dom'])if(req.resolve(name)!==uiRequire.resolve(name))fail(`multiple ${name} instances after install`);
196
- const skill=await fileBytes(req.resolve('@vini/agent/skill')),setup=await fileBytes(req.resolve('@vini/agent/setup'));
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));
197
537
  const launch=Buffer.from(launcher(distribution,path.relative(root,app)||'.'));
198
538
  await write(entry,entryAfter);
199
539
  if(manifest.scripts?.build){buildAttempted=true;await pm(['run','build']);}
200
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}`);}
201
541
  for(const [file,bytes]of [[launchFile,launch],[setupFile,setup],[configFile,config],[skillFile,skill],[agentsFile,agents]])await write(file,bytes);
202
- 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)};
203
543
  await write(receiptPath,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
204
- return {...plan,status:'installed',build:buildAttempted?'passed':'not-configured',recovery:backup};
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};
205
548
  } catch(error) {
206
- if(error.uncertainChildren){uncertain=true;throw new Error(`${error.message}; retained lock and recovery: ${backup}`);}
549
+ if(error.uncertainChildren){const retained=new Error(`${error.message}; retained lock and recovery: ${backup}`);retained.retainInstallLock=true;throw retained;}
550
+ if(!projectMutationStarted&&!modulesMoved)throw new Error(`${error.message}; no project files or dependencies changed; recovery retained: ${backup}`);
207
551
  const issues=[];
208
552
  let mayRecover=!installFailed;
209
553
  if(installFailed)try{
@@ -224,10 +568,12 @@ export async function init(options={},suppliedDistribution,{runner=run}={}) {
224
568
  }catch(recoveryError){issues.push(`package-manager recovery requires review: ${recoveryError.message}`);}
225
569
  if(mayRecover) {
226
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}`);}}
227
- 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}`);}
228
572
  if(!kitStat)await fs.rmdir(kit).catch(()=>{});
229
573
  }
230
- throw new Error(`${error.message}; ${issues.length?'recovery incomplete: '+issues.join('; '):'original files and dependencies restored'}; saved originals: ${backup}${buildAttempted?'; build outputs are not automatically restored':''}`);
231
- } finally {if(!uncertain)await fs.rmdir(operationLock);}
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
+ }
232
578
  }
233
- if(process.argv[1]&&await fs.realpath(process.argv[1]).catch(()=>null)===self){try{const options=parseArgs(process.argv.slice(2));console.log(options.help?usage:JSON.stringify(await init(options),null,2));}catch(error){console.error(error.message);process.exitCode=1;}}
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.0",
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,15 +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.0",
24
- "ui": "@timelex/vini-ui",
25
- "tokens": "@timelex/vini-tokens",
26
- "agent": "@timelex/vini-agent"
24
+ "version": "0.1.0-alpha.11",
25
+ "ui": "@vini-ds/ui",
26
+ "tokens": "@vini-ds/tokens",
27
+ "agent": "@vini-ds/agent"
27
28
  }
28
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
+ }