vini-ds 0.1.0-alpha.11 → 0.1.0-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,15 +1,21 @@
1
1
  # VINi CLI
2
2
 
3
- Connect with `npx vini-ds init`. This is a public alpha, 0.1.0-alpha.11; it supports the bounded setup described below. For a reproducible installation, use the exact version.
3
+ Connect with `npx vini-ds init`. This is a public alpha, 0.1.0-alpha.14; 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.11 init --plan`. Connect: `npx vini-ds@0.1.0-alpha.11 init`.
5
+ Preview: `npx vini-ds@0.1.0-alpha.14 init --plan`. Connect: `npx vini-ds@0.1.0-alpha.14 init`.
6
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.
7
+ Requires an existing Vite project with matching React and React DOM ^18.2.0 or ^19.3.1 and Node 20+. The installer does not edit the React dependency declarations in package.json. Check the lockfile and installed versions after installation; the package manager may resolve dependencies again. 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. A package status of current does not verify the open application page or the MCP connection in the current client. Review the suggested exact version with `npx vini-ds@0.1.0-alpha.11 update --plan`. For the name migration, complete the manual review below and use --imports-migrated; other updates use the same command without --plan. Identify the dev or preview server serving the original application URL. If it still serves old assets, update or restart only that server when its ownership and authorization are clear; otherwise ask its owner. Reload the same URL and exercise the affected component; never terminate an unidentified process. In the current project and client, call the connection's `refresh_connection` with the exact selected target when available. For a legacy connection or incompatible interface reconnect the project MCP once; restart the client only if reconnect is unavailable or already failed. In the same project and client read `vini://system/current`, the affected component contract, and `check_updates`; compare their versions with the target, installed packages and receipt. If the context is stale, follow the refresh or reconnect steps and repeat the checks instead of reinstalling packages just to refresh it. A separate STDIO process does not verify the current client. Treat package installation, the application page, and the current MCP client as separate results; if a check cannot be performed, report it as not verified. Update creates a recovery backup; if installation fails, inspect the reported recovery path before retrying. Previously installed private-GitHub Kits need an explicit migration and are not overwritten.
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.14 update --plan`. For the name migration, complete the manual review below and use --imports-migrated; other updates use the same command without --plan. Identify the dev or preview server serving the original application URL. If it still serves old assets, update or restart only that server when its ownership and authorization are clear; otherwise ask its owner. Reload the same URL and exercise the affected component; never terminate an unidentified process. In the current project and client, call the connection's `refresh_connection` with the exact selected target when available. For a legacy connection or incompatible interface reconnect the project MCP once; restart the client only if reconnect is unavailable or already failed. In the same project and client read `vini://system/current`, the affected component contract, and `check_updates`; compare their versions with the target, installed packages and receipt. If the context is stale, follow the refresh or reconnect steps and repeat the checks instead of reinstalling packages just to refresh it. A separate STDIO process does not verify the current client. Treat package installation, the application page, and the current MCP client as separate results; if a check cannot be performed, report it as not verified. Update creates a recovery backup; if installation fails, inspect the reported recovery path before retrying. Previously installed private-GitHub Kits need an explicit migration and are not overwritten.
10
10
 
11
11
  ## Migrating existing projects to @vini-ds
12
12
 
13
- Confirm the exact new CLI and all three packages are actually published before migrating. For a CLI-managed installation, run `npx vini-ds@0.1.0-alpha.11 update --plan` and review the existing receipt and planned dependency changes. Save the project state and manually review and replace every old `@vini/*` or `@timelex/vini-*` import, CSS path, configuration and other reference with the appropriate `@vini-ds/*` name. The CLI does not rewrite arbitrary project sources. Once that review is complete, run `npx vini-ds@0.1.0-alpha.11 update --imports-migrated`; the flag records your review, not proof of it. The CLI validates the entry, avoids an extra provider and replaces the managed dependencies without aliases. Check the build, lockfile and affected application scenario, then reconnect and verify the actual MCP client.
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.14 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.14 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
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.
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 using older package names 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.
16
+
17
+ ## Adopting an existing native installation
18
+
19
+ For a complete, directly installed pair of `@vini-ds/ui` and `@vini-ds/tokens` at the same version, first run `npx vini-ds@0.1.0-alpha.14 init --plan --adopt-manual`. Review the detected versions, React compatibility, source observations and proposed changes. Use `--cwd` for the project root, `--app-root` when the application is nested, and `--entry` when its entry needs to be selected explicitly. When the plan is ready, run the same command without `--plan`. Adoption preserves the installed UI and tokens version and existing entry, CSS imports and provider; it installs the agent at that same version and keeps a recovery backup. It is not an update to the CLI version. Repeating the completed adoption preserves the existing setup.
20
+
21
+ The plan uses static source evidence; it does not establish what renders in the browser or whether the current Codex client is connected. Verify those separately. A shared or symbolic-link `node_modules` is read for diagnostics but blocks adoption without changing its target; arrange an independently managed application directory before applying. Incomplete, mixed, incompatible or aliased installations require individual review. Older package families still follow the reviewed migration above.
package/cli.mjs CHANGED
@@ -7,10 +7,12 @@ import { isDeepStrictEqual, promisify } from 'node:util';
7
7
  import { execFile, spawn } from 'node:child_process';
8
8
  import ts from 'typescript';
9
9
  import { compareVersions, isExactVersion } from './version.mjs';
10
+ import { diagnoseProject } from './project-diagnostics.mjs';
10
11
 
11
12
  const self=fileURLToPath(import.meta.url);
12
13
  const execFileAsync=promisify(execFile);
13
14
  const digest=value=>createHash('sha256').update(value).digest('hex');
15
+ const shellArg=value=>/^[A-Za-z0-9_./-]+$/u.test(value)?value:`'${value.replaceAll("'", "'\\''")}'`;
14
16
  const fail=message=>{throw new Error(`VINi: ${message}`);};
15
17
  const exists=async file=>fs.lstat(file).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
16
18
  const legacyPackages={ui:'@timelex/vini-ui',tokens:'@timelex/vini-tokens',agent:'@timelex/vini-agent'};
@@ -23,6 +25,9 @@ const pageCheck='Identify the dev or preview server serving the original applica
23
25
  const clientCheck='In the current project and client, use this connection’s refresh_connection with the exact selected target when available; then read vini://system/current, the affected component contract and check_updates through that connection and compare them with the target and installed packages. For a legacy connection or incompatible interface, reconnect the project MCP once; restart the client only if reconnect is unavailable or already failed. Do not reinstall packages only to refresh the connection. A separate STDIO process does not verify the current client; report unavailable checks as not verified.';
24
26
  const generationPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
25
27
  const isGeneration=value=>typeof value==='string'&&value.length===36&&generationPattern.test(value);
