rapidkit 0.34.0 → 0.36.0
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 +137 -706
- package/contracts/backend-import-stack-parity.snapshot.json +36 -36
- package/contracts/infra-stack.v1.json +190 -47
- package/contracts/module-layout.v1.json +12 -3
- package/contracts/module-support.v1.json +20 -0
- package/contracts/runtime-command-surface.v1.json +139 -22
- package/contracts/workspace-intelligence/workspace-context.v1.json +59 -0
- package/contracts/workspace-intelligence/workspace-impact.v1.json +84 -0
- package/contracts/workspace-intelligence/workspace-model-diff.v1.json +105 -0
- package/contracts/workspace-intelligence/workspace-model-snapshot.v1.json +36 -0
- package/contracts/workspace-intelligence/workspace-model.v1.json +50 -0
- package/contracts/workspace-intelligence/workspace-verify.v1.json +111 -0
- package/dist/analyze-HXO6R656.js +1 -0
- package/dist/autopilot-release-FMQ5KND5.js +1 -0
- package/dist/chunk-45KNNNAB.js +2 -0
- package/dist/chunk-7ZSURMR2.js +4 -0
- package/dist/chunk-A5FBGRJA.js +1 -0
- package/dist/{chunk-3TBSWOTY.js → chunk-DC44JPI3.js} +13 -13
- package/dist/chunk-HHJAANUC.js +1 -0
- package/dist/{chunk-2PGMJSO5.js → chunk-HUQ5WRUF.js} +86 -86
- package/dist/chunk-KIB4KHBF.js +3 -0
- package/dist/chunk-KMUWWZRT.js +1 -0
- package/dist/chunk-MCLLP6MW.js +2 -0
- package/dist/chunk-OCGZNSOE.js +1 -0
- package/dist/chunk-TC2PSHT6.js +50 -0
- package/dist/chunk-UY4LZEXK.js +7 -0
- package/dist/chunk-UZW5QFRW.js +5 -0
- package/dist/chunk-VPNHGQIV.js +1 -0
- package/dist/chunk-Y2ZPG7KN.js +9 -0
- package/dist/chunk-YBS2HGO3.js +2 -0
- package/dist/chunk-YJ24EV3P.js +1 -0
- package/dist/create-7R4CGABE.js +1 -0
- package/dist/{doctor-3SBEO7XU.js → doctor-DG3TBPZN.js} +1 -1
- package/dist/imported-projects-registry-ZOCHFWMK.js +1 -0
- package/dist/index.d.ts +29 -2
- package/dist/index.js +135 -129
- package/dist/module-layout-NZ43RSC5.js +1 -0
- package/dist/pipeline-23AEXNF2.js +5 -0
- package/dist/{workspace-AG2MQFTY.js → workspace-ZDL5IQU4.js} +1 -1
- package/dist/workspace-context-YFQQROOZ.js +2 -0
- package/dist/{workspace-contract-Z5VYUF3T.js → workspace-contract-A6QP7FPA.js} +1 -1
- package/dist/workspace-foundation-QVWALXMP.js +1 -0
- package/dist/workspace-intelligence-VLA2RILM.js +1 -0
- package/dist/workspace-model-OO4WOBJS.js +1 -0
- package/dist/workspace-run-NIKH2IKF.js +1 -0
- package/dist/workspace-verify-XEXRCET7.js +1 -0
- package/package.json +14 -4
- package/dist/analyze-SVYRQNLO.js +0 -1
- package/dist/autopilot-release-LBKCP73F.js +0 -1
- package/dist/chunk-4E6ZGX6V.js +0 -1
- package/dist/chunk-ILY6QARY.js +0 -9
- package/dist/chunk-JIECGCLV.js +0 -4
- package/dist/chunk-KXTXQODI.js +0 -5
- package/dist/chunk-QCZGNOTH.js +0 -2
- package/dist/chunk-QUNCXYYK.js +0 -1
- package/dist/chunk-RGXFDBYB.js +0 -7
- package/dist/chunk-SAIWD6VM.js +0 -3
- package/dist/chunk-Y3UKTEZO.js +0 -2
- package/dist/chunk-YV7IQDBM.js +0 -50
- package/dist/create-BO2I3ESU.js +0 -1
- package/dist/module-layout-J56LHEGH.js +0 -1
- package/dist/pipeline-VUQ6AXKF.js +0 -5
- package/dist/workspace-foundation-G74V6K4U.js +0 -1
- package/dist/workspace-run-EDM3SUPA.js +0 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {n,q as q$1,g}from'./chunk-YBS2HGO3.js';import {h,i,f,e}from'./chunk-UZW5QFRW.js';import {a}from'./chunk-VKLL63TL.js';import I from'fs';import w from'path';import S from'chalk';import {execa}from'execa';function ue(e){return I.existsSync(w.join(e,"bun.lock"))||I.existsSync(w.join(e,"bunfig.toml"))?"bun":I.existsSync(w.join(e,"pnpm-lock.yaml"))?"pnpm":I.existsSync(w.join(e,"yarn.lock"))?"yarn":(I.existsSync(w.join(e,"package-lock.json")),"npm")}function de(e,t,r=ue(e)){return r==="npm"?`npm run ${t}`:`${r} run ${t}`}function le(e,t=ue(e)){return `${t} install`}var Ce={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},Pe={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],elixir:["mix deps.get"],ruby:["bundle install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],elixir:["mix compile"],ruby:["gem build *.gemspec"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function pe(e$1,t,r){if(t){let o=t.trim().toLowerCase().replace(/[_.\s]+/g,"-"),a=e(t),g=`${e$1}-${a==="gofiber"?"fiber":a==="gogin"?"gin":a==="dotnet"?"aspnetcore":a!=="unknown"?a:o==="fiber"?"fiber":o==="aspnetcore"||o==="asp-net-core"?"aspnetcore":o}`,f=Ce[g];if(f&&f.commands[r])return f.commands[r]}let n=Pe[r]?.[e$1]??[];return n.length>0?n[0]:void 0}var Fe={test:"test",build:"build",start:"start"};function H(e){if(e.stage==="init")return e.runtime==="node"?le(e.projectPath):pe(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let t=Fe[e.stage];if(t){let r=g(e.projectPath,t,{framework:e.framework});if(r)return de(e.projectPath,r.scriptName)}}return pe(e.runtime,e.framework,e.stage)}function Ae(e){let t=h(e).map(r=>r==="python"?"python":r==="node"||r==="bun"?"node":r==="go"?"go":r==="java"?"java":r==="php"?"php":r==="rust"?"rust":r==="dotnet"?"dotnet":r==="elixir"?"elixir":r==="ruby"?"ruby":r==="clojure"||r==="scala"||r==="kotlin"?"jvm-generic":null).filter(r=>r!==null).filter((r,n,o)=>o.indexOf(r)===n);return {primary:t.length>0?t[0]:"unknown",secondary:t.slice(1)}}function me(e){return Ae(e).primary}function fe(e,t){if(!e)return "unknown";t||(t={setup:["ModuleNotFoundError","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[r,n]of Object.entries(t))for(let o of n)if(new RegExp(o,"i").test(e))return r;return "unknown"}async function z(e){let t=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(t))return {valid:true};try{let n=process.platform==="win32"?"where":"which";if((await execa(n,[t],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${t}' not found or not executable`}}function ge(e,t,r){if(!t)return e;let n=typeof t=="object"&&!Array.isArray(t)&&("dev"in t||"staging"in t||"prod"in t||"default"in t)&&!Object.keys(t).some(o=>["init","test","build","start"].includes(o))?t:{};return r&&typeof n[r]=="string"?n[r]:typeof n.default=="string"?n.default:e}var ye={init:"init",test:"test",build:"build",start:"start"};function Ne(e){return e in ye?ye[e]:null}function he(e,t,r=q$1(e)){let n=Ne(t);if(!n)return {supported:false,reason:`Workspace stage "${t}" is not part of the RapidKit fleet contract.`};if(!r.projectRoot)return {supported:false,reason:"No RapidKit project metadata was detected for this target."};let o=r.commandMap[n];return !o||o.status!=="supported"?{supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`}:{supported:true}}var ke="workspace-run-last.json",$e=new Set(["init","test","build","start"]),Te=new Set([".git","node_modules",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function W(e){try{return await I.promises.access(e,I.constants.F_OK),true}catch{return false}}async function q(e){let t=await I.promises.readFile(e,"utf-8");return JSON.parse(t)}async function De(e,t){await I.promises.mkdir(w.dirname(e),{recursive:true}),await I.promises.writeFile(e,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,"utf-8");}function A(e){return e.replace(/\\/g,"/")}function Ie(e){let t=e?.trim();return t?t.startsWith("project:")?t.slice(8).trim()||null:t:null}async function We(e){return a(e,{skipDirs:Te,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t,r)=>await W(w.join(t,".rapidkit","context.json"))||await W(w.join(t,".rapidkit","project.json"))?true:w.resolve(t)===w.resolve(r)?false:h(t).length>0})}async function Me(e){for(let t of [w.join(".rapidkit","project.json"),w.join(".rapidkit","context.json")]){let r=w.join(e,t);if(await W(r))try{let n=await q(r),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function Oe(e,t,r){let n=Ie(r);if(!n)return {projects:t,normalizedScope:null};let o=A(n).toLowerCase(),a=[];for(let d of t){let g=A(w.relative(e,d)),f=w.basename(d),m=await Me(d);[g,f,m].filter(i=>typeof i=="string"&&i.length>0).map(i=>A(i).toLowerCase()).includes(o)&&a.push(d);}if(a.length===0)throw new Error(`Workspace run scope did not match any project: ${r}`);return {projects:a,normalizedScope:n}}async function Le(e,t,r){let n=await execa("git",["diff","--name-only",`${r}...HEAD`],{cwd:e,reject:false});if(n.exitCode!==0)return new Set(t);let o=n.stdout.split(/\r?\n/).map(d=>d.trim()).filter(d=>d.length>0).map(d=>A(d));if(o.length===0)return new Set;let a=new Set;for(let d of t){let g=A(w.relative(e,d));if(!g||g===".")continue;let f=`${g}/`;o.some(m=>m===g||m.startsWith(f))&&a.add(d);}return a}async function Ge(e,t,r){let n=w.join(e,".rapidkit","workspace.contract.json");if(await W(n))try{let s=await _e(e,t,r,n);if(s.graphStatus!=="missing")return s}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let o=w.join(e,".rapidkit","workspace-dependency-graph.json");if(!await W(o))return {expanded:r,graphStatus:"missing",expansionDepth:0};let a;try{a=await q(o);}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let d=new Set(t.map(s=>w.resolve(s))),g=new Map;if(!a||typeof a!="object"||Array.isArray(a))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let f=Array.isArray(a.projects)?a.projects:[];for(let s of f){if(!s||typeof s!="object"||Array.isArray(s))continue;let x=s,j=typeof x.path=="string"?x.path:"",y=w.resolve(e,j);if(!d.has(y))continue;let c=Array.isArray(x.dependsOn)?x.dependsOn.filter(l=>typeof l=="string"):[];for(let l of c){let v=w.resolve(e,l);d.has(v)&&(g.has(v)||g.set(v,new Set),g.get(v)?.add(y));}}let m=new Set(r),b=[...m],i=0;for(;b.length>0;){let s=b.shift();if(!s)continue;let x=g.get(s);if(x)for(let j of x)m.has(j)||(m.add(j),b.push(j),i+=1);}return {expanded:m,graphStatus:"loaded",expansionDepth:i}}async function _e(e,t,r,n){let o=await q(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let a=o,d=Array.isArray(a.projects)?a.projects:null;if(!d)return {expanded:r,graphStatus:"invalid",expansionDepth:0};let g=new Map,f=new Map;for(let y of t){let c=A(w.relative(e,y));f.set(c,w.resolve(y));}let m=new Map,b=new Map,i=new Map;for(let y of d){if(!y||typeof y!="object"||Array.isArray(y))continue;let c=y,l=typeof c.slug=="string"?c.slug:"",v=typeof c.relativePath=="string"?A(c.relativePath):l,R=f.get(v);!l||!R||g.set(l,R);}for(let y of d){if(!y||typeof y!="object"||Array.isArray(y))continue;let c=y,l=typeof c.slug=="string"?c.slug:"",v=g.get(l);if(!v)continue;let R=c.contracts&&typeof c.contracts=="object"&&!Array.isArray(c.contracts)?c.contracts:{},M=Array.isArray(R.dependsOn)?R.dependsOn.filter(h=>typeof h=="string"):[],N=Array.isArray(R.publishes)?R.publishes.filter(h=>typeof h=="string"):[],$=Array.isArray(R.consumes)?R.consumes.filter(h=>typeof h=="string"):[];for(let h of M){let C=g.get(h);C&&(i.has(C)||i.set(C,new Set),i.get(C)?.add(v));}for(let h of N)m.has(h)||m.set(h,new Set),m.get(h)?.add(v);for(let h of $)b.has(h)||b.set(h,new Set),b.get(h)?.add(v);}for(let[y,c]of m.entries()){let l=b.get(y);if(l)for(let v of c){i.has(v)||i.set(v,new Set);for(let R of l)R!==v&&i.get(v)?.add(R);}}let s=new Set(r),x=[...s],j=0;for(;x.length>0;){let y=x.shift();if(!y)continue;let c=i.get(y);if(c)for(let l of c)s.has(l)||(s.add(l),x.push(l),j+=1);}return {expanded:s,graphStatus:"loaded",expansionDepth:j}}async function Be(e,t){if(typeof t=="boolean")return t;let r=w.join(e,".rapidkit","policies.yml");if(!await W(r))return true;let n="";try{n=await I.promises.readFile(r,"utf-8");}catch{return true}let o=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o?o[1]==="true":true}async function J(e,t){let r=process.argv[1];if(!r)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};let n=await execa(process.execPath,[r,...e],{cwd:t,reject:false,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});return {exitCode:Number(n.exitCode??1),stdout:n.stdout,stderr:n.stderr}}function Ke(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"}function Ve(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}async function He(e){let t=process.cwd();try{process.chdir(e);let{handleInitCommand:r}=await import('./index.js');return {exitCode:await r(["init"]),stdout:"",stderr:""}}finally{process.chdir(t);}}async function ze(e$1){let t=i=>{let s=f(i);return s==="node"||s==="bun"?"node":s==="python"?"python":s==="go"?"go":s==="java"?"java":s==="php"?"php":s==="ruby"?"ruby":s==="rust"?"rust":s==="dotnet"?"dotnet":s==="elixir"?"elixir":s==="clojure"||s==="scala"||s==="kotlin"?"jvm-generic":me(e$1)},r=i=>{if(!i)return;let s=e(i);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(s))return s},n$1=n(e$1),o=n$1?.detection??i(e$1,n$1?.projectJson??null),a=n$1?.contextJson,d=t(o.runtime),g=r(o.key),f$1={},m=new Set(["init","test","build","start"]);if(a?.commands&&typeof a.commands=="object")for(let[i,s]of Object.entries(a.commands))typeof s=="string"&&m.has(i)&&(f$1[i]=s);let b;if(a?.commandEnvironments&&typeof a.commandEnvironments=="object"){let i=a.commandEnvironments;b={dev:typeof i.dev=="string"?i.dev:void 0,staging:typeof i.staging=="string"?i.staging:void 0,prod:typeof i.prod=="string"?i.prod:void 0,default:typeof i.default=="string"?i.default:void 0};}return {runtime:d,framework:g,commandOverrides:Object.keys(f$1).length>0?f$1:void 0,environmentCommandVariants:b,environment:typeof a?.environment=="string"?a.environment:void 0}}async function Je(e,t,r,n,o,a,d){let g=!o?.[t]&&Ke(r),f;if(o&&o[t]?f=o[t]:g?f=`rapidkit ${t}`:f=H({projectPath:e,runtime:r,framework:n,stage:t}),!f)return {exitCode:127,command:`<stage not supported for ${r}>`,message:`No stage command found for runtime '${r}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let m=ge(f,a,d);if(!m)return {exitCode:127,command:f,message:"Failed to resolve stage command",errorCategory:"runtime"};let b=H({projectPath:e,runtime:r,framework:n,stage:t});if(g){if(b){let c=await z(b);if(!c.valid)return {exitCode:127,command:m,message:c.reason||"Command not available",errorCategory:"setup"}}}else {let c=await z(m);if(!c.valid)return {exitCode:127,command:m,message:c.reason||"Command not available",errorCategory:"setup"}}let i=0,s="",x="",j;try{let c=g?t==="init"&&Ve()?await He(e):await J([t],e):await execa(m,[],{cwd:e,reject:false,shell:true});if(i=Number(c.exitCode??0),s=c.stdout,x=c.stderr,i!==0){let l=`${s}
|
|
3
|
+
${x}`;j=fe(l);}}catch(c){return {exitCode:1,command:m,message:c instanceof Error?c.message:"Command execution failed",errorCategory:"runtime"}}return {exitCode:i,command:m,errorCategory:j,healthStatus:void 0,message:i!==0?`Stage failed with exit code ${i}`:void 0}}function we(e){try{return JSON.parse(e)}catch{return null}}function Ue(e){switch(e){case "dotnet":return "Install .NET 8+ SDK, then rerun `npx rapidkit setup dotnet` or `npx rapidkit init`.";case "go":return "Install Go 1.21+, then rerun `npx rapidkit setup go` or `npx rapidkit init`.";case "java":case "jvm-generic":return "Install Java 21+ and Maven/Gradle, then rerun `npx rapidkit setup java` or `npx rapidkit init`.";case "node":return "Install Node.js LTS and npm/pnpm/yarn, then rerun `npx rapidkit setup node` or `npx rapidkit init`.";case "python":return "Install Python 3.10+ and pip/Poetry, then rerun `npx rapidkit setup python` or `npx rapidkit init`.";default:return null}}async function qe(e){let t=[],r=await J(["doctor","workspace","--json"],e);if(r.exitCode!==0)t.push({gate:"doctor-workspace",status:"fail",summary:"doctor workspace command failed"});else {let a=we(r.stdout)?.healthScore,d=Number(a?.errors??0);Number.isFinite(d)&&d>0?t.push({gate:"doctor-workspace",status:"fail",summary:`doctor workspace reports ${d} error(s)`}):t.push({gate:"doctor-workspace",status:"pass",summary:"doctor workspace passed"});}let n=await J(["readiness","--json"],e);if(n.exitCode!==0)t.push({gate:"readiness",status:"fail",summary:"readiness command failed"});else {let o=we(n.stdout),a=String(o?.overallStatus??"").toLowerCase();a==="fail"?t.push({gate:"readiness",status:"fail",summary:"readiness overall status is fail"}):a==="warn"?t.push({gate:"readiness",status:"warn",summary:"readiness overall status is warn"}):t.push({gate:"readiness",status:"pass",summary:"readiness overall status is pass"});}return t}function Ye(e){return $e.has(e)}function Qe(e,t){let r=Math.max(1,Math.min(4,t)),n=Number(e??r);return Number.isFinite(n)?Math.max(1,Math.min(16,Math.trunc(n))):r}async function jt(e){if(!Ye(e.stage))throw new Error(`Unsupported workspace run stage: ${e.stage}`);let t=Date.now(),r=w.resolve(e.workspacePath),n=await We(r),{projects:o,normalizedScope:a}=await Oe(r,n,e.scope),d=e.affected===true,g=e.blastRadius===true,f=e.since?.trim()||"HEAD~1",m=d?await Le(r,o,f):new Set(o),b,i="not-applicable",s=0,x="all";if(d&&g){let p=await Ge(r,n,m);b=p.expanded,i=p.graphStatus,s=p.expansionDepth,x="affected+blast-radius";}else d?(b=m,x="affected"):(b=m,x="all");let j=e.stage==="init"?false:await Be(r,e.enforceGates),y=j?await qe(r):[{gate:"doctor-workspace",status:"skipped",summary:"workspace run gates disabled"},{gate:"readiness",status:"skipped",summary:"workspace run gates disabled"}],c=y.find(p=>p.status==="fail"),l=o.filter(p=>b.has(p)),v=e.continueOnError===true||e.stage==="init",R=e.parallel===true,M=Qe(e.maxWorkers,l.length),N=l.length,$=0;e.json||console.log(S.gray(`Workspace run (${e.stage}) started: ${N} target(s), ${R?`parallel x${M}`:"sequential"}`));let h=new Map;for(let p of n){let k=o.includes(p),u=k&&b.has(p);h.set(p,{path:p,relativePath:A(w.relative(r,p)),selected:u,affected:u,status:"skipped",exitCode:null,durationMs:0,reason:u?void 0:k?"not affected":"outside scope",framework:void 0,runtimeDetected:void 0,executionCommand:void 0});}if(c)for(let p of l){let k=h.get(p);k&&(k.status="skipped",k.reason=`blocked by ${c.gate}`);}else {let p=async k=>{let u=h.get(k);if(!u)return;let D=A(w.relative(r,k));e.json||console.log(S.gray(`\u23F3 [${$}/${N}] ${e.stage} ${D}`)),u.selected=true,u.affected=true;let P=Date.now(),{runtime:E,framework:F,commandOverrides:xe,environmentCommandVariants:ve,environment:Re}=await ze(k);u.runtimeDetected=E,u.framework=F;let te=he(k,e.stage);if(!te.supported){u.status="skipped",u.reason=te.reason??`stage "${e.stage}" unsupported for project`,u.durationMs=Date.now()-P,u.exitCode=null,$+=1;return}let T=await Je(k,e.stage,E,F,xe,ve,Re);if(u.executionCommand=T.command,u.errorCategory=T.errorCategory,u.healthStatus=T.healthStatus,u.durationMs=Date.now()-P,u.exitCode=T.exitCode,T.exitCode===0?(u.status="passed",u.reason=void 0):(u.status="failed",u.reason=T.message||"stage command failed",u.errorMessage=T.message),$+=1,!e.json){let je=N>0?Math.round($/N*100):100,Se=u.status==="passed"?S.green("\u2705"):S.red("\u274C");if(console.log(S.gray(`${Se} [${$}/${N}] (${je}%) ${D} ${u.durationMs}ms`)),u.status==="failed"){u.reason&&console.log(S.red(` Reason: ${u.reason}`)),u.executionCommand&&console.log(S.gray(` Command: ${u.executionCommand}`));let re=Ue(u.runtimeDetected);re&&u.errorCategory==="setup"&&console.log(S.gray(` Hint: ${re}`));}}};if(R&&l.length>1){let k=0,u=false,D=new Array(M).fill(null).map(async()=>{for(;k<l.length;){if(u&&!v)return;let P=k;k+=1;let E=l[P];await p(E),h.get(E)?.status==="failed"&&(u=true);}});if(await Promise.all(D),!v&&u){let P=false;for(let E of l){let F=h.get(E);if(F){if(F.status==="failed"){P=true;continue}P&&F.status==="skipped"&&(F.reason=F.reason||"stopped after failure");}}}}else for(let k of l){await p(k);let u=h.get(k);if(!v&&u?.status==="failed"){let D=l.slice(l.indexOf(k)+1);for(let P of D){let E=h.get(P);E&&(E.status="skipped",E.reason="stopped after failure");}break}}}let C=[];for(let p of n){let k=h.get(p);k&&C.push(k);}let Y=C.filter(p=>p.status==="passed").length,B=C.filter(p=>p.status==="failed").length,Q=C.filter(p=>p.status==="skipped").length,X=e.strict===true,be=B>0||X&&y.some(p=>p.status==="fail"||p.status==="warn")?1:0,Z={schemaVersion:"1.0",workspacePath:r,stage:e.stage,generatedAt:new Date().toISOString(),durationMs:Date.now()-t,options:{affected:d,blastRadius:g,since:d?f:null,parallel:R,maxWorkers:M,continueOnError:v,strict:X,enforceGates:j,scope:a},selection:{mode:x,since:d?f:null,scope:a,graphStatus:i,expansionDepth:s},gates:{enforced:j,results:y,blocked:!!c,blockingGate:c?.gate},summary:{projectCount:n.length,selectedCount:l.length,passed:Y,failed:B,skipped:Q,exitCode:be},projects:C,enterpriseControls:{jsonReady:true,evidencePath:`.rapidkit/reports/${ke}`}},ee=w.join(r,".rapidkit","reports",ke);return await De(ee,Z),e.json||(c&&(console.log(S.red(`\u274C Workspace run blocked by ${c.gate}`)),console.log(S.gray(` ${c.summary}`))),console.log(S.cyan(`Workspace run (${e.stage}) => passed: ${Y}, failed: ${B}, skipped: ${Q}`)),console.log(S.gray(`Report: ${ee}`))),Z}export{ke as a,jt as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import t from'fs';import o from'path';function k(i){let r=o.resolve(i);for(;;){if(t.existsSync(o.join(r,".rapidkit-workspace"))||t.existsSync(o.join(r,".rapidkit","workspace.json")))return r;let e=o.dirname(r);if(e===r)return null;r=e;}}function j(i){let r=o.resolve(i),e=t.existsSync(o.join(r,".rapidkit-workspace"))||t.existsSync(o.join(r,".rapidkit","workspace.json")),n=t.existsSync(o.join(r,".rapidkit","project.json"))||t.existsSync(o.join(r,".rapidkit","context.json"));return e&&!n}export{k as a,j as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-HHJAANUC.js';import {l}from'./chunk-OCGZNSOE.js';import c from'path';import h from'fs-extra';var j=".rapidkit/workspace.contract.json",P=1;function W(e){return e.replace(/\\/g,"/")}function y(e){let r=W(e).trim();return !r||r.startsWith("/")||r.startsWith("~")||/^[a-zA-Z]:\//.test(r)||r.includes("\0")?false:!r.split("/").filter(Boolean).some(o=>o===".."||o===".")}function S(e,r){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||r}function E(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0):[]}async function R(e){let r=c.join(e,".rapidkit","workspace.json");try{let o=await h.readJson(r);return {name:typeof o.workspace_name=="string"&&o.workspace_name.trim()||typeof o.name=="string"&&o.name.trim()||c.basename(e),profile:typeof o.profile=="string"?o.profile:void 0}}catch{return {name:c.basename(e)}}}async function O(e){let r=[],o=[e],n=new Set,i=new Set([".git","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;o.length>0;){let a=o.shift();if(!a||n.has(a))continue;n.add(a);let p=c.join(a,".rapidkit","project.json"),l=c.join(a,".rapidkit","context.json");if(await h.pathExists(p)||await h.pathExists(l)){r.push(await h.pathExists(p)?p:l);continue}let t;try{t=await h.readdir(a,{withFileTypes:true});}catch{continue}for(let s of t)!s.isDirectory()||i.has(s.name)||o.push(c.join(a,s.name));}return r.sort()}function J(e){let r=(e||"").toLowerCase();if(r.includes("fastapi"))return "fastapi";if(r.includes("nestjs"))return "nestjs";if(r.includes("springboot"))return "springboot";if(r.includes("gofiber"))return "fiber";if(r.includes("gogin"))return "gin"}function _(e,r){let o=(e||"").toLowerCase(),n=(r||"").toLowerCase();return o.includes("fastapi")?8e3:o.includes("nestjs")?3e3:o.includes("springboot")?8080:o.includes("gofiber")?3e3:o.includes("gogin")?8080:n==="node"?3e3:n==="python"?8e3:n==="java"||n==="go"?8080:null}function N(e,r){let o=e;for(;r.has(o)&&o<65535;)o+=1;return o}function w(e,r,o){let n=_(r.kit,r.runtime),i=e?.ports||[],a=i.length>0?i:n?[{name:"http",port:N(n,o),protocol:"http"}]:[];for(let t of a)o.add(t.port);let p={...r,...e,slug:e?.slug||r.slug,relativePath:e?.relativePath&&y(e.relativePath)?e.relativePath:r.relativePath,source:e?.source||r.source,relationship:e?.relationship||r.relationship,externalPath:e?.externalPath||r.externalPath,runtime:e?.runtime||r.runtime,framework:e?.framework||r.framework,kit:e?.kit||r.kit,modules:e?.modules?.length?e.modules:r.modules,ports:a,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},l=JSON.stringify(e||null)!==JSON.stringify(p);return {project:p,changed:l}}async function A(e){let r=c.resolve(e.workspacePath),o=await R(r),n=await O(r),i=await a(r),a$1=[];for(let t of i){let s=c.resolve(t.path),d=c.join(s,".rapidkit","project.json"),f=c.join(s,".rapidkit","context.json"),u=await h.pathExists(d)?d:await h.pathExists(f)?f:null;!u||n.some(g=>c.resolve(g)===c.resolve(u))||a$1.push({projectJsonPath:u,registryEntry:t});}let p=[],l=[...n.map(t=>({projectJsonPath:t})),...a$1];for(let{projectJsonPath:t,registryEntry:s}of l){let d=c.dirname(c.dirname(t)),f=W(c.relative(r,d)),u=s!==void 0&&!y(f),g=S(s?.name||c.basename(d),c.basename(d)),k=u?`external/${g}`:f||g,m=await h.readJson(t),C=typeof m.kit_name=="string"&&m.kit_name||typeof m.kit=="string"&&m.kit||void 0,$=typeof m.framework=="string"&&m.framework||J(C);p.push({slug:s?.name||k||c.basename(d),relativePath:k,source:s?.source??"workspace",relationship:s?.relationship,externalPath:u?d:void 0,runtime:typeof m.runtime=="string"?m.runtime:void 0,framework:$,kit:C,modules:E(m.modules),ports:[],contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}return {schemaVersion:P,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:o,projects:p}}async function F(e){let r=c.resolve(e.outputPath||c.join(e.workspacePath,j));if(await h.pathExists(r)&&e.force!==true)throw new Error(`Workspace contract already exists: ${r}. Use --force to overwrite.`);let o=await A({workspacePath:e.workspacePath,now:e.now}),n=new Set,i={...o,projects:o.projects.map(a=>w(void 0,a,n).project)};return await h.ensureDir(c.dirname(r)),await h.writeJson(r,i,{spaces:2}),{contractPath:r,contract:i}}async function K(e){let r=c.resolve(e.workspacePath),o=c.join(r,j),n=await A({workspacePath:r,now:e.now}),i=await h.pathExists(o)?await h.readJson(o):null,a=new Map((i?.projects||[]).map(u=>[u.slug,u])),p=new Set,l=[],t=[],s=[];for(let u of n.projects){let g=a.get(u.slug),k=w(g,u,p);g?k.changed&&t.push(u.slug):l.push(u.slug),s.push(k.project),a.delete(u.slug);}for(let u of a.values()){let g=w(u,u,p);s.push(g.project);}let d={schemaVersion:P,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...n.workspace,...i?.workspace||{},name:i?.workspace?.name||n.workspace.name},projects:s.sort((u,g)=>u.slug.localeCompare(g.slug))};await h.ensureDir(c.dirname(o)),await h.writeJson(o,d,{spaces:2});let f=await V({workspacePath:r});return {contractPath:o,contract:d,addedProjects:l,updatedProjects:t,verification:f}}async function x(e){let r=c.resolve(e.contractPath||c.join(e.workspacePath,j)),o=await h.readJson(r);return {contractPath:r,contract:o}}async function L(e){let{contractPath:r,contract:o}=await x(e),n=o.projects.map(t=>({id:t.slug,label:t.slug,relativePath:t.relativePath,source:t.source,relationship:t.relationship,externalPath:t.externalPath,runtime:t.runtime,framework:t.framework,kit:t.kit,modules:t.modules,ports:t.ports,apis:t.contracts.apis,owns:t.contracts.owns,env:t.contracts.env})),i=new Set(n.map(t=>t.id)),a=new Map,p=[];for(let t of o.projects){for(let s of t.contracts.dependsOn||[])i.has(s)&&p.push({from:s,to:t.slug,type:"dependency",label:"dependsOn"});for(let s of t.contracts.publishes||[])a.has(s)||a.set(s,new Set),a.get(s)?.add(t.slug);}for(let t of o.projects)for(let s of t.contracts.consumes||[]){let d=a.get(s);if(d)for(let f of d)f!==t.slug&&p.push({from:f,to:t.slug,type:"event",label:s});}let l={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:o.workspace,generatedAt:new Date().toISOString(),nodes:n.sort((t,s)=>t.id.localeCompare(s.id)),edges:p.sort((t,s)=>`${t.from}:${t.to}:${t.type}:${t.label}`.localeCompare(`${s.from}:${s.to}:${s.type}:${s.label}`)),summary:{projectCount:n.length,dependencyEdges:p.filter(t=>t.type==="dependency").length,eventEdges:p.filter(t=>t.type==="event").length,portCount:n.reduce((t,s)=>t+s.ports.length,0),apiCount:n.reduce((t,s)=>t+s.apis.length,0)}};return {contractPath:r,graph:l}}async function V(e){let{contractPath:r,contract:o}=await x(e),n=[],i=[];o.kind!=="rapidkit.workspace.contract"&&n.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==P&&n.push(`Contract schemaVersion must be ${P}.`),o.workspace?.name||n.push("Contract workspace.name is required."),Array.isArray(o.projects)||n.push("Contract projects must be an array.");let a=new Set,p=new Map;for(let t of o.projects||[]){if(!t.slug){n.push("Every project must declare slug.");continue}a.has(t.slug)&&n.push(`Duplicate project slug: ${t.slug}.`),a.add(t.slug),t.relativePath?y(t.relativePath)||n.push(`Project ${t.slug} declares unsafe relativePath: ${t.relativePath}.`):n.push(`Project ${t.slug} must declare relativePath.`),t.externalPath&&(t.relationship==="adopted"||t.source==="adopted-local"||t.source==="local-folder"||t.source==="git-url"||n.push(`Project ${t.slug} declares externalPath without imported/adopted provenance.`),c.isAbsolute(t.externalPath)||n.push(`Project ${t.slug} declares non-absolute externalPath.`));for(let s of t.ports||[]){(!Number.isInteger(s.port)||s.port<1||s.port>65535)&&n.push(`Project ${t.slug} declares invalid port: ${s.port}.`);let d=p.get(s.port);d&&n.push(`Port ${s.port} is claimed by both ${d} and ${t.slug}.`),p.set(s.port,t.slug);}for(let s of t.contracts?.apis||[])(!s.name?.trim()||!s.basePath?.startsWith("/"))&&n.push(`Project ${t.slug} declares invalid API contract.`);for(let s of [...t.contracts?.publishes||[],...t.contracts?.consumes||[]])s.trim()||n.push(`Project ${t.slug} declares an empty event contract.`);for(let s of t.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(s)||n.push(`Project ${t.slug} declares invalid env contract: ${s}.`);for(let s of t.contracts?.dependsOn||[])a.has(s);}for(let t of o.projects||[])for(let s of t.contracts?.dependsOn||[])a.has(s)||n.push(`Project ${t.slug} depends on unknown project: ${s}.`);i.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===P?"passed":"failed",message:"Contract schema and kind are valid."}),i.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),i.push({id:"ports",status:n.some(t=>t.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),i.push({id:"dependencies",status:n.some(t=>t.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),i.push({id:"contracts",status:n.some(t=>t.includes("unsafe relativePath")||t.includes("invalid API contract")||t.includes("event contract")||t.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let l$1=await l(e.workspacePath);if(l$1.moduleCount>0){for(let t of l$1.issues)n.push(`${c.basename(t.projectRoot)}: ${t.message} (slug=${t.slug})`);i.push({id:"module-paths",status:l$1.status,message:l$1.status==="passed"?`All ${l$1.moduleCount} registered module(s) resolve under canonical paths.`:`${l$1.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&i.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:n.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:i,violations:n}}
|
|
2
|
+
export{j as a,P as b,O as c,A as d,F as e,K as f,x as g,L as h,V as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import i from'path';import a from'fs-extra';var m="rapidkit.module-layout.v1",c="src/modules/free",h="src/modules/free/{category}/{module}",f="free/{category}/{module}",d="free/",j={fastapi:{moduleCommands:true,injectAnchors:["src/routing/__init__.py","src/modules/__init__.py"],moduleMarkerFiles:["__init__.py"]},nestjs:{moduleCommands:true,injectAnchors:["src/app.module.ts","src/modules/index.ts"],moduleMarkerFiles:["index.ts","module.ts"]}},A=["go","springboot","dotnet"];function p(t){return t.replace(/\\/g,"/")}function g(t){return typeof t=="string"&&t.startsWith(d)}function P(t,e){if(!g(e))throw new Error(`Module slug must start with ${d}: ${e}`);let s=i.join(c,...e.split("/").slice(1));return i.join(t,s)}function w(t){if(!g(t))throw new Error(`Module slug must start with ${d}: ${t}`);return p(i.join(c,...t.split("/").slice(1)))}async function M(t){return await a.pathExists(t)?(await a.stat(t)).isDirectory():false}async function y(t){let e=i.join(t,"registry.json"),s=[],o=0;if(!await a.pathExists(e))return {status:"passed",projectCount:1,moduleCount:0,issues:s};let n=await a.readJson(e);for(let l of n.installed_modules||[]){let u=l?.slug;if(!g(u))continue;o+=1;let r=P(t,u);await M(r)||s.push({projectRoot:t,registryPath:e,slug:u,expectedPath:r,message:`Missing canonical module directory: ${p(i.relative(t,r))}`});}return {status:s.length>0?"failed":"passed",projectCount:1,moduleCount:o,issues:s}}async function O(t){let e=await _(t),s=[],o=[],n=0;for(let l of e){let u=i.dirname(l),r=await y(u);n+=r.moduleCount,o.push(...r.issues),s.push({projectRoot:u,moduleCount:r.moduleCount,issueCount:r.issues.length,status:r.status});}return {workspacePath:t,status:o.length>0?"failed":"passed",projectCount:s.length,moduleCount:n,issues:o,projects:s}}async function _(t){let e=await a.readdir(t,{withFileTypes:true}),s=[];for(let o of e){if(!o.isDirectory())continue;let n=i.join(t,o.name,"registry.json");await a.pathExists(n)&&s.push(n);}return s.sort()}function L(){return {schemaVersion:m,canonicalModuleRoot:c,pathPattern:h,slugPattern:f}}export{m as a,c as b,h as c,f as d,d as e,j as f,A as g,g as h,P as i,w as j,y as k,O as l,L as m};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import {q as q$1}from'./chunk-YBS2HGO3.js';import {i,d,b as b$2,a as a$6}from'./chunk-UZW5QFRW.js';import {c,a as a$3,b as b$1}from'./chunk-NFUXULIF.js';import {a}from'./chunk-VM2TOHNX.js';import {b,f,d as d$1,a as a$5,k,g,i as i$1}from'./chunk-Z5LKRG57.js';import {a as a$4}from'./chunk-2FIX2MDC.js';import {a as a$2}from'./chunk-HHJAANUC.js';import l from'chalk';import {execa}from'execa';import r from'fs-extra';import a$1 from'path';import Pt from'inquirer';var kt=[".eslintrc.js",".eslintrc.cjs",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml","eslint.config.js","eslint.config.mjs","eslint.config.cjs"],wt=["tests","test","src/test","__tests__","e2e","playwright","cypress"],vt=["vitest.config.ts","vitest.config.js","vitest.config.mjs","jest.config.js","jest.config.ts","jest.config.mjs","playwright.config.ts","playwright.config.js","cypress.config.js","cypress.config.ts"],bt=["src","app","pages"],xt=["dev","build","test","lint"];function Ge(e){let n=e?.scripts;if(!n||typeof n!="object"||Array.isArray(n))return {};let i={};for(let[t,c]of Object.entries(n))typeof c=="string"&&c.trim().length>0&&(i[t]=c);return i}async function Ke(e,n){for(let c of kt)if(await r.pathExists(a$1.join(e,c)))return true;let i=n??(await r.pathExists(a$1.join(e,"package.json"))?await r.readJson(a$1.join(e,"package.json")):null);if(!i)return false;if(i.eslintConfig)return true;let t={...i.dependencies??{},...i.devDependencies??{}};return !!(t.eslint||t["@eslint/js"]||t["@eslint/eslintrc"])}async function We(e,n){for(let c of wt)if(await r.pathExists(a$1.join(e,c)))return true;for(let c of vt)if(await r.pathExists(a$1.join(e,c)))return true;let i=Ge(n);if(i.test||i["test:unit"]||i["test:e2e"]||i["test:ci"]||i["test:watch"])return true;let t={...n?.dependencies??{},...n?.devDependencies??{}};return t.vitest||t.jest||t["@playwright/test"]||t.cypress?true:await jt(e)}async function jt(e){let n=["src","app","pages","components"],i=/\.(test|spec)\.(tsx?|jsx?|vue|svelte)$/i,c=new Set(["node_modules",".git","dist","build",".next","coverage",".turbo"]);for(let o of n){let s=a$1.join(e,o);if(!await r.pathExists(s))continue;let d=[{dir:s,depth:0}];for(;d.length>0;){let u=d.shift();if(!u)break;let p=[];try{p=await r.readdir(u.dir);}catch{continue}for(let f of p){let m=a$1.join(u.dir,f);if(i.test(f))return true;if(!(u.depth>=3||c.has(f)||f.startsWith(".")))try{(await r.stat(m)).isDirectory()&&d.push({dir:m,depth:u.depth+1});}catch{continue}}}}return false}async function be(e){for(let n of bt){let i=a$1.join(e,n);if(await r.pathExists(i))try{if((await r.readdir(i)).some(c=>!c.startsWith(".")))return true}catch{continue}}return false}function Ct(e){let n=e.key;return b$2(n).key}function Et(e,n,i){return a$6(n,i).some(c=>!!e[c])}async function Oe(e){let{projectPath:n,detection:i,packageJsonData:t}=e,c=Ct(i),o=b$2(c),s=Ge(t),d=[],u=await r.pathExists(a$1.join(n,"package-lock.json"))||await r.pathExists(a$1.join(n,"pnpm-lock.yaml"))||await r.pathExists(a$1.join(n,"yarn.lock"))||await r.pathExists(a$1.join(n,"bun.lockb"));d.push({id:"frontend-lockfile-integrity",label:"Frontend lockfile integrity",status:u?"pass":"warn",severity:"warn",scope:"project-scoped",reason:u?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml/bun.lockb).",recommendation:u?void 0:"Commit a lockfile for deterministic installs and CI parity."});let p=await r.pathExists(a$1.join(n,"tsconfig.json")),f=await r.pathExists(a$1.join(n,"jsconfig.json")),m=p||f;d.push({id:"frontend-typescript-surface",label:"TypeScript project surface",status:m?"pass":"warn",severity:"warn",scope:"project-scoped",reason:m?p?"tsconfig.json detected.":"jsconfig.json detected.":"No tsconfig.json or jsconfig.json detected.",recommendation:m?void 0:"Add tsconfig.json (or jsconfig.json) for typed frontend builds and IDE parity."});let g=o.fileHints.length>0&&o.fileHints.some(y=>r.pathExistsSync(a$1.join(n,y)));d.push({id:"frontend-framework-config",label:`${o.displayName} config surface`,status:g?"pass":"warn",severity:"warn",scope:"project-scoped",reason:g?`${o.displayName} configuration artifacts detected.`:`No ${o.displayName} config markers detected (${o.fileHints.join(", ")||"n/a"}).`,recommendation:g?void 0:"Keep framework config files in-repo for reproducible dev/build behavior."});for(let y of xt){let k=Et(s,c,y),b=y==="dev"||y==="build";d.push({id:`frontend-script-${y}`,label:`${y} script surface`,status:k?"pass":b?"fail":"warn",severity:b?"error":"warn",scope:"project-scoped",reason:k?`package.json exposes a ${y} script for ${o.displayName}.`:`No ${y} script detected for ${o.displayName}.`,recommendation:k?void 0:`Add a "${a$6(c,y)[0]??y}" script to package.json.`});}let h=await be(n);return d.push({id:"frontend-source-tree",label:"Frontend source tree",status:h?"pass":"warn",severity:"warn",scope:"project-scoped",reason:h?"Application source directories detected (src/app/pages).":"No frontend source directories detected under src/, app/, or pages/.",recommendation:h?void 0:"Ensure the scaffolded application tree exists before running lifecycle commands."}),d}function St(e){return [...new Set(e.filter(n=>n&&n.trim().length>0))]}function Rt(){let e=k().map(t=>a$1.join(t,a$5()?"poetry.exe":"poetry")),n=a$5()?[a$1.join(process.env.APPDATA||"","Python","Scripts","poetry.exe"),a$1.join(process.env.USERPROFILE||"","AppData","Roaming","Python","Scripts","poetry.exe")]:[],i=a$5()?[]:["/usr/local/bin/poetry","/usr/bin/poetry"];return St([...e,...n,...i])}function $t(e){let n=k().map(u=>({location:"Global (user-local)",path:a$1.join(u,a$5()?"rapidkit.exe":"rapidkit")})),i=[{location:"Global (pipx)",path:a$1.join(e,".local","bin","rapidkit")},{location:"Global (pipx)",path:a$1.join(e,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:a$1.join(e,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],t=g(a$1.join(process.cwd(),".venv")),c=i$1(process.cwd()),o=[{location:"Workspace (.venv)",path:t},...c.map(u=>({location:"Workspace (launcher)",path:u}))],s=[...n,...i,...o],d=new Set;return s.filter(u=>d.has(u.path)?false:(d.add(u.path),true))}function Ft(e){let n=new Map([["Workspace (.venv)",0],["Global (user-local)",1],["Global (pipx)",2],["Global (pyenv)",3],["Global (system)",4]]);return [...e].sort((i,t)=>{let c=n.get(i.location)??Number.MAX_SAFE_INTEGER,o=n.get(t.location)??Number.MAX_SAFE_INTEGER;return c!==o?c-o:i.path.localeCompare(t.path)})}function ee(e){let n=0,i=e.issues.some(t=>t.toLowerCase().includes("environment file missing"));return e.hasEnvFile===false&&!i&&(n+=1),typeof e.vulnerabilities=="number"&&e.vulnerabilities>0&&(n+=1),n}function xe(e){return e.filter(n=>ee(n)>0).length}function Pe(e){return e.reduce((n,i)=>n+ee(i),0)}var Dt="doctor-project-scan-v2",Xe="doctor-workspace-cache-v2",At=Object.freeze({version:"doctor-evidence-v1",scoringPolicyVersion:"doctor-score-policy-v1",generatedBy:"rapidkit-npm",deterministicScoreBreakdown:true,scopeModel:"workspace-aggregate-or-project-scoped"});function me(){return {...At}}function fe(e){return !e||e.total<=0?null:Math.round(e.passed/e.total*100)}function Ye(e){return typeof e=="number"?e:Array.isArray(e)?e.length:0}async function Ze(e,n){try{if(!await r.pathExists(e))return null;let i=await r.readJSON(e);return c(i,n)?i:null}catch{return null}}function et(e,n){if(!e?.system)return [];let i=[{id:"python",current:n.python},{id:"poetry",current:n.poetry},{id:"pipx",current:n.pipx},{id:"go",current:n.go},{id:"rapidkitCore",current:n.rapidkitCore}],t=[];for(let c of i){let o=e.system?.[c.id]?.status;!o||o===c.current.status||t.push({id:c.id,from:o,to:c.current.status});}return t}function It(e,n){let i=new Map;for(let g of n.projects)i.set(g.path||g.name,g.issues.length);if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let t=Array.isArray(e.projects)?e.projects:[],c=new Map;for(let g of t){let h=g.path||g.name;h&&c.set(h,Ye(g.issues));}let o=0,s=0,d=new Set,u=new Set,p=new Set([...Array.from(c.keys()),...Array.from(i.keys())]);for(let g of p){let h=c.get(g)??0,y=i.get(g)??0;y>h?(o+=y-h,d.add(g)):y<h&&(s+=h-y,u.add(g));}let f=fe(e.healthScore),m=fe(n.healthScore);return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:o,resolvedIssueCount:s,netIssueDelta:o-s,scoreDeltaPercent:f===null||m===null?null:m-f,systemStatusChanges:et(e,{python:n.python,poetry:n.poetry,pipx:n.pipx,go:n.go,rapidkitCore:n.rapidkitCore}),regressedProjects:Array.from(d).sort(),improvedProjects:Array.from(u).sort()}}function Nt(e,n){if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let i=Ye(e.project?.issues),t=n.project.issues.length,c=Math.max(t-i,0),o=Math.max(i-t,0),s=fe(e.healthScore),d=fe(n.healthScore),u=n.project.path||n.project.name;return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:c,resolvedIssueCount:o,netIssueDelta:c-o,scoreDeltaPercent:s===null||d===null?null:d-s,systemStatusChanges:et(e,{python:n.python,poetry:n.poetry,pipx:n.pipx,go:n.go,rapidkitCore:n.rapidkitCore}),regressedProjects:c>0?[u]:[],improvedProjects:o>0?[u]:[]}}function tt(e){let n=e??[],i=0,t=0;for(let s of n){if(s.scope==="project-scoped"){i+=1;continue}(s.scope==="workspace-aggregate"||s.scope==="host-system")&&(t+=1);}let c=i>0&&t>0?1:0,o=c>0?"mixed":i>0?"scoped":t>0?"aggregated":"unknown";return {scopedCount:i,aggregatedCount:t,mixedCount:c,dominantScope:o}}function $(e,n){return a$5()?`cd "${e}"; ${n}`:`cd ${e} && ${n}`}function q(e){return a$5()?$(e,"Copy-Item .env.example .env"):$(e,"cp .env.example .env")}function Ht(e){return e==="FastAPI"||e==="NestJS"?"first-class":e==="Django"||e==="Flask"||e==="Express"||e==="Fastify"||e==="Koa"||e==="Go/Fiber"||e==="Go/Gin"||e==="Spring Boot"||e==="Rust"||e==="Phoenix"||e==="Elixir"||e==="Clojure"||e==="Scala"||e==="Kotlin"||e==="Deno"||e==="Bun"||e==="PHP"||e==="Laravel"||e==="Ruby"||e==="Ruby on Rails"||e==="ASP.NET"?"extended":"observed"}function Mt(e){return e==="Next.js"||e==="Remix"||e==="Nuxt"||e==="React"||e==="Vue"||e==="Angular"||e==="SvelteKit"||e==="Svelte"||e==="Vite"||e==="Astro"||e==="Solid"?"frontend":e==="Unknown"||e==="Node.js"||e==="Python"?"generic":"backend"}function Tt(e){return e==="NestJS"||e==="Next.js"||e==="Remix"||e==="Nuxt"||e==="React"||e==="Vue"||e==="Angular"||e==="SvelteKit"||e==="Svelte"||e==="Vite"||e==="Astro"||e==="Solid"||e==="Bun"||e==="Express"||e==="Fastify"||e==="Koa"||e==="Node.js"?"node":e==="FastAPI"||e==="Django"||e==="Flask"||e==="Python"?"python":e==="Go/Fiber"||e==="Go/Gin"?"go":e==="Spring Boot"?"java":e==="Rust"?"rust":e==="Elixir"||e==="Phoenix"?"elixir":e==="Clojure"?"clojure":e==="Deno"?"deno":e==="Laravel"||e==="PHP"?"php":e==="Ruby on Rails"||e==="Ruby"?"ruby":e==="ASP.NET"?"dotnet":"unknown"}function je(e,n){let i=q$1(n);e.commandCapabilities=i,e.supportTier=i.frameworkSupportTier;}function ue(e,n,i,t){e.framework=n,e.frameworkConfidence=i,e.supportTier=Ht(n),e.projectKind=Mt(n),e.runtimeFamily=Tt(n);}function nt(e){return e==="python"?"python":e==="node"||e==="bun"?"node":e==="go"?"go":e==="java"?"java":e==="rust"?"rust":e==="elixir"?"elixir":e==="clojure"?"clojure":e==="deno"?"deno":e==="php"?"php":e==="ruby"?"ruby":e==="dotnet"?"dotnet":"unknown"}function Se(e){switch(e.key){case "fastapi":return "FastAPI";case "django":return "Django";case "flask":return "Flask";case "python":return "Python";case "nestjs":return "NestJS";case "nextjs":return "Next.js";case "remix":return "Remix";case "nuxt":return "Nuxt";case "react":return "React";case "vite":return "Vite";case "vue":return "Vue";case "sveltekit":return "SvelteKit";case "svelte":return "Svelte";case "angular":return "Angular";case "astro":return "Astro";case "solid":return "Solid";case "express":return "Express";case "fastify":return "Fastify";case "koa":return "Koa";case "node":return "Node.js";case "gofiber":return "Go/Fiber";case "gogin":return "Go/Gin";case "echo":return "Echo";case "go":return "Go";case "springboot":return "Spring Boot";case "java":return "Java";case "laravel":return "Laravel";case "php":return "PHP";case "rails":return "Ruby on Rails";case "ruby":return "Ruby";case "dotnet":return "ASP.NET";case "phoenix":return "Phoenix";case "elixir":return "Elixir";case "clojure":return "Clojure";case "scala":return "Scala";case "kotlin":return "Kotlin";case "deno":return "Deno";case "bun":return "Bun";case "actix":case "axum":case "rocket":case "rust":return "Rust";case "sinatra":case "symfony":case "unknown":return "Unknown";default:return "Unknown"}}function Bt(e){return e.key==="python"||e.key==="node"||e.key==="go"||e.key==="java"||e.key==="php"||e.key==="ruby"||e.key==="dotnet"||e.key==="rust"||e.key==="elixir"||e.key==="clojure"||e.key==="scala"||e.key==="kotlin"||e.key==="deno"||e.key==="bun"||e.key==="unknown"}function _t(e,n){e.framework=Se(n),e.frameworkKey=n.key,e.importStack=n.importStack,e.frameworkConfidence=n.confidence,e.supportTier=n.supportTier,e.projectKind="frontend",e.runtimeFamily=nt(n.runtime);}function G(e,n){e.framework=Se(n),e.frameworkKey=n.key,e.importStack=n.importStack,e.frameworkConfidence=n.confidence,e.supportTier=n.supportTier,e.projectKind=Bt(n)?"generic":"backend",e.runtimeFamily=nt(n.runtime);}function Gt(e){let n=e.dependencies,i=e.scripts??{},t=(e.kitName??"").toLowerCase(),c=s=>!!n[s],o=Object.values(i).filter(s=>typeof s=="string").join(" ").toLowerCase();return c("next")||o.includes("next ")?{framework:"Next.js",confidence:"high"}:c("nuxt")||o.includes("nuxt ")?{framework:"Nuxt",confidence:"high"}:c("@nestjs/core")||t.startsWith("nestjs.")?{framework:"NestJS",confidence:"high"}:c("express")?{framework:"Express",confidence:"high"}:c("fastify")?{framework:"Fastify",confidence:"high"}:c("koa")?{framework:"Koa",confidence:"high"}:c("@angular/core")?{framework:"Angular",confidence:"high"}:c("@sveltejs/kit")||o.includes("svelte-kit")?{framework:"SvelteKit",confidence:"high"}:c("vue")?{framework:"Vue",confidence:"medium"}:c("react")&&c("react-dom")?{framework:"React",confidence:"medium"}:{framework:"Node.js",confidence:"low"}}async function Kt(e){let n=i(e);return n.runtime!=="python"?{framework:"Python",confidence:"low"}:{framework:Se(n),confidence:n.confidence}}async function Le(e){try{let n=await r.stat(e);return `${a$1.basename(e)}:${n.isDirectory()?"d":"f"}:${n.size}:${n.mtimeMs}`}catch{return `${a$1.basename(e)}:missing`}}async function Wt(e){try{let n=new Set([".git",".venv","node_modules",".rapidkit","dist","build","coverage","__pycache__"]),i=new Set;await ce(e)&&i.add(e);let t=await a$2(e);for(let o of t){let s=a$1.isAbsolute(o.path)?o.path:a$1.join(e,o.path);await ce(s)&&i.add(s);}let c=async(o,s)=>{if(s<0)return;let d=await st(o);for(let u of d){if(ot(u,n))continue;let p=a$1.join(o,u);if(await ce(p)){i.add(p);continue}s>0&&await c(p,s-1);}};return await c(e,1),i.size===0&&(await tn(e,3,n)).forEach(s=>i.add(s)),Array.from(i).sort((o,s)=>o.localeCompare(s))}catch{return []}}async function Ot(e,n){let i=[a$1.join(e,".rapidkit-workspace"),a$1.join(e,".rapidkit","workspace.json"),a$1.join(e,".rapidkit","imported-projects.json"),a$1.join(e,".rapidkit","policies.yml"),a$1.join(e,".rapidkit","toolchain.lock"),a$1.join(e,".rapidkit","cache-config.yml")],t=[".rapidkit/project.json",".rapidkit/context.json",".rapidkit/file-hashes.json","package.json","pyproject.toml","composer.json","Gemfile","Gemfile.lock","go.mod","go.sum","pom.xml","requirements.txt","Dockerfile","Makefile",".env",".env.example","src","modules","tests","test",".venv","node_modules"],c=await Promise.all(i.map(Le)),o=await Promise.all(n.map(async s=>{let d=await Promise.all(t.map(u=>Le(a$1.join(s,u))));return `${s}::${d.join("|")}`}));return [Dt,...c,...o].join("||")}async function Lt(e,n){try{if(!await r.pathExists(e))return null;let i=await r.readJSON(e);return !i||i.signature!==n||!Array.isArray(i.projects)||typeof i.schemaVersion=="string"&&i.schemaVersion!==Xe?null:i}catch{return null}}async function Vt(e,n){try{await r.ensureDir(a$1.dirname(e)),await r.writeJSON(e,n,{spaces:2});}catch{}}async function Jt(e,n,i){let t=a$1.join(e,".rapidkit","reports","doctor-last-run.json");try{return await r.ensureDir(a$1.dirname(t)),await r.writeJSON(t,{schemaVersion:a$3,evidenceType:"workspace",generatedAt:new Date().toISOString(),contract:me(),workspacePath:e,workspaceName:n.workspaceName,projectScanCached:n.projectScanCached??false,projectScanSignature:n.projectScanSignature,cachePath:i,healthScore:n.healthScore,system:{python:n.python,poetry:n.poetry,pipx:n.pipx,go:n.go,rapidkitCore:n.rapidkitCore,versions:{core:n.coreVersion,npm:n.npmVersion}},projects:n.projects,summary:{totalProjects:n.projects.length,totalIssues:n.projects.reduce((c,o)=>c+o.issues.length,0),projectAdvisoryWarningProjects:xe(n.projects),projectAdvisoryWarnings:Pe(n.projects),hasSystemErrors:[n.python,n.rapidkitCore].some(c=>c.status==="error"),scopeProvenance:n.scopeProvenance},driftDelta:n.driftDelta,scoreBreakdown:n.scoreBreakdown??[]},{spaces:2}),t}catch{return}}async function Re(){let[e,n,i,t,c]=await Promise.all([qt(),Ut(),zt(),Qt(),Xt()]);return {python:e,poetry:n,pipx:i,go:t,rapidkitCore:c}}async function qt(){let e=d$1();for(let n of e)try{let{stdout:i}=await execa(n,["--version"],{timeout:3e3}),t=i.match(/Python (\d+\.\d+\.\d+)/);if(t){let c=t[1],[o,s]=c.split(".").map(Number);return o<3||o===3&&s<10?{status:"warn",message:`Python ${c} (requires 3.10+)`,details:`${n} found but version is below minimum requirement`}:{status:"ok",message:`Python ${c}`,details:`Using ${n}`}}}catch{continue}return {status:"error",message:"Python not found",details:"Install Python 3.10+ and ensure it's in PATH"}}async function Ut(){try{let{stdout:e}=await execa("poetry",["--version"],{timeout:3e3}),n=e.match(/Poetry .*version ([\d.]+)/);return n?{status:"ok",message:`Poetry ${n[1]}`,details:"Available for dependency management"}:{status:"warn",message:"Poetry version unknown"}}catch{let e=d$1().map(n=>({cmd:n,args:n==="py"?["-3","-m","poetry","--version"]:["-m","poetry","--version"]}));for(let n of e)try{let{stdout:i}=await execa(n.cmd,n.args,{timeout:3e3,shell:b()}),t=i.match(/Poetry .*version ([\d.]+)/)||i.match(/([\d.]+)/);return {status:"ok",message:t?.[1]?`Poetry ${t[1]}`:"Poetry detected",details:`Available via ${n.cmd} ${n.args.join(" ")}`}}catch{continue}for(let n of Rt())try{if(!await r.pathExists(n))continue;let{stdout:i}=await execa(n,["--version"],{timeout:3e3,shell:b()}),t=i.match(/Poetry .*version ([\d.]+)/)||i.match(/([\d.]+)/);return {status:"ok",message:t?.[1]?`Poetry ${t[1]}`:"Poetry detected",details:`Available at ${n}`}}catch{continue}return {status:"warn",message:"Poetry not installed",details:"Optional: Install for better dependency management"}}}async function zt(){try{let{stdout:e}=await execa("pipx",["--version"],{timeout:3e3});return {status:"ok",message:`pipx ${e.trim()}`,details:"Available for global tool installation"}}catch{let e=d$1();for(let n of e)try{let i=n==="py"?["-3","-m","pipx","--version"]:["-m","pipx","--version"],{stdout:t}=await execa(n,i,{timeout:3e3,shell:b()});return {status:"ok",message:`pipx ${t.trim()}`,details:`Available via ${n} ${i.join(" ")}`}}catch{continue}return {status:"warn",message:"pipx not installed",details:"Optional: Install for isolated Python tools"}}}async function Qt(){try{let{stdout:e}=await execa("go",["version"],{timeout:3e3}),n=e.match(/go version go(\d+\.\d+(?:\.\d+)?)/);return n?{status:"ok",message:`Go ${n[1]}`,details:"Available for Go/Fiber and Go/Gin projects"}:{status:"ok",message:"Go (version unknown)",details:"go found in PATH"}}catch{return {status:"warn",message:"Go not installed",details:"Optional: Required only for gofiber.standard / gogin.standard projects \u2014 https://go.dev/dl/"}}}async function Xt(){let e=process.env.HOME||process.env.USERPROFILE||"",n=[],i=$t(e);for(let{location:c,path:o}of i)try{if(await r.pathExists(o)){let{stdout:s,exitCode:d}=await execa(o,["--version"],{timeout:3e3,reject:false});if(d===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let u=s.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);u&&n.push({location:c,path:o,version:u[1]});}}}catch{continue}if(n.length>0){let c=n.filter(s=>s.location!=="Workspace (launcher)");if(c.length>0){let s=Ft(c),d=s[0].version,u=s.some(m=>m.location==="Workspace (.venv)"),p=s.some(m=>m.location.startsWith("Global (")),f=!u&&p?"Workspace (.venv): not installed (optional). For best project-level performance and isolation, run npx rapidkit workspace run init inside this workspace.":void 0;return {status:"ok",message:`RapidKit Core ${d}`,details:f,paths:s.map(m=>({location:m.location,path:m.path,version:m.version}))}}return {status:"ok",message:`RapidKit Core ${n[0].version}`,details:"Detected via workspace launcher"}}try{let{stdout:c,exitCode:o}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(o===0&&(c.includes("RapidKit Version")||c.includes("RapidKit"))){let s=c.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(s)return {status:"ok",message:`RapidKit Core ${s[1]}`,details:"Available via PATH"}}}catch{}try{let{stdout:c,exitCode:o}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(o===0&&(c.includes("RapidKit Version")||c.includes("RapidKit"))){let s=c.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(s)return {status:"ok",message:`RapidKit Core ${s[1]}`,details:"Available via Poetry"}}}catch{}let t=d$1();for(let c of t)try{let{stdout:o,exitCode:s}=await execa(c,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:3e3,reject:false});if(s===0&&o&&!o.includes("Traceback")&&!o.includes("ModuleNotFoundError")){let d=o.trim();if(d)return {status:"ok",message:`RapidKit Core ${d}`,details:`Available in ${c} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function T(e,n,i){let t=a$1.join(e,"Dockerfile");n.hasDocker=await r.pathExists(t);let c=a$1.join(e,"tests"),o=a$1.join(e,"test"),s=a$1.join(e,"src","test"),d=await r.pathExists(c)||await r.pathExists(o)||await r.pathExists(s),u=false;if(n.framework==="Go/Fiber"||n.framework==="Go/Gin")try{let p=[{dir:e,depth:0}],f=4,m=new Set([".git",".venv","node_modules","dist","build","vendor"]);for(;p.length>0&&!u;){let g=p.shift();if(!g)break;let h=[];try{h=await r.readdir(g.dir);}catch{continue}for(let y of h){let k=a$1.join(g.dir,y),b;try{b=await r.stat(k);}catch{continue}if(b.isFile()&&y.endsWith("_test.go")){u=true;break}b.isDirectory()&&g.depth<f&&!m.has(y)&&!y.startsWith(".")&&p.push({dir:k,depth:g.depth+1});}}}catch{}if(n.hasTests=d||u,n.runtimeFamily==="node"&&!n.hasTests&&(n.hasTests=await We(e,i)),n.runtimeFamily==="node")n.hasCodeQuality=await Ke(e,i);else if(n.framework==="Go/Fiber"||n.framework==="Go/Gin"){let p=a$1.join(e,".golangci.yml"),f=a$1.join(e,".golangci.yaml"),m=a$1.join(e,"Makefile"),g=await r.pathExists(m)&&(await r.readFile(m,"utf8")).includes("golangci-lint");n.hasCodeQuality=await r.pathExists(p)||await r.pathExists(f)||g;}else if(n.runtimeFamily==="python"){let p=a$1.join(e,"ruff.toml"),f=a$1.join(e,"pyproject.toml");if(await r.pathExists(f))try{let m=await r.readFile(f,"utf8");n.hasCodeQuality=m.includes("[tool.ruff]")||await r.pathExists(p);}catch{n.hasCodeQuality=await r.pathExists(p);}}else if(n.framework==="Spring Boot"){let p=a$1.join(e,"pom.xml");if(await r.pathExists(p))try{let f=await r.readFile(p,"utf8");n.hasCodeQuality=f.includes("spotless")||f.includes("checkstyle")||f.includes("pmd")||f.includes("maven-enforcer-plugin");}catch{n.hasCodeQuality=false;}}try{if(n.runtimeFamily==="node"){let{stdout:p}=await execa("npm",["audit","--json"],{cwd:e,reject:false});if(p)try{let m=JSON.parse(p).metadata?.vulnerabilities;m&&(n.vulnerabilities=(m.high||0)+(m.critical||0)+(m.moderate||0));}catch{}}else if(n.runtimeFamily==="python"){let p=a$1.join(e,".venv"),f$1=f(p);if(await r.pathExists(f$1))try{let{stdout:m}=await execa(f$1,["-m","pip","list","--format=json"],{timeout:5e3,reject:false});if(m){JSON.parse(m);n.vulnerabilities=0;}}catch{}}}catch{}}function I(e,n){e.probes||(e.probes=[]),e.probes.push(n);}async function Yt(e,n){let i=n.runtimeFamily||"unknown";if(n.projectKind==="backend"||n.projectKind==="generic"){if(i==="node"){let c=await r.pathExists(a$1.join(e,"package-lock.json"))||await r.pathExists(a$1.join(e,"pnpm-lock.yaml"))||await r.pathExists(a$1.join(e,"yarn.lock"));I(n,{id:"adapter-node-lockfile-integrity",label:"Node adapter lockfile integrity",status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml).",recommendation:c?void 0:"Commit a lockfile for deterministic installs and CI parity."});let o=await r.pathExists(a$1.join(e,"src/main.ts"))||await r.pathExists(a$1.join(e,"src/main.js"))||await r.pathExists(a$1.join(e,"src/server.ts"))||await r.pathExists(a$1.join(e,"src/server.js"));I(n,{id:"adapter-node-boot-entrypoint",label:"Node adapter boot entrypoint",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"Boot entrypoint markers detected for service startup path.":"No canonical Node boot entrypoint markers detected.",recommendation:o?void 0:"Define and document service bootstrap entrypoint (main/server)."});return}if(i==="python"){let c=await r.pathExists(a$1.join(e,"poetry.lock"))||await r.pathExists(a$1.join(e,"requirements.txt"))||await r.pathExists(a$1.join(e,"uv.lock"));I(n,{id:"adapter-python-lockfile-integrity",label:"Python adapter dependency integrity",status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?"Python dependency contract file detected.":"No Python dependency contract file detected (poetry.lock/requirements/uv.lock).",recommendation:c?void 0:"Pin dependency contract for deterministic setup and reproducible CI."});let o=await r.pathExists(a$1.join(e,"app/main.py"))||await r.pathExists(a$1.join(e,"main.py"))||await r.pathExists(a$1.join(e,"manage.py"));I(n,{id:"adapter-python-boot-entrypoint",label:"Python adapter boot entrypoint",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"Python application entrypoint markers detected.":"No Python application entrypoint markers detected.",recommendation:o?void 0:"Expose explicit app/main entrypoint for deterministic boot probes."});return}if(i==="java"){let c=await r.pathExists(a$1.join(e,"mvnw"))||await r.pathExists(a$1.join(e,"gradlew"));I(n,{id:"adapter-java-build-wrapper",label:"Java adapter build wrapper",status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?"Build wrapper detected (mvnw/gradlew).":"No Java build wrapper detected.",recommendation:c?void 0:"Commit mvnw or gradlew for reproducible enterprise pipelines."});return}if(i==="go"){let c=await r.pathExists(a$1.join(e,"go.sum"));I(n,{id:"adapter-go-module-integrity",label:"Go adapter module integrity",status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?"go.sum detected for deterministic module verification.":"go.sum missing; module integrity baseline is incomplete.",recommendation:c?void 0:"Generate and commit go.sum in the repository baseline."});}}}async function Zt(e,n){let i=[a$1.join(e,".rapidkit","doctor.adapters.json"),a$1.join(e,"doctor.adapters.json")];for(let t of i)if(await r.pathExists(t))try{let c=await r.readJSON(t),o=Array.isArray(c?.checks)?c.checks:[];for(let s=0;s<o.length;s+=1){let d=o[s]||{},u=Array.isArray(d.runtimes)?d.runtimes:[];if(u.length>0&&!u.includes(n.runtimeFamily||"unknown"))continue;let p=typeof d.id=="string"&&d.id.trim().length>0?d.id.trim():`adapter-check-${s+1}`,f=typeof d.label=="string"&&d.label.trim().length>0?d.label.trim():p,m=d.severity||"warn",g=Array.isArray(d.anyOfPaths)?d.anyOfPaths.filter(Boolean):[],h=Array.isArray(d.allOfPaths)?d.allOfPaths.filter(Boolean):[],y=g.length===0;for(let L of g)if(await r.pathExists(a$1.join(e,L))){y=true;break}let k=true;for(let L of h)if(!await r.pathExists(a$1.join(e,L))){k=false;break}let b=y&&k;I(n,{id:p,label:f,status:b?"pass":m==="error"?"fail":"warn",severity:m,scope:"project-scoped",reason:b?d.passReason||"Custom adapter contract satisfied.":d.failReason||`Custom adapter check failed from ${a$1.basename(t)}.`,recommendation:d.recommendation});}}catch{I(n,{id:"custom-adapter-config",label:"Custom doctor adapter configuration",status:"warn",severity:"warn",scope:"project-scoped",reason:`Failed to parse ${a$1.basename(t)}.`,recommendation:"Fix JSON syntax in doctor.adapters.json to re-enable adapter checks."});}}async function B(e,n){if(!(n.projectKind==="backend"||n.projectKind==="generic"))return;let t=a$1.join(e,".env"),c=a$1.join(e,".env.example"),o=await r.pathExists(t)||await r.pathExists(c)||await r.pathExists(a$1.join(e,"config"));I(n,{id:"config-surface",label:"Configuration contract surface",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"Configuration artifacts detected (.env/.env.example/config).":"No explicit configuration contract artifacts detected.",recommendation:o?void 0:"Add .env.example or explicit config contract documentation for deterministic setup."});let s={python:["alembic.ini","migrations","versions"],node:["prisma/schema.prisma","migrations","typeorm.config.ts","typeorm.config.js"],go:["migrations","db/migrations"],java:["src/main/resources/db/migration","src/main/resources/liquibase"],rust:["migrations","sqlx-data.json"],elixir:["priv/repo/migrations"],clojure:["resources/migrations","migrations"],deno:["migrations"],php:["database/migrations","migrations"],ruby:["db/migrate"],dotnet:["Migrations","Data/Migrations"],unknown:["migrations"]},d=n.runtimeFamily||"unknown",u=s[d]||s.unknown,p=false;for(let g of u)if(await r.pathExists(a$1.join(e,g))){p=true;break}I(n,{id:"migration-surface",label:"Migration/readiness surface",status:p?"pass":"warn",severity:"warn",scope:"project-scoped",reason:p?"Migration or schema evolution markers detected.":"No migration markers detected for this backend runtime.",recommendation:p?void 0:"Add migration tooling baseline (migrations dir or runtime-native migration config)."});let f=["src/health","src/healthcheck","src/main/resources/application.yml","src/main/resources/application.properties","app/health.py","routes/health.ts","routes/health.js"],m=false;for(let g of f)if(await r.pathExists(a$1.join(e,g))){m=true;break}I(n,{id:"runtime-health-surface",label:"Runtime health probe surface",status:m?"pass":"warn",severity:"warn",scope:"project-scoped",reason:m?"Health endpoint/config markers detected.":"No explicit runtime health endpoint markers detected.",recommendation:m?void 0:"Expose a deterministic health endpoint and keep it covered in verify pack."}),await Yt(e,n);}async function en(e,n,i,t){let c=await Oe({projectPath:e,detection:t,packageJsonData:i});for(let o of c)I(n,o);}async function _(e,n){let i=[a$1.join(e,".rapidkit","doctor.probes.json"),a$1.join(e,"doctor.probes.json")];for(let t of i)if(await r.pathExists(t))try{let c=await r.readJSON(t),o=Array.isArray(c?.probes)?c.probes:[];for(let s=0;s<o.length;s+=1){let d=o[s]||{},u=typeof d.id=="string"&&d.id.trim().length>0?d.id.trim():`custom-probe-${s+1}`,p=typeof d.label=="string"&&d.label.trim().length>0?d.label.trim():u,f=d.severity||"warn",m=Array.isArray(d.anyOfPaths)?d.anyOfPaths.filter(Boolean):[],g=Array.isArray(d.allOfPaths)?d.allOfPaths.filter(Boolean):[],h=m.length===0;for(let b of m)if(await r.pathExists(a$1.join(e,b))){h=true;break}let y=true;for(let b of g)if(!await r.pathExists(a$1.join(e,b))){y=false;break}let k=h&&y;I(n,{id:u,label:p,status:k?"pass":f==="error"?"fail":"warn",severity:f,scope:"project-scoped",reason:k?"Custom probe contract satisfied.":`Custom probe failed from ${a$1.basename(t)}.`,recommendation:d.recommendation});}}catch{I(n,{id:"custom-probe-config",label:"Custom doctor probe configuration",status:"warn",severity:"warn",scope:"project-scoped",reason:`Failed to parse ${a$1.basename(t)}.`,recommendation:"Fix JSON syntax in doctor.probes.json to re-enable custom probes."});}await Zt(e,n);}async function $e(e,n={}){let t={name:a$1.basename(e),path:e,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},c=n.allowNonRapidkit===true,o=a$1.join(e,".rapidkit");if(!await r.pathExists(o)){if(!c)return t.issues.push("Not a valid RapidKit project (missing .rapidkit directory)"),t;t.issues.push("Not a RapidKit-managed project (running generic backend diagnostics)");}try{let w=a$1.join(e,"registry.json");if(await r.pathExists(w)){let v=await r.readJson(w);v.installed_modules&&(t.stats={modules:v.installed_modules.length});}}catch{}try{let{auditProjectModulePaths:w}=await import('./module-layout-NZ43RSC5.js'),v=await w(e);if(v.issues.length>0){for(let C of v.issues)t.issues.push(`${C.message} (${C.slug})`);t.fixCommands=t.fixCommands??[],t.fixCommands.push("npx rapidkit workspace contract verify --strict --json"),t.fixCommands.push("npx rapidkit add module <slug> # reinstall via Core-backed module install");}}catch{}let s=null;try{let w=a$1.join(o,"project.json");if(await r.pathExists(w)){s=await r.readJson(w);let v=s?.kit_name||s?.kit;v&&(t.kit=v);}}catch{}try{let w=a$1.join(e,".git");if(await r.pathExists(w)){let{stdout:v}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false});v&&(t.lastModified=v.trim());}else {let v=await r.stat(e),F=Date.now()-v.mtime.getTime(),D=Math.floor(F/(1e3*60*60*24));t.lastModified=D===0?"today":`${D} day${D>1?"s":""} ago`;}}catch{}let d$1=a$1.join(e,"package.json"),u=a$1.join(e,"pyproject.toml"),p=a$1.join(e,"requirements.txt"),f$1=a$1.join(e,"go.mod"),m=a$1.join(e,"pom.xml"),g=a$1.join(e,"build.sbt"),h=a$1.join(e,"Cargo.toml"),y=a$1.join(e,"mix.exs"),k=a$1.join(e,"deps.edn"),b=a$1.join(e,"project.clj"),L=a$1.join(e,"deno.json"),K=a$1.join(e,"deno.jsonc"),U=a$1.join(e,"bun.lockb"),z=a$1.join(e,"bun.lock"),V=a$1.join(e,"composer.json"),oe=a$1.join(e,"Gemfile"),Q=await r.pathExists(d$1),W=await r.pathExists(u)||await r.pathExists(p),N=await r.pathExists(V),ne=await r.pathExists(oe),ie=await r.pathExists(h),dt=await r.pathExists(y),ut=await r.pathExists(k)||await r.pathExists(b),pt=await r.pathExists(g),mt=await r.pathExists(L)||await r.pathExists(K),de=s?.runtime==="dotnet";try{de=de||await Ve(e,".csproj",3)||await Ve(e,".sln",2);}catch{de=s?.runtime==="dotnet";}let ft=await r.pathExists(f$1)||s?.runtime==="go"||typeof s?.kit_name=="string"&&(s.kit_name.startsWith("gofiber")||s.kit_name.startsWith("gogin")),Fe=Q&&(await r.pathExists(U)||await r.pathExists(z)||typeof s?.packageManager=="string"&&(s?.packageManager).toLowerCase().startsWith("bun@"));if(ft){G(t,i(e,s??null)),t.isGoProject=true,t.venvActive=true,t.coreInstalled=false;try{await execa("go",["version"],{timeout:3e3});}catch{t.issues.push("Go toolchain not found \u2014 install from https://go.dev/dl/"),t.fixCommands?.push("https://go.dev/dl/");}let w=a$1.join(e,"go.sum");return await r.pathExists(w)?t.depsInstalled=true:(t.depsInstalled=false,t.issues.push("Go dependencies not downloaded (go.sum missing)"),t.fixCommands?.push($(e,"go mod tidy"))),await T(e,t),await B(e,t),await _(e,t),t}if(await r.pathExists(m)||s?.runtime==="java"||typeof s?.kit_name=="string"&&s.kit_name.startsWith("springboot")){G(t,i(e,s??null)),t.venvActive=true,t.coreInstalled=false;let w=await r.pathExists(m),v=await r.pathExists(a$1.join(e,"build.gradle"))||await r.pathExists(a$1.join(e,"build.gradle.kts")),C=await r.pathExists(a$1.join(e,"mvnw"))||await r.pathExists(a$1.join(e,"mvnw.cmd")),F=await r.pathExists(a$1.join(e,"gradlew"))||await r.pathExists(a$1.join(e,"gradlew.bat"));try{await execa("java",["-version"],{timeout:3e3,reject:false});}catch{t.issues.push("Java runtime not found \u2014 install JDK 21+ and ensure java is on PATH"),t.fixCommands?.push("https://adoptium.net/");}if(w){if(!C)try{await execa("mvn",["-version"],{timeout:3e3,reject:false});}catch{t.issues.push("Maven not found \u2014 install Maven 3.9+ or add Maven Wrapper"),t.fixCommands?.push("https://maven.apache.org/install.html");}}else if(v&&!F)try{await execa("gradle",["--version"],{timeout:3e3,reject:false});}catch{t.issues.push("Gradle not found \u2014 install Gradle 8+ or add Gradle Wrapper"),t.fixCommands?.push("https://gradle.org/install/");}let D=a$1.join(e,"target"),A=a$1.join(e,"build","libs"),H=a$1.join(e,".rapidkit","cache","java","m2"),j=a$1.join(e,".rapidkit","cache","java","gradle");t.depsInstalled=await r.pathExists(D)||await r.pathExists(A)||await r.pathExists(H)||await r.pathExists(j),t.depsInstalled||(t.issues.push("Java dependencies are not warmed or built yet"),t.fixCommands?.push($(e,"rapidkit init")));let P=a$1.join(e,".env");if(t.hasEnvFile=await r.pathExists(P),!t.hasEnvFile){let X=a$1.join(e,".env.example");await r.pathExists(X)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(q(e)));}let J=a$1.join(e,"src","main","resources","application.yml");if(await r.pathExists(J))try{let X=await r.readFile(J,"utf-8");/include:\s*[^\n]*health/i.test(X)||/management:\s*[\s\S]*endpoint:\s*[\s\S]*health:/i.test(X)||(t.issues.push("Actuator health endpoint exposure is not clearly configured in application.yml"),t.fixCommands?.push($(e,"Ensure management.endpoints.web.exposure.include contains health in src/main/resources/application.yml")));}catch{t.issues.push("Unable to read application.yml for Spring Actuator health checks");}return await T(e,t),await B(e,t),await _(e,t),t}if(ie){G(t,i(e,s??null)),t.venvActive=true,t.coreInstalled=false;let w=a$1.join(e,"Cargo.lock"),v=a$1.join(e,"target");t.depsInstalled=await r.pathExists(w)||await r.pathExists(v),t.depsInstalled||(t.issues.push("Rust dependencies are not resolved yet (Cargo.lock/target missing)"),t.fixCommands?.push($(e,"cargo fetch")));let C=a$1.join(e,".env");if(t.hasEnvFile=await r.pathExists(C),!t.hasEnvFile){let F=a$1.join(e,".env.example");await r.pathExists(F)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(q(e)));}return await T(e,t),await B(e,t),await _(e,t),t}if(dt){G(t,i(e,s??null)),t.venvActive=true,t.coreInstalled=false;let w=a$1.join(e,"mix.lock"),v=a$1.join(e,"deps");t.depsInstalled=await r.pathExists(w)||await r.pathExists(v),t.depsInstalled||(t.issues.push("Elixir dependencies not installed (mix.lock/deps missing)"),t.fixCommands?.push($(e,"mix deps.get")));let C=a$1.join(e,".env");if(t.hasEnvFile=await r.pathExists(C),!t.hasEnvFile){let F=a$1.join(e,".env.example");await r.pathExists(F)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(q(e)));}return await T(e,t),await B(e,t),await _(e,t),t}if(ut){G(t,i(e,s??null)),t.venvActive=true,t.coreInstalled=false;let w=a$1.join(e,".cpcache"),v=a$1.join(e,"target"),C=await r.pathExists(k)||await r.pathExists(b);return t.depsInstalled=await r.pathExists(w)||await r.pathExists(v)||C,t.depsInstalled||(t.issues.push("Clojure dependency cache not initialized"),t.fixCommands?.push($(e,"clojure -P"))),await T(e,t),await B(e,t),await _(e,t),t}if(pt){G(t,i(e,s??null)),t.venvActive=true,t.coreInstalled=false;let w=a$1.join(e,"target");t.depsInstalled=await r.pathExists(w),t.depsInstalled||(t.issues.push("Scala build artifacts missing (run dependency/build warmup)"),t.fixCommands?.push($(e,"sbt compile")));let v=a$1.join(e,".env");if(t.hasEnvFile=await r.pathExists(v),!t.hasEnvFile){let C=a$1.join(e,".env.example");await r.pathExists(C)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(q(e)));}return await T(e,t),await B(e,t),await _(e,t),t}if(mt){G(t,i(e,s??null)),t.venvActive=true,t.coreInstalled=false,t.depsInstalled=true;let w=a$1.join(e,".env");if(t.hasEnvFile=await r.pathExists(w),!t.hasEnvFile){let v=a$1.join(e,".env.example");await r.pathExists(v)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(q(e)));}return await T(e,t),await B(e,t),await _(e,t),t}if(Q){let w=null;try{w=await r.readJson(d$1);}catch{w=null;}let v={...w?.dependencies??{},...w?.devDependencies??{}},C=w?.scripts??{},F=typeof s?.kit_name=="string"?s.kit_name.toLowerCase():typeof s?.kit=="string"?s.kit.toLowerCase():"",D=d(e,s),A=Gt({dependencies:v,scripts:C,kitName:F});if(Fe)ue(t,"Bun","high");else {let j=i(e,s??null);j.key==="nestjs"||j.key==="express"||j.key==="fastify"||j.key==="koa"?G(t,j):D.key!=="unknown"?_t(t,D):j.key!=="unknown"&&j.key!=="node"?G(t,j):ue(t,A.framework,A.confidence);}t.venvActive=true;let H=a$1.join(e,"node_modules");if(await r.pathExists(H))try{let P=(await r.readdir(H)).filter(J=>!J.startsWith(".")&&!J.startsWith("_"));t.depsInstalled=P.length>0;}catch{t.depsInstalled=false;}if(t.depsInstalled||(t.issues.push("Dependencies not installed (node_modules empty or missing)"),t.fixCommands?.push($(e,Fe?"bun install":"rapidkit init"))),t.coreInstalled=false,t.projectKind==="frontend"){let j=[".env",".env.local",".env.development",".env.development.local",".env.production",".env.production.local"];if((await Promise.all(j.map(J=>r.pathExists(a$1.join(e,J))))).some(Boolean))t.hasEnvFile=true;else {let J=a$1.join(e,".env.example");await r.pathExists(J)&&(t.hasEnvFile=false,t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(q(e)));}}else {let j=a$1.join(e,".env");if(t.hasEnvFile=await r.pathExists(j),!t.hasEnvFile){let P=a$1.join(e,".env.example");await r.pathExists(P)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(q(e)));}}if(t.projectKind==="frontend")t.modulesHealthy=await be(e),t.missingModules=[];else {let j=a$1.join(e,"src");if(t.modulesHealthy=true,t.missingModules=[],await r.pathExists(j))try{let P=await r.readdir(j);t.modulesHealthy=P.length>0;}catch{t.modulesHealthy=false;}}return await T(e,t,w),t.projectKind==="frontend"?await en(e,t,w,D.key!=="unknown"?D:d(e,s)):await B(e,t),await _(e,t),t}if(W){let w=await Kt(e);ue(t,w.framework,w.confidence);let v=a$1.join(e,".venv");if(await r.pathExists(v)){t.venvActive=true;let A=f(v);if(await r.pathExists(A)){try{let{stdout:P}=await execa(A,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3});t.coreInstalled=true,t.coreVersion=P.trim();}catch{t.coreInstalled=false;}let H="fastapi";t.framework==="Django"?H="django":t.framework==="Flask"?H="flask":t.framework==="Python"&&(H="");let j=true;if(H)try{await execa(A,["-c",`import ${H}`],{timeout:2e3}),t.depsInstalled=true,j=false;}catch{j=true;}if(j)try{let P=a$1.join(v,"lib");if(await r.pathExists(P)){let X=(await r.readdir(P)).find(ae=>ae.startsWith("python"));if(X){let ae=a$1.join(P,X,"site-packages");if(await r.pathExists(ae)){let gt=(await r.readdir(ae)).filter(ge=>!ge.startsWith("_")&&!ge.includes("dist-info")&&!["pip","setuptools","wheel","pkg_resources"].includes(ge));t.depsInstalled=gt.length>0;}}}t.depsInstalled||(t.issues.push("Dependencies not installed"),t.fixCommands?.push($(e,"rapidkit init")));}catch{t.issues.push("Could not verify dependency installation");}}else t.issues.push("Virtual environment exists but Python executable not found");}else t.issues.push("Virtual environment not created"),t.fixCommands?.push($(e,"rapidkit init"));let C=a$1.join(e,".env");if(t.hasEnvFile=await r.pathExists(C),!t.hasEnvFile){let A=a$1.join(e,".env.example");await r.pathExists(A)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(q(e)));}let F=a$1.join(e,"src"),D=a$1.join(e,"modules");if(t.modulesHealthy=true,t.missingModules=[],await r.pathExists(F)){let A=a$1.join(F,"__init__.py");await r.pathExists(A)||(t.modulesHealthy=false,t.missingModules.push("src/__init__.py"));}if(await r.pathExists(D))try{let A=await st(D);for(let H of A){let j=a$1.join(D,H,"__init__.py");await r.pathExists(j)||(t.modulesHealthy=false,t.missingModules.push(`modules/${H}/__init__.py`));}}catch{}return !t.modulesHealthy&&t.missingModules.length>0&&t.issues.push(`Missing module init files: ${t.missingModules.join(", ")}`),await T(e,t),await B(e,t),await _(e,t),t}if(N){G(t,i(e,s??null)),t.venvActive=true,t.coreInstalled=false;let w=a$1.join(e,"vendor");t.depsInstalled=await r.pathExists(w),t.depsInstalled||(t.issues.push("PHP dependencies not installed (vendor missing)"),t.fixCommands?.push($(e,"composer install")));let v=a$1.join(e,".env");if(t.hasEnvFile=await r.pathExists(v),!t.hasEnvFile){let C=a$1.join(e,".env.example");await r.pathExists(C)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(q(e)));}return await T(e,t),await B(e,t),await _(e,t),t}if(ne){G(t,i(e,s??null)),t.venvActive=true,t.coreInstalled=false;let w=await r.pathExists(a$1.join(e,"Gemfile.lock")),v=await r.pathExists(a$1.join(e,"vendor","bundle"));t.depsInstalled=w||v,t.depsInstalled||(t.issues.push("Ruby dependencies not installed (Gemfile.lock/vendor missing)"),t.fixCommands?.push($(e,"bundle install")));let C=a$1.join(e,".env");return t.hasEnvFile=await r.pathExists(C),await T(e,t),await B(e,t),await _(e,t),t}if(de){G(t,i(e,s??null)),t.venvActive=true,t.coreInstalled=false;let w=a$1.join(e,"obj"),v=a$1.join(e,"src","obj"),C=a$1.join(e,"packages.lock.json");t.depsInstalled=await r.pathExists(w)||await r.pathExists(v)||await r.pathExists(C),t.depsInstalled||(t.issues.push(".NET restore/build artifacts not found"),t.fixCommands?.push($(e,"dotnet restore")));let F=a$1.join(e,".env");return t.hasEnvFile=await r.pathExists(F),await T(e,t),await B(e,t),await _(e,t),t}return ue(t,"Unknown","low"),t.issues.push("Unknown project type (no recognized runtime marker files)"),await T(e,t),await B(e,t),await _(e,t),t}async function st(e){try{return (await r.readdir(e,{withFileTypes:true})).filter(i=>i.isDirectory()).map(i=>i.name)}catch{try{let n=await r.readdir(e),i=[];for(let t of n)try{(await r.stat(a$1.join(e,t))).isDirectory()&&i.push(t);}catch{continue}return i}catch{return []}}}async function Ve(e,n,i){let t=[{dir:e,depth:0}],c=new Set([".git",".rapidkit","node_modules","bin","obj","target"]);for(;t.length>0;){let o=t.shift();if(!o||o.depth>i)continue;let s;try{s=await r.readdir(o.dir,{withFileTypes:true});}catch{continue}for(let d of s){if(d.isFile()&&d.name.toLowerCase().endsWith(n.toLowerCase()))return true;d.isDirectory()&&!c.has(d.name)&&t.push({dir:a$1.join(o.dir,d.name),depth:o.depth+1});}}return false}async function ce(e){let n=a$1.join(e,".rapidkit");if(!await r.pathExists(n))return false;let i=["project.json","context.json","file-hashes.json"];for(let t of i)if(await r.pathExists(a$1.join(n,t)))return true;return false}function ot(e,n){if(n.has(e))return true;let i=e.toLowerCase();return !!(i==="dist"||i.startsWith("dist-")||i.startsWith("dist_")||i==="build"||i.startsWith("build-")||i.startsWith("build_"))}async function tn(e,n,i){let t=new Set,c=[{dir:e,depth:0}];for(;c.length>0;){let o=c.shift();if(!o)break;try{let s=await r.readdir(o.dir);for(let d of s){if(ot(d,i))continue;let u=a$1.join(o.dir,d),p;try{p=await r.stat(u);}catch{continue}if(p.isDirectory()){if(await ce(u)){t.add(u);continue}o.depth<n&&c.push({dir:u,depth:o.depth+1});}}}catch{continue}}return Array.from(t)}async function le(e){let n=a$1.resolve(e),i=a$1.parse(n).root;for(;;){if(await on(n))return n;if(n===i)break;n=a$1.dirname(n);}return null}async function nn(e){let n=a$1.resolve(e),i=await le(n),t=i??a$1.parse(n).root;for(;;){if(await ce(n)||await sn(n)&&(!i||n!==i))return n;if(n===t)break;n=a$1.dirname(n);}return null}function Je(e){let n=a$1.resolve(e);return process.platform==="darwin"?n.replace(/^\/private(?=\/var\/)/,""):n}async function sn(e){let n=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.sbt","Cargo.toml","mix.exs","deps.edn","project.clj","deno.json","deno.jsonc","composer.json","Gemfile"];for(let i of n)if(await r.pathExists(a$1.join(e,i)))return true;return false}async function on(e){let n=[a$1.join(e,".rapidkit-workspace"),a$1.join(e,".rapidkit","workspace-marker.json"),a$1.join(e,".rapidkit","config.json")];return Promise.all(n.map(i=>r.pathExists(i))).then(i=>i.some(Boolean))}function it(e,n){let i=0,t=0,c=0;return e.forEach(s=>{s.status==="ok"?i++:s.status==="warn"?t++:s.status==="error"&&c++;}),n.forEach(s=>{let d=ee(s),u=s.isGoProject?s.issues.length===0&&s.depsInstalled:s.issues.length===0&&s.venvActive&&s.depsInstalled;if(s.issues.length>0||d>0||!u){t++;return}i++;}),{total:i+t+c,passed:i,warnings:t,errors:c}}function at(e,n,i={}){let t=[];for(let o of e)t.push({id:o.id,label:o.label,status:o.result.status,scope:"host-system",policyRuleId:"system-status-derived",reason:o.result.details||o.result.message});let c=[...n].sort((o,s)=>{let d=`${o.path||""}|${o.name||""}`.toLowerCase(),u=`${s.path||""}|${s.name||""}`.toLowerCase();return d.localeCompare(u)});for(let o of c){let s=o.issues.length>0,d=ee(o),u=s||d>0?"warn":"ok",p=s?`${o.issues.length} blocking issue(s)`:d>0?`${d} advisory warning(s)`:"Project checks passed";t.push({id:`project:${o.name}`,label:`Project ${o.name}`,status:u,scope:"project-scoped",policyRuleId:s?"project-blocking-issues":d>0?"project-advisory-warnings":"project-checks-passed",reason:p});}if(i.includeWorkspaceAggregateRules){let o=n.reduce((u,p)=>u+p.issues.length,0),s=Pe(n),d=e.filter(u=>u.result.status==="error").length;t.push({id:"workspace:projects-discovered",label:"Workspace projects discovered",status:n.length>0?"ok":"warn",scope:"workspace-aggregate",policyRuleId:"workspace-project-discovery",reason:n.length>0?`${n.length} project(s) discovered for workspace analysis.`:"No projects discovered for workspace analysis."}),t.push({id:"workspace:system-error-gate",label:"Workspace system error gate",status:d>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-system-error-gate",reason:d>0?`${d} system requirement gate(s) failed.`:"All system requirement gates passed."}),t.push({id:"workspace:blocking-issues-gate",label:"Workspace blocking issues gate",status:o>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-blocking-issues-gate",reason:o>0?`${o} blocking project issue(s) detected.`:"No blocking project issues detected."}),t.push({id:"workspace:advisory-warnings-gate",label:"Workspace advisory warnings gate",status:s>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-advisory-warning-gate",reason:s>0?`${s} advisory warning(s) detected.`:"No advisory warnings detected."});}return t}async function qe(e,n=true){let i=a$1.basename(e);try{let g=a$1.join(e,".rapidkit-workspace");await r.pathExists(g)&&(i=(await r.readJSON(g)).name||i);}catch{try{let g=a$1.join(e,".rapidkit","config.json");i=(await r.readJSON(g)).workspace_name||i;}catch{}}let[t,c]=await Promise.all([Re(),Wt(e)]),o={workspacePath:e,workspaceName:i,python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore,projects:[]};a.debug(`Workspace scan found ${c.length} project(s)`);let s=await Ot(e,c),d=a$1.join(e,".rapidkit","reports","doctor-workspace-cache.json"),u=n?await Lt(d,s):null;if(u){o.projects=u.projects;for(let g of o.projects)je(g,g.path);o.projectScanCached=true,a.debug(`Workspace project health cache hit: ${d}`);}else try{let g=await Promise.all(c.map(h=>$e(h)));for(let h of g)je(h,h.path);o.projects=g,o.projectScanCached=false,await Vt(d,{schemaVersion:Xe,signature:s,generatedAt:new Date().toISOString(),projects:g}),a.debug(`Workspace project health cache refreshed: ${d}`);}catch(g){a.debug(`Failed to scan workspace projects: ${g}`);}o.projectScanSignature=s,o.projectScanCachePath=d;let p=[o.python,o.poetry,o.pipx,o.go,o.rapidkitCore];if(o.healthScore=it(p,o.projects),o.scoreBreakdown=at([{id:"system-python",label:"Python",result:o.python},{id:"system-poetry",label:"Poetry",result:o.poetry},{id:"system-pipx",label:"pipx",result:o.pipx},{id:"system-go",label:"Go",result:o.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:o.rapidkitCore}],o.projects,{includeWorkspaceAggregateRules:true}),o.scopeProvenance=tt(o.scoreBreakdown),o.rapidkitCore.status==="ok"){let g=o.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);g&&(o.coreVersion=g[1]);}let f=a$1.join(e,".rapidkit","reports","doctor-last-run.json"),m=await Ze(f,"workspace");return o.driftDelta=It(m,o),o.evidencePath=await Jt(e,o,u?d:null),o}function Ue(e){return {name:e.name,path:e.path,framework:e.framework,frameworkKey:e.frameworkKey,importStack:e.importStack,runtimeFamily:e.runtimeFamily,projectKind:e.projectKind,supportTier:e.supportTier,frameworkConfidence:e.frameworkConfidence,kit:e.kit,venvActive:e.venvActive,depsInstalled:e.depsInstalled,hasEnvFile:e.hasEnvFile,modulesHealthy:e.modulesHealthy,missingModules:e.missingModules,hasTests:e.hasTests,hasDocker:e.hasDocker,hasCodeQuality:e.hasCodeQuality,vulnerabilities:e.vulnerabilities,coreInstalled:e.coreInstalled,coreVersion:e.coreVersion,lastModified:e.lastModified,stats:e.stats,issues:e.issues,fixCommands:e.fixCommands,probes:e.probes,commandCapabilities:e.commandCapabilities}}async function an(e,n){let i=e||n.projectPath,t=a$1.join(i,".rapidkit","reports","doctor-project-last-run.json");try{return await r.ensureDir(a$1.dirname(t)),await r.writeJSON(t,{schemaVersion:b$1,evidenceType:"project",generatedAt:new Date().toISOString(),contract:me(),workspacePath:e||null,projectPath:n.projectPath,projectName:n.projectName,healthScore:n.healthScore,system:{python:n.python,poetry:n.poetry,pipx:n.pipx,go:n.go,rapidkitCore:n.rapidkitCore},project:n.project,driftDelta:n.driftDelta,summary:{scopeProvenance:n.scopeProvenance},scoreBreakdown:n.scoreBreakdown??[]},{spaces:2}),t}catch{return}}async function rn(e){let n=await le(e),i=await Re(),t=await $e(e,{allowNonRapidkit:true});je(t,e);let c=it([i.python,i.poetry,i.pipx,i.go,i.rapidkitCore],[t]),o={workspacePath:n||void 0,projectPath:e,projectName:a$1.basename(e),python:i.python,poetry:i.poetry,pipx:i.pipx,go:i.go,rapidkitCore:i.rapidkitCore,project:t,healthScore:c};o.scoreBreakdown=at([{id:"system-python",label:"Python",result:o.python},{id:"system-poetry",label:"Poetry",result:o.poetry},{id:"system-pipx",label:"pipx",result:o.pipx},{id:"system-go",label:"Go",result:o.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:o.rapidkitCore}],[o.project]),o.scopeProvenance=tt(o.scoreBreakdown);let s=n||e,d=a$1.join(s,".rapidkit","reports","doctor-project-last-run.json"),u=await Ze(d,"project");return o.driftDelta=Nt(u,o),o.evidencePath=await an(n||void 0,o),o}function R(e,n){let i=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",t=e.status==="ok"?l.green:e.status==="warn"?l.yellow:l.red;console.log(`${i} ${l.bold(n)}: ${t(e.message)}`),e.paths&&e.paths.length>0&&e.paths.forEach(c=>{let o=c.version?l.cyan(` -> ${c.version}`):"";console.log(` ${l.cyan("\u2022")} ${l.gray(c.location)}: ${l.dim(c.path)}${o}`);}),e.details&&console.log(` ${l.gray(e.details)}`);}function ze(e){let n=e.issues.length>0,i=n?"\u26A0\uFE0F":"\u2705",t=n?l.yellow:l.green;if(console.log(`
|
|
2
|
+
${i} ${l.bold("Project")}: ${t(e.name)}`),e.framework){let s=e.framework==="FastAPI"||e.framework==="Django"||e.framework==="Flask"?"\u{1F40D}":e.framework==="NestJS"?"\u{1F985}":e.framework==="Next.js"||e.framework==="Nuxt"||e.framework==="Remix"?"\u25B2":e.framework==="React"||e.framework==="Vite"?"\u269B\uFE0F":e.framework==="Vue"?"\u{1F7E2}":e.framework==="Angular"?"\u{1F170}\uFE0F":e.framework==="SvelteKit"?"\u{1F9E1}":e.framework==="Spring Boot"?"\u2615":e.framework==="Rust"?"\u{1F980}":e.framework==="Elixir"||e.framework==="Phoenix"?"\u{1F9EA}":e.framework==="Clojure"?"\u2699\uFE0F":e.framework==="Scala"?"\u{1F53A}":e.framework==="Kotlin"?"\u{1F7E3}":e.framework==="Deno"?"\u{1F995}":e.framework==="Bun"?"\u{1F956}":e.framework==="Go/Fiber"||e.framework==="Go/Gin"?"\u{1F439}":e.framework==="Laravel"||e.framework==="PHP"?"\u{1F418}":e.framework==="Ruby on Rails"||e.framework==="Ruby"?"\u{1F48E}":e.framework==="ASP.NET"?"\u{1F537}":"\u{1F4E6}";console.log(` ${s} Framework: ${l.cyan(e.framework)}${e.kit?l.gray(` (${e.kit})`):""}`);let d=[];e.runtimeFamily&&d.push(`runtime: ${e.runtimeFamily}`),e.projectKind&&d.push(`kind: ${e.projectKind}`),e.supportTier&&d.push(`support: ${e.supportTier}`),e.frameworkConfidence&&d.push(`confidence: ${e.frameworkConfidence}`),d.length>0&&console.log(` ${l.dim("\u21B3")} ${l.gray(d.join(" \u2022 "))}`);}if(console.log(` ${l.gray(`Path: ${e.path}`)}`),e.runtimeFamily==="python"&&(e.venvActive?console.log(` \u2705 Virtual environment: ${l.green("Active")}`):console.log(` \u274C Virtual environment: ${l.red("Not found")}`),e.coreInstalled?console.log(` ${l.dim("\u2139")} RapidKit Core: ${l.gray(e.coreVersion||"In venv")} ${l.dim("(optional)")}`):console.log(` ${l.dim("\u2139")} RapidKit Core: ${l.gray("Using global installation")} ${l.dim("(recommended)")}`)),e.depsInstalled?console.log(` \u2705 Dependencies: ${l.green("Installed")}`):console.log(` \u26A0\uFE0F Dependencies: ${l.yellow("Not installed")}`),e.hasEnvFile!==void 0&&(e.hasEnvFile?console.log(` \u2705 Environment: ${l.green(".env configured")}`):console.log(` \u26A0\uFE0F Environment: ${l.yellow(".env missing")}`)),e.modulesHealthy!==void 0){let s=e.projectKind==="frontend"?"Source tree":"Modules";e.modulesHealthy?console.log(` \u2705 ${s}: ${l.green("Healthy")}`):e.missingModules&&e.missingModules.length>0?console.log(` \u26A0\uFE0F ${s}: ${l.yellow(`Missing ${e.missingModules.length} init file(s)`)}`):e.projectKind==="frontend"&&console.log(` \u26A0\uFE0F ${s}: ${l.yellow("No application directories detected")}`);}if(e.stats){let s=[];e.stats.modules!==void 0&&s.push(`${e.stats.modules} module${e.stats.modules!==1?"s":""}`),s.length>0&&console.log(` \u{1F4CA} Stats: ${l.cyan(s.join(" \u2022 "))}`);}e.lastModified&&console.log(` \u{1F552} Last Modified: ${l.gray(e.lastModified)}`);let o=[];if(e.hasTests!==void 0&&o.push(e.hasTests?"\u2705 Tests":l.dim("\u2298 No tests")),e.hasDocker!==void 0&&o.push(e.hasDocker?"\u2705 Docker":l.dim("\u2298 No Docker")),e.hasCodeQuality!==void 0){let s=e.runtimeFamily==="node"?"ESLint":e.runtimeFamily==="rust"?"clippy":e.runtimeFamily==="elixir"?"Credo":e.runtimeFamily==="clojure"?"clj-kondo":e.runtimeFamily==="deno"?"deno lint":e.framework==="Spring Boot"?"Static analysis":e.framework==="Go/Fiber"||e.framework==="Go/Gin"?"golangci-lint":e.runtimeFamily==="python"?"Ruff":"Lint";o.push(e.hasCodeQuality?`\u2705 ${s}`:l.dim(`\u2298 No ${s}`));}if(o.length>0&&console.log(` ${o.join(" \u2022 ")}`),e.vulnerabilities!==void 0&&e.vulnerabilities>0&&console.log(` \u26A0\uFE0F Security: ${l.yellow(`${e.vulnerabilities} vulnerability(ies) found`)}`),e.issues.length>0&&(console.log(` ${l.bold("Issues:")}`),e.issues.forEach(s=>{console.log(` \u2022 ${l.yellow(s)}`);}),e.fixCommands&&e.fixCommands.length>0&&(console.log(`
|
|
3
|
+
${l.bold.cyan("\u{1F527} Quick Fix:")}`),e.fixCommands.forEach(s=>{console.log(` ${l.cyan("$")} ${l.white(s)}`);}))),e.probes&&e.probes.length>0){console.log(` ${l.bold("Probe checks:")}`);for(let s of e.probes){let d=s.status==="pass"?"\u2705":s.status==="warn"?"\u26A0\uFE0F":"\u274C";console.log(` ${d} ${s.label}: ${l.gray(s.reason)}`),s.recommendation&&console.log(` ${l.dim("\u21B3")} ${l.gray(s.recommendation)}`);}}if(e.commandCapabilities){let s=e.commandCapabilities;if(console.log(` ${l.bold("Command support:")}`),console.log(` ${l.green("supported")} ${s.supportedCommands.length} \u2022 ${l.yellow("unsupported")} ${s.unsupportedCommands.length} \u2022 ${l.gray("global")} ${s.globalCommands.length}`),s.unsupportedCommands.length>0){let d=s.unsupportedCommands.slice(0,8).join(", "),u=s.unsupportedCommands.length>8?", ...":"";console.log(` ${l.dim("\u21B3")} ${l.gray(`Unsupported here: ${d}${u}`)}`);}}}async function rt(){try{return (await execa("go",["version"],{timeout:a$4(),reject:false})).exitCode===0}catch{return false}}function te(e,n){let i=[new RegExp(`^cd\\s+"([^"]+)"\\s*(?:&&|;)\\s*${n}\\s*$`,"i"),new RegExp(`^cd\\s+'([^']+)'\\s*(?:&&|;)\\s*${n}\\s*$`,"i"),new RegExp(`^cd\\s+(.+?)\\s*(?:&&|;)\\s*${n}\\s*$`,"i")];for(let t of i){let c=e.match(t);if(c?.[1])return {projectPath:c[1].trim()}}return null}function ct(e){return te(e,"cp\\s+\\.env\\.example\\s+\\.env")||te(e,"copy-item\\s+\\.env\\.example\\s+\\.env")}function lt(e){let n=[{pattern:"npm\\s+install",command:"npm",args:["install"]},{pattern:"npm\\s+ci",command:"npm",args:["ci"]},{pattern:"pnpm\\s+install",command:"pnpm",args:["install"]},{pattern:"yarn\\s+install",command:"yarn",args:["install"]},{pattern:"poetry\\s+install",command:"poetry",args:["install"]},{pattern:"pip\\s+install\\s+-r\\s+requirements\\.txt",command:"pip",args:["install","-r","requirements.txt"]},{pattern:"composer\\s+install",command:"composer",args:["install"]},{pattern:"bundle\\s+install",command:"bundle",args:["install"]},{pattern:"dotnet\\s+restore",command:"dotnet",args:["restore"]},{pattern:"cargo\\s+fetch",command:"cargo",args:["fetch"]},{pattern:"mix\\s+deps\\.get",command:"mix",args:["deps.get"]},{pattern:"clojure\\s+-P",command:"clojure",args:["-P"]},{pattern:"sbt\\s+compile",command:"sbt",args:["compile"]}];for(let i of n){let t=te(e,i.pattern);if(t)return {projectPath:t.projectPath,command:i.command,args:i.args}}return null}function Ce(e,n){return /^https?:\/\//i.test(n.trim())?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"manual-url",risk:"safe",executable:false,reason:"Manual guidance URL"}:ct(n)?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"env-copy",risk:"safe",executable:true,reason:"Environment seed copy"}:te(n,"rapidkit\\s+init")?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"rapidkit-init",risk:"guarded",executable:true,reason:"RapidKit initializer may mutate dependencies and configs"}:te(n,"go\\s+mod\\s+tidy")?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"go-mod-tidy",risk:"guarded",executable:true,reason:"Go module graph reconciliation"}:lt(n)?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"dependency-sync",risk:"guarded",executable:true,reason:"Dependency synchronization command"}:{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"shell",risk:"invasive",executable:true,reason:"Generic shell command"}}async function Ee(e){let n=e.filter(p=>p.fixCommands&&p.fixCommands.length>0),i=n.flatMap(p=>(p.fixCommands??[]).map(f=>Ce(p,f))),t=null,c=[],o=0,s=0,d=0,u=0;for(let p of i){let f=p.executable,m;p.kind==="go-mod-tidy"&&(t===null&&(t=await rt()),t||(f=false,m="Go toolchain not available")),f&&(o+=1,p.risk==="safe"&&(s+=1),p.risk==="guarded"&&(d+=1),p.risk==="invasive"&&(u+=1)),c.push({...p,executableInCurrentEnvironment:f,blockedReason:m});}return {generatedAt:new Date().toISOString(),fixableProjects:n.length,totalSteps:c.length,executableSteps:o,risk:{safe:s,guarded:d,invasive:u},steps:c}}function Qe(e){let n=e instanceof Error?e.message:String(e),i=["ETIMEDOUT","ECONNRESET","ECONNREFUSED","EAI_AGAIN","ENOTFOUND","network","503","504"],t=n.toLowerCase();return i.some(c=>t.includes(c.toLowerCase()))}async function cn(e,n){let i=e.get(n);if(i)return i;let t=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,c=a$1.basename(n).replace(/[^a-zA-Z0-9._-]/g,"_"),o=a$1.join(n,".rapidkit","reports","fix-snapshots",`${c}-${t}`);await r.ensureDir(o);let s=[".env","package-lock.json","pnpm-lock.yaml","yarn.lock","poetry.lock","requirements.txt","go.mod","go.sum","Cargo.lock","composer.lock","Gemfile.lock","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile"],d=new Map;for(let p of s){let f=a$1.join(n,p);if(!await r.pathExists(f))continue;let m=a$1.join(o,p);await r.ensureDir(a$1.dirname(m)),await r.copy(f,m,{overwrite:true}),d.set(f,m);}let u={snapshotRoot:o,files:d};return e.set(n,u),u}async function ln(e){for(let[n,i]of e.files.entries())await r.pathExists(i)&&(await r.ensureDir(a$1.dirname(n)),await r.copy(i,n,{overwrite:true}));}async function dn(e){let n=await $e(e,{allowNonRapidkit:true});return {issues:n.issues.length,healthy:n.issues.length===0}}async function se(e,n=false,i={}){let t=await Ee(e),c=e.filter(h=>h.fixCommands&&h.fixCommands.length>0),o=null,s=t.steps.some(h=>h.kind==="go-mod-tidy"&&!h.executableInCurrentEnvironment),d=new Map;if(c.length===0){console.log(l.green(`
|
|
4
|
+
\u2705 No fixes needed - all projects are healthy!`));return}console.log(l.bold.cyan(`
|
|
5
|
+
\u{1F527} Available Fixes:
|
|
6
|
+
`));for(let h of c){let y=h.fixCommands??[];console.log(l.bold(`Project: ${l.yellow(h.name)}`)),y.forEach((k,b)=>{console.log(` ${b+1}. ${l.cyan(k)}`);}),console.log();}if(i.planOnly){if(i.json){console.log(JSON.stringify(t,null,2));return}console.log(l.bold(`
|
|
7
|
+
\u{1F9ED} Remediation Plan
|
|
8
|
+
`)),console.log(l.gray(`Executable steps: ${t.executableSteps}/${t.totalSteps} | risk: safe=${t.risk.safe}, guarded=${t.risk.guarded}, invasive=${t.risk.invasive}`));for(let h of t.steps){let y=h.executableInCurrentEnvironment?l.green("ready"):l.yellow(`blocked${h.blockedReason?` (${h.blockedReason})`:""}`);console.log(` - ${l.cyan(h.projectName)} [${h.risk}] ${h.originalCommand} ${l.gray(`=> ${y}`)}`);}console.log(l.gray(`
|
|
9
|
+
Use --apply to execute this plan non-interactively, or --fix for interactive confirmation.`));return}let u=t.executableSteps,p=t.risk.safe,f=t.risk.guarded,m=t.risk.invasive;if(u===0){console.log(l.gray("\u{1F4A1} No automatic fixes can be applied right now.")),s&&console.log(l.gray(" Install Go to enable go mod tidy fixes, then rerun `rapidkit doctor workspace --fix`."));return}if(!n){console.log(l.gray('\u{1F4A1} Run "npx rapidkit doctor workspace --fix" to apply fixes automatically'));return}if(console.log(l.gray(`Risk policy: safe=${p}, guarded=${f}, invasive=${m}. Guarded/invasive fixes use snapshot + rollback.`)),!i.skipConfirmation){let{confirm:h}=await Pt.prompt([{type:"confirm",name:"confirm",message:`Apply ${c.reduce((y,k)=>y+(k.fixCommands?.length??0),0)} fix(es)?`,default:false}]);if(!h){console.log(l.yellow(`
|
|
10
|
+
\u26A0\uFE0F Fixes cancelled by user`));return}}console.log(l.bold.cyan(`
|
|
11
|
+
\u{1F680} Applying fixes...
|
|
12
|
+
`));let g=new Set;for(let h of c){let y=h.fixCommands??[];console.log(l.bold(`Fixing ${l.cyan(h.name)}...`));for(let k of y){let b$1=Ce(h,k),L=`${h.path}::${k}`;if(!g.has(L)){g.add(L);try{if(console.log(l.gray(` $ ${k}`)),b$1.kind==="manual-url"){console.log(l.yellow(` \u2139 Manual action required: open ${k}`)),console.log(l.green(` \u2705 Recorded as guidance
|
|
13
|
+
`));continue}if(!b$1.executable){console.log(l.yellow(" \u26A0 Step is non-executable by policy")),console.log(l.green(` \u2705 Recorded as guidance
|
|
14
|
+
`));continue}b$1.risk!=="safe"&&await cn(d,b$1.projectPath);let K=ct(k);if(K){let W=a$1.join(K.projectPath,".env.example"),N=a$1.join(K.projectPath,".env");if(!await r.pathExists(W))throw new Error(`.env.example not found at ${W}`);if(await r.pathExists(N)){console.log(l.green(` \u2705 .env already exists
|
|
15
|
+
`));continue}await r.copy(W,N,{overwrite:false,errorOnExist:false}),console.log(l.green(` \u2705 Success
|
|
16
|
+
`));continue}let U=te(k,"rapidkit\\s+init");if(U){await execa("rapidkit",["init"],{cwd:U.projectPath,shell:b(),stdio:"inherit"}),console.log(l.green(` \u2705 Success
|
|
17
|
+
`));continue}let z=te(k,"go\\s+mod\\s+tidy");if(z){if(o===null&&(o=await rt()),!o){console.log(l.yellow(" \u26A0 Go toolchain is not installed \u2014 skipping go mod tidy; install Go to apply this fix.")),console.log(l.green(` \u2705 Recorded as guidance
|
|
18
|
+
`));continue}await execa("go",["mod","tidy"],{cwd:z.projectPath,shell:b(),stdio:"inherit"}),console.log(l.green(` \u2705 Success
|
|
19
|
+
`));continue}let V=lt(k);if(V){let N;for(let ne=1;ne<=2;ne+=1)try{await execa(V.command,V.args,{cwd:V.projectPath,shell:b(),stdio:"inherit"}),N=null;break}catch(ie){if(N=ie,ne<2&&Qe(ie)){console.log(l.yellow(` \u26A0 Retrying dependency sync (${ne}/1)...`));continue}throw ie}if(N)throw N;console.log(l.green(` \u2705 Success
|
|
20
|
+
`));continue}let oe=b$1.kind==="shell"?2:1,Q;for(let W=1;W<=oe;W+=1)try{await execa(k,{shell:true,stdio:"inherit"}),Q=null;break}catch(N){if(Q=N,W<oe&&Qe(N)){console.log(l.yellow(` \u26A0 Retrying command (${W}/${oe-1})...`));continue}throw N}if(Q)throw Q;console.log(l.green(` \u2705 Success
|
|
21
|
+
`));}catch(K){let U=Ce(h,k);if(U.risk!=="safe"){let z=d.get(U.projectPath);if(z)try{await ln(z),console.log(l.yellow(" \u21A9 Rolled back snapshot after failed fix"));}catch(V){console.log(l.red(` \u274C Rollback failed: ${V instanceof Error?V.message:String(V)}`));}}console.log(l.red(` \u274C Failed: ${K instanceof Error?K.message:String(K)}
|
|
22
|
+
`));}}}try{let k=await dn(h.path);console.log(k.healthy?l.green(` \u2705 Post-fix verification passed for ${h.name}`):l.yellow(` \u26A0 Post-fix verification: ${k.issues} issue(s) remain for ${h.name}`));}catch(k){console.log(l.yellow(` \u26A0 Post-fix verification skipped: ${k instanceof Error?k.message:String(k)}`));}}console.log(l.bold.green(`
|
|
23
|
+
\u2705 Fix process completed!`));}function pe(e,n){if(!n.strict&&!n.ci)return 0;let i=Number(e?.errors??0),t=Number(e?.warnings??0);return i>0?1:n.ci&&t>0?2:n.strict&&t>0?1:0}async function In(e={}){let n=!!(e.fix||e.plan||e.apply),i=!e.workspace&&!e.project&&n?await le(process.cwd()):null,t=e.workspace||!!i,c=!!e.project&&!t;if(e.json||console.log(l.bold.cyan(`
|
|
24
|
+
\u{1FA7A} RapidKit Health Check
|
|
25
|
+
`)),t){let o=i??await le(process.cwd());o||(a.error("No RapidKit workspace found in current directory or parents"),a.info('Run this command from within a workspace, or use "rapidkit doctor" for system check'),process.exit(1)),e.json||(i&&console.log(l.gray("\u2139\uFE0F Detected workspace context; enabling workspace checks for --fix")),console.log(l.bold(`Workspace: ${l.cyan(a$1.basename(o))}`)),console.log(l.gray(`Path: ${o}`)));let s=await qe(o);if(e.json||(s.projectScanCached&&console.log(l.gray(`\u2139\uFE0F Reused cached project scan${s.projectScanCachePath?` (${a$1.basename(s.projectScanCachePath)})`:""}`)),s.evidencePath&&console.log(l.gray(`\u2139\uFE0F Evidence saved: ${s.evidencePath}`))),e.json){let f=e.plan?await Ee(s.projects):void 0,m={contract:me(),workspace:{name:a$1.basename(o),path:o},cache:{projectScan:s.projectScanCached??false,projectScanPath:s.projectScanCachePath,evidencePath:s.evidencePath},healthScore:s.healthScore,system:{python:s.python,poetry:s.poetry,pipx:s.pipx,rapidkitCore:s.rapidkitCore,versions:{core:s.coreVersion,npm:s.npmVersion}},projects:s.projects.map(g=>Ue(g)),summary:{totalProjects:s.projects.length,totalIssues:s.projects.reduce((g,h)=>g+h.issues.length,0),projectAdvisoryWarningProjects:xe(s.projects),projectAdvisoryWarnings:Pe(s.projects),hasSystemErrors:[s.python,s.rapidkitCore].some(g=>g.status==="error"),scopeProvenance:s.scopeProvenance},driftDelta:s.driftDelta,scoreBreakdown:s.scoreBreakdown??[],...f?{remediationPlan:f}:{}};return e.quiet||console.log(JSON.stringify(m,null,2)),pe(s.healthScore,e)}if(s.healthScore){let f=s.healthScore,m=Math.round(f.passed/f.total*100),g=m>=80?l.green:m>=50?l.yellow:l.red,h="\u2588".repeat(Math.floor(m/5))+"\u2591".repeat(20-Math.floor(m/5));console.log(l.bold(`
|
|
26
|
+
\u{1F4CA} Health Score:`)),console.log(` ${g(`${m}%`)} ${l.gray(h)}`),console.log(` ${l.green(`\u2705 ${f.passed} passed`)} ${l.gray("|")} ${l.yellow(`\u26A0\uFE0F ${f.warnings} warnings`)} ${l.gray("|")} ${l.red(`\u274C ${f.errors} errors`)}`);}if(console.log(l.bold(`
|
|
27
|
+
|
|
28
|
+
System Tools:
|
|
29
|
+
`)),R(s.python,"Python"),R(s.poetry,"Poetry"),R(s.pipx,"pipx"),R(s.go,"Go"),R(s.rapidkitCore,"RapidKit Core"),s.coreVersion&&s.npmVersion){let f=s.coreVersion.split(".")[1],m=s.npmVersion.split(".")[1];f!==m&&(console.log(l.yellow(`
|
|
30
|
+
\u26A0\uFE0F Version mismatch: Core ${s.coreVersion} / CLI ${s.npmVersion}`)),console.log(l.gray(" Consider updating to matching versions for best compatibility")));}s.projects.length>0?(console.log(l.bold(`
|
|
31
|
+
\u{1F4E6} Projects (${s.projects.length}):`)),s.projects.forEach(f=>ze(f))):(console.log(l.bold(`
|
|
32
|
+
\u{1F4E6} Projects:`)),console.log(l.gray(" No RapidKit projects found in workspace")));let d=s.projects.reduce((f,m)=>f+m.issues.length,0),u=xe(s.projects),p=[s.python,s.rapidkitCore].some(f=>f.status==="error");if(p||d>0||u>0){let f=u>0?` and ${u} advisory warning project(s)`:"";if(console.log(l.bold.yellow(`
|
|
33
|
+
\u26A0\uFE0F Found ${d} project issue(s)${f}`)),p&&console.log(l.bold.red("\u274C System requirements not met")),e.plan)await se(s.projects,false,{planOnly:true,json:e.json});else if(e.fix||e.apply){if(await se(s.projects,true,{skipConfirmation:e.apply===true}),!e.json){let m=await qe(o,false),g=m.projects.reduce((y,k)=>y+k.issues.length,0),h=[m.python,m.rapidkitCore].some(y=>y.status==="error");h||g>0?(console.log(l.bold.yellow(`
|
|
34
|
+
\u26A0\uFE0F Post-fix verification found ${g} remaining issue(s)`)),h&&console.log(l.bold.red("\u274C System requirements still not met"))):console.log(l.bold.green(`
|
|
35
|
+
\u2705 Post-fix verification passed. Workspace is healthy.`)),m.projectScanCached&&console.log(l.gray(`\u2139\uFE0F Reused cached project scan${m.projectScanCachePath?` (${a$1.basename(m.projectScanCachePath)})`:""}`)),m.evidencePath&&console.log(l.gray(`\u2139\uFE0F Evidence refreshed: ${m.evidencePath}`));}}else d>0&&await se(s.projects,false);}else console.log(l.bold.green(`
|
|
36
|
+
\u2705 All checks passed! Workspace is healthy.`));return pe(s.healthScore,e)}else if(c){let o=await nn(process.cwd());o||(await le(process.cwd())?(a.error("No backend project found in current directory within this workspace"),a.info("Run this command from inside a project directory in the workspace")):a.error("No RapidKit project found in current directory or parents"),a.info('Run this command from within a project, or use "rapidkit doctor workspace" for workspace checks'),process.exit(1));let s=await rn(o),d=s.workspacePath?Je(s.workspacePath):null,u=Je(s.project.path);if(e.json){let b=e.plan?await Ee([s.project]):void 0,L={contract:me(),scope:"project",workspace:d?{name:a$1.basename(d),path:d}:null,project:{...Ue(s.project),path:u},evidencePath:s.evidencePath,healthScore:s.healthScore,system:{python:s.python,poetry:s.poetry,pipx:s.pipx,go:s.go,rapidkitCore:s.rapidkitCore},summary:{totalProjects:1,totalIssues:s.project.issues.length,projectAdvisoryWarningProjects:ee(s.project)>0?1:0,projectAdvisoryWarnings:ee(s.project),hasSystemErrors:[s.python,s.rapidkitCore].some(K=>K.status==="error"),scopeProvenance:s.scopeProvenance},driftDelta:s.driftDelta,scoreBreakdown:s.scoreBreakdown??[],...b?{remediationPlan:b}:{}};return e.quiet||console.log(JSON.stringify(L,null,2)),pe(s.healthScore,e)}console.log(l.bold(`Project: ${l.cyan(a$1.basename(o))}`)),console.log(l.gray(`Path: ${o}`)),s.workspacePath&&console.log(l.gray(`Workspace: ${a$1.basename(s.workspacePath)}`)),s.evidencePath&&console.log(l.gray(`\u2139\uFE0F Evidence saved: ${s.evidencePath}`));let p=s.healthScore,f=p.total>0?Math.round(p.passed/p.total*100):0,m=f>=80?l.green:f>=50?l.yellow:l.red,g="\u2588".repeat(Math.floor(f/5))+"\u2591".repeat(20-Math.floor(f/5));console.log(l.bold(`
|
|
37
|
+
\u{1F4CA} Health Score:`)),console.log(` ${m(`${f}%`)} ${l.gray(g)}`),console.log(` ${l.green(`\u2705 ${p.passed} passed`)} ${l.gray("|")} ${l.yellow(`\u26A0\uFE0F ${p.warnings} warnings`)} ${l.gray("|")} ${l.red(`\u274C ${p.errors} errors`)}`),console.log(l.bold(`
|
|
38
|
+
|
|
39
|
+
System Tools:
|
|
40
|
+
`)),R(s.python,"Python"),R(s.poetry,"Poetry"),R(s.pipx,"pipx"),R(s.go,"Go"),R(s.rapidkitCore,"RapidKit Core"),console.log(l.bold(`
|
|
41
|
+
\u{1F4E6} Project (1):`)),ze(s.project);let h=[s.python,s.rapidkitCore].some(b=>b.status==="error"),y=s.project.issues.length,k=ee(s.project);if(h||y>0||k>0){let b=k>0?` and ${k} advisory warning(s)`:"";console.log(l.bold.yellow(`
|
|
42
|
+
\u26A0\uFE0F Found ${y} project issue(s)${b}`)),h&&console.log(l.bold.red("\u274C System requirements not met")),e.plan?await se([s.project],false,{planOnly:true,json:e.json}):e.fix||e.apply?await se([s.project],true,{skipConfirmation:e.apply===true}):y>0&&await se([s.project],false);}else console.log(l.bold.green(`
|
|
43
|
+
\u2705 All checks passed! Project is healthy.`));return pe(s.healthScore,e)}else {console.log(l.bold(`System Tools:
|
|
44
|
+
`));let o=await Re(),s=o.python,d=o.poetry,u=o.pipx,p=o.go,f=o.rapidkitCore;R(s,"Python"),R(d,"Poetry"),R(u,"pipx"),R(p,"Go"),R(f,"RapidKit Core"),[s,f].some(h=>h.status==="error")?(console.log(l.bold.red(`
|
|
45
|
+
\u274C Some required tools are missing`)),(e.fix||e.apply)&&console.log(l.gray(`
|
|
46
|
+
Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "rapidkit doctor workspace --fix"`)),console.log(l.gray(`
|
|
47
|
+
Tip: Run "rapidkit doctor workspace" for workspace-wide checks, or "rapidkit doctor project" for the current project`))):(console.log(l.bold.green(`
|
|
48
|
+
\u2705 All required tools are installed!`)),(e.fix||e.apply)&&console.log(l.gray(`
|
|
49
|
+
Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "rapidkit doctor workspace --fix"`)),console.log(l.gray(`
|
|
50
|
+
Tip: Run "rapidkit doctor workspace" for workspace-wide checks, or "rapidkit doctor project" for the current project`))),console.log("");let g=[s,f].filter(h=>h.status==="error").length;return (e.strict||e.ci)&&g>0?1:0}}export{pe as a,In as b};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import {b as b$1}from'./chunk-KIB4KHBF.js';import {a}from'./chunk-KMUWWZRT.js';import l from'chalk';import q from'fs';import k from'path';import {execa}from'execa';var Q="autopilot-release-last-run.json",X="autopilot-release.json";function C(t){try{return JSON.parse(t)}catch{return null}}function ue(t){let r=k.resolve(t),a$1=a(r);if(!a$1)throw new Error("No RapidKit workspace found in current directory or parents");return a$1}async function b(t,r){let a=process.argv[1];if(!a)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for autopilot execution.",crashed:true};try{let o=await execa(process.execPath,[a,...t],{cwd:r,reject:false,env:{...process.env,RAPIDKIT_AUTOPILOT_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr,crashed:false}}catch(o){return {exitCode:1,stdout:"",stderr:o instanceof Error?o.message:String(o),crashed:true}}}function Y(t){let r=t.toLowerCase();return r==="pass"?"pass":r==="warn"?"warn":r==="fail"?"fail":"warn"}function Z(t){return t.summary.failed>0?"fail":t.gates.results.some(r=>r.status==="warn")?"warn":"pass"}function fe(t){let r=t.filter(o=>o.status!=="skipped");if(r.length===0)return 100;let a=r.reduce((o,e)=>e.status==="pass"?o+1:e.status==="warn"?o+.6:o,0);return Math.round(a/r.length*100)}function me(t){return t.executionError?["Re-run: npx rapidkit autopilot release --mode audit --json","Inspect .rapidkit/reports/autopilot-release-last-run.json for execution failure details"]:t.blockers.length>0?["Run: npx rapidkit doctor workspace --plan","Run: npx rapidkit readiness --json --strict","Run: npx rapidkit workspace run test --affected --strict"]:t.hasWarnings&&t.mode!=="enforce"?["Review warning-level findings in autopilot report","Optionally run: npx rapidkit autopilot release --mode safe-fix"]:["Workspace is release-ready based on current autopilot policy"]}async function D(t,r){await q.promises.mkdir(k.dirname(t),{recursive:true}),await q.promises.writeFile(t,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`,"utf-8");}async function xe(t){let r=ue(t.workspacePath),a=t.mode,o=[],e=[],F,U,I,T,J=0,f=false,L=0,_=0,E=-1,N=-1,c="skipped",d="skipped",ee=a==="enforce"?["doctor","workspace","--json","--strict"]:["doctor","workspace","--json","--ci"];if(t.skipPipelineStages)o.push({name:"doctor-workspace",status:"skipped",durationMs:0,summary:"doctor stage skipped (pipeline already executed)"},{name:"analyze",status:"skipped",durationMs:0,summary:"analyze stage skipped (pipeline already executed)"},{name:"readiness",status:"skipped",durationMs:0,summary:"readiness stage skipped (pipeline already executed)"});else {let s=Date.now(),i=await b([...ee],r),m=Date.now()-s;if(c="pass",i.crashed)c="fail",f=true,e.push(`doctor workspace execution error: ${i.stderr||"unknown error"}`);else if(i.exitCode===1)c="fail",e.push("doctor workspace command failed or reported errors");else if(i.exitCode===2)c="warn",e.push("doctor workspace reported warnings");else if(i.exitCode!==0)c="fail",e.push("doctor workspace command failed");else {let p=C(i.stdout),j=p&&p.healthScore&&typeof p.healthScore=="object"?p.healthScore:{},y=Number(j.errors??0),$=Number(j.warnings??0);Number.isFinite(y)&&y>0?(c="fail",e.push(`doctor workspace reports ${y} error(s)`)):Number.isFinite($)&&$>0&&(c="warn");}E=o.push({name:"doctor-workspace",status:c,durationMs:m,summary:c==="pass"?"doctor workspace passed":c==="warn"?"doctor workspace reported warnings":"doctor workspace reported errors"})-1,a==="enforce"&&c==="warn"&&e.push("doctor workspace reported warnings under enforce mode");let g=Date.now(),w=await b(["analyze","--json"],r),v=Date.now()-g;U=k.join(r,".rapidkit","reports","analyze-last-run.json");let n="pass";if(w.crashed)n="fail",f=true,e.push(`analyze execution error: ${w.stderr||"unknown error"}`);else if(w.exitCode!==0)n=w.exitCode===2?"warn":"fail",e.push(w.exitCode===2?"analyze reported needs-attention verdict":"analyze command failed or reported blocked verdict");else {let p=C(w.stdout),j=p&&p.summary&&typeof p.summary=="object"?p.summary:{},y=String(j.verdict??"ready");y==="blocked"?(n="fail",e.push("analyze reported blocked verdict")):y==="needs-attention"&&(n="warn");}o.push({name:"analyze",status:n,durationMs:v,summary:n==="pass"?"analyze passed":n==="warn"?"analyze reported needs-attention":"analyze reported blocked verdict"}),a==="enforce"&&n==="warn"&&e.push("analyze reported warnings under enforce mode");let P=Date.now(),h=await b(["readiness","--json"],r),R=Date.now()-P;if(d="fail",h.crashed)d="fail",f=true,e.push(`readiness execution error: ${h.stderr||"unknown error"}`);else if(h.exitCode!==0)d="fail",e.push("readiness command failed");else {let p=C(h.stdout),j=String(p?.overallStatus??"fail");if(d=Y(j),typeof p?.evidencePath=="string"&&p.evidencePath.trim().length>0&&(F=p.evidencePath),d==="fail"){let y=Array.isArray(p?.blockingReasons)?p?.blockingReasons.filter($=>typeof $=="string"):[];y.length>0?e.push(...y.map($=>`readiness: ${$}`)):e.push("readiness overall status is fail");}}N=o.push({name:"readiness",status:d,durationMs:R,summary:`readiness overall status is ${d}`})-1,a==="enforce"&&d==="warn"&&e.push("readiness reported warnings under enforce mode");}let te=Date.now(),z=await b(["doctor","workspace","--plan","--json"],r),se=Date.now()-te,S="warn";if(z.crashed)S="fail",f=true,e.push(`doctor remediation plan execution error: ${z.stderr||"unknown error"}`);else if(z.exitCode!==0)S="fail",e.push("doctor remediation plan command failed");else {let s=C(z.stdout),i=s&&s.remediationPlan&&typeof s.remediationPlan=="object"?s.remediationPlan:null,m=Number(i?.totalSteps??0),g=Number(i?.executableSteps??0);Number.isFinite(m)&&m>0&&(L=m),Number.isFinite(g)&&g>0&&(_=g),Number.isFinite(m)&&m===0?S="pass":S="warn";}if(o.push({name:"remediation-plan",status:S,durationMs:se,summary:S==="pass"?"no remediation steps required":"remediation steps available"}),a==="enforce"&&S==="warn"&&e.push("remediation plan has pending steps under enforce mode"),a==="safe-fix"){let s=Date.now(),i=await b(["doctor","workspace","--apply"],r),m=Date.now()-s,g=i.crashed||i.exitCode!==0?"fail":"pass";if(i.crashed)f=true,e.push(`doctor remediation apply execution error: ${i.stderr||"unknown error"}`);else if(g==="fail")e.push("doctor remediation apply failed");else {J=_>0?_:L>0?L:1;let w=await b(["doctor","workspace","--json"],r);if(w.crashed)c="fail",f=true,e.push(`post-apply doctor execution error: ${w.stderr||"unknown error"}`);else if(w.exitCode!==0)c="fail",e.push("post-apply doctor workspace command failed");else {let n=C(w.stdout),P=n&&n.healthScore&&typeof n.healthScore=="object"?n.healthScore:{},h=Number(P.errors??0),R=Number(P.warnings??0);Number.isFinite(h)&&h>0?(c="fail",e.push(`post-apply doctor reports ${h} error(s)`)):Number.isFinite(R)&&R>0?c="warn":c="pass";}E>=0&&(o[E].status=c,o[E].summary=`doctor workspace post-apply status is ${c}`);let v=await b(["readiness","--json"],r);if(v.crashed)d="fail",f=true,e.push(`post-apply readiness execution error: ${v.stderr||"unknown error"}`);else if(v.exitCode!==0)d="fail",e.push("post-apply readiness command failed");else {let n=C(v.stdout),P=String(n?.overallStatus??"fail");if(d=Y(P),typeof n?.evidencePath=="string"&&n.evidencePath.trim().length>0&&(F=n.evidencePath),d==="fail"){let h=Array.isArray(n?.blockingReasons)?n?.blockingReasons.filter(R=>typeof R=="string"):[];h.length>0?e.push(...h.map(R=>`post-apply readiness: ${R}`)):e.push("post-apply readiness overall status is fail");}}N>=0&&(o[N].status=d,o[N].summary=`readiness post-apply overall status is ${d}`);}o.push({name:"remediation-apply",status:g,durationMs:m,summary:g==="pass"?"safe remediation apply completed":"safe remediation apply failed"});}else o.push({name:"remediation-apply",status:"skipped",durationMs:0,summary:"remediation apply is skipped for this mode"});let re=Date.now(),x="pass",A="workspace test/build completed for selected projects";try{let s=await b$1({workspacePath:r,stage:"test",affected:true,since:t.since,parallel:t.parallel,maxWorkers:t.maxWorkers,strict:true,json:true,enforceGates:false});I=k.join(r,".rapidkit","reports","autopilot-workspace-run-test.json"),await D(I,s);let i=Z(s);if(i==="fail")x="fail",A="workspace test stage failed for selected projects",e.push("workspace run test failed for selected projects");else {i==="warn"&&(x="warn",A="workspace test stage completed with warnings",a==="enforce"&&e.push("workspace run test reported warnings under enforce mode"));let m=await b$1({workspacePath:r,stage:"build",affected:true,since:t.since,parallel:t.parallel,maxWorkers:t.maxWorkers,strict:true,json:true,enforceGates:false});T=k.join(r,".rapidkit","reports","autopilot-workspace-run-build.json"),await D(T,m);let g=Z(m);g==="fail"?(x="fail",A="workspace build stage failed for selected projects",e.push("workspace run build failed for selected projects")):g==="warn"&&(x="warn",A="workspace test/build completed with warnings",a==="enforce"&&e.push("workspace run test/build reported warnings under enforce mode"));}}catch(s){x="fail",A="workspace test/build orchestration failed",f=true,e.push(`workspace run orchestration error: ${s instanceof Error?s.message:String(s)}`);}let oe=Date.now()-re;o.push({name:"workspace-run-test-build",status:x,durationMs:oe,summary:A});let M=o.filter(s=>s.status==="warn").length,ae=o.filter(s=>s.status==="fail").length,B=a==="enforce"?o.some(s=>s.status==="warn"||s.status==="fail"):ae>0,W=[...new Set(e)],ne=f||B?Math.max(1,W.length):0,ie=fe(o),le=f||B?"blocked":M>0?"partial":"approved",ce=f?3:B?1:M>0?2:0,pe=me({mode:a,executionError:f,blockers:W,hasWarnings:M>0}),G=k.join(r,".rapidkit","reports"),O=k.join(G,Q),V=k.join(G,X),u={schemaVersion:"autopilot-release-v1",generatedAt:new Date().toISOString(),workspacePath:r,mode:a,summary:{releaseScore:ie,verdict:le,blockers:ne,warnings:M,safeFixesApplied:J,manualActions:W.length,exitCode:ce},stages:o,blockingReasons:W,nextActions:pe,artifacts:{reportPath:O,aliasEvidencePath:V,analyzeEvidencePath:U,readinessEvidencePath:F,workspaceRunTestPath:I,workspaceRunBuildPath:T},enterpriseControls:{jsonReady:true,evidencePath:`.rapidkit/reports/${Q}`,aliasEvidencePath:`.rapidkit/reports/${X}`}};if(await D(O,u),await D(V,u),t.output&&await D(k.resolve(t.output),u),!t.json){console.log(l.bold.cyan(`
|
|
3
|
+
\u{1F680} RapidKit Autopilot Release
|
|
4
|
+
`)),console.log(l.bold(`Workspace: ${l.cyan(k.basename(r))}`)),console.log(l.gray(`Path: ${r}`)),console.log(l.white(`Mode: ${a}`)),console.log(l.white(`Verdict: ${u.summary.verdict==="approved"?l.green("approved"):u.summary.verdict==="partial"?l.yellow("partial"):l.red("blocked")}`)),console.log(l.white(`Release score: ${u.summary.releaseScore}`));for(let s of u.stages){let i=s.status==="pass"?l.green("PASS"):s.status==="warn"?l.yellow("WARN"):s.status==="skipped"?l.gray("SKIP"):l.red("FAIL");console.log(` - ${s.name}: ${i} ${s.summary} (${s.durationMs}ms)`);}if(u.blockingReasons.length>0){console.log(l.bold.red(`
|
|
5
|
+
Blocking reasons:`));for(let s of u.blockingReasons)console.log(l.red(` - ${s}`));}if(u.nextActions.length>0){console.log(l.bold(`
|
|
6
|
+
Next actions:`));for(let s of u.nextActions)console.log(l.gray(` - ${s}`));}console.log(l.gray(`
|
|
7
|
+
Report: ${u.artifacts.reportPath}`));}return u}export{Q as a,X as b,xe as c};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import a from'fs';import s from'path';var m={nextjs:{key:"nextjs",runtime:"node",displayName:"Next.js",supportTier:"extended",importStack:"nextjs",aliases:["next","nextjs","next.js"],dependencyHints:["next"],scriptHints:["next dev","next build","next start"],fileHints:["next.config.js","next.config.mjs","next.config.ts"]},remix:{key:"remix",runtime:"node",displayName:"Remix",supportTier:"extended",importStack:"remix",aliases:["remix"],dependencyHints:["@remix-run/react","@remix-run/node","@remix-run/dev"],scriptHints:["remix dev","remix vite:dev"],fileHints:["remix.config.js","remix.config.mjs"]},nuxt:{key:"nuxt",runtime:"node",displayName:"Nuxt",supportTier:"extended",importStack:"nuxt",aliases:["nuxt","nuxtjs","nuxt.js"],dependencyHints:["nuxt","nuxt3"],scriptHints:["nuxt dev","nuxt build","nuxi dev","nuxi build"],fileHints:["nuxt.config.js","nuxt.config.ts","nuxt.config.mjs"]},react:{key:"react",runtime:"node",displayName:"React",supportTier:"extended",importStack:"react",aliases:["react"],dependencyHints:["react","react-dom"],scriptHints:["react-scripts start","react-scripts build"],fileHints:[]},vite:{key:"vite",runtime:"node",displayName:"Vite",supportTier:"extended",importStack:"vite",aliases:["vite"],dependencyHints:["vite"],scriptHints:["vite","vite dev","vite build"],fileHints:["vite.config.js","vite.config.ts","vite.config.mjs"]},vue:{key:"vue",runtime:"node",displayName:"Vue",supportTier:"extended",importStack:"vue",aliases:["vue","vuejs","vue.js"],dependencyHints:["vue","@vue/cli-service"],scriptHints:["vue-cli-service serve","vue-cli-service build"],fileHints:["vue.config.js"]},sveltekit:{key:"sveltekit",runtime:"node",displayName:"SvelteKit",supportTier:"extended",importStack:"sveltekit",aliases:["sveltekit","svelte-kit"],dependencyHints:["@sveltejs/kit"],scriptHints:["svelte-kit dev","svelte-kit build"],fileHints:["svelte.config.js"]},svelte:{key:"svelte",runtime:"node",displayName:"Svelte",supportTier:"extended",importStack:"svelte",aliases:["svelte"],dependencyHints:["svelte"],scriptHints:["svelte"],fileHints:[]},angular:{key:"angular",runtime:"node",displayName:"Angular",supportTier:"extended",importStack:"angular",aliases:["angular","@angular/core"],dependencyHints:["@angular/core","@angular/cli"],scriptHints:["ng serve","ng build"],fileHints:["angular.json"]},astro:{key:"astro",runtime:"node",displayName:"Astro",supportTier:"extended",importStack:"astro",aliases:["astro"],dependencyHints:["astro"],scriptHints:["astro dev","astro build"],fileHints:["astro.config.js","astro.config.ts","astro.config.mjs"]},solid:{key:"solid",runtime:"node",displayName:"Solid",supportTier:"extended",importStack:"solid",aliases:["solid","solidjs","solid-js"],dependencyHints:["solid-js"],scriptHints:[],fileHints:[]},unknown:{key:"unknown",runtime:"unknown",displayName:"Unknown frontend",supportTier:"observed",importStack:"unknown",aliases:["unknown"],dependencyHints:[],scriptHints:[],fileHints:[]}},B={nextjs:{dev:["dev"],start:["start"],build:["build"],test:["test"],lint:["lint"],format:["format"]},remix:{dev:["dev"],start:["start"],build:["build"],test:["test"],lint:["lint"],format:["format"]},nuxt:{dev:["dev"],start:["start","preview"],build:["build"],test:["test"],lint:["lint"],format:["format"]},react:{dev:["dev","start"],start:["serve"],build:["build"],test:["test"],lint:["lint"],format:["format"]},vite:{dev:["dev"],start:["preview","start"],build:["build"],test:["test"],lint:["lint"],format:["format"]},vue:{dev:["dev","serve"],start:["preview","start"],build:["build"],test:["test"],lint:["lint"],format:["format"]},sveltekit:{dev:["dev"],start:["start","preview"],build:["build"],test:["test"],lint:["lint"],format:["format"]},svelte:{dev:["dev"],start:["preview","start"],build:["build"],test:["test"],lint:["lint"],format:["format"]},angular:{dev:["start","serve"],start:["serve"],build:["build"],test:["test"],lint:["lint"],format:["format"]},astro:{dev:["dev"],start:["start","preview"],build:["build"],test:["test"],lint:["lint"],format:["format"]},solid:{dev:["dev"],start:["preview","start"],build:["build"],test:["test"],lint:["lint"],format:["format"]}};function Y(e,n){let t=typeof e=="string"?S(e):e;return t==="unknown"?[]:B[t]?.[n]??[]}function R(e){try{return a.existsSync(e)?JSON.parse(a.readFileSync(e,"utf8")):null}catch{return null}}function H(e){let n=R(s.join(e,"package.json"));if(!n)return {dependencies:{},scriptText:""};let t={...n.dependencies??{},...n.devDependencies??{},...n.peerDependencies??{}},i=n.scripts??{},o=Object.values(i).filter(u=>typeof u=="string").join(" ").toLowerCase();return {dependencies:t,scriptText:o}}function C(e,n){return n.some(t=>a.existsSync(s.join(e,t)))}function w(e){return e.vite?e.react||e["react-dom"]||e["@vitejs/plugin-react"]?"react":e.vue||e["@vitejs/plugin-vue"]?"vue":e.svelte||e["@sveltejs/vite-plugin-svelte"]?"svelte":e["solid-js"]||e["vite-plugin-solid"]?"solid":null:null}function l(e,n,t){let i=m[e]??m.unknown;return {key:i.key,runtime:i.runtime,displayName:i.displayName,supportTier:i.supportTier,importStack:i.importStack,confidence:n,source:t}}function M(e){return m[e]??m.unknown}function S(e){let n=(e??"").trim().toLowerCase().replace(/[_\s]+/g,"-");if(!n)return "unknown";for(let t of Object.values(m))if(t.aliases.includes(n))return t.key;return "unknown"}function b(e,n){let t=S(typeof n?.framework=="string"?n.framework:typeof n?.kit_name=="string"?n.kit_name:typeof n?.kit=="string"?n.kit:void 0);if(t!=="unknown")return l(t,"high","framework");let{dependencies:i,scriptText:o}=H(e);for(let u of ["nextjs","remix","nuxt","sveltekit","angular","astro","vue","solid","vite","react","svelte"]){let f=m[u];if(f.dependencyHints.some(c=>i[c])){if(u==="vite"){let c=w(i);if(c)return l(c,"high","manifest")}return l(u,"high","manifest")}if(f.fileHints.length>0&&C(e,f.fileHints)){if(u==="vite"){let c=w(i);if(c)return l(c,"high","manifest")}return l(u,"high","manifest")}if(f.scriptHints.some(c=>o.includes(c)))return l(u,"medium","manifest")}return l("unknown","low","unknown")}var k={fastapi:{key:"fastapi",runtime:"python",displayName:"FastAPI",supportTier:"first-class",importStack:"fastapi",aliases:["fastapi"],kitPrefixes:["fastapi"]},django:{key:"django",runtime:"python",displayName:"Django",supportTier:"extended",importStack:"django",aliases:["django"]},flask:{key:"flask",runtime:"python",displayName:"Flask",supportTier:"extended",importStack:"flask",aliases:["flask"]},python:{key:"python",runtime:"python",displayName:"Python",supportTier:"observed",importStack:"unknown",aliases:["python"]},nestjs:{key:"nestjs",runtime:"node",displayName:"NestJS",supportTier:"first-class",importStack:"nestjs",aliases:["nestjs","nest"],kitPrefixes:["nestjs"]},nextjs:{key:"nextjs",runtime:"node",displayName:"Next.js",supportTier:"extended",importStack:"nextjs",aliases:["nextjs","next.js","next"]},remix:{key:"remix",runtime:"node",displayName:"Remix",supportTier:"extended",importStack:"remix",aliases:["remix"]},nuxt:{key:"nuxt",runtime:"node",displayName:"Nuxt",supportTier:"extended",importStack:"nuxt",aliases:["nuxt","nuxtjs","nuxt.js"]},react:{key:"react",runtime:"node",displayName:"React",supportTier:"extended",importStack:"react",aliases:["react"]},vite:{key:"vite",runtime:"node",displayName:"Vite",supportTier:"extended",importStack:"vite",aliases:["vite"]},vue:{key:"vue",runtime:"node",displayName:"Vue",supportTier:"extended",importStack:"vue",aliases:["vue","vuejs","vue.js"]},sveltekit:{key:"sveltekit",runtime:"node",displayName:"SvelteKit",supportTier:"extended",importStack:"sveltekit",aliases:["sveltekit","svelte-kit"]},svelte:{key:"svelte",runtime:"node",displayName:"Svelte",supportTier:"extended",importStack:"svelte",aliases:["svelte"]},angular:{key:"angular",runtime:"node",displayName:"Angular",supportTier:"extended",importStack:"angular",aliases:["angular","@angular/core"]},astro:{key:"astro",runtime:"node",displayName:"Astro",supportTier:"extended",importStack:"astro",aliases:["astro"]},solid:{key:"solid",runtime:"node",displayName:"Solid",supportTier:"extended",importStack:"solid",aliases:["solid","solidjs","solid-js"]},express:{key:"express",runtime:"node",displayName:"Express",supportTier:"extended",importStack:"express",aliases:["express"]},fastify:{key:"fastify",runtime:"node",displayName:"Fastify",supportTier:"extended",importStack:"unknown",aliases:["fastify"]},koa:{key:"koa",runtime:"node",displayName:"Koa",supportTier:"extended",importStack:"koa",aliases:["koa"]},node:{key:"node",runtime:"node",displayName:"Node.js",supportTier:"observed",importStack:"unknown",aliases:["node","nodejs","typescript","javascript"]},gofiber:{key:"gofiber",runtime:"go",displayName:"Go/Fiber",supportTier:"extended",importStack:"go",aliases:["gofiber","fiber","go-fiber","go/fiber"],kitPrefixes:["gofiber"]},gogin:{key:"gogin",runtime:"go",displayName:"Go/Gin",supportTier:"extended",importStack:"go",aliases:["gogin","gin","go-gin","go/gin"],kitPrefixes:["gogin"]},echo:{key:"echo",runtime:"go",displayName:"Echo",supportTier:"extended",importStack:"go",aliases:["echo"]},go:{key:"go",runtime:"go",displayName:"Go",supportTier:"observed",importStack:"go",aliases:["go","golang"],kitPrefixes:["go"]},springboot:{key:"springboot",runtime:"java",displayName:"Spring Boot",supportTier:"extended",importStack:"springboot",aliases:["springboot","spring","spring-boot"],kitPrefixes:["springboot"]},java:{key:"java",runtime:"java",displayName:"Java",supportTier:"observed",importStack:"unknown",aliases:["java"]},laravel:{key:"laravel",runtime:"php",displayName:"Laravel",supportTier:"extended",importStack:"unknown",aliases:["laravel"]},symfony:{key:"symfony",runtime:"php",displayName:"Symfony",supportTier:"extended",importStack:"unknown",aliases:["symfony"]},php:{key:"php",runtime:"php",displayName:"PHP",supportTier:"observed",importStack:"unknown",aliases:["php"]},rails:{key:"rails",runtime:"ruby",displayName:"Ruby on Rails",supportTier:"extended",importStack:"rails",aliases:["rails","ruby-on-rails","ruby on rails"]},sinatra:{key:"sinatra",runtime:"ruby",displayName:"Sinatra",supportTier:"extended",importStack:"unknown",aliases:["sinatra"]},ruby:{key:"ruby",runtime:"ruby",displayName:"Ruby",supportTier:"observed",importStack:"unknown",aliases:["ruby"]},dotnet:{key:"dotnet",runtime:"dotnet",displayName:"ASP.NET Core",supportTier:"extended",importStack:"dotnet",aliases:["dotnet","asp.net","aspnet","asp.net core","csharp","c#"],kitPrefixes:["dotnet","aspnet","aspnetcore"]},actix:{key:"actix",runtime:"rust",displayName:"Actix-web",supportTier:"extended",importStack:"unknown",aliases:["actix","actix-web"]},axum:{key:"axum",runtime:"rust",displayName:"Axum",supportTier:"extended",importStack:"unknown",aliases:["axum"]},rocket:{key:"rocket",runtime:"rust",displayName:"Rocket",supportTier:"extended",importStack:"unknown",aliases:["rocket"]},rust:{key:"rust",runtime:"rust",displayName:"Rust",supportTier:"observed",importStack:"unknown",aliases:["rust"]},phoenix:{key:"phoenix",runtime:"elixir",displayName:"Phoenix",supportTier:"extended",importStack:"unknown",aliases:["phoenix"]},elixir:{key:"elixir",runtime:"elixir",displayName:"Elixir",supportTier:"observed",importStack:"unknown",aliases:["elixir"]},clojure:{key:"clojure",runtime:"clojure",displayName:"Clojure",supportTier:"extended",importStack:"unknown",aliases:["clojure"]},scala:{key:"scala",runtime:"scala",displayName:"Scala",supportTier:"extended",importStack:"unknown",aliases:["scala"]},kotlin:{key:"kotlin",runtime:"kotlin",displayName:"Kotlin",supportTier:"extended",importStack:"unknown",aliases:["kotlin"]},deno:{key:"deno",runtime:"deno",displayName:"Deno",supportTier:"extended",importStack:"unknown",aliases:["deno"]},bun:{key:"bun",runtime:"bun",displayName:"Bun",supportTier:"extended",importStack:"unknown",aliases:["bun"]},unknown:{key:"unknown",runtime:"unknown",displayName:"Unknown",supportTier:"observed",importStack:"unknown",aliases:["unknown"]}},F=new Map;for(let e of Object.values(k))for(let n of e.aliases)F.set(n,e.key);function r(e,n,t){let i=k[e]??k.unknown;return {key:i.key,runtime:i.runtime,displayName:i.displayName,supportTier:i.supportTier,importStack:i.importStack,confidence:n,source:t}}function N(e){return e.trim().toLowerCase().replace(/[_\s]+/g,"-")}function d(e){try{return a.existsSync(e)?a.readFileSync(e,"utf8").toLowerCase():""}catch{return ""}}function K(e){try{return a.existsSync(e)?JSON.parse(a.readFileSync(e,"utf8")):null}catch{return null}}function x(e,n){if(n<0||!a.existsSync(e))return [];let t=[],i=[];try{i=a.readdirSync(e,{withFileTypes:true});}catch{return []}for(let o of i){let u=s.join(e,o.name);o.isDirectory()?t.push(...x(u,n-1)):t.push(u);}return t}function g(e,n,t=2){return x(e,t).some(i=>i.toLowerCase().endsWith(n.toLowerCase()))}function j(e,n,t=2){return x(e,t).filter(i=>i.toLowerCase().endsWith(n.toLowerCase()))}function D(e){let n=N(e??"");if(!n)return "unknown";for(let t of Object.values(k))if(t.kitPrefixes?.some(i=>n.startsWith(i)))return t.key;return "unknown"}function p(e){return e?F.get(N(e))??"unknown":"unknown"}function ee(e){return p(e)}function ne(e){let n=p(e);return n!=="unknown"?k[n].runtime:"unknown"}function L(e){let n=D(e.kitName);if(n!=="unknown")return r(n,"high","kit");let t=p(e.framework);if(t!=="unknown")return r(t,"high","framework");let i=p(e.runtime);return i!=="unknown"?r(i,"medium","runtime"):r("unknown","low","unknown")}function E(e){let n=K(s.join(e,"package.json"));if(!n)return r("unknown","low","unknown");let t={...n.dependencies??{},...n.devDependencies??{}},i=n.scripts??{},o=Object.values(i).filter(u=>typeof u=="string").join(" ").toLowerCase();return t["@nestjs/core"]||o.includes("nest start")?r("nestjs","high","manifest"):t.express?r("express","high","manifest"):t.fastify?r("fastify","high","manifest"):t.koa?r("koa","high","manifest"):r("node","medium","marker")}function A(e){let n=[d(s.join(e,"pyproject.toml")),d(s.join(e,"requirements.txt")),d(s.join(e,"requirements.in"))].join(`
|
|
2
|
+
`);return n.includes("fastapi")?r("fastapi","high","manifest"):n.includes("django")?r("django","high","manifest"):n.includes("flask")?r("flask","high","manifest"):n.trim()?r("python","medium","marker"):r("unknown","low","unknown")}function _(e){let n=[d(s.join(e,"go.mod")),d(s.join(e,"main.go"))].join(`
|
|
3
|
+
`);return n.includes("github.com/gofiber/fiber")?r("gofiber","high","manifest"):n.includes("github.com/gin-gonic/gin")?r("gogin","high","manifest"):n.includes("github.com/labstack/echo")?r("echo","high","manifest"):n.trim()?r("go","medium","marker"):r("unknown","low","unknown")}function I(e){let n=[d(s.join(e,"pom.xml")),d(s.join(e,"build.gradle")),d(s.join(e,"build.gradle.kts"))].join(`
|
|
4
|
+
`);return n.includes("spring-boot")||n.includes("org.springframework")?r("springboot","high","manifest"):n.trim()?r("java","medium","marker"):r("unknown","low","unknown")}function O(e){let n=d(s.join(e,"composer.json"));return n.includes("laravel/framework")?r("laravel","high","manifest"):n.includes("symfony/")?r("symfony","high","manifest"):n.trim()?r("php","medium","marker"):r("unknown","low","unknown")}function P(e){let n=d(s.join(e,"Gemfile"));return n.includes("gem 'rails'")||n.includes('gem "rails"')?r("rails","high","manifest"):n.includes("gem 'sinatra'")||n.includes('gem "sinatra"')?r("sinatra","high","manifest"):n.trim()?r("ruby","medium","marker"):r("unknown","low","unknown")}function z(e){let t=[...j(e,".csproj",3),...j(e,".sln",2)].map(i=>d(i)).join(`
|
|
5
|
+
`);return t.includes("microsoft.net.sdk.web")||t.includes("microsoft.aspnetcore")||t.includes("swashbuckle.aspnetcore")?r("dotnet","high","manifest"):t.trim()?r("dotnet","medium","marker"):r("unknown","low","unknown")}function G(e){let n=d(s.join(e,"Cargo.toml"));return n.includes("actix-web")?r("actix","high","manifest"):n.includes("axum")?r("axum","high","manifest"):n.includes("rocket")?r("rocket","high","manifest"):n.trim()?r("rust","medium","marker"):r("unknown","low","unknown")}function V(e){let n=d(s.join(e,"mix.exs"));return n.includes("phoenix")?r("phoenix","high","manifest"):n.trim()?r("elixir","medium","marker"):r("unknown","low","unknown")}function W(e){let n=[],t=i=>{n.includes(i)||n.push(i);};return a.existsSync(s.join(e,"go.mod"))&&t("go"),a.existsSync(s.join(e,"Cargo.toml"))&&t("rust"),(a.existsSync(s.join(e,"pom.xml"))||a.existsSync(s.join(e,"build.gradle"))||a.existsSync(s.join(e,"build.gradle.kts")))&&t("java"),a.existsSync(s.join(e,"mix.exs"))&&t("elixir"),a.existsSync(s.join(e,"composer.json"))&&t("php"),(g(e,".csproj")||g(e,".sln"))&&t("dotnet"),a.existsSync(s.join(e,"package.json"))&&t("node"),a.existsSync(s.join(e,"Gemfile"))&&t("ruby"),(a.existsSync(s.join(e,"pyproject.toml"))||a.existsSync(s.join(e,"setup.py"))||a.existsSync(s.join(e,"requirements.txt"))||a.existsSync(s.join(e,"requirements.in")))&&t("python"),(a.existsSync(s.join(e,"deps.edn"))||a.existsSync(s.join(e,"project.clj")))&&t("clojure"),a.existsSync(s.join(e,"build.sbt"))&&t("scala"),(a.existsSync(s.join(e,"deno.json"))||a.existsSync(s.join(e,"deno.jsonc")))&&t("deno"),(a.existsSync(s.join(e,"bun.lockb"))||a.existsSync(s.join(e,"bun.lock")))&&t("bun"),(a.existsSync(s.join(e,"settings.gradle.kts"))||g(s.join(e,"src"),".kt",3))&&t("kotlin"),n}function te(e,n){let t=L({framework:typeof n?.framework=="string"?n.framework:void 0,runtime:typeof n?.runtime=="string"?n.runtime:void 0,kitName:typeof n?.kit_name=="string"?n.kit_name:typeof n?.kit=="string"?n.kit:void 0});if(t.key!=="unknown")return t;let i=W(e);if(i.includes("node")){let o=b(e,n);if(o.key!=="unknown")return o;let u=E(e);if(u.key!=="unknown")return u}if(i.includes("python")){let o=A(e);if(o.key!=="unknown")return o}if(i.includes("go")){let o=_(e);if(o.key!=="unknown")return o}if(i.includes("java")){let o=I(e);if(o.key!=="unknown")return o}if(i.includes("php")){let o=O(e);if(o.key!=="unknown")return o}if(i.includes("ruby")){let o=P(e);if(o.key!=="unknown")return o}if(i.includes("rust")){let o=G(e);if(o.key!=="unknown")return o}if(i.includes("elixir")){let o=V(e);if(o.key!=="unknown")return o}if(i.includes("dotnet")){let o=z(e);if(o.key!=="unknown")return o}return i.includes("clojure")?r("clojure","medium","marker"):i.includes("scala")?r("scala","medium","marker"):i.includes("kotlin")?r("kotlin","medium","marker"):i.includes("deno")?r("deno","high","marker"):i.includes("bun")?r("bun","high","marker"):i.length>0?r(p(i[0]),"medium","runtime"):r("unknown","low","unknown")}export{Y as a,M as b,S as c,b as d,ee as e,ne as f,L as g,W as h,te as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$4}from'./chunk-YJ24EV3P.js';import {a as a$3,q as q$1,k as k$1}from'./chunk-YBS2HGO3.js';import {i,h}from'./chunk-UZW5QFRW.js';import {a}from'./chunk-RV6HBTFC.js';import {a as a$2}from'./chunk-VKLL63TL.js';import {a as a$1}from'./chunk-HHJAANUC.js';import p from'path';import f from'fs-extra';var V="workspace-model.v1",K=".rapidkit/reports/workspace-model.json",L=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","bun.lock","bun.lockb","deps.edn","project.clj","build.sbt","docker-compose.yml","docker-compose.yaml","terraform.tf"],q=new Set([".git",".hg",".svn",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next",".turbo"]);function _(t,e){return (p.relative(t,e)||".").split(p.sep).join("/")}async function N(t){try{if(!await f.pathExists(t))return null;let e=await f.readJSON(t);return e&&typeof e=="object"?e:null}catch{return null}}async function z(t,e){for(let r of e)if(await f.pathExists(p.join(t,r)))return true;return false}function H(t){let e=Number.parseInt(process.env.RAPIDKIT_WORKSPACE_MODEL_SCAN_DEPTH??"",10),r=typeof t=="number"&&Number.isFinite(t)?t:Number.isFinite(e)?e:4;return Math.min(12,Math.max(1,Math.trunc(r)))}async function J(t,e){let r=p.resolve(t),n=[{dirPath:r,depth:0}],s=new Set,o=new Set;for(;n.length>0;){let i=n.shift();if(!i)continue;let a=p.resolve(i.dirPath);if(o.has(a))continue;if(o.add(a),a!==r&&await z(a,L)){s.add(a);continue}if(i.depth>=e)continue;let g=[];try{g=await f.readdir(a,{withFileTypes:true});}catch{continue}for(let m of g)!m.isDirectory()||q.has(m.name)||m.name.startsWith(".")&&m.name!==".config"||n.push({dirPath:p.join(a,m.name),depth:i.depth+1});}return Array.from(s).sort((i,a)=>i.localeCompare(a))}function G(t){let e=new Set,r=[];for(let n of t){let s=p.resolve(n);e.has(s)||(e.add(s),r.push(s));}return r.sort((n,s)=>n.localeCompare(s))}function D(t,e){let r=t?.[e];return typeof r=="string"&&r.trim()?r.trim():void 0}function U(t,e){return t?.[e]===true}function Q(t,e,r){let n=t?.frontend&&typeof t.frontend=="object"&&!Array.isArray(t.frontend)?t.frontend:void 0,s=D(n,"generator"),o=D(n,"command_display"),i=typeof e=="string"&&e.startsWith("frontend.");if(!(!s&&!i))return {...s?{id:s}:{},...e?{kit:e}:{},displayName:r,source:U(n,"official_generator")?"official-generator":"metadata",...o?{commandDisplay:o}:{}}}async function X(t){let e=[".rapidkit/project.json",".rapidkit/context.json","package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","Dockerfile","docker-compose.yml","README.md"],r=[];for(let n of e)await f.pathExists(p.join(t,n))&&r.push(n);return r}async function k(t,e,r){let n=p.join(t,e),s=await f.pathExists(n),o={path:e.split(p.sep).join("/"),exists:s};if(s&&r){let i=await N(n);typeof i?.generatedAt=="string"&&(o.generatedAt=i.generatedAt);let a=i?.status??i?.result??i?.verdict;typeof a=="string"&&(o.status=a);}return o}async function Y(t,e,r){let s=`${_(t,e)}/.rapidkit/reports`,o=await k(t,`${s}/doctor-project-last-run.json`,r);return {doctor:o?.exists===true?o:await k(t,`${s}/doctor-last-run.json`,r),analyze:await k(t,`${s}/analyze-last-run.json`,r),readiness:await k(t,`${s}/release-readiness-last-run.json`,r)}}async function Z(t,e,r){let n=a$3(e),s=i(e,n),o=q$1(e),i$1=k$1(s.runtime),a=await a$4(e,n),g=typeof n?.name=="string"&&n.name.trim()?n.name.trim():p.basename(e),m=typeof n?.kit_name=="string"?n.kit_name:typeof n?.kit=="string"?n.kit:void 0,y=typeof n?.engine=="string"?n.engine:o.engine!=="unknown"?o.engine:void 0,c=Q(n,m,s.displayName);return {name:g,path:_(t,e),...r.includeAbsolutePaths?{absolutePath:e}:{},kind:a,runtime:s.runtime,runtimeCandidates:h(e),framework:s.key,frameworkDisplayName:s.displayName,confidence:s.confidence,detectionSource:s.source,supportTier:s.supportTier,runtimeSupportTier:i$1.tier,runtimeDoctorSupport:i$1.doctorSupport,moduleSupport:o.moduleSupport,...m?{kit:m}:{},...y?{engine:y}:{},...c?{generator:c}:{},commands:{supported:o.supportedCommands,unsupported:o.unsupportedCommands,global:o.globalCommands,fleetStages:o.fleetStages,localOnly:o.localOnlyCommands,map:o.commandMap},importantFiles:await X(e),evidence:await Y(t,e,r.includeEvidence),provenance:{path:"filesystem discovery",runtime:s.source,framework:s.source,commands:"project command capability matrix",evidence:"project .rapidkit/reports"}}}async function ee(t){return N(p.join(t,".rapidkit","workspace.json"))}function te(t){return t.some(e=>e.kind==="frontend")&&t.length>1?"full-stack-workspace":t.some(e=>e.kind==="frontend")?"frontend-workspace":t.length>1?"backend-platform":"backend-workspace"}function oe(t){let e=new Set;for(let r of t){let n=`${r.name} ${r.path}`.toLowerCase();for(let s of ["auth","billing","payment","notification","order","admin","report","search","analytics"])n.includes(s)&&e.add(s);}return Array.from(e).sort()}function u(t,e,r,n){return {severity:t,code:e,message:r,target:n}}function $(t){let e=[];t.workspace.name.trim()||e.push(u("error","workspace.name.missing","Workspace name could not be resolved.","workspace")),t.workspace.type==="observed-workspace"&&e.push(u("warning","workspace.marker.missing","Workspace marker is missing; model is based on filesystem observation.","workspace.marker")),t.summary.projectCount===0&&e.push(u("warning","workspace.projects.empty","No project roots were detected in this workspace.","projects")),t.contracts.exists||e.push(u("warning","workspace.contract.missing","Workspace contract is missing; dependency and API edges may be incomplete.",t.contracts.workspaceContractPath));let r=new Map;for(let o of t.projects){let i=o.name.toLowerCase(),a=r.get(i)??[];a.push(o),r.set(i,a),o.importantFiles.length||e.push(u("warning","project.markers.missing",`Project ${o.name} has no important manifest files recorded.`,o.path)),o.runtime==="unknown"&&e.push(u("warning","project.runtime.unknown",`Project ${o.name} runtime could not be confidently detected.`,o.path));let g=["test","build"];for(let c of g)o.commands.supported.includes(c)&&o.commands.unsupported.includes(c)&&e.push(u("error","project.commands.conflict",`Project ${o.name} marks ${c} as both supported and unsupported.`,o.path));let m=new Set(o.commands.fleetStages),y=new Set(o.commands.localOnly);for(let c of o.commands.fleetStages){y.has(c)&&e.push(u("error","project.commands.scope-conflict",`Project ${o.name} marks ${c} as both fleet and local-only.`,o.path));let d=o.commands.map[c];(!d||d.status!=="supported"||d.fleetEligible!==true||d.executionScope!=="fleet")&&e.push(u("error","project.commands.fleet-stage-invalid",`Project ${o.name} advertises ${c} as a fleet stage without a supported fleet capability.`,o.path));}for(let c of o.commands.localOnly){let d=o.commands.map[c];(!d||d.status!=="supported"||d.executionScope!=="local-only"||d.fleetEligible===true)&&e.push(u("error","project.commands.local-only-invalid",`Project ${o.name} advertises ${c} as local-only without a matching local-only capability.`,o.path));}for(let c of Object.values(o.commands.map))c.status==="supported"&&(c.fleetEligible===true&&!m.has(c.command)&&e.push(u("error","project.commands.fleet-stage-missing",`Project ${o.name} capability ${c.command} is fleet-eligible but missing from fleetStages.`,o.path)),c.executionScope==="local-only"&&c.fleetEligible!==true&&!y.has(c.command)&&e.push(u("error","project.commands.local-only-missing",`Project ${o.name} capability ${c.command} is local-only but missing from localOnly commands.`,o.path)));}for(let[o,i]of r.entries())i.length>1&&e.push(u("error","project.name.duplicate",`Project name "${o}" is ambiguous across ${i.length} project roots.`,i.map(a=>a.path).join(", ")));let n=e.filter(o=>o.severity==="error").length,s=e.filter(o=>o.severity==="warning").length;return {status:n>0?"failed":s>0?"warning":"passed",errors:n,warnings:s,issues:e}}function ge(t){return $(t)}async function ke(t){let e=p.resolve(t.workspacePath),r=t.includeAbsolutePaths===true,n=t.includeEvidence===true,s=H(t.observableScanDepth),o=t.now??new Date,[i,a$3,g,m,y]=await Promise.all([a(e),ee(e),a$1(e),a$2(e,{descendIntoMatchedProjects:false}),J(e,s)]),c=G([...m,...y,...g.map(l=>p.isAbsolute(l.path)?l.path:p.join(e,l.path))]),d=await Promise.all(c.map(l=>Z(e,l,{includeAbsolutePaths:r,includeEvidence:n}))),B=typeof a$3?.workspace_name=="string"?a$3.workspace_name:typeof a$3?.name=="string"?a$3.name:i?.name||p.basename(e),b=typeof a$3?.profile=="string"?a$3.profile:typeof a$3?.mode=="string"?a$3.mode:void 0,F=Array.from(new Set(d.map(l=>l.kind))).sort(),w=Array.from(new Set(d.map(l=>l.runtime))).sort(),I=Array.from(new Set(d.map(l=>l.framework))).sort(),h=[".rapidkit/policies.yml",".rapidkit/policies.yaml"].find(l=>f.existsSync(p.join(e,l))),j=".rapidkit/workspace.contract.json",v=await f.pathExists(p.join(e,j)),P={schemaVersion:V,generatedAt:o.toISOString(),workspace:{name:B,root:e,...b?{profile:b}:{},type:i?"rapidkit-workspace":"observed-workspace",...i?{marker:{createdBy:i.createdBy,version:i.version,createdAt:i.createdAt}}:{}},identity:{workspaceType:te(d),surfaces:F,runtimeFamilies:w,businessCapabilities:oe(d)},discovery:{observableScanDepth:s},projects:d,policies:{mode:typeof a$3?.policy_mode=="string"?a$3.policy_mode:typeof a$3?.policyMode=="string"?a$3.policyMode:"warn",source:h??null,exists:!!h},contracts:{workspaceContractPath:j,exists:v,status:v?"known":"missing"},evidence:{doctor:await k(e,".rapidkit/reports/doctor-last-run.json",n),analyze:await k(e,".rapidkit/reports/analyze-last-run.json",n),readiness:await k(e,".rapidkit/reports/release-readiness-last-run.json",n),pipeline:await k(e,".rapidkit/reports/pipeline-last-run.json",n)},summary:{projectCount:d.length,runtimes:w,frameworks:I,firstClassProjects:d.filter(l=>l.supportTier==="first-class").length,observedProjects:d.filter(l=>l.supportTier==="observed").length}},T=$(P);return {...P,validation:T}}async function ye(t,e){let r=p.join(e,K);return await f.ensureDir(p.dirname(r)),await f.writeJSON(r,t,{spaces:2}),r}export{V as a,K as b,ge as c,ke as d,ye as e};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import {a,b as b$1}from'./chunk-KMUWWZRT.js';import {h as h$1,i}from'./chunk-UZW5QFRW.js';import {a as a$1}from'./chunk-VKLL63TL.js';import h from'fs';import o from'path';import s from'chalk';var I=new Set([".git",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function y(e){try{return await h.promises.access(e,h.constants.F_OK),true}catch{return false}}async function v(e){try{let t=JSON.parse(await h.promises.readFile(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function G(e){try{return await h.promises.readFile(e,"utf-8")}catch{return ""}}function E(e){return a(e)}async function S(e,t){return await y(o.join(e,".rapidkit","project.json"))||await y(o.join(e,".rapidkit","context.json"))?true:b$1(e)?false:o.resolve(e)===o.resolve(t)?h$1(e).length>0:h$1(e).length>0}async function T(e){let t=await a$1(e,{skipDirs:I,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:S});return t.length>0?t:b$1(e)?[]:h$1(e).length>0?[e]:[]}function N(e,t){return o.relative(e,t).replace(/\\/g,"/")||"."}async function b(e,t){for(let n of t)if(await y(o.join(e,n)))return true;return false}async function K(e){return b(e,["health","health.ts","health.js","health.py","health.go","health.kt","health.rb","health.php","healthcheck","health-check","src/health.ts","src/health.js","src/health.py","src/health.go","src/health.kt","src/health.rb","src/health.php","src/healthcheck.ts","src/healthcheck.js","src/liveness.ts","src/readiness.ts","src/ping.ts"])}async function O(e){if(await b(e,["tests","test","__tests__","src/__tests__","pytest.ini","vitest.config.ts","jest.config.ts"]))return true;let n=await v(o.join(e,"package.json")),i=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return typeof i.test=="string"&&i.test.trim().length>0}async function _(e){let t=await v(o.join(e,"package.json")),n=t?.scripts&&typeof t.scripts=="object"?t.scripts:{};return Object.keys(n).sort()}function f(e,t,n,i,r,c){return {id:e,severity:t,target:n,title:i,detail:r,remediation:c}}function J(e){let t=e.reduce((n,i)=>i.severity==="fail"?n+28:i.severity==="warn"?n+12:n+3,0);return Math.max(0,100-t)}async function M(e,t){let n=await v(o.join(t,".rapidkit","project.json")),i$1=i(t,n),r=h$1(t),c=i$1.runtime==="unknown"?r[0]||"unknown":i$1.runtime,a=N(e,t),d=a,m=await _(t),u=await y(o.join(t,".rapidkit","project.json"))||await y(o.join(t,".rapidkit","context.json")),g=await O(t),k=await b(t,["Dockerfile","dockerfile"]),w=await b(t,[".env.example","env.example","config/env.example"]),A=await b(t,[".github/workflows/ci.yml",".github/workflows/ci.yaml",".github/workflows/main.yml",".github/workflows/build.yml",".github/workflows/test.yml",".github/workflows/deploy.yml",".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml"]),z=await K(t),l=[];return i$1.key==="unknown"&&l.push(f("project.stack.unknown","fail",d,"Project stack is unknown","RapidKit cannot confidently classify this backend project.","Add .rapidkit/project.json metadata or import the project with `rapidkit import`.")),u||l.push(f("project.marker.missing","warn",d,"RapidKit marker is missing","The project can be detected by files, but it is not registered with RapidKit metadata.","Run `rapidkit import <path>` from a workspace or create the project through RapidKit.")),g||l.push(f("project.tests.missing","warn",d,"Test entrypoint is missing","No common test folder, config, or package test script was found.","Add a test command so `rapidkit workspace run test --affected` can gate changes.")),w||l.push(f("project.env.example.missing","info",d,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.")),A||l.push(f("project.ci.missing","warn",d,"Continuous integration is missing","No recognized CI/CD configuration file was detected for this project.","Add CI configuration so tests and checks run automatically for every change.")),z||l.push(f("project.health.missing","info",d,"Health or readiness probe is missing","The project has no obvious health or readiness endpoint to support automated deployment and runtime checks.","Add a simple health endpoint and document it for readiness gates and observability.")),k||l.push(f("project.container.missing","info",d,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.")),{name:o.basename(t),path:t,relativePath:a,runtime:c,framework:i$1.key,confidence:i$1.confidence,supportTier:i$1.supportTier,hasRapidKitMarker:u,hasTests:g,hasDockerfile:k,hasEnvExample:w,hasCiConfig:A,hasHealthEndpoint:z,scripts:m,findings:l,score:J(l)}}function W(e){return e.name.toLowerCase()}async function H(e){let t=new Map(e.map(r=>[W(r),r])),n=[];for(let r of e){let c=await v(o.join(r.path,"package.json")),a={...c?.dependencies??{},...c?.devDependencies??{},...c?.peerDependencies??{}};for(let m of Object.keys(a)){let u=m.replace(/^@[^/]+\//,"").toLowerCase(),g=t.get(u);g&&g.relativePath!==r.relativePath&&n.push({from:r.relativePath,to:g.relativePath,kind:"package"});}let d=await G(o.join(r.path,"pyproject.toml"));for(let m of e)m.relativePath!==r.relativePath&&d.includes(m.name)&&n.push({from:r.relativePath,to:m.relativePath,kind:"workspace-reference"});}let i=new Set;return n.filter(r=>{let c=`${r.from}\0${r.to}\0${r.kind}`;return i.has(c)?false:(i.add(c),true)})}function B(e,t){let n=new Map;for(let i of e)n.set(i.relativePath,{project:i.relativePath,directDependents:0,directDependencies:0});for(let i of t){let r=n.get(i.from),c=n.get(i.to);r&&(r.directDependencies+=1),c&&(c.directDependents+=1);}return Array.from(n.values()).sort((i,r)=>r.directDependents-i.directDependents||r.directDependencies-i.directDependencies)}async function U(e){let t=await v(o.join(e,".rapidkit","workspace.json"));return typeof t?.profile=="string"?t.profile:null}function V(e){return {fail:e.filter(t=>t.severity==="fail").length,warn:e.filter(t=>t.severity==="warn").length,info:e.filter(t=>t.severity==="info").length}}function L(e){if(e.projectCount===0)return e.workspaceDetected?["Add your first project: npx rapidkit create project <name> --kit <kit>","Import an existing service: npx rapidkit import <path>"]:["Create a RapidKit workspace: npx rapidkit create workspace my-workspace --profile polyglot","Import an existing service: npx rapidkit import ../service"];let t=[];return e.findings.some(n=>n.id==="workspace.marker.missing")&&t.push("Initialize workspace metadata with `rapidkit bootstrap --profile polyglot`."),e.findings.some(n=>n.id==="project.marker.missing")&&t.push("Register detected projects with `rapidkit import <path>` or recreate them via `rapidkit create project`."),e.findings.some(n=>n.id==="project.tests.missing")&&t.push("Add test entrypoints, then gate changes with `rapidkit workspace run test --affected --strict`."),e.findings.some(n=>n.id==="project.ci.missing")&&t.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(n=>n.id==="project.health.missing")&&t.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasGraph||t.push("Create `.rapidkit/workspace-dependency-graph.json` or use analyze output as the first graph seed."),t.push("Run `rapidkit autopilot release --mode audit --json` before release."),Array.from(new Set(t))}async function ie(e={}){let t=o.resolve(e.workspacePath||process.cwd());if(!await y(t))throw new Error(`Workspace path does not exist: ${t}`);let n=E(t)??t,i=await y(o.join(n,".rapidkit-workspace"))||await y(o.join(n,".rapidkit","workspace.json")),r=await U(n),c=await T(n),a=await Promise.all(c.map(p=>M(n,p))),d=await H(a),m=B(a,d),u=[];i||u.push(f("workspace.marker.missing","warn",".","Workspace metadata is missing","The directory can be analyzed, but it is not a registered RapidKit workspace.","Run `rapidkit create workspace` or `rapidkit bootstrap --profile polyglot` in a workspace root.")),a.length===0&&u.push(f("workspace.projects.missing","warn",".","No backend projects detected","RapidKit did not find runtime markers or project metadata under this root.","Create a project with `rapidkit create project` or import one with `rapidkit import <path>`."));let g=[...u,...a.flatMap(p=>p.findings)],k=V(g),w={};for(let p of a)w[p.runtime]=(w[p.runtime]||0)+1;let A=a.length>0?Math.round(a.reduce((p,P)=>p+P.score,0)/a.length):0,z=u.reduce((p,P)=>p+(P.severity==="fail"?20:P.severity==="warn"?8:2),0),l=Math.max(0,A-z),F=k.fail>0||e.strict&&k.warn>0?"blocked":k.warn>0?"needs-attention":"ready",D={schemaVersion:"rapidkit-analyze-v1",generatedAt:new Date().toISOString(),workspacePath:n,workspaceDetected:i,profile:r,summary:{score:l,verdict:F,projectCount:a.length,runtimeCount:Object.keys(w).length,findings:k},runtimes:w,projects:a,dependencyGraph:{status:d.length>0?"generated":"empty",edges:d,topImpactedProjects:m.slice(0,5)},findings:g,nextActions:L({findings:g,projectCount:a.length,hasGraph:d.length>0,workspaceDetected:i}),enterpriseControls:{jsonReady:true,ciGateCommand:"rapidkit analyze --json --strict",releaseGateCommand:"rapidkit autopilot release --mode enforce --json",evidencePath:".rapidkit/reports/analyze-last-run.json"}};if(e.output&&(await h.promises.mkdir(o.dirname(o.resolve(e.output)),{recursive:true}),await h.promises.writeFile(o.resolve(e.output),`${JSON.stringify(D,null,2)}
|
|
2
|
+
`)),!e.output&&i){let p=o.join(n,".rapidkit","reports","analyze-last-run.json");await h.promises.mkdir(o.dirname(p),{recursive:true}),await h.promises.writeFile(p,`${JSON.stringify(D,null,2)}
|
|
3
|
+
`);}return D}function re(e){let t=e.summary.verdict==="ready"?s.green:e.summary.verdict==="needs-attention"?s.yellow:s.red;if(console.log(s.bold(`
|
|
4
|
+
RapidKit Workspace Analysis
|
|
5
|
+
`)),console.log(s.cyan("Workspace:"),e.workspacePath),console.log(s.cyan("Profile:"),e.profile||"not configured"),console.log(s.cyan("Score:"),`${e.summary.score}/100`),console.log(s.cyan("Verdict:"),t(e.summary.verdict)),console.log(s.gray(`Projects: ${e.summary.projectCount}, runtimes: ${e.summary.runtimeCount}, findings: ${e.summary.findings.fail} fail / ${e.summary.findings.warn} warn / ${e.summary.findings.info} info`)),e.projects.length>0){console.log(s.bold(`
|
|
6
|
+
Projects`));for(let n of e.projects){let i=n.score>=85?s.green("pass"):n.score>=65?s.yellow("watch"):s.red("risk");console.log(` ${n.relativePath} ${s.gray(`${n.runtime}/${n.framework}`)} ${i} ${n.score}/100`);}}if(e.dependencyGraph.status==="generated"&&(console.log(s.bold(`
|
|
7
|
+
Dependency Graph`)),console.log(s.gray(` edges: ${e.dependencyGraph.edges.length}`)),e.dependencyGraph.topImpactedProjects.length>0)){console.log(s.gray(" Top impacted projects:"));for(let n of e.dependencyGraph.topImpactedProjects.slice(0,3))console.log(` ${n.project} (${n.directDependents} dependents, ${n.directDependencies} dependencies)`);}if(e.findings.length>0){console.log(s.bold(`
|
|
8
|
+
Top Findings`));for(let n of e.findings.slice(0,8)){let i=n.severity==="fail"?s.red:n.severity==="warn"?s.yellow:s.gray;console.log(` ${i(n.severity.toUpperCase())} ${n.target}: ${n.title}`),console.log(s.gray(` ${n.remediation}`));}}console.log(s.bold(`
|
|
9
|
+
Next Actions`));for(let n of e.nextActions.slice(0,5))console.log(s.gray(` - ${n}`));console.log();}export{ie as a,re as b};
|