vini-ds 0.1.0-alpha.3 → 0.1.0-alpha.5

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 (3) hide show
  1. package/README.md +9 -3
  2. package/cli.mjs +161 -53
  3. package/package.json +7 -7
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; 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.5; 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.3 init --plan`. Connect: `npx vini-ds@0.1.0-alpha.3 init`.
5
+ Preview: `npx vini-ds@0.1.0-alpha.5 init --plan`. Connect: `npx vini-ds@0.1.0-alpha.5 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.3 update --plan`, then run 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. Reconnect the project-local VINi MCP in the current client and read `vini://system/current`, the affected component contract, and `check_updates` there. A separate STDIO process does not verify the current client. Treat package installation, the application page, and the current MCP client as separate results. 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.
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.5 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. Reconnect the project-local VINi MCP in the current client. If a reconnect control is unavailable or reconnect was already attempted and the context remains stale, fully quit and reopen that client. 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 reconnect or fallback 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.5 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.5 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
@@ -2,19 +2,34 @@
2
2
  import { promises as fs } 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';
10
9
 
11
10
  const self=fileURLToPath(import.meta.url);
11
+ const execFileAsync=promisify(execFile);
12
12
  const digest=value=>createHash('sha256').update(value).digest('hex');
13
13
  const fail=message=>{throw new Error(`VINi: ${message}`);};
14
14
  const exists=async file=>fs.lstat(file).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
15
- const css=['@vini/tokens/fonts.css','@vini/tokens/themes.css','@vini/tokens/typography.css','@vini/ui/styles.css'];
15
+ const legacyPackages={ui:'@timelex/vini-ui',tokens:'@timelex/vini-tokens',agent:'@timelex/vini-agent'};
16
+ const nativeDsPackages={ui:'@vini-ds/ui',tokens:'@vini-ds/tokens',agent:'@vini-ds/agent'};
17
+ const packageKeys=['ui','tokens','agent'];
18
+ const isNativeDs=distribution=>!!distribution&&packageKeys.every(key=>distribution[key]===nativeDsPackages[key]);
19
+ const localNames=distribution=>Object.fromEntries(packageKeys.map(key=>[key,isNativeDs(distribution)?nativeDsPackages[key]:`@vini/${key}`]));
20
+ const packageSpec=(distribution,key)=>distribution[key]===localNames(distribution)[key]?distribution.version:`npm:${distribution[key]}@${distribution.version}`;
21
+ 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.';
22
+ const clientCheck='Reconnect the project-local VINi MCP in the current client. If a reconnect control is unavailable or reconnect was already attempted and the context remains stale, fully quit and reopen that client. In the same project and client, read vini://system/current, the affected component contract and check_updates; compare their versions with the target and installed packages. If the context is stale, do not reinstall packages just to refresh it; follow these reconnect or fallback steps and repeat the client checks. A separate STDIO process does not verify the current client. If these checks cannot be performed, report the client MCP as not verified.';
23
+ function validateNativeManifest(info,key,distribution){
24
+ if(!isNativeDs(distribution))return;
25
+ 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`);
26
+ if(key==='ui'){
27
+ const name=distribution.tokens,dep=info.dependencies?.[name],peer=info.peerDependencies?.[name];
28
+ 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');
29
+ }
30
+ }
16
31
  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]';
32
+ 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
33
 
19
34
  export function parseArgs(args) {
20
35
  if(args.length===1&&['--help','-h'].includes(args[0]))return {help:true};
@@ -24,10 +39,12 @@ export function parseArgs(args) {
24
39
  for(let i=1;i<args.length;i++) {
25
40
  if(args[i]==='--plan'){if(options.plan)fail('duplicate --plan');options.plan=true;continue;}
26
41
  if(args[i]==='--json'){if(options.json)fail('duplicate --json');options.json=true;continue;}
42
+ if(args[i]==='--imports-migrated'){if(options.importsMigrated)fail('duplicate --imports-migrated');options.importsMigrated=true;continue;}
27
43
  const key=names[args[i]];if(!key||options[key]||!args[i+1]||args[i+1].startsWith('--'))fail(usage);options[key]=args[++i];
28
44
  }
29
45
  if(options.packageManager&&!['npm','pnpm'].includes(options.packageManager))fail('only npm and pnpm are supported');
30
46
  if(options.json&&options.command!=='status')fail('--json is supported by status');
47
+ if(options.importsMigrated&&options.command!=='update')fail('--imports-migrated is supported by update');
31
48
  if(options.command==='status'&&(options.plan||options.entry||options.packageManager))fail(usage);
32
49
  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
50
  return options;
@@ -49,22 +66,30 @@ function distributionCheck(value) {
49
66
  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}`);
