Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
e9e2e50
feat: recursively discover React package.json workspaces and avoid ge…
AlexanderLevenskikh Nov 22, 2026
697b477
fix: quickstart selects recursive React package roots and never scans…
AlexanderLevenskikh Nov 22, 2026
4ca8232
fix: cap discovered roots to valid rule applicability and preserve am…
AlexanderLevenskikh Nov 22, 2026
e59b136
fix: present clear discovery instructions for ambiguous monorepo work…
AlexanderLevenskikh Nov 22, 2026
e17c6ca
fix: exclude confirmed Nx/Yarn and .NET generated output from source …
AlexanderLevenskikh Nov 22, 2026
9ebcb5e
test: update quickstart to require real package manifests and never u…
AlexanderLevenskikh Nov 22, 2026
7332348
test: reproduce deep BILLY-like workspaces, Nx/Yarn/generated files a…
AlexanderLevenskikh Nov 22, 2026
6c74d63
docs: explain recursive package-based React discovery and safe no-fal…
AlexanderLevenskikh Nov 22, 2026
6c6c2b5
docs: explain recursive package-based React discovery and safe no-fal…
AlexanderLevenskikh Nov 22, 2026
bebdb5f
docs: explain recursive package-based React discovery and safe no-fal…
AlexanderLevenskikh Nov 22, 2026
5405339
feat(quickstart): add read-only discovery-only preview with zero cata…
AlexanderLevenskikh Nov 22, 2026
cb19c96
feat(cli): add quickstart --discover-only for recursive React manifes…
AlexanderLevenskikh Nov 22, 2026
5c77fb2
test: discovery-only preview does not scan source or mutate catalog, …
AlexanderLevenskikh Nov 22, 2026
c72e086
docs: show discovery-only and one-command React analysis for BILLY
AlexanderLevenskikh Nov 22, 2026
052494b
docs: prefer cheap read-only package inventory before large monorepo …
AlexanderLevenskikh Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 9 additions & 3 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-монорепозитория

Expand Down
6 changes: 4 additions & 2 deletions bin/selfreview.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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;i<args.length;i++) {
const arg=args[i];
Expand Down Expand Up @@ -135,7 +136,8 @@ export function main(args=process.argv.slice(2)) {
};
const result=quickstartProject({
projectPath:absolute,dataDir,configPath:one(options,'config'),
sourcePaths:options['source-path']??[],enrich:!!options.enrich,semantic:!!options.semantic,
sourcePaths:options['source-path']??[],discoverOnly:!!options['discover-only'],
enrich:!!options.enrich,semantic:!!options.semantic,
tsconfig:one(options,'tsconfig'),semanticProfile:one(options,'semantic-profile'),
minFiles:numeric('min-files',3),maxFiles:numeric('max-files',20000),
maxPatterns:numeric('max-patterns',100),maxSemanticFiles:numeric('max-semantic-files',4000),
Expand Down
10 changes: 9 additions & 1 deletion docs/CODEBASE_SEMANTIC.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,15 @@ npm.cmd ci --ignore-scripts
node .\bin\selfreview.mjs quickstart --project-path 'C:\Users\levenskikh\Desktop\billy'
~~~

Будет автоматически найдена папка react-apps (на глубине до 3 папок), выбран или создан локальный каталог SelfReview, а отчёт появится в \`C:\Users\levenskikh\Desktop\selfreview-data\billy\react-apps.mine.json\`. По умолчанию это read-only. При повторном запуске существующий каталог не перезаписывается.
SelfReview рекурсивно найдёт все доступные \`package.json\` вне директорий сборки, отберёт пакеты с React-зависимостями и запишет их список и признаки определения в \`sourceDiscovery.matches\`. Глубина не ограничена тремя уровнями; действует защитный предел обхода. Никакого сканирования всего BILLY при неудачном обнаружении больше нет. Отчёт появится по адресу \`C:\Users\levenskikh\Desktop\selfreview-data\billy\react-apps.mine.json\`. При повторном запуске существующий каталог не перезаписывается.

Для большого BILLY сначала проверь обнаруженные каталоги, не читая исходники и не изменяя каталог правил:

~~~powershell
node .\bin\selfreview.mjs quickstart --project-path 'C:\Users\levenskikh\Desktop\billy' --discover-only
~~~

Поле `sourceDiscovery.matches` покажет пути к вложенным React-пакетам, SHA-256 соответствующих `package.json` и признаки React-зависимостей. При неполном обнаружении команда возвращает exit 2 и не запускает сканирование всего монорепозитория.

Чтобы **обогатить каталог кандидатами** и при желании запустить P2:

Expand Down
70 changes: 41 additions & 29 deletions src/quickstart.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;i<found.length;i++)for(let j=i+1;j<found.length;j++)
assert(!contained(found[i],found[j])&&!contained(found[j],found[i]),
'Overlapping source roots are not allowed');
return [...new Set(found)].sort();
return folder;
});
const unique=[...new Set(found)].sort();
for(let i=0;i<unique.length;i++)for(let j=i+1;j<unique.length;j++) {
assert(!contained(unique[i],unique[j]),'Overlapping source roots are not allowed');
}
const found=[];
function visit(directory,depth){
if(depth>3)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)){
Expand Down Expand Up @@ -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,
Expand All @@ -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){
Expand All @@ -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':
Expand All @@ -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,
Expand Down
Loading
Loading