diff --git a/README.md b/README.md index 75a12eb..05eaee7 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ From an installed SelfReview clone, run: node .\bin\selfreview.mjs quickstart --project-path 'C:\Users\levenskikh\Desktop\billy' ``` -The command locates `react-apps`, creates a catalog only when none exists at the selected data location, and mines read-only AST observations. Add `--enrich` to import unapproved candidates and `--semantic` to opt into a bounded TypeScript import graph and React review. Existing approvals are not promoted or overwritten. If rules live in a different config, provide its exact path with `--config`. See [P2 semantic walkthrough](docs/CODEBASE_SEMANTIC.md) and [Russian commands](docs/CODEBASE_SEMANTIC.ru.md). +The command recursively discovers `package.json` manifests at any normal nested workspace depth, chooses React-dependent packages (including Next and Vite React projects), skips generated Nx/Yarn/.NET outputs and reports evidence in `sourceDiscovery.matches`. It never falls back to scanning the whole repository if no React project is confirmed. Existing catalog approvals are preserved; a new catalog is only created if none exists at the selected data location. Add `--enrich` to import unapproved candidates and `--semantic` to opt into a bounded TypeScript import graph and React review. Existing approvals are not promoted or overwritten. If rules live in a different config, provide its exact path with `--config`. See [P2 semantic walkthrough](docs/CODEBASE_SEMANTIC.md) and [Russian commands](docs/CODEBASE_SEMANTIC.ru.md). ## Discover conventions from an existing React monorepo diff --git a/README.ru.md b/README.ru.md index 3830683..712f8a3 100644 --- a/README.ru.md +++ b/README.ru.md @@ -27,13 +27,19 @@ CLI и адаптер ESLint. ## Быстрый запуск BILLY одной командой (P2) -Из установленного SelfReview: +Из установленного SelfReview сначала проверь найденные React-проекты **без анализа всех исходников и без изменения правил**: ```powershell -node .\bin\selfreview.mjs quickstart --project-path 'C:\Users\levenskikh\Desktop\billy' +node .\bin\selfreview.mjs quickstart --project-path 'C:\Users\levenskikh\Desktop\billy' --discover-only ``` -Команда находит `react-apps`, использует существующий каталог в папке результатов или создаёт новый, если его ещё нет, и собирает AST-наблюдения без изменения проекта. `--enrich` добавляет только неподтверждённые кандидаты, `--semantic` включает ограниченный TypeScript-анализ. Если твои старые правила находятся в другом месте, передай существующий `--config`. [Пошаговая инструкция P2](docs/CODEBASE_SEMANTIC.ru.md). +Затем запусти майнинг и P2: + +```powershell +node .\bin\selfreview.mjs quickstart --project-path 'C:\Users\levenskikh\Desktop\billy' --enrich --semantic +``` + +Команда **рекурсивно находит `package.json`** (не только в папках первого уровня), выбирает проекты по зависимостям React/Next/Vite React, пропускает Nx/Yarn-кэши и .NET-сборки и перечисляет найденные каталоги в `sourceDiscovery.matches`. Исходники других проектов не анализируются. Существующий каталог правил сохраняется, а при отсутствии найденных React-пакетов сканирование всего BILLY **не** запускается. `--enrich` добавляет только неподтверждённые кандидаты, `--semantic` включает ограниченный TypeScript-анализ. Если твои старые правила находятся в другом месте, передай существующий `--config`. [Пошаговая инструкция P2](docs/CODEBASE_SEMANTIC.ru.md). ## Изучение исходников React-монорепозитория diff --git a/bin/selfreview.mjs b/bin/selfreview.mjs index 77b8274..43322fa 100755 --- a/bin/selfreview.mjs +++ b/bin/selfreview.mjs @@ -25,6 +25,7 @@ learn --scope NAME [--docs FILE_OR_FOLDER ...] [--mr FILE ...] mine --project ID [--code FOLDER ...] [--min-files 3] [--max-files 20000] [--max-patterns 60] [--out REPORT.json] [--enrich] quickstart --project-path FOLDER [--data-dir FOLDER] [--source-path FOLDER ...] + [--discover-only] # recursive React package.json inventory, no code scan [--enrich] [--semantic] [--tsconfig FILE] [--max-semantic-files 4000] semantic --project ID [--code FOLDER ...] [--tsconfig FILE] [--semantic-profile FILE] [--max-semantic-files 4000] [--out FILE] @@ -60,7 +61,7 @@ No AI API or network requests; no execution of inspected project code. function argumentsOf(args) { const positional=[],options={}; - const booleans=new Set(['help','version','json','no-code','merge-base','staged','new-only','enrich','semantic']); + const booleans=new Set(['help','version','json','no-code','merge-base','staged','new-only','enrich','semantic','discover-only']); const values=new Set(['config','scope','project','extends','docs','mr','diff','comments','proposals','code','min-samples','threshold','min-files','max-files','max-patterns','knowledge','tsconfig','semantic-profile','max-semantic-files','semantic-code','project-path','data-dir','source-path','by','reason','format','out','base','file','input']); for (let i=0;ifs.realpathSync(path.resolve(input))); - assert(found.every(folder=>contained(root,folder)&&fs.statSync(folder).isDirectory()), + if (!explicitRoots?.length) return discoverReactPackages(root); + const found = explicitRoots.map(input => { + const folder=fs.realpathSync(path.resolve(input)); + assert(contained(root,folder) && fs.statSync(folder).isDirectory(), 'All --source-path folders must exist under --project-path'); - for(let i=0;i3)return; - const entries=fs.readdirSync(directory,{withFileTypes:true}); - for(const entry of entries){ - if(!entry.isDirectory()||entry.isSymbolicLink()||EXCLUDED_DIRS.has(entry.name))continue; - const folder=path.join(directory,entry.name); - if(entry.name.toLowerCase()==='react-apps'){found.push(fs.realpathSync(folder));continue;} - // Limit discovery to the top few levels instead of searching a huge repo. - if(depth<3)visit(folder,depth+1); - } - } - visit(root,0); - return found.length?[...new Set(found)].sort():[root]; + return {status:'EXPLICIT',mode:'EXPLICIT_SOURCE_ROOTS',complete:true,codeRoots:unique, + matches:[],coverage:{complete:true,gaps:[],gapCount:0}}; } function preparedConfig(root,folder,filename){ if(fs.existsSync(filename)){ @@ -80,8 +71,30 @@ export function quickstartProject(options){ const configFile=path.resolve(options.configPath??path.join(folder,'selfreview.config.json')); if(!fs.existsSync(configFile))assert(contained(folder,configFile), 'A new quickstart config must be created inside --data-dir; use --config to reuse an existing policy anywhere'); - const selected=projectRoots(root,options.sourcePaths); - const rootFallback=!options.sourcePaths?.length&&selected.length===1&&selected[0]===root; + const sourceDiscovery=projectRoots(root,options.sourcePaths); + const selected=sourceDiscovery.codeRoots; + if(options.discoverOnly){ + const status=!sourceDiscovery.complete?'SOURCE_DISCOVERY_INCOMPLETE': + selected.length?'REACT_PACKAGES_DISCOVERED':'SOURCE_ROOT_UNCERTAIN'; + return {schemaVersion:1,mode:'quickstart-discovery',status,exitCode:status==='REACT_PACKAGES_DISCOVERED'?0:2, + projectRoot:root,codeRoots:selected,config:configFile,sourceDiscovery, + sourceCodeAnalyzed:false,configCreated:false,catalogChanged:false, + next:'Inspect sourceDiscovery.matches, then rerun without --discover-only to perform AST mining.'}; + } + if(!sourceDiscovery.complete || !selected.length) { + const incomplete=!sourceDiscovery.complete; + const status=incomplete?'SOURCE_DISCOVERY_INCOMPLETE':'SOURCE_ROOT_UNCERTAIN'; + return {schemaVersion:1,mode:'quickstart',status,exitCode:2, + projectRoot:root,codeRoots:selected,config:configFile, + configCreated:false,existingPolicyPreserved:true, + sourceDiscovery, + mining:{status:'NOT_RUN_UNVERIFIED_ROOTS',analyzedFiles:0,patternCount:0}, + enrichment:{status:'NOT_APPLIED_UNVERIFIED_ROOTS'}, + semantic:{status:'NOT_RUN_UNVERIFIED_ROOTS'}, + next:incomplete? + 'Resolve sourceDiscovery.coverage.gaps; no catalog changes or source analysis were performed.': + 'No safe React package roots selected. Inspect sourceDiscovery.matches/omitted or pass --source-path; no full-repository fallback was run.'}; + } const {context,projectId,scope,created}=preparedConfig(root,folder,configFile); const mine=mineProject(context,projectId,{codePaths:selected, minFiles:options.minFiles??3,maxFiles:options.maxFiles??20000, @@ -90,9 +103,9 @@ export function quickstartProject(options){ writeJson(reportPath,publicMineReport(mine)); let enrichment={status:'NOT_REQUESTED'}; if(options.enrich){ - enrichment=mine.coverage.complete&&!rootFallback + enrichment=mine.coverage.complete&&mine.analyzedFiles>0 ?{status:'CANDIDATES_IMPORTED',...enrichMine(context,mine)} - :{status:'NOT_APPLIED_INCOMPLETE',reason:rootFallback?'react-apps was not found; select --source-path before importing candidates':'Fix coverage.gaps, then rerun'}; + :{status:'NOT_APPLIED_INCOMPLETE',reason:'No complete analyzable React sources; fix mining.coverage.gaps before enriching.'}; } let semantic={status:'NOT_REQUESTED'},semanticPath=null; if(options.semantic){ @@ -109,7 +122,7 @@ export function quickstartProject(options){ semantic={status:reviewed.status,exitCode:reviewed.exitCode,coverage:reviewed.coverage,report:semanticPath}; } } - const status=rootFallback?'SOURCE_ROOT_UNCERTAIN':!mine.coverage.complete?'INCOMPLETE_MINING': + const status=!mine.coverage.complete||mine.analyzedFiles===0?'INCOMPLETE_MINING': semantic.status==='INCOMPLETE'?'INCOMPLETE_SEMANTIC': semantic.status==='NOT_RUN_AMBIGUOUS_TSCONFIG'?'SEMANTIC_REQUIRES_CONFIG': semantic.exitCode===1?'VIOLATIONS': @@ -120,8 +133,7 @@ export function quickstartProject(options){ existingPolicyPreserved:!created, firstTimeCatalog:created?{ warning:'A new empty catalog was created. Any existing policy elsewhere must be selected using --config; it was not imported.'}:null, - sourceDiscovery:rootFallback?{reason:'REACT_APPS_NOT_FOUND',action:'Pass --source-path with the actual React source folder; no enrichment was applied'}: - {mode:options.sourcePaths?.length?'EXPLICIT':'AUTO_REACT_APPS'}, + sourceDiscovery, mining:{report:reportPath,status:mine.status,analyzedFiles:mine.analyzedFiles, patternCount:mine.patterns.length,coverage:mine.coverage}, enrichment,semantic, diff --git a/src/react-discovery.mjs b/src/react-discovery.mjs new file mode 100644 index 0000000..182e879 --- /dev/null +++ b/src/react-discovery.mjs @@ -0,0 +1,140 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { EXCLUDED_DIRS, contained, posix, sha256 } from './util.mjs'; + +// Discover local package manifests as inert data, never by requiring their modules. +// Explicit bounded traversal avoids scanning generated .NET/Nx/Yarn output in large monorepos. +const IGNORED = new Set([...EXCLUDED_DIRS, + '.nx','.yarn','.cache','.turbo','.output','.parcel-cache','.angular', + 'obj','bin','out','Debug','Release','storybook-static','tmp','temp']); +const REACT_MARKERS = new Set([ + 'react','react-dom','react-native','react-scripts','next','gatsby', + '@types/react','@vitejs/plugin-react','@vitejs/plugin-react-swc', + '@remix-run/react','@tanstack/react-router', +]); +const MAX_DIRS=150000, MAX_MANIFESTS=20000, MAX_MANIFEST_SIZE=512*1024; +const MAX_REACT_ROOTS=100, MAX_DEPTH=100, MAX_GAPS=150; +const normalize = value => posix(value); +const relative = (root,file) => normalize(path.relative(root,file))||'.'; +const exactDir = (a,b) => process.platform==='win32'?a.toLowerCase()===b.toLowerCase():a===b; + +function markersFor(data){ + const deps={...data.dependencies,...data.devDependencies,...data.peerDependencies,...data.optionalDependencies}; + return [...REACT_MARKERS].filter(key=>typeof deps[key]==='string').sort(); +} +function readManifest(filename,root){ + const file=relative(root,filename); + const stat=fs.lstatSync(filename); + if(!stat.isFile()||stat.isSymbolicLink())return {error:{path:file,reason:'PACKAGE_MANIFEST_NOT_REGULAR_FILE'}}; + if(stat.size>MAX_MANIFEST_SIZE)return {error:{path:file,reason:'PACKAGE_MANIFEST_TOO_LARGE',bytes:stat.size}}; + const content=fs.readFileSync(filename); + const raw=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(content); + const data=JSON.parse(raw); + if(!data||typeof data!=='object'||Array.isArray(data)) + return {error:{path:file,reason:'INVALID_PACKAGE_MANIFEST'}}; + return {manifest:{ + path:file, directory:relative(root,path.dirname(filename)), + name:typeof data.name==='string'?data.name:null, + markers:markersFor(data),sha256:sha256(content), + hasWorkspaces:Boolean(data.workspaces), + }}; +} + +export function discoverReactPackages(projectRoot){ + const root=fs.realpathSync(path.resolve(projectRoot)); + const visited=new Set(),stack=[{folder:root,depth:0}]; + const matches=[],manifestList=[],gaps=[]; + let scannedDirectories=0,packageJsonScanned=0,skippedGeneratedDirectories=0, + skippedSymlinks=0,unmatchedManifests=0,truncatedGaps=0; + + function gap(entry){ + if(gaps.lengthMAX_DIRS){ + gap({path:relative(root,folder),reason:'DIRECTORY_DISCOVERY_LIMIT',limit:MAX_DIRS}); + break; + } + let entries; + try{entries=fs.readdirSync(folder,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name,'en'));} + catch(error){gap({path:relative(root,folder),reason:'DIRECTORY_UNREADABLE',code:error.code??'UNKNOWN'});continue;} + for(const entry of entries){ + const child=path.join(folder,entry.name); + if(entry.isSymbolicLink()){ + if(IGNORED.has(entry.name)) {skippedGeneratedDirectories++;continue;} + skippedSymlinks++; + gap({path:relative(root,child),reason:'SYMLINK_NOT_FOLLOWED'}); + continue; + } + if(entry.isDirectory()){ + if(IGNORED.has(entry.name)){skippedGeneratedDirectories++;continue;} + if(depth+1>MAX_DEPTH){ + gap({path:relative(root,child),reason:'DEPTH_DISCOVERY_LIMIT',limit:MAX_DEPTH}); + continue; + } + stack.push({folder:child,depth:depth+1}); + } else if(entry.isFile()&&entry.name==='package.json'){ + if(packageJsonScanned>=MAX_MANIFESTS){ + gap({path:relative(root,child),reason:'PACKAGE_MANIFEST_LIMIT',limit:MAX_MANIFESTS}); + stack.length=0;break; + } + packageJsonScanned++; + try{ + const parsed=readManifest(child,root); + if(parsed.error){gap(parsed.error);continue;} + const item=parsed.manifest; + manifestList.push(item); + if(item.markers.length)matches.push(item); + else unmatchedManifests++; + }catch(error){ + gap({path:relative(root,child),reason:'PACKAGE_MANIFEST_PARSE_ERROR', + code:error.code??(error instanceof SyntaxError?'INVALID_JSON':'INVALID_UTF8_OR_READ')}); + } + } + } + } + // Prefer explicitly described nested React packages over their ancestor workspace + // shell. In particular, never silently scan an entire polyglot monorepo. + const candidates=matches.sort((a,b)=>a.directory.split('/').length-b.directory.split('/').length|| + a.directory.localeCompare(b.directory,'en')); + const selected=[],omitted=[]; + for(const item of candidates){ + const folder=path.resolve(root,item.directory); + if(exactDir(folder,root)&&manifestList.some(other=>other.directory!=='.')){ + omitted.push({path:item.directory,reason:'WORKSPACE_ROOT_NOT_AUTO_SELECTED'});continue; + } + if(candidates.some(other=>other!==item&&other.directory!==item.directory&& + contained(folder,path.resolve(root,other.directory)))){ + omitted.push({path:item.directory,reason:'NESTED_REACT_PACKAGE_SELECTED'});continue; + } + selected.push(item); + if(selected.length>MAX_REACT_ROOTS){ + gap({path:item.directory,reason:'REACT_PACKAGE_LIMIT',limit:MAX_REACT_ROOTS}); + selected.pop();break; + } + } + const codeRoots=selected.map(item=>path.resolve(root,item.directory)).sort(); + const status=gaps.length?'INCOMPLETE': + codeRoots.length?'FOUND_REACT_PACKAGES':matches.length?'AMBIGUOUS_WORKSPACE_ROOT':'NO_REACT_PACKAGES'; + return { + status,complete:gaps.length===0,mode:'RECURSIVE_PACKAGE_JSON', + discoveryDepthLimit:MAX_DEPTH,scanRoot:root, + packageJsonScanned,scannedDirectories,reactPackagesMatched:matches.length, + reactPackagesSelected:codeRoots.length,unmatchedManifests, + skippedGeneratedDirectories,skippedSymlinks, + matches:selected.map(item=>({ + path:item.directory,manifest:item.path,name:item.name, + evidence:{kind:'package.json',sha256:item.sha256,reactMarkers:item.markers}, + })), + omitted,codeRoots,coverage:{ + complete:gaps.length===0,gaps,gapCount:gaps.length+truncatedGaps, + omittedGapDetails:truncatedGaps, + note:'Only packages with explicit React-related dependencies are auto-selected. Workspace roots and unrelated packages are not treated as React projects.', + }, + }; +} diff --git a/src/util.mjs b/src/util.mjs index f367956..a3e4f79 100644 --- a/src/util.mjs +++ b/src/util.mjs @@ -5,7 +5,7 @@ import crypto from 'node:crypto'; export const VERSION = '0.2.0'; export const EXTENSIONS = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts']); export const DEFAULT_INCLUDE = [...EXTENSIONS].map(e => `**/*${e}`); -export const EXCLUDED_DIRS = new Set(['node_modules', '.git', '.selfreview', 'dist', 'build', 'coverage', '.next', '.nuxt', 'vendor']); +export const EXCLUDED_DIRS = new Set(['node_modules', '.git', '.selfreview', 'dist', 'build', 'coverage', '.next', '.nuxt', 'vendor', '.nx', '.yarn', '.cache', '.turbo', '.parcel-cache', 'obj', 'bin']); export const posix = value => value.replaceAll('\\', '/'); export const sha256 = value => crypto.createHash('sha256').update(value).digest('hex'); export function stable(value) { diff --git a/test/quickstart.test.mjs b/test/quickstart.test.mjs index 9227b43..a158a85 100644 --- a/test/quickstart.test.mjs +++ b/test/quickstart.test.mjs @@ -13,6 +13,10 @@ function fixture(t){ t.after(()=>fs.rmSync(temp,{recursive:true,force:true})); const root=path.join(temp,'billy'),react=path.join(root,'react-apps'),data=path.join(temp,'my-reports'); fs.mkdirSync(react,{recursive:true}); + fs.writeFileSync(path.join(react,'package.json'),JSON.stringify({ + name:'@billy/sample-react-app',private:true, + dependencies:{react:'^18.3.1','react-dom':'^18.3.1'}, + })); for(let i=0;i<3;i++)fs.writeFileSync(path.join(react,'Component'+i+'.tsx'), "import { Button } from '@team/ui';\n"+ "export const Widget"+i+" = () =>