50
67
  return value;
51
68
  }
69
+ function familyTransition(from,to) {
70
+ const keys=['ui','tokens','agent'];
71
+ if(keys.every(key=>from[key]===to[key]))return 'same';
72
+ if(keys.every(key=>from[key]===legacyPackages[key]&&to[key]===`@vini/${key}`)&&compareVersions(to.version,from.version)>0)return 'legacy-to-native';
73
+ 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';
74
+ return 'unsupported';
75
+ }
52
76
  export function transformEntry(source,file='main.tsx',distribution) {
53
77
  if(source.startsWith('\uFEFF'))fail('entry has a BOM; review it manually');
54
78
  const ast=ts.createSourceFile(file,source,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
55
79
  if(ast.parseDiagnostics.length)fail('entry has syntax errors');
80
+ const local=localNames(distribution),css=[`${local.tokens}/fonts.css`,`${local.tokens}/themes.css`,`${local.tokens}/typography.css`,`${local.ui}/styles.css`];
56
81
  const rootNames=new Set(),rootNamespaces=new Set(),providers=new Set(),imports=new Set();
57
82
  for(const statement of ast.statements)if(ts.isImportDeclaration(statement)&&ts.isStringLiteral(statement.moduleSpecifier)) {
58
83
  const module=statement.moduleSpecifier.text;imports.add(module);
59
- 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`);}
84
+ 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
85
  const clause=statement.importClause,bindings=clause?.namedBindings;
61
86
  if(module==='react-dom/client') {
62
87
  if(clause?.name)rootNamespaces.add(clause.name.text);
63
88
  if(bindings&&ts.isNamespaceImport(bindings))rootNamespaces.add(bindings.name.text);
64
89
  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
90
  }
66
- 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);
67
- if(module==='@vini/ui'&&bindings&&ts.isNamespaceImport(bindings))providers.add(`${bindings.name.text}.ThemeBrandProvider`);
91
+ 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);
92
+ if(module===local.ui&&bindings&&ts.isNamespaceImport(bindings))providers.add(`${bindings.name.text}.ThemeBrandProvider`);
68
93
  }
69
94
  const renders=[];
70
95
  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 +101,7 @@ export function transformEntry(source,file='main.tsx',distribution) {
76
101
  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
102
  let result=source;const prepend=css.filter(item=>!imports.has(item)).map(item=>`import ${JSON.stringify(item)};`);
78
103
  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 "@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);}
104
+ 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
105
  else if(found[0]!==jsx){
81
106
  // A provider directly inside StrictMode/Fragment still covers the whole app.
82
107
  const outer=ts.isJsxElement(jsx)?jsx.children:ts.isJsxFragment(jsx)?jsx.children:[];
@@ -101,21 +126,41 @@ function agentsMerge(source) {
101
126
  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
127
  return source+(source&&!source.endsWith('\n')?'\n':'')+(source?'\n':'')+pointer+'\n';
103
128
  }
104
- export async function run(executable,args,{cwd,timeout=600000,env=process.env}={}) {
129
+ export async function run(executable,args,{cwd,timeout=600000,env=process.env,stdoutOnly=false}={}) {
105
130
  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);};
131
+ 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;
132
+ const finish=error=>{if(done)return;done=true;clearTimeout(timer);clearTimeout(killTimer);error?reject(error):resolve(stdoutOnly?stdout:output);};
108
133
  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
- for(const stream of [child.stdout,child.stderr])stream.on('data',buf=>{output=(output+buf.toString()).slice(-16000);});
134
+ child.stdout.on('data',buf=>{const value=buf.toString();stdout=(stdout+value).slice(-16000);output=(output+value).slice(-16000);});
135
+ child.stderr.on('data',buf=>{output=(output+buf.toString()).slice(-16000);});
110
136
  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
137
  });
112
138
  }
113
- async function resolveManifest(req,name,subpath='') {
114
- const resolved=req.resolve(name+subpath);let dir=path.dirname(resolved);
139
+ async function projectModuleEntry(app,entry) {
140
+ const modules=path.join(app,'node_modules'),stat=await exists(modules);
141
+ if(!stat||stat.isSymbolicLink()||!stat.isDirectory())fail('node_modules must be a real project directory');
142
+ const root=await fs.realpath(modules),resolved=await fs.realpath(entry);
143
+ if(!resolved.startsWith(root+path.sep))fail('installed package resolves outside project node_modules');
144
+ return resolved;
145
+ }
146
+ async function manifestForEntry(resolved,name,app) {
147
+ resolved=await projectModuleEntry(app,resolved);let dir=path.dirname(resolved);
115
148
  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
149
  }
150
+ // Node caches resolved pnpm symlink targets in-process. A completed install may
151
+ // replace those symlinks, so inspect the new installation in a fresh process.
152
+ async function freshResolveMaybe(manifest,names,cwd) {
153
+ 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"}}})));';
154
+ 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'})`);}
155
+ 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;
156
+ }
157
+ async function freshResolve(manifest,names,cwd) {
158
+ const entries=await freshResolveMaybe(manifest,names,cwd);
159
+ for(let i=0;i<names.length;i++)if(entries[i].error)fail(`cannot resolve ${names[i]} after install (${entries[i].error})`);
160
+ return entries.map(entry=>entry.path);
161
+ }
117
162
  async function verifyAgentContext(runner,entry,distribution,cwd) {
118
- const result=JSON.parse(await runner(process.execPath,[entry,'--check'],{cwd,timeout:10000}));
163
+ const result=JSON.parse(await runner(process.execPath,[entry,'--check'],{cwd,timeout:10000,stdoutOnly:true}));
119
164
  if(result.ok!==true||result.name!==distribution.agent||result.version!==distribution.version)fail('installed agent selfcheck does not match the CLI distribution');
120
165
  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
166
  return result;
@@ -132,23 +177,41 @@ async function readInstallation(root,requestedApp,expected) {
132
177
  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
178
  const relative=requestedApp??receipt?.appRoot??'.';const app=await fs.realpath(path.resolve(root,relative));
134
179
  if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
180
+ let appRootMatchesReceipt=null;
181
+ if(receipt){
182
+ const recorded=typeof receipt.appRoot==='string'?await fs.realpath(path.resolve(root,receipt.appRoot)).catch(()=>null):null;
183
+ appRootMatchesReceipt=!!recorded&&(recorded===root||recorded.startsWith(root+path.sep))&&recorded===app;
184
+ }
135
185
  const manifestPath=path.join(app,'package.json');await safeParents(root,manifestPath);
136
- const manifest=json(await fileBytes(manifestPath),manifestPath);const req=createRequire(manifestPath);
186
+ const manifest=json(await fileBytes(manifestPath),manifestPath);
137
187
  const dependencies={...manifest.optionalDependencies,...manifest.devDependencies,...manifest.dependencies};
138
188
  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
189
  const installed={};let installedAgent;
140
- for(const key of ['ui','tokens','agent']) {
141
- const alias=`@vini/${key}`;let actual=null,error=null;
142
- try{const pkg=await resolveManifest(req,alias,key==='agent'?'/mcp':'');actual={name:pkg.manifest.name,version:pkg.manifest.version};if(key==='agent')installedAgent=pkg;}
190
+ const keys=['ui','tokens','agent'],local=localNames(receipt?.distribution??expected),resolved=await freshResolveMaybe(manifestPath,keys.map(key=>`${local[key]}${key==='agent'?'/mcp':''}`),app);
191
+ for(const [index,key] of keys.entries()) {
192
+ const alias=local[key];let actual=null,error=null;
193
+ 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};if(key==='agent')installedAgent=pkg;}
143
194
  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[key]===alias?receipt.distribution.version:`npm:${receipt.distribution[key]}@${receipt.distribution.version}`):null;
195
+ const declared=dependencies[alias]??null,recorded=receipt?packageSpec(receipt.distribution,key):null;
145
196
  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};