28
+ // Interpret only the exact simple caret ranges this CLI can prove; anything
29
+ // else is reported unknown instead of guessing semver compatibility.
30
+ function peerAccepts(range,version){return typeof range==='string'&&typeof version==='string'&&range.split('||').some(part=>{const match=/^\s*\^(\d+)\.(\d+)\.(\d+)\s*$/u.exec(part),v=/^(\d+)\.(\d+)\.(\d+)$/u.exec(version);return !!match&&!!v&&Number(match[1])>0&&Number(v[1])===Number(match[1])&&(Number(v[2])>Number(match[2])||Number(v[2])===Number(match[2])&&Number(v[3])>=Number(match[3]));});}
26
31
  function validateNativeManifest(info,key,distribution){
27
32
  if(!isNativeDs(distribution))return;
28
33
  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`);
@@ -32,7 +37,9 @@ function validateNativeManifest(info,key,distribution){
32
37
  }
33
38
  }
34
39
  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 -->';
35
- const usage='vini init|update [--plan] [--imports-migrated] | status [--json] [--cwd PROJECT] [--app-root APP] [--entry src/main.tsx] [--package-manager npm|pnpm] [--registry HTTPS_URL]';
40
+ const usage='vini init [--plan] [--adopt-manual] | update [--plan] [--imports-migrated] | status [--json] [--cwd PROJECT] [--app-root APP] [--entry src/main.tsx] [--package-manager npm|pnpm] [--registry HTTPS_URL]';
41
+ // The package builder disables 19 for a retained delivery whose UI peers do not include it.
42
+ const supportedReact19 = true;
36
43
 
37
44
  export function parseArgs(args) {
38
45
  if(args.length===1&&['--help','-h'].includes(args[0]))return {help:true};
@@ -43,12 +50,14 @@ export function parseArgs(args) {
43
50
  if(args[i]==='--plan'){if(options.plan)fail('duplicate --plan');options.plan=true;continue;}
44
51
  if(args[i]==='--json'){if(options.json)fail('duplicate --json');options.json=true;continue;}
45
52
  if(args[i]==='--imports-migrated'){if(options.importsMigrated)fail('duplicate --imports-migrated');options.importsMigrated=true;continue;}
53
+ if(args[i]==='--adopt-manual'){if(options.adoptManual)fail('duplicate --adopt-manual');options.adoptManual=true;continue;}
46
54
  const key=names[args[i]];if(!key||options[key]||!args[i+1]||args[i+1].startsWith('--'))fail(usage);options[key]=args[++i];
47
55
  }
48
56
  if(options.packageManager&&!['npm','pnpm'].includes(options.packageManager))fail('only npm and pnpm are supported');
49
57
  if(options.json&&options.command!=='status')fail('--json is supported by status');
50
58
  if(options.importsMigrated&&options.command!=='update')fail('--imports-migrated is supported by update');
51
- if(options.command==='status'&&(options.plan||options.entry||options.packageManager))fail(usage);
59
+ if(options.adoptManual&&options.command!=='init')fail('--adopt-manual is supported by init');
60
+ if(options.command==='status'&&(options.plan||options.packageManager))fail(usage);
52
61
  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)');}
53
62
  return options;
54
63
  }
@@ -150,15 +159,15 @@ export async function run(executable,args,{cwd,timeout=600000,env=process.env,st
150
159
  child.on('error',error=>finish(error));child.on('close',code=>{if(timed)return;finish(code===0?null:new Error(`${executable} exited ${code}:\n${output}`));});
151
160
  });
152
161
  }
153
- async function projectModuleEntry(app,entry) {
162
+ async function projectModuleEntry(app,entry,{observeLinked=false}={}) {
154
163
  const modules=path.join(app,'node_modules'),stat=await exists(modules);
155
- if(!stat||stat.isSymbolicLink()||!stat.isDirectory())fail('node_modules must be a real project directory');
164
+ if(!stat||(!stat.isDirectory()&&!(observeLinked&&stat.isSymbolicLink())))fail('node_modules must be a real project directory');
156
165
  const root=await fs.realpath(modules),resolved=await fs.realpath(entry);
157
166
  if(!resolved.startsWith(root+path.sep))fail('installed package resolves outside project node_modules');
158
167
  return resolved;
159
168
  }
160
- async function manifestForEntry(resolved,name,app) {
161
- resolved=await projectModuleEntry(app,resolved);let dir=path.dirname(resolved);
169
+ async function manifestForEntry(resolved,name,app,options) {
170
+ resolved=await projectModuleEntry(app,resolved,options);let dir=path.dirname(resolved);
162
171
  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;}
163
172
  }
164
173
  // Node caches resolved pnpm symlink targets in-process. A completed install may
@@ -200,20 +209,55 @@ async function readInstallation(root,requestedApp,expected) {
200
209
  const manifestBytes=await fileBytes(manifestPath),manifest=json(manifestBytes,manifestPath);
201
210
  const dependencies={...manifest.optionalDependencies,...manifest.devDependencies,...manifest.dependencies};
202
211
  const lockfiles=[];for(const name of ['package-lock.json','pnpm-lock.yaml']){const bytes=await fileBytes(path.join(app,name),true);if(bytes)lockfiles.push({name,sha256:`sha256:${digest(bytes)}`});}
203
- const installed={};let installedAgent;
212
+ const modulePath=path.join(app,'node_modules'),moduleStat=await exists(modulePath);
213
+ const modules=moduleStat?.isSymbolicLink()?{status:'linked',target:await fs.realpath(modulePath).catch(()=>null)}:moduleStat?.isDirectory()?{status:'local',target:await fs.realpath(modulePath)}:{status:moduleStat?'unsupported':'missing',target:null};
214
+ const installed={};let installedAgent,uiPeers=null,uiRoot=null;
204
215
  const keys=['ui','tokens','agent'],local=localNames(receipt?.distribution??expected),resolved=await freshResolveMaybe(manifestPath,keys.map(key=>`${local[key]}${key==='agent'?'/mcp':''}`),app);
205
216
  for(const [index,key] of keys.entries()) {
206
217
  const alias=local[key];let actual=null,error=null,manifestSha256=null;
207
- try{if(resolved[index].error){const problem=new Error('not resolvable');problem.code=resolved[index].error;throw problem;}const pkg=await manifestForEntry(resolved[index].path,alias,app);validateNativeManifest(pkg.manifest,key,receipt?.distribution??expected);actual={name:pkg.manifest.name,version:pkg.manifest.version};manifestSha256=`sha256:${digest(JSON.stringify(pkg.manifest))}`;if(key==='agent')installedAgent=pkg;}
218
+ 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,{observeLinked:true});validateNativeManifest(pkg.manifest,key,{...(receipt?.distribution??expected),version:pkg.manifest.version});actual={name:pkg.manifest.name,version:pkg.manifest.version};manifestSha256=`sha256:${digest(JSON.stringify(pkg.manifest))}`;if(key==='agent')installedAgent=pkg;if(key==='ui'){uiPeers=pkg.manifest.peerDependencies??{};uiRoot=pkg.root;}}
208
219
  catch(problem){if(problem.code==='MODULE_NOT_FOUND'||problem.code==='ERR_PACKAGE_PATH_NOT_EXPORTED')error='not-resolvable';else error='metadata-unavailable';}
209
220
  const declared=dependencies[alias]??null,recorded=receipt?packageSpec(receipt.distribution,key):null;
210
- installed[key]={declared,actual,error,manifestSha256,matchesLauncher:!!actual&&actual.name===expected[key]&&actual.version===expected.version,matchesReceipt:!!actual&&!!receipt&&actual.name===receipt.distribution[key]&&actual.version===receipt.distribution.version&&declared===recorded};
221
+ installed[key]={declared,actual,error,manifestSha256,matchesLauncher:!!actual&&actual.name===expected[key]&&actual.version===expected.version,matchesReceipt:!!actual&&!!receipt&&modules.status==='local'&&actual.name===receipt.distribution[key]&&actual.version===receipt.distribution.version&&declared===recorded};
211
222
  }
212
223
  let launcher='not-installed';
213
224
  if(receipt){const file=path.join(root,'.vini-ds/npm-launcher.mjs');await safeParents(root,file);const bytes=await fileBytes(file,true);launcher=bytes&&digest(bytes)===receipt.launcherSha256?'matches-receipt':'missing-or-modified';}
214
225
  let agentContext=null;
215
226
  if(installedAgent)try{const file=path.join(installedAgent.root,'context/current.json');const bytes=await fileBytes(file,true);if(bytes){const current=json(bytes,file);agentContext={name:current.name??null,version:current.version??null,packages:current.packages??null,sha256:`sha256:${digest(bytes)}`,baseline:current.baseline??null,release:current.viniRelease??null};}}catch{}
216
- return {projectRoot:root,appRoot:app,appRootMatchesReceipt,receipt:receipt?{distribution:receipt.distribution,appRoot:receipt.appRoot,...(typeof receipt.generation==='string'?{generation:receipt.generation}:{})}:null,launcher:{status:launcher,expected:receipt?.distribution??null},installed,appManifestSha256:`sha256:${digest(manifestBytes)}`,lockfiles,agentContext};
227
+ const runtime={};const runtimeNames=['react','react-dom'],runtimeEntries=await freshResolveMaybe(manifestPath,runtimeNames,app);
228
+ for(const [i,name] of runtimeNames.entries()){
229
+ let actual=null,error=null,reactPeer=null;try{if(runtimeEntries[i].error)throw new Error(runtimeEntries[i].error);const pkg=await manifestForEntry(runtimeEntries[i].path,name,app,{observeLinked:true});actual={name:pkg.manifest.name,version:pkg.manifest.version};reactPeer=pkg.manifest.peerDependencies?.react??null;}catch(problem){error=problem.message;}
230
+ runtime[name]={declared:dependencies[name]??null,actual,error,uiPeer:uiPeers?.[name]??null,...(name==='react-dom'?{reactPeer}:{})};
231
+ }
232
+ const runtimeCompatibility=runtime.react.actual&&runtime['react-dom'].actual&&runtime.react.uiPeer&&runtime['react-dom'].uiPeer&&runtime['react-dom'].reactPeer?{
233
+ status:peerAccepts(runtime.react.uiPeer,runtime.react.actual.version)&&peerAccepts(runtime['react-dom'].uiPeer,runtime['react-dom'].actual.version)&&peerAccepts(runtime['react-dom'].reactPeer,runtime.react.actual.version)?'compatible-by-observed-caret-peers':'unverified-or-incompatible',scope:'installed manifest peers only; does not establish full runtime support',
234
+ }:{status:'unknown',scope:'installed manifest peers only; does not establish full runtime support'};
235
+ const runtimeIdentity={};const uiRuntime=uiRoot?await freshResolveMaybe(path.join(uiRoot,'package.json'),runtimeNames,app):[];
236
+ for(const [i,name] of runtimeNames.entries()){
237
+ try{if(!runtimeEntries[i]?.path||!uiRuntime[i]?.path)throw new Error('not resolved');const [appPath,uiPath]=await Promise.all([projectModuleEntry(app,runtimeEntries[i].path,{observeLinked:true}),projectModuleEntry(app,uiRuntime[i].path,{observeLinked:true})]);runtimeIdentity[name]={status:appPath===uiPath?'same':'different',appPath,uiPath};}catch{runtimeIdentity[name]={status:'unknown'};}
238
+ }
239
+ const manual=manualInstallation(manifest,installed,expected,receipt);
240
+ return {projectRoot:root,appRoot:app,appRootMatchesReceipt,receipt:receipt?{distribution:receipt.distribution,appRoot:receipt.appRoot,...(typeof receipt.generation==='string'?{generation:receipt.generation}:{})}:null,launcher:{status:launcher,expected:receipt?.distribution??null},installed,runtime,runtimeCompatibility,runtimeIdentity,modules,manual,appManifestSha256:`sha256:${digest(manifestBytes)}`,lockfiles,agentContext};
241
+ }
242
+ function manualInstallation(manifest,installed,distribution,receipt) {
243
+ if(receipt)return {status:'managed-by-receipt',reason:null};
244
+ const sections=['dependencies','devDependencies','peerDependencies','optionalDependencies'];
245
+ const records=[];
246
+ for(const section of sections)for(const [name,spec] of Object.entries(manifest[section]??{})){
247
+ const known=packageKeys.some(key=>[distribution[key],legacyPackages[key],`@vini/${key}`,nativeDsPackages[key]].includes(name));
248
+ const alias=typeof spec==='string'&&/^npm:@(?:vini-ds|vini|timelex)\//u.test(spec.trim());
249
+ if(known||alias)records.push({section,name,spec});
250
+ }
251
+ if(!records.length&&!packageKeys.some(key=>installed[key]?.actual))return {status:'not-installed',reason:null};
252
+ if(!isNativeDs(distribution))return {status:'manual-incomplete',reason:'Manual adoption requires the direct @vini-ds package family; inspect existing package identities.',declarations:records};
253
+ const ui=installed.ui?.actual,tokens=installed.tokens?.actual,agent=installed.agent?.actual;
254
+ const expected=key=>records.filter(item=>item.name===distribution[key]);
255
+ const clean=['ui','tokens'].every(key=>expected(key).length===1&&expected(key)[0].section==='dependencies'&&isExactVersion(expected(key)[0].spec)&&installed[key]?.actual?.name===distribution[key]&&installed[key]?.actual?.version===expected(key)[0].spec);
256
+ const agentRecords=expected('agent');
257
+ const agentClean=agentRecords.length===0&&!agent||agentRecords.length===1&&agentRecords[0].section==='devDependencies'&&isExactVersion(agentRecords[0].spec)&&agent?.name===distribution.agent&&agent.version===agentRecords[0].spec&&agent.version===ui?.version;
258
+ const noOther=records.every(item=>packageKeys.some(key=>item.name===distribution[key]));
259
+ if(!clean||!ui||!tokens||ui.version!==tokens.version||!agentClean||!noOther)return {status:'manual-incomplete',reason:'VINi declarations or installed package identities/versions are incomplete, conflicting, or not exact; review them before adoption.',declarations:records};
260
+ return {status:'manual-installed',reason:null,version:ui.version,declarations:records};
217
261
  }
218
262
  function contextMatchesReceipt(state) {
219
263
  const d=state.receipt?.distribution,c=state.agentContext;
@@ -253,6 +297,12 @@ function unverifiedStatus(root,target,reason) {
253
297
  const verification=verificationState(target,state);verification.installation={...verification.installation,status:'not-verified',matchesTarget:null};
254
298
  return {status:'unknown',statusScope:'package-installation-and-registry',...state,launcherVersion:target.version,launcherMatchesInstalled:false,available:{status:'not-checked',reason},familyTransition:null,changes:{status:'unknown'},nextStep:reason,verification,mutated:false};
255
299
  }
300
+ async function inspectProject(root,app,entry) {
301
+ try {
302
+ if(!entry){const names=['src/main.tsx','src/main.jsx','src/main.ts','src/main.js'];const found=[];for(const name of names)if(await exists(path.join(app,name)))found.push(path.join(app,name));if(found.length!==1)return {status:'not-inspected',reason:'Select the app entry explicitly to inspect CSS, providers and fonts.'};entry=found[0];}
303
+ return {status:'observed',...await diagnoseProject({projectRoot:root,appRoot:app,entry})};
304
+ }catch(error){return {status:'not-inspected',reason:String(error.message??error)};}
305
+ }
256
306
  // These observations are returned with the command, not persisted as a new receipt.
257
307
  // A package/launcher check cannot establish what a running application or MCP client sees.
258
308
  function verificationState(target,state) {
@@ -260,7 +310,7 @@ function verificationState(target,state) {
260
310
  const matched=!!receipt&&state.appRootMatchesReceipt===true&&state.launcher.status==='matches-receipt'&&contextMatchesReceipt(state)&&packageKeys.every(key=>state.installed[key].matchesReceipt);
261
311
  const matchesTarget=matched&&receipt.version===target.version&&packageKeys.every(key=>receipt[key]===target[key]&&state.installed[key].actual?.name===target[key]&&state.installed[key].actual?.version===target.version);
262
312
  return {target:{version:target.version,packages:Object.fromEntries(packageKeys.map(key=>[key,target[key]]))},
263
- installation:{status:!receipt?'not-installed':matched?'matched':'mismatch',matchesTarget,receipt,packages:state.installed},
313
+ installation:{status:!receipt?(state.manual?.status??'not-installed'):matched?'matched':'mismatch',matchesTarget,receipt,packages:state.installed},
264
314
  applicationPage:{status:'not-verified',nextStep:pageCheck},
265
315
  clientMcp:{status:'not-verified',nextStep:clientCheck},
266
316
  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.'}};
@@ -334,9 +384,11 @@ export async function status(options={},suppliedDistribution,{request=requestMet
334
384
  const latest=published.status==='available'?published.distribution.version:null;
335
385
  const family=aligned&&published.status==='available'?familyTransition(state.receipt.distribution,published.distribution):null;
336
386
  const ordering=aligned&&latest?compareVersions(installedVersion,latest):null;
337
- const relation=!state.receipt?'not-installed':!aligned?'mismatch':published.status!=='available'||family==='unsupported'?'unknown':ordering===0?'current':ordering<0?'update-available':'ahead-of-latest';
338
- const next=relation==='not-installed'?`npx ${cli.name}@${expected.version} init --plan`:relation==='mismatch'?(state.appRootMatchesReceipt===false?'Selected app root differs from the recorded npm setup; review the receipt before updating.':!contextMatchesReceipt(state)?'The installed agent context is missing or differs from the recorded package set; inspect the agent and receipt before changing the setup.':'Installed packages or launcher differ from the receipt; resolve the mismatch before updating.'):relation==='unknown'?(family==='unsupported'?'Installed and available package families do not have a supported automatic transition; review the distribution before migration.':'Registry unavailable; retry status before deciding about updates.'):relation==='update-available'?`npx ${cli.name}@${latest} update --plan`:relation==='ahead-of-latest'?'Installed release is newer than the registry latest tag; no downgrade is selected.':'Installed package versions match the latest available release.';
339
- return {status:relation,statusScope:'package-installation-and-registry',...state,launcherVersion:expected.version,launcherMatchesInstalled:installedToLauncher,available:published,familyTransition:family,changes:published.status==='available'&&family!=='unsupported'?transition(published.release,installedVersion,latest):{status:'unknown'},nextStep:next,verification:verificationState(expected,state),mutated:false};
387
+ const relation=!state.receipt?state.manual.status:!aligned?'mismatch':published.status!=='available'||family==='unsupported'?'unknown':ordering===0?'current':ordering<0?'update-available':'ahead-of-latest';
388
+ const appRelative=path.relative(root,state.appRoot)||'.',planLocation=` --cwd ${shellArg(root)}${appRelative==='.'?'':` --app-root ${shellArg(appRelative)}`}${options.entry?` --entry ${shellArg(options.entry)}`:''}`;
389
+ const next=relation==='manual-installed'?`Manual UI/tokens are present without a CLI receipt. Review npx ${cli.name}@${expected.version} init --plan --adopt-manual${planLocation}; the running page and client MCP remain separate checks.${state.modules.status==='linked'?' node_modules is shared via a symbolic link: use an independently managed app directory before applying; the linked target will not be changed.':''}`:relation==='manual-incomplete'?state.manual.reason:relation==='not-installed'?`npx ${cli.name}@${expected.version} init --plan`:relation==='mismatch'?(state.appRootMatchesReceipt===false?'Selected app root differs from the recorded npm setup; review the receipt before updating.':!contextMatchesReceipt(state)?'The installed agent context is missing or differs from the recorded package set; inspect the agent and receipt before changing the setup.':'Installed packages or launcher differ from the receipt; resolve the mismatch before updating.'):relation==='unknown'?(family==='unsupported'?'Installed and available package families do not have a supported automatic transition; review the distribution before migration.':'Registry unavailable; retry status before deciding about updates.'):relation==='update-available'?`npx ${cli.name}@${latest} update --plan`:relation==='ahead-of-latest'?'Installed release is newer than the registry latest tag; no downgrade is selected.':'Installed package versions match the latest available release.';
390
+ const diagnostics=await inspectProject(root,state.appRoot,options.entry?path.resolve(state.appRoot,options.entry):undefined);if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))return unverifiedStatus(root,expected,lockReason);
391
+ return {status:relation,statusScope:'package-installation-and-registry',...state,diagnostics,launcherVersion:expected.version,launcherMatchesInstalled:installedToLauncher,available:published,familyTransition:family,changes:published.status==='available'&&family!=='unsupported'?transition(published.release,installedVersion,latest):{status:'unknown'},nextStep:next,verification:verificationState(expected,state),mutated:false};
340
392
  }
341
393
  export function formatStatus(result) {
342
394
  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');
@@ -344,7 +396,10 @@ export function formatStatus(result) {
344
396
  const changes=result.changes.status==='available'?`\nChanges: ${result.changes.summary}\nComponents: ${result.changes.components.join(', ')||'none listed'}`:'';
345
397
  const release=result.available.release;
346
398
  const site=release?`\nAtlas: ${release.atlas.url} (${release.atlas.siteRelease}, commit ${release.atlas.commit})\nAtlas archive: ${release.atlas.archiveSha256}\nDelivery: ${release.delivery.id}; package manifest: ${release.delivery.packageManifestSha256}; gateway manifest: ${release.delivery.manifestSha256}`:'';
347
- return `VINi package status: ${result.status}\nSelected CLI target: ${result.verification.target.version}\n${installed}\nLauncher expects: ${result.launcherVersion}\nReceipt: ${result.receipt?.distribution.version??'not installed'}; launcher: ${result.launcher.status}\nAvailable published release: ${available}${site}${changes}\n${result.nextStep}\nUpdate completion: not verified\nApplication page: not verified\n${result.verification.applicationPage.nextStep}\nCurrent client MCP: not verified\n${result.verification.clientMcp.nextStep}`;
399
+ const runtime=result.runtime?['react','react-dom'].map(name=>`${name}: declared ${result.runtime[name]?.declared??'missing'}; installed ${result.runtime[name]?.actual?.version??'not resolved'}; UI peer ${result.runtime[name]?.uiPeer??'not observed'}`).join('\n'):'';
400
+ const d=result.diagnostics;
401
+ const source=d?.status==='observed'?`\nStatic source observations (not proof of rendered page):\nCSS imports: ${d.css.imports.map(item=>`${item.file}:${item.line} ${item.specifier}`).join('; ')||'none found'}\nProvider uses: ${d.provider.jsxUses.map(item=>`${item.file}:${item.line} ${item.binding}`).join('; ')||'none found'}\nFont imports: ${d.fonts.imports.map(item=>`${item.file}:${item.line} ${item.specifier} (${item.status??'inspected'})`).join('; ')||'none found'}\nPotentially broad CSS rules (inspect actual cascade):\n${d.css.potentiallyBroadRules.map(item=>`${item.file}:${item.line} ${item.selector} [${item.properties.join(', ')}]${item.media.length?' '+item.media.join(' '):''}`).join('\n')||'none found'}\nUnresolved source imports: ${d.unresolved.length}; coverage: ${d.coverage}`:`\nSource diagnostics: ${d?.reason??'not inspected'}`;
402
+ return `VINi package status: ${result.status}\nSelected CLI target: ${result.verification.target.version}\n${installed}\n${runtime}\nCompatibility: ${result.runtimeCompatibility?.status??'unknown'} (observed installed peers only)\nReact identity (app / UI): ${result.runtimeIdentity?.react?.status??'unknown'}; React DOM: ${result.runtimeIdentity?.['react-dom']?.status??'unknown'}\nnode_modules: ${result.modules?.status??'not verified'}${result.modules?.status==='linked'?` -> ${result.modules.target??'unresolved'}`:''}\nLauncher expects: ${result.launcherVersion}\nReceipt: ${result.receipt?.distribution.version??'not installed'}; launcher: ${result.launcher.status}\nAvailable published release: ${available}${site}${changes}${source}\n${result.nextStep}\nUpdate completion: not verified\nApplication page: not verified\n${result.verification.applicationPage.nextStep}\nCurrent client MCP: not verified\n${result.verification.clientMcp.nextStep}`;
348
403
  }
349
404
  function launcher(distribution,appRelative) {
350
405
  return `// Generated by VINi npm CLI; resolves persistent project packages, never npx cache.\nimport { createRequire } from 'node:module';\nimport { readFileSync, existsSync, realpathSync } from 'node:fs';\nimport { spawn } from 'node:child_process';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst project=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');\nconst appRelative=${JSON.stringify(appRelative)};\nconst req=createRequire(path.join(project,appRelative,'package.json'));\nconst expected=${JSON.stringify(distribution)};\nconst local=${JSON.stringify(localNames(distribution))};\nlet agentRoot;\nfor(const key of ['tokens','ui','agent']) { const entry=req.resolve(local[key]+(key==='agent'?'/mcp':'')); let dir=path.dirname(entry), meta; while(true){const file=path.join(dir,'package.json');if(existsSync(file)){meta=JSON.parse(readFileSync(file,'utf8'));if(meta.name&&meta.version)break;} const parent=path.dirname(dir);if(parent===dir)throw Error('VINi package metadata missing');dir=parent;} if(meta.name!==expected[key]||meta.version!==expected.version)throw Error('VINi installed package/agent versions differ; inspect the receipt and installed packages');if(key==='agent')agentRoot=realpathSync(dir);}\nlet supervisor;try{supervisor=realpathSync(req.resolve(local.agent+'/supervisor'));}catch{throw Error('Installed VINi agent does not provide a managed connection; review the selected release and reconnect the project MCP');}\nif(!supervisor.startsWith(agentRoot+path.sep))throw Error('VINi supervisor is outside the selected agent package');\nconst child=spawn(process.execPath,[supervisor,'--project-root',project,'--app-root',appRelative],{stdio:'inherit',cwd:project});\nfor(const sig of ['SIGINT','SIGTERM'])process.on(sig,()=>child.kill(sig));\nchild.on('error',error=>{console.error(error.message);process.exitCode=1;});\nchild.on('exit',(code,signal)=>{process.exitCode=code??1;});\n`;
@@ -414,8 +469,8 @@ export async function init(options={},suppliedDistribution,dependencies={}) {
414
469
 
415
470
  async function initWithLock(options={},suppliedDistribution,{runner=run,releaseMetadata,recordRecovery}={}) {
416
471
  const cli=suppliedDistribution?null:json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package');
417
- const distribution=distributionCheck(suppliedDistribution??cli.viniDistribution);
418
- const release=releaseMetadata??cli?.viniRelease;
472
+ let distribution=distributionCheck(suppliedDistribution??cli.viniDistribution);
473
+ let release=releaseMetadata??cli?.viniRelease;
419
474
  if(release&&!validRelease(release))fail('invalid CLI release metadata');
420
475
  const root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
421
476
  const kit=path.join(root,'.vini-ds'),receiptPath=path.join(kit,'npm-install.json');await safeParents(root,receiptPath);
@@ -428,14 +483,53 @@ async function initWithLock(options={},suppliedDistribution,{runner=run,releaseM
428
483
  if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
429
484
  const manifestFile=path.join(app,'package.json'),manifest=json(await fileBytes(manifestFile),manifestFile);
430
485
  const deps={...manifest.devDependencies,...manifest.dependencies};
431
- if(!deps.react||!deps['react-dom']||![deps.react,deps['react-dom']].every(value=>typeof value==='string'&&/^(?:\^|~)?18(?:\.|$)/.test(value)))fail('this alpha requires existing React and React DOM 18 dependencies; their versions will not be replaced');
486
+ const initial=await readInstallation(root,path.relative(root,app)||'.',distribution);
487
+ const resumingAdoption=!!previous&&!!options.adoptManual&&previous.entryMode==='preserved-manual';
488
+ if(options.adoptManual&&previous&&!resumingAdoption)fail('this project already has a managed receipt; use status or update');
489
+ if(options.adoptManual&&!previous&&initial.manual.status!=='manual-installed')fail(`manual adoption requires a verified installed direct UI/tokens pair: ${initial.manual.reason??initial.manual.status}`);
490
+ if(resumingAdoption){if(packageKeys.some(key=>previous.distribution[key]!==distribution[key]))fail('recorded adoption uses a different package family');distribution=previous.distribution;release=null;}
491
+ const directIncomplete=isNativeDs(distribution)&&initial.manual.status==='manual-incomplete'&&(initial.manual.declarations??[]).every(item=>packageKeys.some(key=>item.name===distribution[key]));
492
+ if(!previous&&directIncomplete&&options.plan)return {status:'plan-only',command:'init',projectRoot:root,appRoot:app,installedStatus:initial.manual.status,installed:initial.installed,runtime:initial.runtime,runtimeCompatibility:initial.runtimeCompatibility,modules:initial.modules,manual:initial.manual,diagnostics:await inspectProject(root,app),mutated:false,nextStep:initial.manual.reason,applicationPage:'not-verified',nativeClient:'not-verified'};
493
+ if(!previous&&directIncomplete)fail(initial.manual.reason);
494
+ if(!previous&&initial.manual.status==='manual-installed'&&!options.adoptManual&&!options.plan)fail('existing direct VINi packages are not managed by this npm setup; review init --plan --adopt-manual, then explicitly choose adoption');
495
+ const adopting=!previous&&initial.manual.status==='manual-installed'&&(options.adoptManual||options.plan);
496
+ if(adopting){
497
+ if(compareVersions(initial.manual.version,distribution.version)>0)fail('installed manual release is newer than this CLI; use its matching or newer CLI and do not downgrade');
498
+ distribution={...distribution,version:initial.manual.version};
499
+ if(distribution.version!==(suppliedDistribution??cli.viniDistribution).version)release=null;
500
+ }
501
+ // Accept a bounded exact/caret/tilde declaration whose lower bound is covered by
502
+ // the public compatibility range. Do not rewrite React dependency declarations.
503
+ const runtimeMajor = value => {
504
+ const match = typeof value === 'string' && /^(?:\^|~)?(18|19)\.(\d+)\.(\d+)$/.exec(value);
505
+ if (!match) return null;
506
+ const major = Number(match[1]), minor = Number(match[2]), patch = Number(match[3]);
507
+ if (major === 18 && minor < 2) return null;
508
+ if (major === 19 && (!supportedReact19 || minor < 3 || (minor === 3 && patch < 1))) return null;
509
+ return major;
510
+ };
511
+ const reactMajor = runtimeMajor(deps.react), domMajor = runtimeMajor(deps['react-dom']);
512
+ if (!reactMajor || reactMajor !== domMajor) fail(`this alpha requires matching existing React and React DOM dependencies in ${supportedReact19 ? '^18.2.0 or ^19.3.1' : '^18.2.0'}; their dependency declarations will not be changed`);
513
+ if(adopting||resumingAdoption){
514
+ for(const name of ['react','react-dom']){const observed=initial.runtime[name];if(observed.actual?.name!==name||!peerAccepts(observed.uiPeer,observed.actual.version))fail(`installed ${name} is not verified compatible with the existing UI peer ${observed.uiPeer??'(not available)'}`);}
515
+ if(!peerAccepts(initial.runtime['react-dom'].reactPeer,initial.runtime.react.actual.version))fail('installed react-dom peer for React is incompatible or cannot be interpreted safely');
516
+ if(initial.runtime.react.actual.version.split('.')[0]!==initial.runtime['react-dom'].actual.version.split('.')[0])fail('installed React and React DOM majors differ');
517
+ for(const name of ['react','react-dom'])if(deps[name]!==initial.runtime[name].actual.version)fail(`manual adoption requires the existing ${name} declaration to match its exact installed version; review version and lockfile first`);
518
+ for(const name of ['react','react-dom'])if(initial.runtimeIdentity[name].status!=='same')fail(`existing UI and app do not resolve the same ${name} instance; inspect installed dependencies`);
519
+ }
432
520
  const manager=await managerFor(root,app,options,manifest);
433
521
  let entry;
434
522
  if(options.entry)entry=path.resolve(app,options.entry);
435
523
  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];}
436
524
  await safeParents(root,entry);if(entry!==app&&!entry.startsWith(app+path.sep))fail('entry must be inside app');
437
525
  const entryBefore=await fileBytes(entry);let entryAfter,entryPreparation='ready';
438
- try {entryAfter=Buffer.from(transformEntry(text(entryBefore,entry),entry,distribution));}
526
+ const diagnostics=await inspectProject(root,app,entry);
527
+ const requiredCss=[`${localNames(distribution).tokens}/fonts.css`,`${localNames(distribution).tokens}/themes.css`,`${localNames(distribution).tokens}/typography.css`,`${localNames(distribution).ui}/styles.css`];
528
+ const missingCss=requiredCss.filter(specifier=>!diagnostics.css?.imports?.some(item=>item.specifier===specifier&&item.kind==='static'&&item.reachability==='static'&&item.resolution?.status==='resolved'));
529
+ const allProviderUses=diagnostics.provider?.jsxUses??[],providerUses=allProviderUses.filter(item=>item.reachability==='static').length;
530
+ const incompleteGraph=diagnostics.status!=='observed'||diagnostics.scope?.truncated||diagnostics.unresolved?.length>0;
531
+ const adoptionEvidence={status:!incompleteGraph&&missingCss.length===0&&providerUses===1&&allProviderUses.length===1?'observed':'review-required',missingCss,providerUses,otherProviderUses:allProviderUses.length-providerUses,incompleteGraph:!!incompleteGraph,note:'Source observations (including traversed literal dynamic imports) do not prove the rendered root, active styles, fonts or client MCP.'};
532
+ try {entryAfter=adopting||resumingAdoption||previous?.entryMode==='preserved-manual'?entryBefore:Buffer.from(transformEntry(text(entryBefore,entry),entry,distribution));}
439
533
  catch(error){if(options.plan&&previous&&isNativeDs(distribution)&&/direct .* import requires an explicit manual-to-CLI migration/.test(error.message)){entryAfter=null;entryPreparation='manual-import-migration-required';}else throw error;}
440
534
  if(previous){
441
535
  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');}
@@ -447,7 +541,7 @@ async function initWithLock(options={},suppliedDistribution,{runner=run,releaseM
447
541
  for(const key of ['ui','tokens','agent'])for(const published of new Set([distribution[key],legacyPackages[key],`@vini/${key}`,nativeDsPackages[key]])){
448
542
  const canonical=priorLocal?.[key]??targetLocal[key];
449
543
  if(name===canonical){
450
- if(!previous)fail(`existing ${canonical} dependency is not managed by this npm setup; migrate explicitly`);
544
+ if(!previous&&!adopting)fail(`existing ${canonical} dependency is not managed by this npm setup; migrate explicitly`);
451
545
  if(section!==(key==='agent'?'devDependencies':'dependencies'))fail(`${canonical} appears in an unexpected dependency section; review the npm setup`);
452
546
  }
453
547
  if(name===targetLocal[key]&&targetLocal[key]!==canonical)fail(`existing ${name} dependency is not managed by this npm setup; migrate explicitly`);
@@ -478,16 +572,20 @@ async function initWithLock(options={},suppliedDistribution,{runner=run,releaseM
478
572
  const config=Buffer.from(configMerge(before.get(configFile)?text(before.get(configFile),configFile):'',configTable,previous?.configTable));
479
573
  const agents=Buffer.from(agentsMerge(before.get(agentsFile)?text(before.get(agentsFile),agentsFile):''));
480
574
  const current=await readInstallation(root,path.relative(root,app)||'.',distribution);
575
+ if(adopting&&(!isDeepStrictEqual(initial.manual,current.manual)||!isDeepStrictEqual(initial.runtime,current.runtime)||!isDeepStrictEqual(initial.modules,current.modules)||packageKeys.some(key=>!isDeepStrictEqual(initial.installed[key].actual,current.installed[key].actual)||initial.installed[key].manifestSha256!==current.installed[key].manifestSha256)))fail('manual installation changed while planning; review it before adoption');
481
576
  const installedAligned=!!previous&&current.launcher.status==='matches-receipt'&&contextMatchesReceipt(current)&&['ui','tokens','agent'].every(key=>current.installed[key].matchesReceipt);
482
577
  const migration=!!previous&&familyTransition(previous.distribution,distribution)==='manual-import-migration';
483
- const plan={status:'plan-only',command:options.command??'init',projectRoot:root,appRoot:app,entry:path.relative(app,entry),entryPreparation,packageManager:manager,installed:current.installed,installedStatus:previous?(installedAligned?'matches-receipt':'mismatch'):'not-installed',from:previous?.distribution??null,to:distribution,distribution,changes:transition(release,installedAligned?previous.distribution.version:null,distribution.version),release:release??null,restart:clientCheck,dependencies:{[targetLocal.ui]:alias('ui'),[targetLocal.tokens]:alias('tokens')},devDependencies:{[targetLocal.agent]:alias('agent')},...(migration?{removeDependencies:Object.values(priorLocal),manualMigration:'Review and replace all old imports and configuration in the project before update; pass --imports-migrated only after review. The CLI checks the entry and build but cannot verify every source file.'}:{}),agent:'project-local Codex MCP + Skill',applicationPage:'not-verified',nativeClient:'not-verified',verification:verificationState(distribution,current),postUpdateSteps:[pageCheck,clientCheck],globalConfig:'unchanged',supported:'React 18, Vite direct createRoot(...).render(JSX), standalone npm/pnpm app'};
578
+ const plan={status:'plan-only',command:options.command??'init',projectRoot:root,appRoot:app,entry:path.relative(app,entry),entryPreparation:adopting?'preserve-existing-entry':entryPreparation,packageManager:manager,installed:current.installed,runtime:current.runtime,modules:current.modules,manual:current.manual,installedStatus:previous?(installedAligned?'matches-receipt':'mismatch'):current.manual.status,from:previous?.distribution??(adopting?distribution:null),to:distribution,distribution,changes:transition(release,installedAligned?previous.distribution.version:null,distribution.version),release:release??null,restart:clientCheck,dependencies:{[targetLocal.ui]:alias('ui'),[targetLocal.tokens]:alias('tokens')},devDependencies:{[targetLocal.agent]:alias('agent')},...(adopting?{manualAdoption:{explicit:!!options.adoptManual,preserveEntry:true,preserveVersion:true,blocked:current.modules.status==='linked',nextStep:current.modules.status==='linked'?'node_modules is a symbolic link to shared dependencies; first choose an independently managed app directory. This command will not change its target.':'Review this plan, CSS/provider diagnostics and backup, then run init --adopt-manual.'}}:{}),...(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/React DOM ${supportedReact19?'^18.2.0 or ^19.3.1':'^18.2.0'}, Vite direct createRoot(...).render(JSX), standalone npm/pnpm app`};
579
+ plan.diagnostics=diagnostics;plan.runtimeCompatibility=current.runtimeCompatibility;plan.runtimeIdentity=current.runtimeIdentity;
580
+ if(adopting){plan.manualAdoption.sourceEvidence=adoptionEvidence;if(adoptionEvidence.status!=='observed'){plan.manualAdoption.blocked=true;plan.manualAdoption.nextStep='Review missing CSS imports and provider use. Static scanning cannot prove the rendered application; no files will be changed.';}}
484
581
  if(options.plan)return plan;
582
+ if(adopting&&adoptionEvidence.status!=='observed')fail('manual adoption requires the four VINi CSS imports and one observed ThemeBrandProvider use; review source and rerun the plan');
485
583
  if(migration&&!options.importsMigrated)fail('review and migrate all project imports and configuration before update; then pass --imports-migrated');
486
584
  if(previous&&!installedAligned)fail('installed packages, agent context or launcher differ from the receipt; resolve the mismatch before updating');
487
585
  const recoveryRoot=path.join(root,'.vini-ds-recovery');await safeParents(root,path.join(recoveryRoot,'placeholder'));
488
586
  const recoveryRootExisted=!!await exists(recoveryRoot);
489
587
  const modules=path.join(app,'node_modules');
490
- const moduleStat=await exists(modules);if(moduleStat&&(moduleStat.isSymbolicLink()||!moduleStat.isDirectory()))fail('node_modules must be a real directory');
588
+ const moduleStat=await exists(modules);if(moduleStat&&(moduleStat.isSymbolicLink()||!moduleStat.isDirectory()))fail('node_modules must be a real directory; linked/shared dependencies require an independent app installation before applying');
491
589
  let backup;await fs.mkdir(recoveryRoot,{recursive:true,mode:0o700});backup=await fs.mkdtemp(path.join(recoveryRoot,'npm-'));await recordRecovery(backup);
492
590
  const expected=new Map(before);let modulesMoved=false,modulesMayHaveChanged=false,projectMutationStarted=false,installFailed=false,buildAttempted=false;
493
591
  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);};
@@ -533,13 +631,18 @@ async function initWithLock(options={},suppliedDistribution,{runner=run,releaseM
533
631
  if(!supervisor.startsWith(agentRoot+path.sep))fail('agent supervisor must belong to the installed agent package');
534
632
  const uiPeers=await freshResolve(path.join(packageRoots.ui.root,'package.json'),['react','react-dom'],app);
535
633
  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`);
634
+ if(adopting||resumingAdoption){
635
+ const actualReact=await manifestForEntry(reactEntry,'react',app),actualDom=await manifestForEntry(reactDomEntry,'react-dom',app);
636
+ for(const [name,pkg] of [['react',actualReact],['react-dom',actualDom]])if(pkg.manifest.name!==name||pkg.manifest.version!==initial.runtime[name].actual.version||!peerAccepts(packageRoots.ui.manifest.peerDependencies?.[name],pkg.manifest.version))fail(`installed ${name} changed or is incompatible after manual adoption`);
637
+ if(!peerAccepts(actualDom.manifest.peerDependencies?.react,actualReact.manifest.version))fail('installed react-dom peer is incompatible after manual adoption');
638
+ }
536
639
  const skill=await fileBytes(await projectModuleEntry(app,skillEntry)),setup=await fileBytes(await projectModuleEntry(app,setupEntry));
537
640
  const launch=Buffer.from(launcher(distribution,path.relative(root,app)||'.'));
538
- await write(entry,entryAfter);
641
+ if(!entryBefore.equals(entryAfter))await write(entry,entryAfter);
539
642
  if(manifest.scripts?.build){buildAttempted=true;await pm(['run','build']);}
540
643
  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}`);}
541
644
  for(const [file,bytes]of [[launchFile,launch],[setupFile,setup],[configFile,config],[skillFile,skill],[agentsFile,agents]])await write(file,bytes);
542
- const receipt={installer:'vini-npm',generation:randomUUID(),distribution,appRoot:path.relative(root,app)||'.',entry:path.relative(app,entry),configTable,skillSha256:digest(skill),launcherSha256:digest(launch)};
645
+ const receipt={installer:'vini-npm',generation:randomUUID(),distribution,appRoot:path.relative(root,app)||'.',entry:path.relative(app,entry),...(adopting||resumingAdoption||previous?.entryMode==='preserved-manual'?{entryMode:'preserved-manual'}:{}),configTable,skillSha256:digest(skill),launcherSha256:digest(launch)};
543
646
  await write(receiptPath,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
544
647
  const finalState=await readInstallation(root,path.relative(root,app)||'.',distribution);
545
648
  const verification=verificationState(distribution,finalState);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vini-ds",
3
- "version": "0.1.0-alpha.11",
3
+ "version": "0.1.0-alpha.14",
4
4
  "type": "module",
5
5
  "description": "VINi React project and local agent setup",
6
6
  "bin": {
@@ -15,15 +15,38 @@
15
15
  "files": [
16
16
  "cli.mjs",
17
17
  "version.mjs",
18
+ "project-diagnostics.mjs",
18
19
  "README.md"
19
20
  ],
20
21
  "dependencies": {
21
22
  "typescript": "5.5.4"
22
23
  },
23
24
  "viniDistribution": {
24
- "version": "0.1.0-alpha.11",
25
+ "version": "0.1.0-alpha.14",
25
26
  "ui": "@vini-ds/ui",
26
27
  "tokens": "@vini-ds/tokens",
27
28
  "agent": "@vini-ds/agent"
29
+ },
30
+ "viniRelease": {
31
+ "atlas": {
32
+ "url": "https://vini-atlas.twc1.net/",
33
+ "siteRelease": "source-snapshot-20261115-alpha14-cd297982",
34
+ "commit": "cd297982e98dec55702786ba9684b035d9b8f972",
35
+ "archiveSha256": "sha256:5e04130f2e54dbbfbefd1bbdaf12b14fe32dee6fb3c819d9f3f69dfefabcda0f"
36
+ },
37
+ "delivery": {
38
+ "id": "candidate-aeb9566ccd8ab46b",
39
+ "manifestSha256": "sha256:7a506ceb8d42a7e04f4d0e4fb7dfaec442b29b0f221a0483625bd8af899d4dea",
40
+ "packageManifestSha256": "sha256:f2431364911438a5ac24f4f76cf73bc4246535ced70fb530754af64e1d69125e"
41
+ },
42
+ "changes": {
43
+ "fromVersion": "0.1.0-alpha.13",
44
+ "summary": "Расширены примеры и учебные материалы Atlas, доступные через MCP; обновлены предпросмотры и поведение всплывающих элементов Atlas.",
45
+ "components": []
46
+ }
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "https://github.com/youtimelex/vini.git"
28
51
  }
29
52
  }
@@ -0,0 +1,250 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import ts from 'typescript';
5
+
6
+ // Static, read-only evidence for a specific app entry; it cannot establish what
7
+ // an already running page loaded or whether the rendered root uses a provider.
8
+ const supported = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.css']);
9
+ const moduleExt = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.css', '/index.ts', '/index.tsx', '/index.js', '/index.jsx'];
10
+ const important = /^(?:all|align(?:-.+)?|appearance|background(?:-.+)?|border(?:-.+)?|box-sizing|color|display|filter|flex(?:-.+)?|font(?:-.+)?|gap|height|inset(?:-.+)?|justify(?:-.+)?|letter-spacing|line-height|margin(?:-.+)?|max-(?:width|height)|min-(?:width|height)|opacity|outline(?:-.+)?|overflow(?:-.+)?|padding(?:-.+)?|position|text(?:-.+)?|transform|visibility|white-space|width|z-index|--vini-.+)$/i;
11
+ const rootSelector = /^(?:\*|html|body|:root)(?=$|[\s.#[:>+~])/i;
12
+ const broadElement = /^(?:button|input|select|textarea|label|a|p|h[1-6]|svg|img|table|th|td)(?=$|[\s[:>+~])/i;
13
+ const within = (parent, child) => child === parent || child.startsWith(parent + path.sep);
14
+ const lineAt = (s, offset) => 1 + (s.slice(0, offset).match(/\n/g) ?? []).length;
15
+
16
+ function cleanComments(s) {
17
+ return s.replace(/\/\*[\s\S]*?\*\//g, value => value.replace(/[^\n]/g, ' '));
18
+ }
19
+
20
+ // Traverse balanced CSS blocks and retain @media conditions. This is a
21
+ // deliberately conservative triage, not a full cascade or CSS parser.
22
+ function cssWarnings(source, file) {
23
+ const text = cleanComments(source), warnings = [];
24
+ const scan = (begin, end, media) => {
25
+ let start = begin, quote = '', escaped = false, parens = 0;
26
+ for (let i = begin; i < end; i++) {
27
+ const c = text[i];
28
+ if (quote) { if (escaped) escaped = false; else if (c === '\\') escaped = true; else if (c === quote) quote = ''; continue; }
29
+ if (c === '"' || c === "'") { quote = c; continue; }
30
+ if (c === '(') { parens++; continue; }
31
+ if (c === ')') { parens = Math.max(0, parens - 1); continue; }
32
+ if (c === ';' && parens === 0) { start = i + 1; continue; }
33
+ if (c !== '{' || parens) continue;
34
+ const raw = text.slice(start, i), selector = raw.trim();
35
+ let depth = 1, j = i + 1, blockQuote = '', blockEscape = false;
36
+ for (; j < end && depth; j++) {
37
+ const x = text[j];
38
+ if (blockQuote) { if (blockEscape) blockEscape = false; else if (x === '\\') blockEscape = true; else if (x === blockQuote) blockQuote = ''; continue; }
39
+ if (x === '"' || x === "'") blockQuote = x;
40
+ else if (x === '{') depth++;
41
+ else if (x === '}') depth--;
42
+ }
43
+ if (depth) break;
44
+ const close = j - 1;
45
+ if (/^@media\b/i.test(selector)) scan(i + 1, close, [...media, selector]);
46
+ else if (/^@(?:supports|layer|container|scope)\b/i.test(selector)) scan(i + 1, close, media);
47
+ else if (selector && !selector.startsWith('@')) {
48
+ const cssModule = file.endsWith('.module.css');
49
+ const suspect = selector.split(',').map(v => v.trim()).map(v => {
50
+ if (cssModule && !v.includes(':global(')) return null;
51
+ const positiveSlots = v.replace(/:not\(\s*\[data-slot[^\]]*\]\s*\)/gi, '');
52
+ const kinds = [];
53
+ if (rootSelector.test(v) || broadElement.test(v) || /^\*?:focus-visible(?:\b|$)/i.test(v) || v.startsWith(':global(')) kinds.push('broad-selector');
54
+ if (/\[data-slot(?:\s*[~|^$*]?=|\s*\])/i.test(positiveSlots)) kinds.push('component-slot-selector');
55
+ if (media.length && /(?:^|[\s>+~])\.sidebar(?=$|[\s.#[:>+~])/i.test(v)) kinds.push('sidebar-media-selector');
56
+ return kinds.length ? { selector: v, kinds } : null;
57
+ }).filter(Boolean);
58
+ if (suspect.length) {
59
+ const body = text.slice(i + 1, close);
60
+ // Nested declarations are not assumed to apply to the outer rule.
61
+ if (!body.includes('{')) {
62
+ const properties = [...body.matchAll(/(?:^|;)\s*([\w-]+)\s*:/g)].map(m => m[1]).filter(p => important.test(p));
63
+ if (properties.length) warnings.push({ file, line: lineAt(text, start + raw.search(/\S/)), selector: suspect.map(x => x.selector).join(', '), kinds: [...new Set(suspect.flatMap(x => x.kinds))], properties: [...new Set(properties)], media, interpretation: 'Potentially affects VINi elements; inspect the cascade and actual page before deciding.' });
64
+ }
65
+ }
66
+ }
67
+ i = close; start = j;
68
+ }
69
+ };
70
+ scan(0, text.length, []);
71
+ return warnings;
72
+ }
73
+
74
+ async function existingFile(file) {
75
+ try { return (await fs.stat(file)).isFile(); } catch { return false; }
76
+ }
77
+ async function resolveLocal(parent, specifier, appReal) {
78
+ const base = path.resolve(path.dirname(parent), specifier.split(/[?#]/, 1)[0]);
79
+ for (const suffix of moduleExt) {
80
+ const candidate = base + suffix;
81
+ if (!supported.has(path.extname(candidate)) || !(await existingFile(candidate))) continue;
82
+ const real = await fs.realpath(candidate);
83
+ if (!within(appReal, real)) return { blocked: true, path: candidate };
84
+ return { path: real };
85
+ }
86
+ return null;
87
+ }
88
+
89
+ function importsAndProvider(content, file) {
90
+ const script = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true,
91
+ file.endsWith('.tsx') ? ts.ScriptKind.TSX : file.endsWith('.jsx') ? ts.ScriptKind.JSX : ts.ScriptKind.TS);
92
+ const imports = [], providerBindings = new Set(), uses = [];
93
+ for (const item of script.statements) {
94
+ if ((ts.isImportDeclaration(item) || ts.isExportDeclaration(item)) && item.moduleSpecifier && ts.isStringLiteral(item.moduleSpecifier)) {
95
+ const spec = item.moduleSpecifier.text;
96
+ const clause = ts.isImportDeclaration(item) ? item.importClause : undefined;
97
+ const typeOnly = Boolean(clause?.isTypeOnly);
98
+ imports.push({ specifier: spec, line: lineAt(content, item.getStart(script)), kind: typeOnly ? 'type-only' : 'static' });
99
+ if (!typeOnly && /^@(?:vini-ds|vini)\/ui$/.test(spec)) {
100
+ const bindings = clause?.namedBindings;
101
+ if (bindings && ts.isNamedImports(bindings)) for (const element of bindings.elements) {
102
+ if (!element.isTypeOnly && (element.propertyName ?? element.name).text === 'ThemeBrandProvider') providerBindings.add(element.name.text);
103
+ }
104
+ if (bindings && ts.isNamespaceImport(bindings)) providerBindings.add(`${bindings.name.text}.ThemeBrandProvider`);
105
+ }
106
+ }
107
+ }
108
+ const visit = node => {
109
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
110
+ const name = node.tagName.getText(script);
111
+ if (providerBindings.has(name)) uses.push({ file, line: lineAt(content, node.getStart(script)), binding: name });
112
+ }
113
+ if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
114
+ const argument = node.arguments[0];
115
+ const literal = argument && (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument));
116
+ imports.push({ specifier: literal ? argument.text : null, line: lineAt(content, node.getStart(script)), kind: 'dynamic', literal: Boolean(literal) });
117
+ }
118
+ ts.forEachChild(node, visit);
119
+ };
120
+ visit(script);
121
+ return { imports, uses, providerImports: [...providerBindings].map(binding => ({ file, binding })) };
122
+ }
123
+
124
+ function packageCssResolution(require, specifier) {
125
+ try { return { status: 'resolved', path: require.resolve(specifier) }; }
126
+ catch (error) { return { status: 'unresolved', reason: error.code ?? 'resolution-failed' }; }
127
+ }
128
+
129
+ async function inspectFontImport(require, specifier, location) {
130
+ try {
131
+ const css = require.resolve(specifier), text = await fs.readFile(css, 'utf8');
132
+ const packageName = specifier.split('/').slice(0, 2).join('/');
133
+ let packageRoot = path.dirname(css);
134
+ while (true) {
135
+ try { if (JSON.parse(await fs.readFile(path.join(packageRoot, 'package.json'), 'utf8')).name === packageName) break; } catch {}
136
+ const parent = path.dirname(packageRoot);
137
+ if (parent === packageRoot) throw new Error('font stylesheet package root not found');
138
+ packageRoot = parent;
139
+ }
140
+ const realPackageRoot = await fs.realpath(packageRoot);
141
+ const files = [...text.matchAll(/url\(\s*(['"]?)([^)'"\s]+)\1\s*\)/gi)]
142
+ .map(match => match[2]).filter(url => !/^(?:data:|https?:|\/\/|#)/i.test(url));
143
+ const checked = [];
144
+ for (const url of [...new Set(files)].slice(0, 256)) {
145
+ let target;
146
+ try { target = path.resolve(path.dirname(css), decodeURIComponent(url.split(/[?#]/, 1)[0])); } catch { checked.push({ url, status: 'invalid-asset-url' }); continue; }
147
+ if (!within(packageRoot, target)) { checked.push({ url, status: 'outside-package-not-inspected' }); continue; }
148
+ const real = await fs.realpath(target).catch(() => null);
149
+ if (real && !within(realPackageRoot, real)) { checked.push({ url, status: 'outside-package-not-inspected' }); continue; }
150
+ checked.push({ url, status: real && await existingFile(real) ? 'present' : 'missing' });
151
+ }
152
+ return { ...location, specifier, resolvedStylesheet: css, referencedLocalAssets: checked.length,
153
+ missingLocalAssets: checked.filter(item => item.status === 'missing').map(item => item.url),
154
+ uninspectedAssets: checked.filter(item => !['missing', 'present'].includes(item.status)), truncated: files.length > 256 };
155
+ } catch (error) { return { ...location, specifier, status: 'unresolved', reason: error.code ?? 'read-failed' }; }
156
+ }
157
+
158
+ async function inspectLocalFontRules(content, file, appReal) {
159
+ const source = cleanComments(content), records = [];
160
+ for (const match of source.matchAll(/@font-face\s*\{([^{}]*)\}/gi)) {
161
+ const body = match[1], family = /(?:^|;)\s*font-family\s*:\s*([^;]+)/i.exec(body)?.[1].trim() ?? null;
162
+ const assets = [];
163
+ for (const item of body.matchAll(/url\(\s*(['"]?)([^)'"\s]+)\1\s*\)/gi)) {
164
+ const url = item[2];
165
+ if (/^(?:data:|https?:|\/\/|#)/i.test(url)) { assets.push({ url, status: 'external-or-embedded-not-checked' }); continue; }
166
+ let target;
167
+ try {
168
+ const decoded = decodeURIComponent(url.split(/[?#]/, 1)[0]);
169
+ target = decoded.startsWith('/') ? path.join(appReal, 'public', decoded.slice(1)) : path.resolve(path.dirname(file), decoded);
170
+ } catch { assets.push({ url, status: 'invalid-asset-url' }); continue; }
171
+ if (!within(appReal, target)) { assets.push({ url, status: 'outside-app-not-inspected' }); continue; }
172
+ const real = await fs.realpath(target).catch(() => null);
173
+ if (real && !within(appReal, real)) { assets.push({ url, status: 'outside-app-not-inspected' }); continue; }
174
+ assets.push({ url, status: real && await existingFile(real) ? 'present' : 'missing' });
175
+ }
176
+ records.push({ file, line: lineAt(source, match.index), family, assets });
177
+ }
178
+ return records;
179
+ }
180
+
181
+ export async function diagnoseProject({ projectRoot, appRoot, entry }) {
182
+ if (!path.isAbsolute(projectRoot ?? '') || !path.isAbsolute(appRoot ?? '') || !path.isAbsolute(entry ?? ''))
183
+ throw new Error('projectRoot, appRoot and entry must be absolute paths');
184
+ const rootReal = await fs.realpath(projectRoot), appReal = await fs.realpath(appRoot), entryReal = await fs.realpath(entry);
185
+ if (!within(rootReal, appReal) || !within(appReal, entryReal)) throw new Error('entry must be inside the selected app and project');
186
+ const require = createRequire(path.join(appReal, 'package.json'));
187
+ // Drain the static graph first, so a file reachable via both paths keeps its
188
+ // stronger static classification; dynamic imports never become proof of use.
189
+ const staticQueue = [entryReal], dynamicQueue = [], visited = new Set(), imports = [], dynamicImports = [], providerImports = [], providerUses = [], warnings = [], unresolved = [], fonts = [], localFonts = [];
190
+ const schedule = (file, reachability) => (reachability === 'static' ? staticQueue : dynamicQueue).push(file);
191
+ const maxFiles = 1500, maxBytes = 2 * 1024 * 1024;
192
+ while ((staticQueue.length || dynamicQueue.length) && visited.size < maxFiles) {
193
+ const reachability = staticQueue.length ? 'static' : 'dynamic';
194
+ const file = (reachability === 'static' ? staticQueue : dynamicQueue).shift();
195
+ if (visited.has(file)) continue;
196
+ visited.add(file);
197
+ const stat = await fs.stat(file);
198
+ if (stat.size > maxBytes) { unresolved.push({ file, reachability, reason: 'file exceeds scan limit' }); continue; }
199
+ const content = await fs.readFile(file, 'utf8');
200
+ if (file.endsWith('.css')) {
201
+ warnings.push(...cssWarnings(content, file).map(x => ({ ...x, reachability })));
202
+ localFonts.push(...(await inspectLocalFontRules(content, file, appReal)).map(x => ({ ...x, reachability })));
203
+ for (const item of cleanComments(content).matchAll(/@import\s+(?:url\(\s*)?['"]([^'"]+)['"]/gi)) {
204
+ const specifier = item[1], line = lineAt(content, item.index);
205
+ const observed = { file, line, specifier, kind: 'css-import', reachability };
206
+ if (/^@vini(?:-ds)?\/(?:tokens|ui)\/.+\.css$/i.test(specifier)) observed.resolution = packageCssResolution(require, specifier);
207
+ imports.push(observed);
208
+ if (specifier.startsWith('.')) { const next = await resolveLocal(file, specifier, appReal); if (next?.path && !next.blocked) schedule(next.path, reachability); else unresolved.push({ file, line, specifier, reachability, reason: next?.blocked ? 'outside selected app' : 'not found' }); }
209
+ if (/^(?:@vini(?:-ds)?\/tokens\/fonts\.css|@fontsource\/[a-z0-9-]+\/[^/]+\.css)$/i.test(specifier)) fonts.push(await inspectFontImport(require, specifier, { file, line, reachability }));
210
+ }
211
+ continue;
212
+ }
213
+ const parsed = importsAndProvider(content, file);
214
+ providerImports.push(...parsed.providerImports.map(x => ({ ...x, reachability }))); providerUses.push(...parsed.uses.map(x => ({ ...x, reachability })));
215
+ for (const item of parsed.imports) {
216
+ const itemReachability = reachability === 'dynamic' || item.kind === 'dynamic' ? 'dynamic' : 'static';
217
+ const location = { file, line: item.line, reachability: itemReachability };
218
+ if (item.kind === 'dynamic') {
219
+ dynamicImports.push({ ...location, specifier: item.specifier, literal: item.literal });
220
+ if (!item.literal) { unresolved.push({ ...location, specifier: null, reason: 'computed dynamic import not evaluated' }); continue; }
221
+ }
222
+ const observed = { ...location, specifier: item.specifier, kind: item.kind };
223
+ if (/^@vini(?:-ds)?\/(?:tokens|ui)\/.+\.css$/i.test(item.specifier)) observed.resolution = packageCssResolution(require, item.specifier);
224
+ imports.push(observed);
225
+ if (item.kind === 'type-only') continue;
226
+ if (item.specifier.startsWith('.')) {
227
+ const ext = path.extname(item.specifier.split(/[?#]/, 1)[0]);
228
+ if (ext && !supported.has(ext)) { unresolved.push({ ...location, specifier: item.specifier, reason: 'non-source import not inspected' }); continue; }
229
+ const next = await resolveLocal(file, item.specifier, appReal);
230
+ if (next?.path && !next.blocked) schedule(next.path, itemReachability); else unresolved.push({ ...location, specifier: item.specifier, reason: next?.blocked ? 'outside selected app' : 'not found' });
231
+ } else if (item.specifier.startsWith('@/') || item.specifier.startsWith('~/') || item.specifier.startsWith('/')) {
232
+ unresolved.push({ ...location, specifier: item.specifier, reason: 'project alias or absolute import not resolved by static scan' });
233
+ } else if (item.kind === 'dynamic') {
234
+ unresolved.push({ ...location, specifier: item.specifier, reason: 'external dynamic module not inspected' });
235
+ }
236
+ if (/^(?:@vini(?:-ds)?\/tokens\/fonts\.css|@fontsource\/[a-z0-9-]+\/[^/]+\.css)$/i.test(item.specifier))
237
+ fonts.push(await inspectFontImport(require, item.specifier, location));
238
+ }
239
+ }
240
+ const cssImports = imports.filter(item => /\.css(?:[?#].*)?$/.test(item.specifier));
241
+ return {
242
+ scope: { projectRoot: rootReal, appRoot: appReal, entry: entryReal, scannedFiles: visited.size, truncated: staticQueue.length + dynamicQueue.length > 0 },
243
+ dynamicImports,
244
+ coverage: 'Static and literal dynamic imports reachable from the selected entry are labelled separately; external modules, alias paths, runtime imports, HTML links, CSS-in-JS and browser-loaded assets are not fully evaluated.',
245
+ css: { imports: cssImports, potentiallyBroadRules: warnings },
246
+ provider: { imports: providerImports, jsxUses: providerUses, note: 'JSX observations do not cover every possible provider pattern and do not prove which provider wraps a rendered root.' },
247
+ fonts: { imports: fonts, localRules: localFonts, note: 'Existing asset files do not prove that a browser requested or rendered the fonts.' },
248
+ unresolved
249
+ };
250
+ }