vini-ds 0.0.0-stage → 0.1.0-alpha.1

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 +8 -2
  2. package/cli.mjs +340 -0
  3. package/package.json +49 -4
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # VINi CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Connect with `npx vini-ds init`. This is a public alpha, 0.1.0-alpha.1; it supports the bounded setup described below. For a reproducible installation, use the exact version.
4
+
5
+ Preview: `npx vini-ds@0.1.0-alpha.1 init --plan`. Connect: `npx vini-ds@0.1.0-alpha.1 init`.
6
+
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
+
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.1 update --plan`, then run the same command without `--plan`. Restart the project-local agent and read `vini://system/current` to verify the installed context. 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.
package/cli.mjs ADDED
@@ -0,0 +1,340 @@
1
+ #!/usr/bin/env node
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { createRequire } from 'node:module';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { isDeepStrictEqual } from 'node:util';
8
+ import { spawn } from 'node:child_process';
9
+ import ts from 'typescript';
10
+
11
+ const self=fileURLToPath(import.meta.url);
12
+ const digest=value=>createHash('sha256').update(value).digest('hex');
13
+ const fail=message=>{throw new Error(`VINi: ${message}`);};
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'];
16
+ 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]';
18
+
19
+ export function parseArgs(args) {
20
+ if(args.length===1&&['--help','-h'].includes(args[0]))return {help:true};
21
+ const options={command:args[0]??'init',plan:false};
22
+ if(!['init','update','status'].includes(options.command))fail(usage);
23
+ const names={'--cwd':'cwd','--app-root':'appRoot','--entry':'entry','--package-manager':'packageManager','--registry':'registry'};
24
+ for(let i=1;i<args.length;i++) {
25
+ if(args[i]==='--plan'){if(options.plan)fail('duplicate --plan');options.plan=true;continue;}
26
+ if(args[i]==='--json'){if(options.json)fail('duplicate --json');options.json=true;continue;}
27
+ const key=names[args[i]];if(!key||options[key]||!args[i+1]||args[i+1].startsWith('--'))fail(usage);options[key]=args[++i];
28
+ }
29
+ if(options.packageManager&&!['npm','pnpm'].includes(options.packageManager))fail('only npm and pnpm are supported');
30
+ if(options.json&&options.command!=='status')fail('--json is supported by status');
31
+ if(options.command==='status'&&(options.plan||options.entry||options.packageManager))fail(usage);
32
+ 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
+ return options;
34
+ }
35
+ async function fileBytes(file,optional=false) {
36
+ const stat=await exists(file);if(!stat){if(optional)return null;fail(`missing ${file}`);}
37
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.size>4*1024*1024)fail(`expected bounded regular file: ${file}`);
38
+ return fs.readFile(file);
39
+ }
40
+ async function safeParents(root,file) {
41
+ const rel=path.relative(root,file);if(rel.startsWith('..'+path.sep)||path.isAbsolute(rel)||rel==='..')fail('file escapes project');
42
+ let current=root;
43
+ for(const part of rel.split(path.sep).slice(0,-1)){current=path.join(current,part);const stat=await exists(current);if(stat&&(stat.isSymbolicLink()||!stat.isDirectory()))fail(`unsafe project directory ${current}`);}
44
+ }
45
+ function text(bytes,label) {const value=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);if(value.charCodeAt(0)===0xfeff)fail(`${label}: BOM requires manual review`);return value;}
46
+ function json(bytes,label){try{return JSON.parse(text(bytes,label));}catch{fail(`invalid JSON: ${label}`);}}
47
+ function distributionCheck(value) {
48
+ if(!value||!/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/.test(value.version??''))fail('CLI distribution has no exact version');
49
+ 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
+ return value;
51
+ }
52
+ export function transformEntry(source,file='main.tsx',distribution) {
53
+ if(source.startsWith('\uFEFF'))fail('entry has a BOM; review it manually');
54
+ const ast=ts.createSourceFile(file,source,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
55
+ if(ast.parseDiagnostics.length)fail('entry has syntax errors');
56
+ const rootNames=new Set(),rootNamespaces=new Set(),providers=new Set(),imports=new Set();
57
+ for(const statement of ast.statements)if(ts.isImportDeclaration(statement)&&ts.isStringLiteral(statement.moduleSpecifier)) {
58
+ 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`);}
60
+ const clause=statement.importClause,bindings=clause?.namedBindings;
61
+ if(module==='react-dom/client') {
62
+ if(clause?.name)rootNamespaces.add(clause.name.text);
63
+ if(bindings&&ts.isNamespaceImport(bindings))rootNamespaces.add(bindings.name.text);
64
+ 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
+ }
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`);
68
+ }
69
+ const renders=[];
70
+ 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');
71
+ function visit(node){if(ts.isCallExpression(node)&&ts.isPropertyAccessExpression(node.expression)&&node.expression.name.text==='render'&&isCreate(node.expression.expression))renders.push(node);ts.forEachChild(node,visit);}
72
+ visit(ast);
73
+ if(renders.length!==1||renders[0].arguments.length!==1)fail('supported entry requires exactly one createRoot(...).render(JSX); use --entry or wire VINi explicitly');
74
+ const argument=renders[0].arguments[0];let jsx=argument;while(ts.isParenthesizedExpression(jsx))jsx=jsx.expression;
75
+ if(!ts.isJsxElement(jsx)&&!ts.isJsxSelfClosingElement(jsx)&&!ts.isJsxFragment(jsx))fail('render argument must be a JSX tree');
76
+ 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
+ let result=source;const prepend=css.filter(item=>!imports.has(item)).map(item=>`import ${JSON.stringify(item)};`);
78
+ 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);}
80
+ else if(found[0]!==jsx){
81
+ // A provider directly inside StrictMode/Fragment still covers the whole app.
82
+ const outer=ts.isJsxElement(jsx)?jsx.children:ts.isJsxFragment(jsx)?jsx.children:[];
83
+ const meaningful=outer.filter(node=>!ts.isJsxText(node)||node.text.trim());
84
+ if(meaningful.length!==1||meaningful[0]!==found[0])fail('existing ThemeBrandProvider covers only part of the root; review entry explicitly');
85
+ }
86
+ if(prepend.length)result=prepend.join('\n')+'\n'+result;
87
+ return result;
88
+ }
89
+ function configMerge(source,next,previous) {
90
+ if(source.includes('\r')||source.includes('"""')||source.includes("'''"))fail('Codex config multiline strings/CRLF need manual merge');
91
+ if(/^[ \t]*(?:mcp_servers|["']mcp_servers["'])[ \t]*[.=]/m.test(source))fail('inline Codex MCP settings need manual merge');
92
+ const headers=[...source.matchAll(/^[ \t]*\[([^\n]+)\][ \t]*(?:#.*)?$/gm)];
93
+ const related=headers.filter(m=>m[1].replace(/[\s'"\[\]]/g,'').startsWith('mcp_servers.vini-ds'));
94
+ if(related.length>1||(related.length===1&&related[0][0]!=='[mcp_servers.vini-ds]'))fail('ambiguous vini-ds config; preserve and migrate it manually');
95
+ if(!related.length)return source+(source&&!source.endsWith('\n')?'\n':'')+(source?'\n':'')+next+'\n';
96
+ const target=related[0],end=headers.find(m=>m.index>target.index)?.index??source.length;
97
+ const existing=source.slice(target.index,end).trimEnd();if(existing!==next&&existing!==previous)fail('existing vini-ds config is not managed by this npm installer; migrate explicitly');
98
+ const tail=source.slice(target.index,end).match(/\s*$/)?.[0]??'\n';return source.slice(0,target.index)+next+(tail||'\n')+source.slice(end);
99
+ }
100
+ function agentsMerge(source) {
101
+ 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
+ return source+(source&&!source.endsWith('\n')?'\n':'')+(source?'\n':'')+pointer+'\n';
103
+ }
104
+ export async function run(executable,args,{cwd,timeout=600000,env=process.env}={}) {
105
+ 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);};
108
+ 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);});
110
+ 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
+ });
112
+ }
113
+ async function resolveManifest(req,name,subpath='') {
114
+ const resolved=req.resolve(name+subpath);let dir=path.dirname(resolved);
115
+ 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
+ }
117
+ async function verifyAgentContext(runner,entry,distribution,cwd) {
118
+ const result=JSON.parse(await runner(process.execPath,[entry,'--check'],{cwd,timeout:10000}));
119
+ if(result.ok!==true||result.name!==distribution.agent||result.version!==distribution.version)fail('installed agent selfcheck does not match the CLI distribution');
120
+ 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
+ return result;
122
+ }
123
+ // This is a description of one published transition, never a universal changelog.
124
+ function transition(release,fromVersion,toVersion) {
125
+ const changes=release?.changes;
126
+ 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};
127
+ return {status:'available',from:fromVersion,to:toVersion,summary:changes.summary,components:changes.components};
128
+ }
129
+ async function readInstallation(root,requestedApp,expected) {
130
+ const receiptPath=path.join(root,'.vini-ds/npm-install.json');await safeParents(root,receiptPath);
131
+ const raw=await fileBytes(receiptPath,true);let receipt=null;
132
+ 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
+ const relative=requestedApp??receipt?.appRoot??'.';const app=await fs.realpath(path.resolve(root,relative));
134
+ if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
135
+ const manifestPath=path.join(app,'package.json');await safeParents(root,manifestPath);
136
+ const manifest=json(await fileBytes(manifestPath),manifestPath);const req=createRequire(manifestPath);
137
+ const dependencies={...manifest.optionalDependencies,...manifest.devDependencies,...manifest.dependencies};
138
+ 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
+ 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;}
143
+ 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;
145
+ installed[key]={declared,actual,error,matchesLauncher:!!actual&&actual.name===expected[key]&&actual.version===expected.version,matchesReceipt:!!actual&&!!receipt&&actual.name===receipt.distribution[key]&&actual.version===receipt.distribution.version&&declared===recorded};
146
+ }
147
+ let launcher='not-installed';
148
+ 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
+ let agentContext=null;
150
+ if(installedAgent){const file=path.join(installedAgent.root,'context/current.json');const bytes=await fileBytes(file,true);if(bytes){const current=json(bytes,file);agentContext={version:current.version??null,baseline:current.baseline??null,release:current.viniRelease??null};}}
151
+ return {projectRoot:root,appRoot:app,receipt:receipt?{distribution:receipt.distribution,appRoot:receipt.appRoot}:null,launcher:{status:launcher,expected:receipt?.distribution??null},installed,lockfiles,agentContext};
152
+ }
153
+ 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
+ function validRelease(value) {
155
+ const safe=x=>typeof x==='string'&&x.length>0&&x.length<=2000&&!/[\u0000-\u001f\u007f]/u.test(x);
156
+ const web=x=>{if(!safe(x))return false;try{const u=new URL(x);return u.protocol==='https:'&&!u.username&&!u.password&&!u.search&&!u.hash;}catch{return false;}};
157
+ return value===null||!!value&&web(value.atlas?.url)&&/^sha256:[0-9a-f]{64}$/u.test(value.atlas.archiveSha256??'')&&safe(value.atlas.siteRelease)&&/^[0-9a-f]{40}$/u.test(value.atlas.commit??'')&&safe(value.delivery?.id)&&/^sha256:[0-9a-f]{64}$/u.test(value.delivery.manifestSha256??'')&&/^sha256:[0-9a-f]{64}$/u.test(value.delivery.packageManifestSha256??'')&&safe(value.changes?.fromVersion)&&safe(value.changes?.summary)&&Array.isArray(value.changes?.components)&&value.changes.components.length<=500&&value.changes.components.every(x=>safe(x)&&x.length<=100);
158
+ }
159
+ function compareVersions(a,b) {
160
+ const parse=x=>{const m=/^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?$/u.exec(x??'');if(!m)throw new Error('invalid published version');return {core:m.slice(1,4).map(Number),pre:m[4]?.split('.')??null};};
161
+ const x=parse(a),y=parse(b);for(let i=0;i<3;i++)if(x.core[i]!==y.core[i])return Math.sign(x.core[i]-y.core[i]);
162
+ if(!x.pre||!y.pre)return x.pre? -1:y.pre?1:0;
163
+ for(let i=0;i<Math.max(x.pre.length,y.pre.length);i++){const l=x.pre[i],r=y.pre[i];if(l===undefined||r===undefined)return l===undefined?-1:1;if(l===r)continue;const ln=/^\d+$/u.test(l),rn=/^\d+$/u.test(r);if(ln&&rn)return Math.sign(Number(l)-Number(r));if(ln!==rn)return ln?-1:1;return l<r?-1:1;}return 0;
164
+ }
165
+ function registryUrl(raw) {
166
+ const url=new URL(raw);if(url.username||url.password||url.search||url.hash||(url.protocol!=='https:'&&!(url.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(url.hostname))))fail('registry must use HTTPS (HTTP localhost is allowed for testing)');
167
+ if(!url.pathname.endsWith('/'))url.pathname+='/';return url;
168
+ }
169
+ async function requestMetadata(url) {
170
+ const response=await fetch(url,{headers:{accept:'application/vnd.npm.install-v1+json, application/json'},redirect:'error',signal:AbortSignal.timeout(8000)});
171
+ if(!response.ok)throw new Error(`registry HTTP ${response.status}`);
172
+ const length=Number(response.headers.get('content-length')??0);if(length>2*1024*1024)throw new Error('registry metadata too large');
173
+ const reader=response.body?.getReader();if(!reader)throw new Error('registry metadata body missing');let total=0,chunks=[];
174
+ 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();}
175
+ return JSON.parse(Buffer.concat(chunks.map(x=>Buffer.from(x))).toString('utf8'));
176
+ }
177
+ async function availableRelease(registry,cliName,expected,request=requestMetadata) {
178
+ try {
179
+ const root=registryUrl(registry),endpoint=(name,version)=>new URL(`${encodeURIComponent(name)}/${encodeURIComponent(version)}`,root).href;
180
+ const latest=await request(endpoint(cliName,'latest'));
181
+ if(latest?.name!==cliName||!validIntegrity(latest?.dist?.integrity)||latest.version!==latest.viniDistribution?.version)throw new Error('invalid latest CLI identity or integrity');
182
+ const distribution=distributionCheck(latest.viniDistribution);
183
+ if(!validRelease(latest.viniRelease??null))throw new Error('invalid release metadata');
184
+ if(['ui','tokens','agent'].some(key=>distribution[key]!==expected[key]))throw new Error('latest CLI publishes a different package family');
185
+ const entries=await Promise.all(['ui','tokens','agent'].map(async key=>{
186
+ const info=await request(endpoint(distribution[key],distribution.version));
187
+ 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');}
189
+ if(key==='agent'&&!isDeepStrictEqual(info.viniRelease??null,latest.viniRelease??null))throw new Error('CLI and agent release metadata differ');
190
+ return [key,{name:info.name,version:info.version,integrity:info.dist.integrity}];
191
+ }));const packages=Object.fromEntries(entries);
192
+ return {status:'available',distribution,cli:{name:latest.name,version:latest.version,integrity:latest.dist.integrity},packages,release:latest.viniRelease??null};
193
+ } catch(error) {return {status:'unavailable',reason:String(error.message??error)};}
194
+ }
195
+ export async function status(options={},suppliedDistribution,{request=requestMetadata,cliName,release}={}) {
196
+ const cli=suppliedDistribution?{name:cliName??'vini-ds',viniDistribution:suppliedDistribution,viniRelease:release}:json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package');
197
+ const expected=distributionCheck(cli.viniDistribution),root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
198
+ const state=await readInstallation(root,options.appRoot,expected);
199
+ const registry=options.registry??process.env.npm_config_registry??'https://registry.npmjs.org/';
200
+ 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);
202
+ const installedVersion=aligned?state.receipt.distribution.version:null;
203
+ const installedToLauncher=aligned&&['ui','tokens','agent'].every(key=>state.installed[key].matchesLauncher);
204
+ const latest=published.status==='available'?published.distribution.version:null;
205
+ 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};
209
+ }
210
+ export function formatStatus(result) {
211
+ 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');
212
+ const available=result.available.status==='available'?result.available.distribution.version:`unknown (${result.available.reason})`;
213
+ const changes=result.changes.status==='available'?`\nChanges: ${result.changes.summary}\nComponents: ${result.changes.components.join(', ')||'none listed'}`:'';
214
+ const release=result.available.release;
215
+ 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}`;
217
+ }
218
+ 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`;
220
+ }
221
+ async function managerFor(root,app,options,manifest) {
222
+ const dirs=[];let dir=app;while(true){dirs.push(dir);if(dir===root)break;dir=path.dirname(dir);}
223
+ let manager=options.packageManager;
224
+ for(const directory of dirs){for(const foreign of ['yarn.lock','bun.lock','bun.lockb'])if(await exists(path.join(directory,foreign)))fail('this alpha supports npm/pnpm only');
225
+ const npm=await exists(path.join(directory,'package-lock.json')),pnpm=await exists(path.join(directory,'pnpm-lock.yaml'));
226
+ if(npm&&pnpm)fail('mixed npm/pnpm lockfiles');const lockManager=npm?'npm':pnpm?'pnpm':null;
227
+ if(lockManager){if(manager&&manager!==lockManager)fail('package-manager conflicts with lockfile');manager=lockManager;}
228
+ if(await exists(path.join(directory,'pnpm-workspace.yaml'))||directory!==app&&(await exists(path.join(directory,'package-lock.json'))))fail('workspace install is not supported by this alpha; choose an independent app root');
229
+ }
230
+ if(manifest.packageManager){const declared=/^(npm|pnpm)@/.exec(manifest.packageManager)?.[1];if(!declared||manager&&manager!==declared)fail('unsupported or conflicting packageManager');manager=declared;}
231
+ if(manifest.workspaces)fail('workspace root is not supported by this alpha; choose a standalone Vite app');
232
+ return manager??'npm';
233
+ }
234
+ export async function init(options={},suppliedDistribution,{runner=run,releaseMetadata}={}) {
235
+ const cli=suppliedDistribution?null:json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package');
236
+ const distribution=distributionCheck(suppliedDistribution??cli.viniDistribution);
237
+ const release=releaseMetadata??cli?.viniRelease;
238
+ if(release&&!validRelease(release))fail('invalid CLI release metadata');
239
+ const root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
240
+ const app=await fs.realpath(path.resolve(root,options.appRoot??'.'));
241
+ if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
242
+ const manifestFile=path.join(app,'package.json'),manifest=json(await fileBytes(manifestFile),manifestFile);
243
+ 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
+ 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
+ const manager=await managerFor(root,app,options,manifest);
248
+ let entry;
249
+ if(options.entry)entry=path.resolve(app,options.entry);
250
+ 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
+ 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`);}
261
+ const lockfile=path.join(app,manager==='npm'?'package-lock.json':'pnpm-lock.yaml');
262
+ 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
+ const files=[manifestFile,lockfile,entry,configFile,agentsFile,skillFile,launchFile,setupFile,receiptPath];
264
+ const before=new Map();for(const file of files){await safeParents(root,file);before.set(file,await fileBytes(file,true));}
265
+ if(before.get(skillFile)&&(!previous||digest(before.get(skillFile))!==previous.skillSha256))fail('existing VINi Skill is modified or belongs to another setup');
266
+ if(previous&&(!before.get(launchFile)||digest(before.get(launchFile))!==previous.launcherSha256))fail('existing VINi launcher was modified');
267
+ const configTable=`[mcp_servers.vini-ds]\ncommand = "node"\nargs = [${JSON.stringify(launchFile)}]\nenabled = true\nstartup_timeout_sec = 10`;
268
+ const config=Buffer.from(configMerge(before.get(configFile)?text(before.get(configFile),configFile):'',configTable,previous?.configTable));
269
+ const agents=Buffer.from(agentsMerge(before.get(agentsFile)?text(before.get(agentsFile),agentsFile):''));
270
+ const current=await readInstallation(root,path.relative(root,app)||'.',distribution);
271
+ 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 the project-local agent after updating; then check vini://system/current.',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'};
273
+ if(options.plan)return plan;
274
+ const recoveryRoot=path.join(root,'.vini-ds-recovery');await safeParents(root,path.join(recoveryRoot,'placeholder'));
275
+ const recoveryRootExisted=!!await exists(recoveryRoot);
276
+ const modules=path.join(app,'node_modules');
277
+ const moduleStat=await exists(modules);if(moduleStat&&(moduleStat.isSymbolicLink()||!moduleStat.isDirectory()))fail('node_modules must be a real directory');
278
+ 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;}
279
+ 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;}
280
+ const expected=new Map(before);let modulesMoved=false,projectMutationStarted=false,installFailed=false,buildAttempted=false,uncertain=false;
281
+ const write=async(file,bytes)=>{await safeParents(root,file);const current=await fileBytes(file,true),expectedBytes=expected.get(file);if(current===null?expectedBytes!==null:expectedBytes===null||!current.equals(expectedBytes))fail(`concurrent change: ${file}`);await fs.mkdir(path.dirname(file),{recursive:true});const temporary=path.join(path.dirname(file),`.vini-${randomUUID()}`);await fs.writeFile(temporary,bytes,{flag:'wx',mode:(await exists(file))?.mode&0o777||0o600});await fs.rename(temporary,file);expected.set(file,bytes);};
282
+ const pm=async(args)=>runner(manager==='npm'?'npm':'corepack',manager==='npm'?args:['pnpm',...args],{cwd:app});
283
+ const registry=options.registry?[`--registry=${options.registry}`]:[];
284
+ try {
285
+ 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'];
286
+ const manifestAfter=Buffer.from(JSON.stringify(next,null,2)+'\n');
287
+ const unchanged=previous&&JSON.stringify(previous.distribution)===JSON.stringify(distribution)&&before.get(manifestFile).equals(manifestAfter)&&entryBefore.equals(entryAfter)&&before.get(configFile)?.equals(config)&&before.get(agentsFile)?.equals(agents)&&before.get(skillFile)!==null&&before.get(setupFile)!==null;
288
+ let verified=false;
289
+ 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{}}
290
+ 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'};}
291
+ for(const [file,bytes]of before)if(bytes!==null){const target=path.join(backup,'files',path.relative(root,file));await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,bytes);}
292
+ if(moduleStat){await fs.rename(modules,path.join(backup,'node_modules'));modulesMoved=true;}
293
+ projectMutationStarted=true;
294
+ await write(manifestFile,manifestAfter);
295
+ try {await pm(manager==='npm'?['install','--ignore-scripts','--strict-peer-deps','--no-audit','--no-fund',...registry]:['install','--ignore-scripts','--config.strict-peer-dependencies=true','--no-frozen-lockfile',...registry]);}
296
+ catch(error){installFailed=true;throw error;}
297
+ expected.set(manifestFile,await fileBytes(manifestFile));expected.set(lockfile,await fileBytes(lockfile));
298
+ const req=createRequire(manifestFile),packageRoots={};
299
+ 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;}
300
+ await verifyAgentContext(runner,packageRoots.agent.entry,distribution,app);
301
+ 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`);
302
+ const skill=await fileBytes(req.resolve('@vini/agent/skill')),setup=await fileBytes(req.resolve('@vini/agent/setup'));
303
+ const launch=Buffer.from(launcher(distribution,path.relative(root,app)||'.'));
304
+ await write(entry,entryAfter);
305
+ if(manifest.scripts?.build){buildAttempted=true;await pm(['run','build']);}
306
+ for(const file of [manifestFile,lockfile,entry]){const bytes=await fileBytes(file);if(!bytes.equals(expected.get(file)))fail(`project files changed during build: ${file}`);}
307
+ for(const [file,bytes]of [[launchFile,launch],[setupFile,setup],[configFile,config],[skillFile,skill],[agentsFile,agents]])await write(file,bytes);
308
+ const receipt={installer:'vini-npm',distribution,appRoot:path.relative(root,app)||'.',entry:path.relative(app,entry),configTable,skillSha256:digest(skill),launcherSha256:digest(launch)};
309
+ await write(receiptPath,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
310
+ return {...plan,status:'installed',build:buildAttempted?'passed':'not-configured',recovery:backup};
311
+ } catch(error) {
312
+ if(error.uncertainChildren){uncertain=true;throw new Error(`${error.message}; retained lock and recovery: ${backup}`);}
313
+ if(!projectMutationStarted&&!modulesMoved)throw new Error(`${error.message}; no project files or dependencies changed; recovery retained: ${backup}`);
314
+ const issues=[];
315
+ let mayRecover=!installFailed;
316
+ if(installFailed)try{
317
+ // A completed package-manager failure may have written a partial lock and
318
+ // modules. Preserve those outputs, but only restore while our manifest
319
+ // and every other protected project file still match the last completed
320
+ // stage. A user edit to any of those files keeps the whole recovery manual.
321
+ for(const file of files.filter(file=>file!==lockfile)){
322
+ const current=await fileBytes(file,true),exp=expected.get(file);
323
+ if(current===null?exp!==null:exp===null||!current.equals(exp))throw new Error(`${path.relative(root,file)} changed during package installation`);
324
+ }
325
+ const partialModules=await exists(modules);
326
+ if(partialModules&&(partialModules.isSymbolicLink()||!partialModules.isDirectory()))throw new Error('node_modules changed type during package installation');
327
+ const partialLock=await fileBytes(lockfile,true);
328
+ if(partialLock!==null){const retained=path.join(backup,'failed-files',path.relative(root,lockfile));await fs.mkdir(path.dirname(retained),{recursive:true});await fs.writeFile(retained,partialLock,{flag:'wx'});}
329
+ expected.set(lockfile,partialLock);
330
+ mayRecover=true;
331
+ }catch(recoveryError){issues.push(`package-manager recovery requires review: ${recoveryError.message}`);}
332
+ if(mayRecover) {
333
+ for(const [file,bytes]of before){try{const current=await fileBytes(file,true),exp=expected.get(file);if(current===null?exp!==null:exp===null||!current.equals(exp))throw new Error('changed after last completed step');if(bytes===null){if(current)await fs.unlink(file);}else await write(file,bytes);}catch(e){issues.push(`${path.relative(root,file)}: ${e.message}`);}}
334
+ try{const failed=await exists(modules);if(failed){if(failed.isSymbolicLink()||!failed.isDirectory())throw new Error('node_modules changed type');await fs.rename(modules,path.join(backup,'node_modules-failed'));}if(modulesMoved)await fs.rename(path.join(backup,'node_modules'),modules);}catch(e){issues.push(`node_modules: ${e.message}`);}
335
+ if(!kitStat)await fs.rmdir(kit).catch(()=>{});
336
+ }
337
+ 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':''}`);
338
+ } finally {if(!uncertain)await fs.rmdir(operationLock);}
339
+ }
340
+ 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,51 @@
1
1
  {
2
2
  "name": "vini-ds",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.1",
4
+ "type": "module",
5
+ "description": "VINi React project and local agent setup",
6
+ "bin": {
7
+ "vini": "cli.mjs"
8
+ },
9
+ "engines": {
10
+ "node": ">=20"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "files": [
16
+ "cli.mjs",
17
+ "README.md"
18
+ ],
19
+ "dependencies": {
20
+ "typescript": "5.5.4"
21
+ },
22
+ "viniDistribution": {
23
+ "version": "0.1.0-alpha.1",
24
+ "ui": "@timelex/vini-ui",
25
+ "tokens": "@timelex/vini-tokens",
26
+ "agent": "@timelex/vini-agent"
27
+ },
28
+ "viniRelease": {
29
+ "atlas": {
30
+ "url": "https://vini-atlas-pilot.layero.app/",
31
+ "archiveSha256": "sha256:d34523af2875a85b00fb41177ec4e3d539d6281cef23523b6253156781503647",
32
+ "siteRelease": "public-atlas-20261103-final",
33
+ "commit": "5b77933f6f7c37bea346e8e2276fc4952086be1d"
34
+ },
35
+ "delivery": {
36
+ "id": "candidate-33650c3731824b54",
37
+ "manifestSha256": "sha256:2d5f20b571a1ca5d330e46641c044afa5c97b14477ad83bfe1670df9b464893a",
38
+ "packageManifestSha256": "sha256:e937711fe54769b392b1cffc2982b4801e1339eee87ddbc1e6f726916bc06d8e"
39
+ },
40
+ "changes": {
41
+ "fromVersion": "0.1.0-alpha.0",
42
+ "summary": "Среди изменений — компоненты компоновки Container, Grid, Inline и Stack. Пакеты UI и токенов обновлены до сборки Atlas от 03.11.2026; в CLI добавлены проверка версии и план обновления, в MCP — проверка обновлений. Перечень изменений компонентов не является полным.",
43
+ "components": [
44
+ "Container",
45
+ "Grid",
46
+ "Inline",
47
+ "Stack"
48
+ ]
49
+ }
50
+ }
51
+ }