146
197
  }
147
198
  let launcher='not-installed';
148
199
  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
200
  let agentContext=null;
150
201
  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};
202
+ return {projectRoot:root,appRoot:app,appRootMatchesReceipt,receipt:receipt?{distribution:receipt.distribution,appRoot:receipt.appRoot}:null,launcher:{status:launcher,expected:receipt?.distribution??null},installed,lockfiles,agentContext};
203
+ }
204
+ // These observations are returned with the command, not persisted as a new receipt.
205
+ // A package/launcher check cannot establish what a running application or MCP client sees.
206
+ function verificationState(target,state) {
207
+ const receipt=state.receipt?.distribution??null;
208
+ const matched=!!receipt&&state.appRootMatchesReceipt===true&&state.launcher.status==='matches-receipt'&&packageKeys.every(key=>state.installed[key].matchesReceipt);
209
+ 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);
210
+ return {target:{version:target.version,packages:Object.fromEntries(packageKeys.map(key=>[key,target[key]]))},
211
+ installation:{status:!receipt?'not-installed':matched?'matched':'mismatch',matchesTarget,receipt,packages:state.installed},
212
+ applicationPage:{status:'not-verified',nextStep:pageCheck},
213
+ clientMcp:{status:'not-verified',nextStep:clientCheck},
214
+ 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
215
  }
