From e9e2e502a29398ac9aacb67265a41fb12da761d5 Mon Sep 17 00:00:00 2001 From: AlexanderLevenskikh Date: Sun, 22 Nov 2026 23:24:18 +0500 Subject: [PATCH 01/15] feat: recursively discover React package.json workspaces and avoid generated-tree scans --- src/react-discovery.mjs | 140 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 src/react-discovery.mjs diff --git a/src/react-discovery.mjs b/src/react-discovery.mjs new file mode 100644 index 0000000..7966ff3 --- /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=2000, 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':'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.', + }, + }; +} From 697b477805cbeb68cfaf76659658f5aa28307bbf Mon Sep 17 00:00:00 2001 From: AlexanderLevenskikh Date: Sun, 22 Nov 2026 23:24:51 +0500 Subject: [PATCH 02/15] fix: quickstart selects recursive React package roots and never scans the whole monorepo by fallback --- src/quickstart.mjs | 62 ++++++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 29 deletions(-) diff --git a/src/quickstart.mjs b/src/quickstart.mjs index 9e63bdd..ec9e41a 100644 --- a/src/quickstart.mjs +++ b/src/quickstart.mjs @@ -3,34 +3,25 @@ import path from 'node:path'; import { loadConfig, loadCatalog, projectInfo } from './config.mjs'; import { mineProject, enrichMine, publicMineReport } from './mine.mjs'; import { reviewProjectSemantics } from './semantic.mjs'; -import { assert, contained, posix, slug, writeJson, EXCLUDED_DIRS } from './util.mjs'; +import { assert, contained, posix, slug, writeJson } from './util.mjs'; +import { discoverReactPackages } from './react-discovery.mjs'; // A local, noninteractive entry point: no target repo mutations, no user globals, // no compiler plugins and no loss of existing approval decisions. function projectRoots(root, explicitRoots) { - if(explicitRoots?.length){ - const found=explicitRoots.map(input=>fs.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,22 @@ 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(!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 React-related package.json was detected. Pass --source-path with an explicit React source directory; no whole-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 +95,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 +114,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 +125,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, From 4ca82322bef5a97c2db9429c78207736b308fc95 Mon Sep 17 00:00:00 2001 From: AlexanderLevenskikh Date: Sun, 22 Nov 2026 23:25:08 +0500 Subject: [PATCH 03/15] fix: cap discovered roots to valid rule applicability and preserve ambiguous root status --- src/react-discovery.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/react-discovery.mjs b/src/react-discovery.mjs index 7966ff3..182e879 100644 --- a/src/react-discovery.mjs +++ b/src/react-discovery.mjs @@ -13,7 +13,7 @@ const REACT_MARKERS = new Set([ '@remix-run/react','@tanstack/react-router', ]); const MAX_DIRS=150000, MAX_MANIFESTS=20000, MAX_MANIFEST_SIZE=512*1024; -const MAX_REACT_ROOTS=2000, MAX_DEPTH=100, MAX_GAPS=150; +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; @@ -120,7 +120,7 @@ export function discoverReactPackages(projectRoot){ } const codeRoots=selected.map(item=>path.resolve(root,item.directory)).sort(); const status=gaps.length?'INCOMPLETE': - codeRoots.length?'FOUND_REACT_PACKAGES':'NO_REACT_PACKAGES'; + 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, From e59b1366f1782227edc020be24eff2bb3373cbbf Mon Sep 17 00:00:00 2001 From: AlexanderLevenskikh Date: Sun, 22 Nov 2026 23:25:10 +0500 Subject: [PATCH 04/15] fix: present clear discovery instructions for ambiguous monorepo workspace roots --- src/quickstart.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/quickstart.mjs b/src/quickstart.mjs index ec9e41a..3c20921 100644 --- a/src/quickstart.mjs +++ b/src/quickstart.mjs @@ -85,7 +85,7 @@ export function quickstartProject(options){ semantic:{status:'NOT_RUN_UNVERIFIED_ROOTS'}, next:incomplete? 'Resolve sourceDiscovery.coverage.gaps; no catalog changes or source analysis were performed.': - 'No React-related package.json was detected. Pass --source-path with an explicit React source directory; no whole-repository fallback was run.'}; + '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, From e17c6ca1a88c41ec99e8d0aff5a73fce3855b02a Mon Sep 17 00:00:00 2001 From: AlexanderLevenskikh Date: Sun, 22 Nov 2026 23:25:12 +0500 Subject: [PATCH 05/15] fix: exclude confirmed Nx/Yarn and .NET generated output from source traversal --- src/util.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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) { From 9ebcb5e58499c413ceface6300abef1b189bcff3 Mon Sep 17 00:00:00 2001 From: AlexanderLevenskikh Date: Sun, 22 Nov 2026 23:25:24 +0500 Subject: [PATCH 06/15] test: update quickstart to require real package manifests and never use whole-repo fallback --- test/quickstart.test.mjs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) 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+" = () =>