153
216
  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
217
  function validRelease(value) {
@@ -185,7 +248,15 @@ async function availableRelease(registry,cliName,expected,request=requestMetadat
185
248
  const entries=await Promise.all(['ui','tokens','agent'].map(async key=>{
186
249
  const info=await request(endpoint(distribution[key],distribution.version));
187
250
  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
- if(key==='ui'){const alias=distribution.tokens==='@vini/tokens'?distribution.version:`npm:${distribution.tokens}@${distribution.version}`;if(info.dependencies?.['@vini/tokens']!==alias)throw new Error('published UI token dependency does not match the release');}
251
+ validateNativeManifest(info,key,distribution);
252
+ if(key==='ui'){
253
+ const token=localNames(distribution).tokens,native=distribution.tokens===token;
254
+ const dependency=info.dependencies?.[token];
255
+ const peer=info.peerDependencies?.[token];
256
+ const optional=Object.hasOwn(info.optionalDependencies??{},token)||info.peerDependenciesMeta?.[token]?.optional===true;
257
+ 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');
258
+ 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');
259
+ }
189
260
  if(key==='agent'&&!isDeepStrictEqual(info.viniRelease??null,latest.viniRelease??null))throw new Error('CLI and agent release metadata differ');
190
261
  return [key,{name:info.name,version:info.version,integrity:info.dist.integrity}];
191
262
  }));const packages=Object.fromEntries(entries);
@@ -198,14 +269,15 @@ export async function status(options={},suppliedDistribution,{request=requestMet
198
269
  const state=await readInstallation(root,options.appRoot,expected);
199
270
  const registry=options.registry??process.env.npm_config_registry??'https://registry.npmjs.org/';
200
271
  const published=await availableRelease(registry,cli.name,expected,request);
201
- const aligned=!!state.receipt&&state.launcher.status==='matches-receipt'&&['ui','tokens','agent'].every(key=>state.installed[key].matchesReceipt);
272
+ const aligned=!!state.receipt&&state.appRootMatchesReceipt&&state.launcher.status==='matches-receipt'&&['ui','tokens','agent'].every(key=>state.installed[key].matchesReceipt);
202
273
  const installedVersion=aligned?state.receipt.distribution.version:null;
203
274
  const installedToLauncher=aligned&&['ui','tokens','agent'].every(key=>state.installed[key].matchesLauncher);
204
275
  const latest=published.status==='available'?published.distribution.version:null;
276
+ const family=aligned&&published.status==='available'?familyTransition(state.receipt.distribution,published.distribution):null;
205
277
  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};
278
+ const relation=!state.receipt?'not-installed':!aligned?'mismatch':published.status!=='available'||family==='unsupported'?'unknown':ordering===0?'current':ordering<0?'update-available':'ahead-of-latest';
279
+ 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.':'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.';
280
+ 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
281
  }
210
282
  export function formatStatus(result) {
211
283
  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 +285,10 @@ export function formatStatus(result) {
213
285
  const changes=result.changes.status==='available'?`\nChanges: ${result.changes.summary}\nComponents: ${result.changes.components.join(', ')||'none listed'}`:'';
214
286
  const release=result.available.release;
215
287
  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}`;
288
+ 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
289
  }
218
290
  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,${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`;
291
+ 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)};\nconst local=${JSON.stringify(localNames(distribution))};\nlet server;\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; 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`;
220
292
  }
221
293
  async function managerFor(root,app,options,manifest) {
222
294
  const dirs=[];let dir=app;while(true){dirs.push(dir);if(dir===root)break;dir=path.dirname(dir);}
@@ -237,27 +309,56 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
237
309
  const release=releaseMetadata??cli?.viniRelease;
238
310
  if(release&&!validRelease(release))fail('invalid CLI release metadata');
239
311
  const root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
240
- const app=await fs.realpath(path.resolve(root,options.appRoot??'.'));
312
+ const kit=path.join(root,'.vini-ds'),receiptPath=path.join(kit,'npm-install.json');await safeParents(root,receiptPath);
313
+ const kitStat=await exists(kit),receiptBytes=await fileBytes(receiptPath,true);let previous=null;
314
+ if(kitStat&&!receiptBytes)fail('existing .vini-ds belongs to another setup; migrate the private-GitHub Kit explicitly before npm init');
315
+ 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);}
316
+ if(options.command==='update'&&!previous)fail('no npm VINi setup to update; use init');
317
+ if(previous&&typeof previous.appRoot!=='string')fail('npm setup receipt has no valid app root');
318
+ const app=await fs.realpath(path.resolve(root,options.appRoot??previous?.appRoot??'.'));
241
319
  if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
242
320
  const manifestFile=path.join(app,'package.json'),manifest=json(await fileBytes(manifestFile),manifestFile);
243
321
  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
322
  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
323
  const manager=await managerFor(root,app,options,manifest);
248
324
  let entry;
249
325
  if(options.entry)entry=path.resolve(app,options.entry);
250
326
  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
327
  await safeParents(root,entry);if(entry!==app&&!entry.startsWith(app+path.sep))fail('entry must be inside app');
252
- const entryBefore=await fileBytes(entry),entryAfter=Buffer.from(transformEntry(text(entryBefore,entry),entry,distribution));
253
- const kit=path.join(root,'.vini-ds'),receiptPath=path.join(kit,'npm-install.json');await safeParents(root,receiptPath);
254
- const kitStat=await exists(kit),receiptBytes=await fileBytes(receiptPath,true);let previous=null;
255
- if(kitStat&&!receiptBytes)fail('existing .vini-ds belongs to another setup; migrate the private-GitHub Kit explicitly before npm init');
256
- 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);}
257
- if(options.command==='update'&&!previous)fail('no npm VINi setup to update; use init');
258
- const alias=(key)=>distribution[key]===`@vini/${key}`?distribution.version:`npm:${distribution[key]}@${distribution.version}`;
259
- 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');
260
- 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`);}
328
+ const entryBefore=await fileBytes(entry);let entryAfter,entryPreparation='ready';
329
+ try {entryAfter=Buffer.from(transformEntry(text(entryBefore,entry),entry,distribution));}
330
+ 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;}
331
+ if(previous){
332
+ 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');}
333
+ if(recordedApp!==root&&!recordedApp.startsWith(root+path.sep))fail('recorded npm app root is outside project');
334
+ if(recordedApp!==app)fail('selected app root differs from the recorded npm setup');
335
+ }
336
+ const targetLocal=localNames(distribution),priorLocal=previous?localNames(previous.distribution):null;
337
+ for(const section of ['dependencies','devDependencies','peerDependencies','optionalDependencies'])for(const [name,spec] of Object.entries(manifest[section]??{})){
338
+ for(const key of ['ui','tokens','agent'])for(const published of new Set([distribution[key],legacyPackages[key],`@vini/${key}`,nativeDsPackages[key]])){
339
+ const canonical=priorLocal?.[key]??targetLocal[key];
340
+ if(name===canonical){
341
+ if(!previous)fail(`existing ${canonical} dependency is not managed by this npm setup; migrate explicitly`);
342
+ if(section!==(key==='agent'?'devDependencies':'dependencies'))fail(`${canonical} appears in an unexpected dependency section; review the npm setup`);
343
+ }
344
+ if(name===targetLocal[key]&&targetLocal[key]!==canonical)fail(`existing ${name} dependency is not managed by this npm setup; migrate explicitly`);
345
+ 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`);
346
+ const value=typeof spec==='string'?spec.trim():'';
347
+ if(value===`npm:${published}`||value.startsWith(`npm:${published}@`)){
348
+ const recorded=previous&&name===canonical&&section===(key==='agent'?'devDependencies':'dependencies')&&previous.distribution[key]===published&&spec===`npm:${published}@${previous.distribution.version}`;
349
+ if(!recorded)fail(`unmanaged alias ${name} for ${published} requires an explicit manual-to-CLI migration; use one package identity`);
350
+ }
351
+ }
352
+ }
353
+ if(previous){
354
+ const sameNames=packageKeys.every(key=>previous.distribution[key]===distribution[key]);
355
+ 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));
356
+ if(!sameNames&&supportedFamilyChange&&compareVersions(distribution.version,previous.distribution.version)<=0)fail('package family migration requires a newer release; no downgrade is selected');
357
+ if(familyTransition(previous.distribution,distribution)==='unsupported')fail('package family transition is not supported; review the installed distribution before migration');
358
+ if(compareVersions(distribution.version,previous.distribution.version)<0)fail('installed release is newer than the requested release; no downgrade is selected');
359
+ }
360
+ const alias=(key)=>packageSpec(distribution,key);
361
+ 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
362
  const lockfile=path.join(app,manager==='npm'?'package-lock.json':'pnpm-lock.yaml');
262
363
  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
364
  const files=[manifestFile,lockfile,entry,configFile,agentsFile,skillFile,launchFile,setupFile,receiptPath];
@@ -269,11 +370,11 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
269
370
  const agents=Buffer.from(agentsMerge(before.get(agentsFile)?text(before.get(agentsFile),agentsFile):''));
270
371
  const current=await readInstallation(root,path.relative(root,app)||'.',distribution);
271
372
  const installedAligned=!!previous&&current.launcher.status==='matches-receipt'&&['ui','tokens','agent'].every(key=>current.installed[key].matchesReceipt);
272
- const plan={status:'plan-only',command:options.command??'init',projectRoot:root,appRoot:app,entry:path.relative(app,entry),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:'Restart or reconnect the project-local VINi MCP in the current client; then read vini://system/current, the affected component contract and check_updates in that client.',dependencies:{'@vini/ui':alias('ui'),'@vini/tokens':alias('tokens')},devDependencies:{'@vini/agent':alias('agent')},agent:'project-local Codex MCP + Skill',applicationPage:'not-verified',nativeClient:'not-verified',postUpdateSteps:[
273
- '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.',
274
- 'Reconnect the project-local VINi MCP in the current client and read vini://system/current, the affected component contract and check_updates there. A separate STDIO process does not verify the current client.'
275
- ],globalConfig:'unchanged',supported:'React 18, Vite direct createRoot(...).render(JSX), standalone npm/pnpm app'};
373
+ const migration=!!previous&&familyTransition(previous.distribution,distribution)==='manual-import-migration';
374
+ 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:'Reconnect the project-local VINi MCP in the current client. Restart the client only if reconnect is unavailable or was already attempted and the context remains stale; then read vini://system/current, the affected component contract and check_updates in that client.',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'};
276
375
  if(options.plan)return plan;
376
+ if(migration&&!options.importsMigrated)fail('review and migrate all project imports and configuration before update; then pass --imports-migrated');
377
+ if(previous&&!installedAligned)fail('installed packages or launcher differ from the receipt; resolve the mismatch before updating');
277
378
  const recoveryRoot=path.join(root,'.vini-ds-recovery');await safeParents(root,path.join(recoveryRoot,'placeholder'));
278
379
  const recoveryRootExisted=!!await exists(recoveryRoot);
279
380
  const modules=path.join(app,'node_modules');
@@ -285,11 +386,13 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
285
386
  const pm=async(args)=>runner(manager==='npm'?'npm':'corepack',manager==='npm'?args:['pnpm',...args],{cwd:app});
286
387
  const registry=options.registry?[`--registry=${options.registry}`]:[];
287
388
  try {
288
- 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'];
389
+ const next=structuredClone(manifest);next.dependencies={...next.dependencies};next.devDependencies={...next.devDependencies};
390
+ if(migration)for(const key of packageKeys){delete next.dependencies[priorLocal[key]];delete next.devDependencies[priorLocal[key]];}
391
+ 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];
289
392
  const manifestAfter=Buffer.from(JSON.stringify(next,null,2)+'\n');
290
393
  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;
291
394
  let verified=false;
292
- 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{}}
395
+ 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{}}
293
396
  if(verified){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'};}
294
397
  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);}
295
398
  if(moduleStat){await fs.rename(modules,path.join(backup,'node_modules'));modulesMoved=true;}
@@ -298,11 +401,13 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
298
401
  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]);}
299
402
  catch(error){installFailed=true;throw error;}
300
403
  expected.set(manifestFile,await fileBytes(manifestFile));expected.set(lockfile,await fileBytes(lockfile));
301
- const req=createRequire(manifestFile),packageRoots={};
302
- 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;}
404
+ const packageRoots={};
405
+ const [tokensEntry,uiEntry,agentEntry,skillEntry,setupEntry,reactEntry,reactDomEntry]=await freshResolve(manifestFile,[targetLocal.tokens,targetLocal.ui,`${targetLocal.agent}/mcp`,`${targetLocal.agent}/skill`,`${targetLocal.agent}/setup`,'react','react-dom'],app);
406
+ 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;}
303
407
  await verifyAgentContext(runner,packageRoots.agent.entry,distribution,app);
304
- 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`);
305
- const skill=await fileBytes(req.resolve('@vini/agent/skill')),setup=await fileBytes(req.resolve('@vini/agent/setup'));
408
+ const uiPeers=await freshResolve(path.join(packageRoots.ui.root,'package.json'),['react','react-dom'],app);
409
+ 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`);
410
+ const skill=await fileBytes(await projectModuleEntry(app,skillEntry)),setup=await fileBytes(await projectModuleEntry(app,setupEntry));
306
411
  const launch=Buffer.from(launcher(distribution,path.relative(root,app)||'.'));
307
412
  await write(entry,entryAfter);
308
413
  if(manifest.scripts?.build){buildAttempted=true;await pm(['run','build']);}
@@ -310,7 +415,10 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
310
415
  for(const [file,bytes]of [[launchFile,launch],[setupFile,setup],[configFile,config],[skillFile,skill],[agentsFile,agents]])await write(file,bytes);
311
416
  const receipt={installer:'vini-npm',distribution,appRoot:path.relative(root,app)||'.',entry:path.relative(app,entry),configTable,skillSha256:digest(skill),launcherSha256:digest(launch)};
312
417
  await write(receiptPath,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
313
- return {...plan,status:'installed',build:buildAttempted?'passed':'not-configured',recovery:backup};
418
+ const finalState=await readInstallation(root,path.relative(root,app)||'.',distribution);
419
+ const verification=verificationState(distribution,finalState);
420
+ if(!verification.installation.matchesTarget)fail('installed packages or launcher do not match the newly written receipt');
421
+ return {...plan,status:'installed',installed:finalState.installed,installedStatus:'matches-receipt',verification,build:buildAttempted?'passed':'not-configured',recovery:backup};
314
422
  } catch(error) {
315
423
  if(error.uncertainChildren){uncertain=true;throw new Error(`${error.message}; retained lock and recovery: ${backup}`);}
316
424
  if(!projectMutationStarted&&!modulesMoved)throw new Error(`${error.message}; no project files or dependencies changed; recovery retained: ${backup}`);
@@ -337,7 +445,7 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
337
445
  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}`);}
338
446
  if(!kitStat)await fs.rmdir(kit).catch(()=>{});
339
447
  }
340
- 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':''}`);
448
+ throw 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':''}`);
341
449
  } finally {if(!uncertain)await fs.rmdir(operationLock);}
342
450
  }
343
451
  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",
3
+ "version": "0.1.0-alpha.5",
4
4
  "type": "module",
5
5
  "description": "VINi React project and local agent setup",
6
6
  "bin": {
@@ -20,10 +20,10 @@
20
20
  "typescript": "5.5.4"
21
21
  },
22
22
  "viniDistribution": {
23
- "version": "0.1.0-alpha.3",
24
- "ui": "@timelex/vini-ui",
25
- "tokens": "@timelex/vini-tokens",
26
- "agent": "@timelex/vini-agent"
23
+ "version": "0.1.0-alpha.5",
24
+ "ui": "@vini-ds/ui",
25
+ "tokens": "@vini-ds/tokens",
26
+ "agent": "@vini-ds/agent"
27
27
  },
28
28
  "viniRelease": {
29
29
  "atlas": {
@@ -38,8 +38,8 @@
38
38
  "packageManifestSha256": "sha256:44fc4d1f985ebe9d66344ec2cdb45640023eab886028dc7bb8e0be07f8c989e7"
39
39
  },
40
40
  "changes": {
41
- "fromVersion": "0.1.0-alpha.2",
42
- "summary": "CLI и контекст агента уточняют проверку работающего приложения и MCP после обновления. Компоненты и токены не менялись; Atlas указан как подготовленный исходный снимок, а не deploy.",
41
+ "fromVersion": "0.1.0-alpha.4",
42
+ "summary": "Проверка выбранной версии, установленной связки и устаревшего MCP; отдельные результаты страницы и клиента.",
43
43
  "components": []
44
44
  }
45
45
  }