rapidkit 0.40.1 → 0.41.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 +36 -2
- package/contracts/agent-customization-pack.v1.json +52 -2
- package/contracts/extension-cli-compatibility.v1.json +14 -2
- package/contracts/runtime-command-surface.v1.json +7 -1
- package/contracts/workspace-intelligence/agent-action-outcome.v1.json +22 -0
- package/contracts/workspace-intelligence/blocker-resolution.v1.json +65 -0
- package/contracts/workspace-intelligence/doctor-fix-result.v1.json +34 -0
- package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +91 -0
- package/contracts/workspace-intelligence/workspace-contract-verify.v1.json +51 -0
- package/contracts/workspace-intelligence/workspace-explain.v1.json +31 -0
- package/contracts/workspace-intelligence/workspace-intelligence-history.v1.json +36 -0
- package/contracts/workspace-intelligence/workspace-operational-skill.v1.json +37 -0
- package/contracts/workspace-intelligence/workspace-skills-index.v1.json +27 -0
- package/dist/analyze-JVMUCQ22.js +1 -0
- package/dist/autopilot-release-GM5ALPWO.js +1 -0
- package/dist/chunk-424B73UF.js +1 -0
- package/dist/chunk-44GSDNPQ.js +1 -0
- package/dist/chunk-56RL5OB6.js +2 -0
- package/dist/chunk-64RTZBHU.js +2 -0
- package/dist/chunk-73IS6RIM.js +7 -0
- package/dist/{chunk-VQMZC5TC.js → chunk-AO6PG3K2.js} +1 -1
- package/dist/chunk-AT3EQ2S7.js +2 -0
- package/dist/{chunk-3YLMCP3V.js → chunk-CDCYRBAY.js} +1 -1
- package/dist/chunk-DMUEGR36.js +2 -0
- package/dist/{chunk-4FJQWL7P.js → chunk-FPUNOIAR.js} +1 -1
- package/dist/chunk-FVCZGUVX.js +1 -0
- package/dist/chunk-ICGWHIMK.js +1 -0
- package/dist/{workspace-graph-ICB7OVAZ.js → chunk-JEI6BTZI.js} +1 -1
- package/dist/{chunk-ERCD6NFF.js → chunk-KTQZUWAM.js} +1 -1
- package/dist/{chunk-RXWM5DSC.js → chunk-MGUJWRZA.js} +2 -2
- package/dist/chunk-MIWDCR6I.js +2 -0
- package/dist/{chunk-6G2KSHP6.js → chunk-OLDPVVSV.js} +1 -1
- package/dist/chunk-P5ODFWB2.js +13 -0
- package/dist/{chunk-4Q2ZZKGB.js → chunk-PCXSTKZ5.js} +1 -1
- package/dist/{chunk-6KD5F6LX.js → chunk-Q2KZIBV4.js} +1 -1
- package/dist/chunk-QN2LPLHO.js +1 -0
- package/dist/chunk-RIZCWYRR.js +1 -0
- package/dist/chunk-VMJA36WD.js +1 -0
- package/dist/chunk-WA6JYVJM.js +2 -0
- package/dist/{chunk-G76C74EV.js → chunk-XOVB2ZP5.js} +1 -1
- package/dist/chunk-Y2SCTWL4.js +32 -0
- package/dist/chunk-YOQ2546V.js +50 -0
- package/dist/{chunk-ZWKLRZE5.js → chunk-ZQRFVFKK.js} +2 -2
- package/dist/{create-XVDDQA42.js → create-UGXMC4CT.js} +1 -1
- package/dist/{demo-kit-RWGOEDW4.js → demo-kit-2VI4H6OJ.js} +1 -1
- package/dist/{doctor-UOLOGJ2Z.js → doctor-LCKG5S76.js} +1 -1
- package/dist/{dotnet-webapi-clean-RTBRPDPL.js → dotnet-webapi-clean-K33C77EI.js} +1 -1
- package/dist/{gofiber-standard-UGIRKPKL.js → gofiber-standard-BQ4HCXL2.js} +1 -1
- package/dist/{gogin-standard-HJ7SPFNT.js → gogin-standard-PUBCYW3A.js} +1 -1
- package/dist/index.d.ts +45 -7
- package/dist/index.js +123 -106
- package/dist/{pipeline-XK62WL4D.js → pipeline-MKNYPNGD.js} +1 -1
- package/dist/{springboot-standard-IWJSVDLZ.js → springboot-standard-XFVQI37R.js} +1 -1
- package/dist/{workspace-L4ITCKMM.js → workspace-FDMJD5XI.js} +1 -1
- package/dist/workspace-agent-sync-WJIZCZX5.js +1 -0
- package/dist/{workspace-context-NMMQMHNU.js → workspace-context-RYOQYGOP.js} +1 -1
- package/dist/workspace-contract-ITFCJCHI.js +1 -0
- package/dist/workspace-explain-VKSUKP3O.js +1 -0
- package/dist/workspace-explain-contract-CLHQ3XEH.js +1 -0
- package/dist/workspace-feedback-65NR3EZH.js +1 -0
- package/dist/{workspace-foundation-HNIRAIBF.js → workspace-foundation-SILFUKL5.js} +1 -1
- package/dist/workspace-graph-2A5THUCI.js +1 -0
- package/dist/workspace-history-VPDADQKG.js +1 -0
- package/dist/{workspace-intelligence-64IWAYHS.js → workspace-intelligence-YOZQBAK5.js} +1 -1
- package/dist/workspace-mcp-serve-OOLITFCK.js +3 -0
- package/dist/workspace-model-VMMLHJWI.js +1 -0
- package/dist/workspace-registry-summary-ZXGKL2NT.js +1 -0
- package/dist/workspace-run-IHB2TPMD.js +1 -0
- package/dist/workspace-verify-3CAKAZIL.js +1 -0
- package/dist/workspace-watch-3MEZRSEE.js +1 -0
- package/docs/contracts/ARTIFACT_CATALOG.md +3 -1
- package/docs/contracts/NAMING_AND_COEXISTENCE.md +58 -0
- package/docs/workspace-run.md +25 -1
- package/package.json +1 -1
- package/dist/analyze-RHQM4AB2.js +0 -1
- package/dist/autopilot-release-OJTLXPMX.js +0 -1
- package/dist/chunk-5VBRMLRU.js +0 -7
- package/dist/chunk-7VI4U7Q5.js +0 -2
- package/dist/chunk-FV5A3N3I.js +0 -2
- package/dist/chunk-GDGATWR5.js +0 -2
- package/dist/chunk-GOM3RFB3.js +0 -2
- package/dist/chunk-KYH364KQ.js +0 -1
- package/dist/chunk-OWNGSAO3.js +0 -2
- package/dist/chunk-QPEBI6AB.js +0 -2
- package/dist/chunk-TYZPPUBH.js +0 -1
- package/dist/chunk-WHCON2VN.js +0 -50
- package/dist/chunk-X7PWDIQW.js +0 -1
- package/dist/workspace-agent-sync-G7JU77IK.js +0 -25
- package/dist/workspace-contract-D5O4OZD5.js +0 -1
- package/dist/workspace-history-LHUTLE3S.js +0 -1
- package/dist/workspace-model-SDHH5RBC.js +0 -1
- package/dist/workspace-registry-summary-MIPHVB56.js +0 -1
- package/dist/workspace-run-SPP32MPV.js +0 -1
- package/dist/workspace-verify-6Q6MGRG6.js +0 -1
- package/dist/workspace-watch-JDXVGW4H.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {b as b$4,a as a$6}from'./chunk-
|
|
2
|
+
import {a as a$c}from'./chunk-ICGWHIMK.js';import {b as b$4,a as a$6}from'./chunk-FPUNOIAR.js';import {b as b$b,a as a$e,l as l$2}from'./chunk-Y2SCTWL4.js';import {b as b$c,a as a$h}from'./chunk-FVCZGUVX.js';import {e as e$3}from'./chunk-AT3EQ2S7.js';import {a as a$f}from'./chunk-VMJA36WD.js';import {a as a$7}from'./chunk-KMUWWZRT.js';import {b as b$5,d as d$2,a as a$4,c as c$1,f as f$5,e as e$4}from'./chunk-PCXSTKZ5.js';import {g,b as b$1,c,d,m,l,h as h$1,k,a as a$8,j as j$1,f as f$6,i as i$5}from'./chunk-XOVB2ZP5.js';import {a as a$2,b as b$2}from'./chunk-CDCYRBAY.js';import {a as a$a}from'./chunk-A5FBGRJA.js';import {a as a$d}from'./chunk-424B73UF.js';import {a as a$g}from'./chunk-WA6JYVJM.js';import {c as c$4,d as d$5,e as e$2,f as f$4,g as g$2,a as a$i}from'./chunk-QN2LPLHO.js';import {j,a as a$5,b as b$6,c as c$2,d as d$3,e as e$1,f as f$2,q as q$1,s as s$2,h as h$3,m as m$1,i as i$1,r,t as t$1,g as g$1,p as p$1,k as k$2,o as o$1}from'./chunk-YBS2HGO3.js';export{i as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-YBS2HGO3.js';import {i as i$2}from'./chunk-UZW5QFRW.js';import {f as f$7}from'./chunk-DMUEGR36.js';import {h,a as a$3,q,s as s$1,p,t,m as m$2,l as l$1,n,k as k$1,o,i as i$4}from'./chunk-ZQRFVFKK.js';import {b as b$8,d as d$6}from'./chunk-RV6HBTFC.js';import {a as a$b}from'./chunk-VKLL63TL.js';import {b,a as a$1}from'./chunk-Q2KZIBV4.js';import {f,d as d$1,b as b$7}from'./chunk-OLDPVVSV.js';import {c as c$5}from'./chunk-MIWDCR6I.js';import {f as f$1,e,d as d$4,i as i$3,a as a$9,g as g$3}from'./chunk-GX7UU7LL.js';import {a,h as h$2,i,f as f$3,b as b$a,d as d$7,c as c$6,j as j$2}from'./chunk-Z5LKRG57.js';import {c as c$7}from'./chunk-2FIX2MDC.js';import {c as c$3,b as b$9}from'./chunk-HHJAANUC.js';import {Command,Option}from'commander';import s from'chalk';import w from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import*as R from'fs-extra';import R__default from'fs-extra';import b$3,{promises,createWriteStream}from'fs';import Qn,{tmpdir}from'os';import {execa}from'execa';import sr,{createVerify,createHash,createHmac}from'crypto';import ci from'http';import li from'https';function Xi(){return d$7()}function Zi(t,e){return t==="py"?["-3",...e]:e}function ea(t){return typeof t=="object"&&t!==null}async function ta(t,e,o,r=c$7()){try{let n=await execa(t,e,{cwd:o,timeout:r,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function oa(t,e){let o=["-m","rapidkit",...t],r=Xi();for(let n of r){let i=await ta(n,Zi(n,o),e?.cwd,e?.timeoutMs);if(!i.ok)continue;let a=(i.stdout??"").trim();try{let c=JSON.parse(a);return ea(c)?{ok:true,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,data:c}:{ok:false,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}catch{return {ok:false,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}}return {ok:false}}async function Un(t,e){let o=await oa(["project","detect","--path",t,"--json"],e);return !o.ok||!o.data||o.data.schema_version!==1?{ok:false,command:o.command,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr}:o}var Hn=new Set(["create"]),Ho=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),ra=new Set(["pip","poetry","venv","pipx","python"]);function qn(t){return typeof t=="string"&&ra.has(t)}function qo(t,e){return !t||Hn.has(t)?false:a$9.has(t)?true:e?.has(t)??false}function zo(t,e=null){let o=t[0];return !o||o.startsWith("-")||Hn.has(o)||o==="init"?false:qo(o,e)?true:t.filter(n=>!n.startsWith("-")&&!Ho.has(n)).length<=1?false:t.length>1}var mt=w.join(Qn.homedir(),".rapidkitrc.json"),na=w.join(Qn.homedir(),".rapidkit","config.json");function zn(t){try{if(!b$3.existsSync(t))return {};let e=b$3.readFileSync(t,"utf-8"),o=JSON.parse(e);return !o||typeof o!="object"||Array.isArray(o)?{}:o}catch{return {}}}function Xn(t){if(process.platform!=="win32")try{b$3.chmodSync(t,384);}catch{}}function ft(){let t=zn(mt),e=zn(na);return b$3.existsSync(mt)&&Xn(mt),{...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled,telemetry:t.telemetry??e.telemetry}}function so(t){let o={...ft(),...t};b$3.writeFileSync(mt,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),Xn(mt);}function Mt(){return process.env.OPENAI_API_KEY||ft().openaiApiKey||null}function Yo(){return ft().aiEnabled!==false}function Qo(){return mt}function Zn(t){let e=t.command("config").description("Configure RapidKit settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async o=>{let r=o.key;r?r.startsWith("sk-")||(console.log(s.red(`
|
|
3
3
|
\u274C Invalid API key format (should start with sk-)
|
|
4
4
|
`)),process.exit(1)):r=(await b$2([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:i=>i?i.startsWith("sk-")?i.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,so({openaiApiKey:r}),console.log(s.green(`
|
|
5
5
|
\u2705 OpenAI API key saved successfully!
|
|
6
|
-
`)),console.log(s.gray(`Stored in: ${
|
|
6
|
+
`)),console.log(s.gray(`Stored in: ${Qo()}`)),console.log(s.cyan(`
|
|
7
7
|
\u{1F389} You can now use AI features:`)),console.log(s.white(' rapidkit ai recommend "I need user authentication"')),console.log(s.gray(`
|
|
8
8
|
\u{1F4A1} To generate module embeddings (one-time):`)),console.log(s.white(" cd rapidkit-npm")),console.log(s.white(` npx tsx src/ai/generate-embeddings.ts
|
|
9
9
|
`));}),e.command("show").description("Show current configuration").action(()=>{let o=ft();if(console.log(s.bold(`
|
|
10
10
|
\u2699\uFE0F RapidKit Configuration
|
|
11
11
|
`)),o.openaiApiKey){let r=o.openaiApiKey.substring(0,8)+"..."+o.openaiApiKey.slice(-4);console.log(s.cyan("OpenAI API Key:"),s.white(r));}else console.log(s.cyan("OpenAI API Key:"),s.red("Not set")),console.log(s.gray(" Set with: rapidkit config set-api-key"));console.log(s.cyan("AI Features:"),o.aiEnabled!==false?s.green("Enabled"):s.red("Disabled")),console.log(s.gray(`
|
|
12
|
-
\u{1F4C1} Config file: ${
|
|
12
|
+
\u{1F4C1} Config file: ${Qo()}
|
|
13
13
|
`));}),e.command("remove-api-key").description("Remove stored OpenAI API key").action(async()=>{if(!ft().openaiApiKey){console.log(s.yellow(`
|
|
14
14
|
\u26A0\uFE0F No API key is currently stored
|
|
15
15
|
`));return}(await b$2([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(so({openaiApiKey:void 0}),console.log(s.green(`
|
|
@@ -20,7 +20,7 @@ Cancelled
|
|
|
20
20
|
\u274C Invalid action: ${o}`)),console.log(s.gray(`Use: rapidkit config ai enable|disable
|
|
21
21
|
`)),process.exit(1));let r=o==="enable";so({aiEnabled:r}),console.log(s.green(`
|
|
22
22
|
\u2705 AI features ${r?"enabled":"disabled"}
|
|
23
|
-
`));});}var io=null,ao=false,Qo=null;async function Hi(){return Qo||(Qo=(await import('openai')).default),Qo}function Jn(){ao=true;}function Kn(t){let o=new Array(1536),r=0;for(let i=0;i<t.length;i++)r=(r<<5)-r+t.charCodeAt(i),r=r&r;for(let i=0;i<1536;i++)r=r*1664525+1013904223&4294967295,o[i]=r/4294967295*2-1;let n=Math.sqrt(o.reduce((i,a)=>i+a*a,0));return o.map(i=>i/n)}async function co(t){let e=await Hi();io=new e({apiKey:t});}function Gn(){if(!io)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return io}async function Zo(t){return ao?Kn(t):(await Gn().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function Vn(t){return ao?t.map(Kn):(await Gn().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(r=>r.embedding)}function Bn(){return io!==null}function gt(){return ao}function Xo(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function qi(t){return !t||typeof t!="object"?{}:t}var tr=[{id:"authentication-core",name:"Authentication Core",category:"auth",description:"Complete authentication system with password hashing, JWT tokens, OAuth 2.0, and secure session management",longDescription:"Production-ready authentication with bcrypt password hashing, JWT access/refresh tokens, OAuth 2.0 providers (Google, GitHub, etc), rate limiting, and security best practices.",keywords:["auth","login","password","jwt","oauth","token","authentication","security","signin","signup"],framework:"both",dependencies:[],useCases:["User login and logout","Password reset flow","OAuth social login (Google, GitHub)","JWT authentication","Secure session management","Token refresh","Rate limiting"]},{id:"users-core",name:"Users Core",category:"auth",description:"User management system with profiles, roles, permissions, and user CRUD operations",longDescription:"Complete user management with user profiles, role-based access control (RBAC), permissions, user search, soft delete, and audit trails.",keywords:["user","profile","role","permission","rbac","management","admin","accounts"],framework:"both",dependencies:["authentication-core"],useCases:["User registration","User profile management","Role management (admin, user, etc)","Permission system","User administration dashboard","Soft delete users"]},{id:"session-management",name:"Session Management",category:"auth",description:"Secure session handling with Redis storage, session rotation, and device tracking",longDescription:"Advanced session management with Redis-backed storage, automatic session rotation, device fingerprinting, IP tracking, and session revocation.",keywords:["session","redis","cookie","storage","device","tracking"],framework:"both",dependencies:["authentication-core","redis-cache"],useCases:["User session management","Remember me functionality","Device tracking","Session security","Logout from all devices","Session expiration"]},{id:"db-postgres",name:"PostgreSQL",category:"database",description:"PostgreSQL integration with async SQLAlchemy, migrations, connection pooling, and query optimization",longDescription:"Production-ready PostgreSQL with async SQLAlchemy 2.0, Alembic migrations, connection pooling, query optimization, JSON support, and full-text search.",keywords:["postgres","postgresql","database","sql","sqlalchemy","migration","orm","relational"],framework:"both",dependencies:[],useCases:["Relational database","Complex SQL queries","Database transactions","Data integrity","Production-grade database","ACID compliance"]},{id:"db-mongodb",name:"MongoDB",category:"database",description:"MongoDB integration with Motor async driver, schema validation, and aggregation pipelines",longDescription:"Async MongoDB with Motor driver, Pydantic schema validation, aggregation pipelines, indexes, and Atlas integration.",keywords:["mongodb","mongo","nosql","document","database","motor"],framework:"both",dependencies:[],useCases:["Document storage","Flexible schema","Real-time data","JSON documents","Unstructured data","Analytics"]},{id:"stripe-payment",name:"Stripe Payment",category:"payment",description:"Stripe integration with payment intents, subscriptions, webhooks, and customer portal",longDescription:"Complete Stripe integration with Payment Intents API, subscription management, automatic webhooks, customer portal, refunds, and SCA compliance.",keywords:["stripe","payment","subscription","billing","checkout","webhook","credit card"],framework:"both",dependencies:[],useCases:["Accept credit card payments","Subscription billing","One-time payments","Checkout flow","Payment webhooks","Refunds and disputes"]},{id:"email",name:"Email",category:"communication",description:"Email sending with templates, SMTP/SendGrid/AWS SES support, and queue management",longDescription:"Production email system with Jinja2 templates, multiple providers (SMTP, SendGrid, AWS SES), queue management, retry logic, and bounce handling.",keywords:["email","mail","smtp","sendgrid","ses","template","notification"],framework:"both",dependencies:[],useCases:["Welcome emails","Password reset emails","Notifications","Marketing emails","Transactional emails","Email templates"]},{id:"sms",name:"SMS",category:"communication",description:"SMS sending with Twilio, verification codes, and delivery tracking",longDescription:"SMS integration with Twilio, verification codes, two-factor authentication, delivery tracking, and international support.",keywords:["sms","twilio","text","message","2fa","verification","otp"],framework:"both",dependencies:[],useCases:["2FA verification codes","SMS notifications","Phone verification","OTP generation","SMS alerts"]},{id:"redis-cache",name:"Redis Cache",category:"infrastructure",description:"Redis caching with decorators, TTL management, and cache invalidation patterns",longDescription:"Redis integration with async client, caching decorators, TTL management, cache invalidation, pub/sub, and rate limiting.",keywords:["redis","cache","memory","performance","speed","pubsub"],framework:"both",dependencies:[],useCases:["API response caching","Session storage","Rate limiting","Real-time features","Performance optimization","Pub/sub messaging"]},{id:"celery",name:"Celery",category:"infrastructure",description:"Background task processing with Celery, periodic tasks, and monitoring",longDescription:"Celery task queue with Redis/RabbitMQ backend, periodic tasks (cron), task monitoring, retry logic, and failure handling.",keywords:["celery","task","background","queue","async","worker","job","cron"],framework:"fastapi",dependencies:["redis-cache"],useCases:["Background email sending","Data processing","Report generation","Scheduled tasks","Long-running jobs"]},{id:"storage",name:"Storage",category:"infrastructure",description:"File storage with S3, local filesystem, and image processing",longDescription:"Unified storage interface for AWS S3, local files, image resizing, format conversion, CDN integration, and presigned URLs.",keywords:["storage","s3","file","upload","image","cdn","aws"],framework:"both",dependencies:[],useCases:["File uploads","Image storage","Document management","Profile pictures","Media files","CDN integration"]}],qe=null,er=0,zi=300*1e3;function Yi(t){let e=qi(t),o=e.slug||e.name||e.id||e.module_id||"",r=Xo(e.keywords??e.tags);return {id:o,name:e.display_name||e.name||"",category:Qi(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:r.map(n=>n.toLowerCase()),framework:Zi(e.framework),dependencies:Xo(e.dependencies),useCases:Xo(e.use_cases??e.useCases)}}function Qi(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function Zi(t){if(!t)return "both";if(typeof t=="string"){if(t.toLowerCase().includes("fastapi"))return "fastapi";if(t.toLowerCase().includes("nest"))return "nestjs"}return "both"}async function Xi(){try{let t=await g$2(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.match(/\{[\s\S]*\}/),o=e?e[0]:t.stdout,r=JSON.parse(o),n=[];return Array.isArray(r)?n=r:r.modules&&Array.isArray(r.modules)?n=r.modules:r.data&&Array.isArray(r.data)&&(n=r.data),n.map(Yi).filter(i=>i.id&&i.name)}catch(t){return console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",t.message),console.warn(" Using fallback module catalog (11 modules)"),tr}}async function lo(){let t=Date.now();return gt()?(qe=tr,er=t,qe):(qe&&t-er<zi||(qe=await Xi(),er=t,qe.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),qe=tr)),qe)}var ta=fileURLToPath(import.meta.url),Hn=w.dirname(ta),ht=null,qn=new Map;function oa(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function ra(t){let e=qn.get(t.id);if(e)return e;let o=await Zo(oa(t));return qn.set(t.id,o),o}function na(){if(ht)return ht;let t=[w.join(Hn,"../../data/modules-embeddings.json"),w.join(Hn,"../data/modules-embeddings.json"),w.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(b$3.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let o=b$3.readFileSync(e,"utf-8"),r=JSON.parse(o);if(Array.isArray(r)?ht={model:"mock-or-text-embedding-3-small",dimension:r[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:r}:ht=r,!ht)throw new Error("failed to load embeddings data");return ht}function zn(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let o=0,r=0,n=0;for(let a=0;a<t.length;a++)o+=t[a]*e[a],r+=t[a]*t[a],n+=e[a]*e[a];let i=Math.sqrt(r)*Math.sqrt(n);return i===0?0:o/i}function Yn(t,e){let o=e.toLowerCase(),r=t.keywords.filter(n=>o.includes(n)||n.includes(o));return r.length>0?`Matches: ${r.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function Qn(t,e=5){let o=await lo(),r=await Zo(t);if(gt()){let a=await Promise.all(o.map(async c=>{let l=await ra(c);return {module:c,score:zn(r,l),reason:Yn(c,t)}}));return a.sort((c,l)=>l.score-c.score),a.slice(0,e)}let i=na().modules.map(a=>{let c=o.find(g=>g.id===a.id);if(!c)return null;let l=zn(r,a.embedding);return {module:c,score:l,reason:Yn(c,t)}}).filter(a=>a!==null);return i.sort((a,c)=>c.score-a.score),i.slice(0,e)}var ia=fileURLToPath(import.meta.url),Zn=w.dirname(ia);function Xn(t){return t instanceof Error?t.message:String(t)}function aa(){return [w.join(Zn,"../../data/modules-embeddings.json"),w.join(Zn,"../data/modules-embeddings.json"),w.join(process.cwd(),"data/modules-embeddings.json")]}function es(){let t=aa();for(let e of t)if(b$3.existsSync(e))try{let o=JSON.parse(b$3.readFileSync(e,"utf-8")),r=Array.isArray(o)?o:o.modules||[];return {exists:true,path:e,moduleCount:r.length,generatedAt:o.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function uo(t=true,e){try{if(!Bn()&&!gt())return console.log(s.red(`
|
|
23
|
+
`));});}var io=null,ao=false,Xo=null;async function sa(){return Xo||(Xo=(await import('openai')).default),Xo}function es(){ao=true;}function ts(t){let o=new Array(1536),r=0;for(let i=0;i<t.length;i++)r=(r<<5)-r+t.charCodeAt(i),r=r&r;for(let i=0;i<1536;i++)r=r*1664525+1013904223&4294967295,o[i]=r/4294967295*2-1;let n=Math.sqrt(o.reduce((i,a)=>i+a*a,0));return o.map(i=>i/n)}async function co(t){let e=await sa();io=new e({apiKey:t});}function os(){if(!io)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return io}async function Zo(t){return ao?ts(t):(await os().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function rs(t){return ao?t.map(ts):(await os().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(r=>r.embedding)}function ns(){return io!==null}function gt(){return ao}function er(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function ia(t){return !t||typeof t!="object"?{}:t}var or=[{id:"authentication-core",name:"Authentication Core",category:"auth",description:"Complete authentication system with password hashing, JWT tokens, OAuth 2.0, and secure session management",longDescription:"Production-ready authentication with bcrypt password hashing, JWT access/refresh tokens, OAuth 2.0 providers (Google, GitHub, etc), rate limiting, and security best practices.",keywords:["auth","login","password","jwt","oauth","token","authentication","security","signin","signup"],framework:"both",dependencies:[],useCases:["User login and logout","Password reset flow","OAuth social login (Google, GitHub)","JWT authentication","Secure session management","Token refresh","Rate limiting"]},{id:"users-core",name:"Users Core",category:"auth",description:"User management system with profiles, roles, permissions, and user CRUD operations",longDescription:"Complete user management with user profiles, role-based access control (RBAC), permissions, user search, soft delete, and audit trails.",keywords:["user","profile","role","permission","rbac","management","admin","accounts"],framework:"both",dependencies:["authentication-core"],useCases:["User registration","User profile management","Role management (admin, user, etc)","Permission system","User administration dashboard","Soft delete users"]},{id:"session-management",name:"Session Management",category:"auth",description:"Secure session handling with Redis storage, session rotation, and device tracking",longDescription:"Advanced session management with Redis-backed storage, automatic session rotation, device fingerprinting, IP tracking, and session revocation.",keywords:["session","redis","cookie","storage","device","tracking"],framework:"both",dependencies:["authentication-core","redis-cache"],useCases:["User session management","Remember me functionality","Device tracking","Session security","Logout from all devices","Session expiration"]},{id:"db-postgres",name:"PostgreSQL",category:"database",description:"PostgreSQL integration with async SQLAlchemy, migrations, connection pooling, and query optimization",longDescription:"Production-ready PostgreSQL with async SQLAlchemy 2.0, Alembic migrations, connection pooling, query optimization, JSON support, and full-text search.",keywords:["postgres","postgresql","database","sql","sqlalchemy","migration","orm","relational"],framework:"both",dependencies:[],useCases:["Relational database","Complex SQL queries","Database transactions","Data integrity","Production-grade database","ACID compliance"]},{id:"db-mongodb",name:"MongoDB",category:"database",description:"MongoDB integration with Motor async driver, schema validation, and aggregation pipelines",longDescription:"Async MongoDB with Motor driver, Pydantic schema validation, aggregation pipelines, indexes, and Atlas integration.",keywords:["mongodb","mongo","nosql","document","database","motor"],framework:"both",dependencies:[],useCases:["Document storage","Flexible schema","Real-time data","JSON documents","Unstructured data","Analytics"]},{id:"stripe-payment",name:"Stripe Payment",category:"payment",description:"Stripe integration with payment intents, subscriptions, webhooks, and customer portal",longDescription:"Complete Stripe integration with Payment Intents API, subscription management, automatic webhooks, customer portal, refunds, and SCA compliance.",keywords:["stripe","payment","subscription","billing","checkout","webhook","credit card"],framework:"both",dependencies:[],useCases:["Accept credit card payments","Subscription billing","One-time payments","Checkout flow","Payment webhooks","Refunds and disputes"]},{id:"email",name:"Email",category:"communication",description:"Email sending with templates, SMTP/SendGrid/AWS SES support, and queue management",longDescription:"Production email system with Jinja2 templates, multiple providers (SMTP, SendGrid, AWS SES), queue management, retry logic, and bounce handling.",keywords:["email","mail","smtp","sendgrid","ses","template","notification"],framework:"both",dependencies:[],useCases:["Welcome emails","Password reset emails","Notifications","Marketing emails","Transactional emails","Email templates"]},{id:"sms",name:"SMS",category:"communication",description:"SMS sending with Twilio, verification codes, and delivery tracking",longDescription:"SMS integration with Twilio, verification codes, two-factor authentication, delivery tracking, and international support.",keywords:["sms","twilio","text","message","2fa","verification","otp"],framework:"both",dependencies:[],useCases:["2FA verification codes","SMS notifications","Phone verification","OTP generation","SMS alerts"]},{id:"redis-cache",name:"Redis Cache",category:"infrastructure",description:"Redis caching with decorators, TTL management, and cache invalidation patterns",longDescription:"Redis integration with async client, caching decorators, TTL management, cache invalidation, pub/sub, and rate limiting.",keywords:["redis","cache","memory","performance","speed","pubsub"],framework:"both",dependencies:[],useCases:["API response caching","Session storage","Rate limiting","Real-time features","Performance optimization","Pub/sub messaging"]},{id:"celery",name:"Celery",category:"infrastructure",description:"Background task processing with Celery, periodic tasks, and monitoring",longDescription:"Celery task queue with Redis/RabbitMQ backend, periodic tasks (cron), task monitoring, retry logic, and failure handling.",keywords:["celery","task","background","queue","async","worker","job","cron"],framework:"fastapi",dependencies:["redis-cache"],useCases:["Background email sending","Data processing","Report generation","Scheduled tasks","Long-running jobs"]},{id:"storage",name:"Storage",category:"infrastructure",description:"File storage with S3, local filesystem, and image processing",longDescription:"Unified storage interface for AWS S3, local files, image resizing, format conversion, CDN integration, and presigned URLs.",keywords:["storage","s3","file","upload","image","cdn","aws"],framework:"both",dependencies:[],useCases:["File uploads","Image storage","Document management","Profile pictures","Media files","CDN integration"]}],qe=null,tr=0,aa=300*1e3;function ca(t){let e=ia(t),o=e.slug||e.name||e.id||e.module_id||"",r=er(e.keywords??e.tags);return {id:o,name:e.display_name||e.name||"",category:la(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:r.map(n=>n.toLowerCase()),framework:da(e.framework),dependencies:er(e.dependencies),useCases:er(e.use_cases??e.useCases)}}function la(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function da(t){if(!t)return "both";if(typeof t=="string"){if(t.toLowerCase().includes("fastapi"))return "fastapi";if(t.toLowerCase().includes("nest"))return "nestjs"}return "both"}async function pa(){try{let t=await g$3(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.match(/\{[\s\S]*\}/),o=e?e[0]:t.stdout,r=JSON.parse(o),n=[];return Array.isArray(r)?n=r:r.modules&&Array.isArray(r.modules)?n=r.modules:r.data&&Array.isArray(r.data)&&(n=r.data),n.map(ca).filter(i=>i.id&&i.name)}catch(t){return console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",t.message),console.warn(" Using fallback module catalog (11 modules)"),or}}async function lo(){let t=Date.now();return gt()?(qe=or,tr=t,qe):(qe&&t-tr<aa||(qe=await pa(),tr=t,qe.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),qe=or)),qe)}var ma=fileURLToPath(import.meta.url),is=w.dirname(ma),ht=null,as=new Map;function fa(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function ga(t){let e=as.get(t.id);if(e)return e;let o=await Zo(fa(t));return as.set(t.id,o),o}function ha(){if(ht)return ht;let t=[w.join(is,"../../data/modules-embeddings.json"),w.join(is,"../data/modules-embeddings.json"),w.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(b$3.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let o=b$3.readFileSync(e,"utf-8"),r=JSON.parse(o);if(Array.isArray(r)?ht={model:"mock-or-text-embedding-3-small",dimension:r[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:r}:ht=r,!ht)throw new Error("failed to load embeddings data");return ht}function cs(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let o=0,r=0,n=0;for(let a=0;a<t.length;a++)o+=t[a]*e[a],r+=t[a]*t[a],n+=e[a]*e[a];let i=Math.sqrt(r)*Math.sqrt(n);return i===0?0:o/i}function ls(t,e){let o=e.toLowerCase(),r=t.keywords.filter(n=>o.includes(n)||n.includes(o));return r.length>0?`Matches: ${r.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function ds(t,e=5){let o=await lo(),r=await Zo(t);if(gt()){let a=await Promise.all(o.map(async c=>{let l=await ga(c);return {module:c,score:cs(r,l),reason:ls(c,t)}}));return a.sort((c,l)=>l.score-c.score),a.slice(0,e)}let i=ha().modules.map(a=>{let c=o.find(g=>g.id===a.id);if(!c)return null;let l=cs(r,a.embedding);return {module:c,score:l,reason:ls(c,t)}}).filter(a=>a!==null);return i.sort((a,c)=>c.score-a.score),i.slice(0,e)}var wa=fileURLToPath(import.meta.url),ps=w.dirname(wa);function us(t){return t instanceof Error?t.message:String(t)}function ka(){return [w.join(ps,"../../data/modules-embeddings.json"),w.join(ps,"../data/modules-embeddings.json"),w.join(process.cwd(),"data/modules-embeddings.json")]}function ms(){let t=ka();for(let e of t)if(b$3.existsSync(e))try{let o=JSON.parse(b$3.readFileSync(e,"utf-8")),r=Array.isArray(o)?o:o.modules||[];return {exists:true,path:e,moduleCount:r.length,generatedAt:o.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function uo(t=true,e){try{if(!ns()&&!gt())return console.log(s.red(`
|
|
24
24
|
\u274C OpenAI not initialized`)),console.log(s.yellow("Please set your API key:")),console.log(s.white(" rapidkit config set-api-key")),console.log(s.gray(` OR set: export OPENAI_API_KEY="sk-..."
|
|
25
25
|
`)),false;console.log(s.blue(`
|
|
26
26
|
\u{1F916} Generating AI embeddings for RapidKit modules...
|
|
@@ -28,17 +28,17 @@ Cancelled
|
|
|
28
28
|
`));let r=o.length*50/1e6*.02;if(console.log(s.cyan(`\u{1F4B0} Estimated cost: ~$${r.toFixed(3)}`)),console.log(s.gray(` (Based on ${o.length} modules at $0.02/1M tokens)
|
|
29
29
|
`)),t){let{confirm:a}=await b$2([{type:"confirm",name:"confirm",message:"Generate embeddings now?",default:true}]);if(!a)return console.log(s.yellow(`
|
|
30
30
|
\u26A0\uFE0F Embeddings generation cancelled
|
|
31
|
-
`)),false}let n=o.map(a=>`${a.name}. ${a.description}. ${a.longDescription}. Keywords: ${a.keywords.join(", ")}. Use cases: ${a.useCases.join(", ")}.`),i=b$
|
|
31
|
+
`)),false}let n=o.map(a=>`${a.name}. ${a.description}. ${a.longDescription}. Keywords: ${a.keywords.join(", ")}. Use cases: ${a.useCases.join(", ")}.`),i=b$7(`Generating embeddings for ${o.length} modules...`,{component:"ai",phase:"embeddings.generate"});try{let a=await rs(n);i.succeed(`Generated embeddings for ${o.length} modules`);let c={model:"text-embedding-3-small",dimension:a[0].length,generated_at:new Date().toISOString(),modules:o.map((m,p)=>({id:m.id,name:m.name,embedding:a[p]}))},l=e||w.join(process.cwd(),"data","modules-embeddings.json"),g=w.dirname(l);return b$3.existsSync(g)||b$3.mkdirSync(g,{recursive:true}),b$3.writeFileSync(l,JSON.stringify(c,null,2)),console.log(s.green(`
|
|
32
32
|
\u2705 Embeddings generated successfully!`)),console.log(s.gray(`\u{1F4C1} Saved to: ${l}`)),console.log(s.gray(`\u{1F4CA} Size: ${o.length} modules, ${a[0].length} dimensions
|
|
33
|
-
`)),true}catch(a){i.fail("Failed to generate embeddings");let c=
|
|
33
|
+
`)),true}catch(a){i.fail("Failed to generate embeddings");let c=us(a);return c.includes("429")?(console.log(s.red(`
|
|
34
34
|
\u274C OpenAI API quota exceeded`)),console.log(s.yellow(`Please check your billing: https://platform.openai.com/account/billing
|
|
35
35
|
`))):c.includes("401")?(console.log(s.red(`
|
|
36
36
|
\u274C Invalid API key`)),console.log(s.yellow("Please set a valid API key:")),console.log(s.white(` rapidkit config set-api-key
|
|
37
37
|
`))):console.log(s.red(`
|
|
38
38
|
\u274C Error: ${c}
|
|
39
39
|
`)),false}}catch(o){return console.log(s.red(`
|
|
40
|
-
\u274C Failed to generate embeddings: ${
|
|
41
|
-
`)),false}}async function
|
|
40
|
+
\u274C Failed to generate embeddings: ${us(o)}
|
|
41
|
+
`)),false}}async function fs(t=true){if(ms().exists)return true;if(console.log(s.yellow(`
|
|
42
42
|
\u26A0\uFE0F Module embeddings not found`)),console.log(s.gray(`AI recommendations require embeddings to be generated.
|
|
43
43
|
`)),!t)return console.log(s.red("\u274C Cannot generate embeddings in non-interactive mode")),console.log(s.white(`Run: rapidkit ai generate-embeddings
|
|
44
44
|
`)),false;let{action:o}=await b$2([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"\u{1F680} Generate embeddings now (OpenAI key for production, or mock mode for testing)",value:"generate"},{name:"\u{1F4DD} Show me how to generate them manually",value:"manual"},{name:"\u274C Cancel",value:"cancel"}]}]);return o==="generate"?await uo(true):(o==="manual"&&(console.log(s.cyan(`
|
|
@@ -46,21 +46,21 @@ Cancelled
|
|
|
46
46
|
`)),console.log(s.white("1. Get OpenAI API key from: https://platform.openai.com/api-keys")),console.log(s.white("2. Set the API key:")),console.log(s.gray(" rapidkit config set-api-key")),console.log(s.gray(` OR: export OPENAI_API_KEY="sk-..."
|
|
47
47
|
`)),console.log(s.white("3. Generate embeddings:")),console.log(s.gray(` rapidkit ai generate-embeddings
|
|
48
48
|
`)),console.log(s.cyan(`\u{1F4B0} Cost: ~$0.50 one-time
|
|
49
|
-
`))),false)}async function
|
|
49
|
+
`))),false)}async function gs(){let t=ms();return t.exists?(console.log(s.blue(`
|
|
50
50
|
\u{1F504} Updating embeddings...`)),console.log(s.gray(`Current: ${t.moduleCount} modules`)),console.log(s.gray(`Generated: ${t.generatedAt||"unknown"}
|
|
51
51
|
`)),t.path?await uo(true,t.path):false):(console.log(s.yellow(`
|
|
52
52
|
\u26A0\uFE0F No existing embeddings found`)),console.log(s.gray(`Use: rapidkit ai generate-embeddings
|
|
53
|
-
`)),false)}function
|
|
53
|
+
`)),false)}function rr(t){if(t&&typeof t=="object"){let e=t;return {message:typeof e.message=="string"?e.message:String(t),code:typeof e.code=="string"?e.code:void 0}}return {message:String(t)}}function hs(t,e=0){console.log(JSON.stringify(t,null,2)),e!==0&&process.exit(e);}function ys(t){let e=t.command("ai").description("AI-powered features");e.command("recommend").description("Get AI-powered module recommendations").argument("[query]",'What do you want to build? (e.g., "user authentication with email")').option("-n, --number <count>","Number of recommendations","5").option("--json","Output as JSON").action(async(o,r)=>{try{Yo()||(r.json&&hs({ok:false,error:{code:"AI_DISABLED",message:"AI features are disabled",remediation:"rapidkit config ai enable"}},1),console.log(s.yellow(`
|
|
54
54
|
\u26A0\uFE0F AI features are disabled`)),console.log(s.gray(`Enable with: rapidkit config ai enable
|
|
55
55
|
`)),process.exit(1));let n=Mt();n?await co(n):(r.json||(console.log(s.yellow(`
|
|
56
56
|
\u26A0\uFE0F OpenAI API key not configured - using MOCK MODE for testing
|
|
57
57
|
`)),console.log(s.gray("\u{1F4DD} Note: Mock embeddings provide approximate results for testing.")),console.log(s.gray(` For production, configure your OpenAI API key:
|
|
58
58
|
`)),console.log(s.white(" 1. Get your key from: https://platform.openai.com/api-keys")),console.log(s.white(" 2. Configure it: rapidkit config set-api-key")),console.log(s.gray(` OR set: export OPENAI_API_KEY="sk-proj-..."
|
|
59
|
-
`))),
|
|
59
|
+
`))),es());let i=o;i||(i=(await b$2([{type:"input",name:"query",message:"\u{1F916} What do you want to build?",validate:d=>d.length===0?"Please enter a description":d.length<3?"Please be more specific (at least 3 characters)":true}])).query),r.json||console.log(s.blue(`
|
|
60
60
|
\u{1F916} Analyzing your request...
|
|
61
|
-
`)),!n||await
|
|
61
|
+
`)),!n||await fs(!r.json)||(r.json&&hs({ok:false,query:i,error:{code:"EMBEDDINGS_MISSING",message:"Module embeddings are not available",remediation:"rapidkit ai generate-embeddings"}},1),console.log(s.yellow(`
|
|
62
62
|
\u26A0\uFE0F Cannot proceed without embeddings
|
|
63
|
-
`)),process.exit(1));let c=parseInt(r.number,10),l=await
|
|
63
|
+
`)),process.exit(1));let c=parseInt(r.number,10),l=await ds(i,c);if(l.length===0||l[0].score<.3)if(console.log(s.yellow(`
|
|
64
64
|
\u26A0\uFE0F No matching modules found in RapidKit registry.
|
|
65
65
|
`)),console.log(s.cyan(`\u{1F4A1} Options:
|
|
66
66
|
`)),console.log(s.white("1. Create custom module:")),console.log(s.gray(" rapidkit modules scaffold <name> --category <category>")),console.log(s.gray(` Example: rapidkit modules scaffold blockchain-integration --category integrations
|
|
@@ -68,23 +68,23 @@ Cancelled
|
|
|
68
68
|
`)),console.log(s.white("3. Request feature:")),console.log(s.gray(` https://github.com/rapidkitlabs/rapidkit/issues
|
|
69
69
|
`)),l.length>0)console.log(s.yellow(`\u26A0\uFE0F Low confidence matches found:
|
|
70
70
|
`));else return;if(r.json){console.log(JSON.stringify({query:i,recommendations:l},null,2));return}console.log(s.green.bold(`\u{1F4E6} Recommended Modules:
|
|
71
|
-
`)),l.forEach((p,d)=>{let
|
|
72
|
-
`));let{shouldInstall:m}=await b$2([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(m){let{selectedModules:p}=await b$2([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:l.map(
|
|
71
|
+
`)),l.forEach((p,d)=>{let f=(p.score*100).toFixed(1),u=p.score>.8?" \u2B50":"";console.log(s.bold(`${d+1}. ${p.module.name}${u}`)),console.log(s.gray(` ${p.module.description}`)),console.log(s.cyan(` Match: ${f}%`)+s.gray(` - ${p.reason}`)),console.log(s.yellow(` Category: ${p.module.category}`)),p.module.dependencies.length>0&&console.log(s.magenta(` Requires: ${p.module.dependencies.join(", ")}`)),console.log();});let g=l.slice(0,3).map(p=>p.module.id);console.log(s.cyan("\u{1F4A1} Quick install (top 3):")),console.log(s.white(` rapidkit add module ${g.join(" ")}
|
|
72
|
+
`));let{shouldInstall:m}=await b$2([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(m){let{selectedModules:p}=await b$2([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:l.map(f=>({name:`${f.module.name} - ${f.module.description}`,value:f.module.id,checked:f.score>.7}))}]),d=p;if(d.length>0){console.log(s.blue(`
|
|
73
73
|
\u{1F4E6} Installing ${d.length} modules...
|
|
74
|
-
`)),console.log(s.gray(`Command: rapidkit add module ${d.join(" ")}`));let
|
|
75
|
-
\u274C RapidKit modules are not available for ${
|
|
76
|
-
`));return}let
|
|
74
|
+
`)),console.log(s.gray(`Command: rapidkit add module ${d.join(" ")}`));let f=a$5(process.cwd());if(f?.module_support===false){let h=f?.runtime==="java"?"Spring Boot":"Go";console.log(s.red(`
|
|
75
|
+
\u274C RapidKit modules are not available for ${h} npm-level kits.`)),console.log(s.gray(` The module system requires Python and is currently only supported for FastAPI and NestJS projects.
|
|
76
|
+
`));return}let u=await f$1(["add","module",...d],{cwd:process.cwd()});console.log(u===0?s.green(`
|
|
77
77
|
\u2705 Selected modules installed successfully
|
|
78
78
|
`):s.red(`
|
|
79
|
-
\u274C Module installation failed (exit code: ${
|
|
79
|
+
\u274C Module installation failed (exit code: ${u})
|
|
80
80
|
`));}else console.log(s.gray(`
|
|
81
81
|
No modules selected
|
|
82
|
-
`));}}catch(n){let i=
|
|
82
|
+
`));}}catch(n){let i=rr(n);f.error(`
|
|
83
83
|
\u274C Error:`,i.message),i.code==="invalid_api_key"?(console.log(s.yellow(`
|
|
84
84
|
\u{1F4A1} Your API key may be invalid or expired`)),console.log(s.cyan(` Update it: rapidkit config set-api-key
|
|
85
85
|
`))):i.message.includes("embeddings file not found")&&(console.log(s.yellow(`
|
|
86
86
|
\u{1F4A1} Module embeddings not generated yet`)),console.log(s.cyan(" Generate them (one-time):")),console.log(s.white(" cd rapidkit-npm")),console.log(s.white(' export OPENAI_API_KEY="sk-proj-..."')),console.log(s.white(` npx tsx src/ai/generate-embeddings.ts
|
|
87
|
-
`))),process.exit(1);}}),e.command("info").description("Show AI features information").action(()=>{let o=Mt(),r=
|
|
87
|
+
`))),process.exit(1);}}),e.command("info").description("Show AI features information").action(()=>{let o=Mt(),r=Yo();console.log(s.bold(`
|
|
88
88
|
\u{1F916} RapidKit AI Features
|
|
89
89
|
`)),console.log(s.cyan("Status:"),r?s.green("Enabled"):s.red("Disabled")),console.log(s.cyan("API Key:"),o?s.green("Configured \u2713"):s.red("Not configured \u2717")),console.log(s.bold(`
|
|
90
90
|
\u{1F4E6} Available Features:
|
|
@@ -98,128 +98,128 @@ No modules selected
|
|
|
98
98
|
`)),console.log(s.white("1. Get your key from: https://platform.openai.com/api-keys")),console.log(s.white("2. Configure it: rapidkit config set-api-key")),console.log(s.gray(`
|
|
99
99
|
OR set environment variable:`)),console.log(s.white(` export OPENAI_API_KEY="sk-proj-..."
|
|
100
100
|
`)),process.exit(1)),co(o);let r=await uo(true);r&&(console.log(s.green("\u2705 Ready to use AI recommendations!")),console.log(s.cyan(`Try: rapidkit ai recommend "authentication"
|
|
101
|
-
`))),process.exit(r?0:1);}catch(o){let r=
|
|
101
|
+
`))),process.exit(r?0:1);}catch(o){let r=rr(o);f.error("Failed to generate embeddings:",r.message),process.exit(1);}}),e.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let o=Mt();o||(console.log(s.red(`
|
|
102
102
|
\u274C OpenAI API key not configured
|
|
103
103
|
`)),console.log(s.white(`Set your API key: rapidkit config set-api-key
|
|
104
|
-
`)),process.exit(1)),co(o);let r=await
|
|
105
|
-
`,"utf-8");}function
|
|
104
|
+
`)),process.exit(1)),co(o);let r=await gs();process.exit(r?0:1);}catch(o){let r=rr(o);f.error("Failed to update embeddings:",r.message),process.exit(1);}});}var Pa="rapidkit.product-factory-plan.v1",ba="rapidkit.private-product-manifest.v1";function Nt(t,e=""){return typeof t=="string"&&t.trim()?t.trim():e}function nr(t){return typeof t=="string"&&t.trim()?t.trim():null}function ja(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function ws(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function vs(t){if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(t))throw new Error(`Invalid product slug "${t}". Use lowercase letters, numbers, and hyphens.`)}function xa(t,e,o){let r=Nt(t.slug);if(!r)throw new Error(`Backlog product at index ${e} is missing slug.`);vs(r);let n=ws(t.modules),i=ws(t.moduleGaps);return {rank:ja(t.rank,e+1),slug:r,title:Nt(t.title,r),category:Nt(t.category,"Uncategorized"),tier:Nt(t.tier,"pro"),summary:Nt(t.summary),modules:n,moduleGaps:i,recommendedKit:o,workspaceProfile:"enterprise",readiness:{status:i.length>0?"blocked-by-module-gaps":"ready-for-private-manifest",blockingGaps:i}}}function Ca(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Backlog must be a JSON object.");return t}async function Sa(t){let e=w.resolve(process.cwd(),t),o=Ca(await R__default.readJson(e));if(!Array.isArray(o.products))throw new Error("Backlog must contain a products array.");return {absolutePath:e,payload:o}}function Ra(t,e){let o=[...t];if(e.tier){let r=e.tier.toLowerCase();o=o.filter(n=>n.tier.toLowerCase()===r);}if(e.category){let r=e.category.toLowerCase();o=o.filter(n=>n.category.toLowerCase()===r);}if(e.limit){let r=Number.parseInt(e.limit,10);if(!Number.isInteger(r)||r<1)throw new Error("--limit must be a positive integer.");o=o.slice(0,r);}return o}async function Ps(t){let e=t.kit?.trim()||"fastapi.standard",{absolutePath:o,payload:r}=await Sa(t.backlogPath),n=r.products,i=n.map((m,p)=>xa(m,p,e)),a=Ra(i,t),c=new Set(a.flatMap(m=>m.modules)),l=a.flatMap(m=>m.moduleGaps),g=a.filter(m=>m.readiness.status==="ready-for-private-manifest").length;return {schemaVersion:Pa,generatedAt:(t.now??new Date).toISOString(),source:{backlogPath:o,backlogSchemaVersion:nr(r.schemaVersion),purpose:nr(r.purpose),publicationRule:nr(r.publicationRule)},defaults:{kit:e,workspaceProfile:"enterprise",projectSlug:"api"},stats:{totalProducts:n.length,plannedProducts:a.length,readyProducts:g,blockedProducts:a.length-g,uniqueModules:c.size,knownModuleGaps:l.length},products:a}}function wt(t){return JSON.stringify(t,null,2)}function Ea(t){return `sha256:${sr.createHash("sha256").update(wt(t)).digest("hex")}`}async function _a(t){let e=await Ps({backlogPath:t.backlogPath,kit:t.kit,now:t.now}),o=e.products.find(i=>i.slug===t.slug);if(!o)throw new Error(`Product "${t.slug}" was not found in backlog.`);let r=t.outputRoot||"../rapidkit-examples-pro",n={schemaVersion:ba,generatedAt:e.generatedAt,product:{rank:o.rank,slug:o.slug,title:o.title,category:o.category,tier:o.tier,summary:o.summary},workspace:{name:o.slug,profile:"enterprise",outputHint:w.join(r,o.slug)},projects:[{slug:"api",kit:o.recommendedKit,runtime:"python",framework:"fastapi",modules:o.modules,moduleGaps:o.moduleGaps}],factory:{sourceBacklogPath:e.source.backlogPath,manifestChecksum:"",requiredCommands:[`npx rapidkit create workspace ${o.slug} --yes --profile enterprise`,`npx rapidkit create project ${o.recommendedKit} api --yes --skip-install`,"npx rapidkit init","npx rapidkit workspace run test --strict --json","npx rapidkit readiness --strict --json"],releaseEvidencePath:`.rapidkit/product-factory/${o.slug}/release-evidence.json`}};return {...n,factory:{...n.factory,manifestChecksum:Ea({...n,factory:{...n.factory,manifestChecksum:""}})}}}async function ks(t,e,o=false){let r=w.resolve(process.cwd(),t);if(!o&&await R__default.pathExists(r))throw new Error(`Refusing to overwrite existing file: ${r}. Use --force.`);await R__default.ensureDir(w.dirname(r)),await R__default.writeFile(r,`${wt(e)}
|
|
105
|
+
`,"utf-8");}function Aa(t,e){let o=w.join(".rapidkit","product-factory","manifests",`${e}.manifest.json`);return t?t.endsWith(".json")?t:w.join(t,`${e}.manifest.json`):o}function Ia(t,e){console.log(s.bold(`
|
|
106
106
|
RapidKit Product Factory Plan
|
|
107
107
|
`)),console.log(s.cyan("Products:"),s.white(String(t.stats.plannedProducts))),console.log(s.cyan("Ready:"),s.green(String(t.stats.readyProducts))),console.log(s.cyan("Blocked:"),s.yellow(String(t.stats.blockedProducts))),console.log(s.cyan("Unique modules:"),s.white(String(t.stats.uniqueModules))),console.log(s.cyan("Known gaps:"),s.yellow(String(t.stats.knownModuleGaps))),e&&console.log(s.gray(`
|
|
108
108
|
Wrote plan: ${w.resolve(process.cwd(),e)}`)),console.log(s.gray(`
|
|
109
109
|
Next: npx rapidkit product manifest create <slug> --from-backlog <file>
|
|
110
|
-
`));}function
|
|
110
|
+
`));}function $a(t,e){console.log(s.bold(`
|
|
111
111
|
RapidKit Private Product Manifest
|
|
112
112
|
`)),console.log(s.cyan("Product:"),s.white(t.product.slug)),console.log(s.cyan("Kit:"),s.white(t.projects[0].kit)),console.log(s.cyan("Modules:"),s.white(String(t.projects[0].modules.length))),console.log(s.cyan("Module gaps:"),s.yellow(String(t.projects[0].moduleGaps.length))),console.log(s.cyan("Checksum:"),s.white(t.factory.manifestChecksum)),console.log(s.gray(`
|
|
113
113
|
Wrote manifest: ${w.resolve(process.cwd(),e)}
|
|
114
|
-
`));}function
|
|
115
|
-
`,"utf-8"),o}async function fo(t,e,o){let r=await Ca(t);if(r.requireReasonForDestructiveOps&&!o.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(r.requireSafetySnapshotForDestructiveOps&&o.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(o.permanent&&!r.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return r}function ir(t=process.cwd()){let e=w.resolve(t),o=w.resolve(Wn.tmpdir());for(;;){if(e!==o&&(R__default.existsSync(w.join(e,".rapidkit-workspace"))||R__default.existsSync(w.join(e,".rapidkit","workspace.json"))))return e;let r=w.dirname(e);if(r===e)return null;e=r;}}function Ye(t){let e=t?w.resolve(t):ir(process.cwd());if(!e)throw new Error("Not inside a RapidKit workspace. Run from workspace root or pass --workspace.");if(!R__default.existsSync(w.join(e,".rapidkit-workspace"))&&!R__default.existsSync(w.join(e,".rapidkit","workspace.json")))throw new Error(`Workspace path is not a RapidKit workspace: ${e}`);return e}async function Ra(t){let e=await ja(w.join(t,".rapidkit","workspace.json")),o=e?.workspace_name??e?.name;return typeof o=="string"&&o.trim()?o.trim():w.basename(t)}function go(t){return w.join(t,".rapidkit","snapshots")}function Tt(t){return w.join(t,".rapidkit","archive","projects")}function ar(t){return w.join(t,"files")}function Ea(t){return w.join(Wn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${nr.randomBytes(4).toString("hex")}`)}function cr(t,e){let o=w.relative(t,e);if(!o)return true;let r=o.split(w.sep);return r[0]===".rapidkit"&&["snapshots","archive","audit"].includes(r[1]||"")?false:!r.some(n=>ba.has(n))}async function _a(t){return (await a$c(t,{descendIntoMatchedProjects:false})).map(o=>({name:w.basename(o),relativePath:w.relative(t,o)}))}async function Aa(t,e){let o=[];for(let r of Pa){let n=w.join(t,r);if(!await R__default.pathExists(n))continue;let i=w.join(e,r);await R__default.copy(n,i,{filter:a=>cr(t,a)}),o.push(r);}return o}async function Ia(t,e){await R__default.writeJson(w.join(t,"snapshot.json"),e,{spaces:2});}async function lr(t){let e=w.join(t,"snapshot.json"),o=await R__default.readJson(e);if(!o||typeof o!="object"||o.schema!==ps)throw new Error(`Invalid RapidKit workspace snapshot manifest: ${e}`);return o}async function $a(t){let e=0,o=0,r=[t];for(;r.length>0;){let n=r.shift();if(!n)continue;let i=[];try{i=await R__default.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){let c=w.join(n,a.name);if(a.isDirectory()){r.push(c);continue}if(a.isFile())try{let l=await R__default.stat(c);e+=1,o+=l.size;}catch{}}}return {files:e,bytes:o}}async function vt(t={}){let e=Ye(t.workspacePath),o=t.name?t.name:`snapshot-${kt()}`,r=sr(o),n=w.join(go(e),r),i=Ea(r);if(await R__default.pathExists(n))throw new Error(`Snapshot already exists: ${r}`);let a=ar(i);try{await R__default.ensureDir(a);let c=t.includeProjects?"full":"metadata",l=c==="full"?["."]:await Aa(e,a);c==="full"&&await R__default.copy(e,a,{filter:m=>cr(e,m)});let g={schema:ps,name:r,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await Ra(e),workspacePath:e,copiedPaths:l,projects:await _a(e)};return await Ia(i,g),await R__default.ensureDir(w.dirname(n)),await R__default.move(i,n,{overwrite:false}),await Je(e,{action:"snapshot.create",target:r,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:l,snapshotPath:n,projectCount:g.projects.length}}),{manifest:g,snapshotPath:n}}catch(c){throw await R__default.remove(i),await Je(e,{action:"snapshot.create",target:r,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function ms(t){let e=Ye(t.workspacePath),o=w.join(go(e),sr(t.name));if(!await R__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await lr(o),n=ar(o),i=await $a(n);return {manifest:r,snapshotPath:o,filesRoot:n,estimatedFileCount:i.files,estimatedBytes:i.bytes}}async function fs(t={}){let e=Ye(t.workspacePath),o=go(e);if(!await R__default.pathExists(o))return [];let r=await R__default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=w.join(o,i.name);try{n.push({...await lr(a),snapshotPath:a});}catch{}}return n.sort((i,a)=>a.createdAt.localeCompare(i.createdAt))}async function gs(t){let e=Ye(t.workspacePath),o=w.join(go(e),sr(t.name));if(!await R__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await lr(o),n=ar(o),i=r.mode==="full"?["."]:Array.from(new Set(r.copiedPaths.map(l=>l.startsWith(".rapidkit/")?".rapidkit":l)));if(t.dryRun)return await Je(e,{action:"snapshot.restore",target:r.name,status:"planned",reason:t.reason,details:{restoredPaths:i}}),{workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await fo(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let a;if(t.safetySnapshot!==false&&(a=(await vt({workspacePath:e,name:`pre-restore-${r.name}-${kt()}`,reason:`Automatic safety snapshot before restoring ${r.name}`,includeProjects:false})).snapshotPath),r.mode==="full")await R__default.copy(n,e,{overwrite:true,errorOnExist:false,filter:l=>cr(n,l)});else for(let l of r.copiedPaths)await R__default.copy(w.join(n,l),w.join(e,l),{overwrite:true,errorOnExist:false});let c={workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:false,safetySnapshotPath:a};return await Je(e,{action:"snapshot.restore",target:r.name,status:"succeeded",reason:t.reason,details:{restoredPaths:i,safetySnapshotPath:a}}),c}function hs(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function ys(t,e){let o=hs(e),r=w.isAbsolute(o)?w.resolve(o):w.resolve(t,o);if(r.startsWith(`${w.resolve(t)}${w.sep}`)&&await R__default.pathExists(r))return r;let i=(await a$c(t,{descendIntoMatchedProjects:false})).filter(a=>{let c=w.relative(t,a);return w.basename(a)===o||c===o});if(i.length===0)throw new Error(`Project not found in workspace: ${e}`);if(i.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return i[0]}async function dr(t){try{let{syncWorkspaceProjects:e}=await import('./workspace-L4ITCKMM.js');await e(t,true);}catch{}}function Ma(t,e){let o=nr.randomBytes(4).toString("hex");return w.join(Tt(t),`${e}-${kt()}-${o}`)}async function ws(t){let e=w.join(t,"rapidkit-archive.json"),o=await R__default.readJson(e);if(!o||typeof o!="object"||o.schema!==us)throw new Error(`Invalid RapidKit archive manifest: ${e}`);return o}async function pr(t={}){let e=Ye(t.workspacePath),o=Tt(e);if(!await R__default.pathExists(o))return [];let r=await R__default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=w.join(o,i.name),c=w.join(a,"rapidkit-archive.json");try{n.push({...await ws(a),archivePath:a,manifestPath:c});}catch{}}return n.sort((i,a)=>a.archivedAt.localeCompare(i.archivedAt))}async function Na(t,e){let o=hs(e),r=w.isAbsolute(o)?w.resolve(o):w.resolve(Tt(t),o);if(r.startsWith(`${w.resolve(Tt(t))}${w.sep}`)&&await R__default.pathExists(w.join(r,"rapidkit-archive.json")))return r;let i=(await pr({workspacePath:t})).filter(a=>w.basename(a.archivePath)===o||a.projectName===o||w.relative(Tt(t),a.archivePath)===o);if(i.length===0)throw new Error(`Archived project not found: ${e}`);if(i.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return i[0].archivePath}async function ur(t){let e=Ye(t.workspacePath),o=await ys(e,t.project),r=w.basename(o),n=Ma(e,r),i=w.join(n,"rapidkit-archive.json");if(t.dryRun)return await Je(e,{action:"project.archive",target:r,status:"planned",reason:t.reason,details:{projectPath:o,archivePath:n}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,dryRun:true};await fo(e,"project.archive",{reason:t.reason,safetySnapshot:true});let a=await vt({workspacePath:e,name:`pre-archive-${r}-${kt()}`,reason:t.reason||`Automatic safety snapshot before archiving ${r}`,includeProjects:false});await R__default.ensureDir(w.dirname(n)),await R__default.move(o,n,{overwrite:false});let c={schema:us,projectName:r,originalPath:o,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:a.snapshotPath};return await R__default.writeJson(i,c,{spaces:2}),await c$3(e,[o]),await dr(e),await Je(e,{action:"project.archive",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath,dryRun:false}}async function ks(t){if(!t.permanent)return ur(t);let e=Ye(t.workspacePath),o=await ys(e,t.project),r=w.basename(o);if(t.confirm!==r)throw new Error(`Permanent delete requires --confirm ${r}`);if(t.dryRun)return await Je(e,{action:"project.delete",target:r,status:"planned",reason:t.reason,details:{projectPath:o,permanent:true}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",dryRun:true};await fo(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await vt({workspacePath:e,name:`pre-delete-${r}-${kt()}`,reason:t.reason||`Automatic safety snapshot before deleting ${r}`,includeProjects:false});return await R__default.remove(o),await c$3(e,[o]),await dr(e),await Je(e,{action:"project.delete",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function vs(t){let e=Ye(t.workspacePath),o=await Na(e,t.archive),r=await ws(o),n=t.targetName?.trim()||r.projectName,i=w.join(e,n);if(!i.startsWith(`${w.resolve(e)}${w.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await R__default.pathExists(i)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${i}`);if(t.dryRun)return await Je(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:o,projectPath:i}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:w.join(o,"rapidkit-archive.json"),dryRun:true};await fo(e,"project.restore",{reason:t.reason,safetySnapshot:true});let a=await vt({workspacePath:e,name:`pre-restore-project-${n}-${kt()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false});return await R__default.move(o,i,{overwrite:t.force===true}),await dr(e),await Je(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:o,projectPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:w.join(i,"rapidkit-archive.json"),safetySnapshotPath:a.snapshotPath,dryRun:false}}var Da="rapidkit.infra-stack.v1",bs="rapidkit.infra-plan.v1",Pt=".rapidkit/infra/docker-compose.yml",bt=".rapidkit/reports/infra-plan.json",gr=".rapidkit/infra/.env.example";function Ta(){let t=w.dirname(fileURLToPath(import.meta.url)),e=[w.join(t,"../../contracts/infra-stack.v1.json"),w.join(t,"../contracts/infra-stack.v1.json")];for(let o of e)if(b$3.existsSync(o))return o;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var fr=null;function it(t){if(fr)return fr;let e=Ta(),o=b$3.readFileSync(e,"utf-8"),r=JSON.parse(o);if(r.schemaVersion!==Da)throw new Error(`Unsupported infra stack schema: ${r.schemaVersion}`);return Wa(r),(fr=r),r}function Wa(t){let e=new Set(Object.keys(t.services));for(let[o,r]of Object.entries(t.moduleMappings)){if(!Array.isArray(r))throw new Error(`Invalid moduleMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`moduleMappings/${o} references unknown service '${n}'`)}for(let[o,r]of Object.entries(t.envVarMappings)){if(!Array.isArray(r))throw new Error(`Invalid envVarMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`envVarMappings/${o} references unknown service '${n}'`)}}function js(t,e){let o=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[o]||[]}function jt(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function xs(t,e){let o={};for(let r of e){let n=t.services[r];n&&Object.assign(o,n.connectionEnv);}return o}async function Fa(t){let e=w.join(t,"registry.json");if(!await R__default.pathExists(e))return [];try{let r=(await R__default.readJson(e)).installed_modules||[];return [...new Set(r.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function La(t){let e=w.join(t,".env.example");if(!await R__default.pathExists(e))return [];try{let o=await R__default.readFile(e,"utf-8"),r=[];for(let n of o.split(`
|
|
116
|
-
`)){let i=n.trim();if(!i||i.startsWith("#"))continue;let a=i.match(/^([A-Z0-9_]+)=/);a?.[1]&&r.push(a[1]);}return r}catch{return []}}async function
|
|
117
|
-
`)){let n=
|
|
118
|
-
`)?JSON.stringify(t):t}function
|
|
119
|
-
`)}function
|
|
120
|
-
`)}function
|
|
121
|
-
`);e.push("services:");for(let r of t.plan.services){let n=t.contract.services[r.id];if(n){if(e.push(` ${r.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: rapidkit-${r.id}`),n.command?.length){let i=n.command.map(a=>JSON.stringify(a)).join(", ");e.push(` command: [${i}]`);}if(n.env&&Object.keys(n.env).length>0){e.push(" environment:");let i={...n.env,...t.plan.serviceEnvOverrides?.[r.id]||{}};e.push(
|
|
122
|
-
`)}function
|
|
114
|
+
`));}function bs(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(o,r)=>{try{let n=await Ps({backlogPath:o,kit:r.kit,tier:r.tier,category:r.category,limit:r.limit});r.output&&await ks(r.output,n,true),r.json?console.log(wt(n)):Ia(n,r.output);}catch(n){let i=n instanceof Error?n.message:String(n);r.json?console.log(wt({ok:false,error:{message:i}})):console.error(s.red(`Product plan failed: ${i}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(o,r)=>{try{vs(o);let n=await _a({backlogPath:r.fromBacklog,slug:o,kit:r.kit,outputRoot:r.workspaceOutput}),i=Aa(r.output,o);await ks(i,n,r.force===true),r.json?console.log(wt(n)):$a(n,i);}catch(n){let i=n instanceof Error?n.message:String(n);r.json?console.log(wt({ok:false,error:{message:i}})):console.error(s.red(`Product manifest create failed: ${i}`)),process.exit(1);}});}var xs="rapidkit-workspace-snapshot-v1",Cs="rapidkit-project-archive-v1",Ma=[".rapidkit/workspace.json",".rapidkit-workspace","rapidkit.config.json","rapidkit.config.js","rapidkit.config.cjs","rapidkit.config.mjs","package.json"],Oa=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),Dt={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function kt(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function ir(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!e)throw new Error("Snapshot name must contain at least one letter or number.");return e.slice(0,120)}async function Na(t){try{let e=await R__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Da(t,e){if(!t)return e;let o=t.trim().toLowerCase();return ["true","yes","1","on"].includes(o)?true:["false","no","0","off"].includes(o)?false:e}async function Ta(t){let e=w.join(t,".rapidkit","policies.yml");if(!await R__default.pathExists(e))return {...Dt};try{let o=await R__default.readFile(e,"utf-8"),r=(n,i)=>{let a=o.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return Da(a?.[1],i)};return {requireReasonForDestructiveOps:r("require_reason_for_destructive_ops",Dt.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:r("require_safety_snapshot_for_destructive_ops",Dt.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:r("allow_permanent_delete",Dt.allowPermanentDelete)}}catch{return {...Dt}}}function Wa(t){return w.join(t,".rapidkit","audit","events.jsonl")}async function Je(t,e){let o={schema:"rapidkit-workspace-audit-event-v1",id:sr.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},r=Wa(t);return await R__default.ensureDir(w.dirname(r)),await R__default.appendFile(r,`${JSON.stringify(o)}
|
|
115
|
+
`,"utf-8"),o}async function fo(t,e,o){let r=await Ta(t);if(r.requireReasonForDestructiveOps&&!o.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(r.requireSafetySnapshotForDestructiveOps&&o.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(o.permanent&&!r.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return r}function ar(t=process.cwd()){let e=w.resolve(t),o=w.resolve(Qn.tmpdir());for(;;){if(e!==o&&(R__default.existsSync(w.join(e,".rapidkit-workspace"))||R__default.existsSync(w.join(e,".rapidkit","workspace.json"))))return e;let r=w.dirname(e);if(r===e)return null;e=r;}}function Ye(t){let e=t?w.resolve(t):ar(process.cwd());if(!e)throw new Error("Not inside a RapidKit workspace. Run from workspace root or pass --workspace.");if(!R__default.existsSync(w.join(e,".rapidkit-workspace"))&&!R__default.existsSync(w.join(e,".rapidkit","workspace.json")))throw new Error(`Workspace path is not a RapidKit workspace: ${e}`);return e}async function Fa(t){let e=await Na(w.join(t,".rapidkit","workspace.json")),o=e?.workspace_name??e?.name;return typeof o=="string"&&o.trim()?o.trim():w.basename(t)}function go(t){return w.join(t,".rapidkit","snapshots")}function Tt(t){return w.join(t,".rapidkit","archive","projects")}function cr(t){return w.join(t,"files")}function La(t){return w.join(Qn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${sr.randomBytes(4).toString("hex")}`)}function lr(t,e){let o=w.relative(t,e);if(!o)return true;let r=o.split(w.sep);return r[0]===".rapidkit"&&["snapshots","archive","audit"].includes(r[1]||"")?false:!r.some(n=>Oa.has(n))}async function Ja(t){return (await a$b(t,{descendIntoMatchedProjects:false})).map(o=>({name:w.basename(o),relativePath:w.relative(t,o)}))}async function Ka(t,e){let o=[];for(let r of Ma){let n=w.join(t,r);if(!await R__default.pathExists(n))continue;let i=w.join(e,r);await R__default.copy(n,i,{filter:a=>lr(t,a)}),o.push(r);}return o}async function Ga(t,e){await R__default.writeJson(w.join(t,"snapshot.json"),e,{spaces:2});}async function dr(t){let e=w.join(t,"snapshot.json"),o=await R__default.readJson(e);if(!o||typeof o!="object"||o.schema!==xs)throw new Error(`Invalid RapidKit workspace snapshot manifest: ${e}`);return o}async function Va(t){let e=0,o=0,r=[t];for(;r.length>0;){let n=r.shift();if(!n)continue;let i=[];try{i=await R__default.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){let c=w.join(n,a.name);if(a.isDirectory()){r.push(c);continue}if(a.isFile())try{let l=await R__default.stat(c);e+=1,o+=l.size;}catch{}}}return {files:e,bytes:o}}async function vt(t={}){let e=Ye(t.workspacePath),o=t.name?t.name:`snapshot-${kt()}`,r=ir(o),n=w.join(go(e),r),i=La(r);if(await R__default.pathExists(n))throw new Error(`Snapshot already exists: ${r}`);let a=cr(i);try{await R__default.ensureDir(a);let c=t.includeProjects?"full":"metadata",l=c==="full"?["."]:await Ka(e,a);c==="full"&&await R__default.copy(e,a,{filter:m=>lr(e,m)});let g={schema:xs,name:r,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await Fa(e),workspacePath:e,copiedPaths:l,projects:await Ja(e)};return await Ga(i,g),await R__default.ensureDir(w.dirname(n)),await R__default.move(i,n,{overwrite:false}),await Je(e,{action:"snapshot.create",target:r,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:l,snapshotPath:n,projectCount:g.projects.length}}),{manifest:g,snapshotPath:n}}catch(c){throw await R__default.remove(i),await Je(e,{action:"snapshot.create",target:r,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function Ss(t){let e=Ye(t.workspacePath),o=w.join(go(e),ir(t.name));if(!await R__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await dr(o),n=cr(o),i=await Va(n);return {manifest:r,snapshotPath:o,filesRoot:n,estimatedFileCount:i.files,estimatedBytes:i.bytes}}async function Rs(t={}){let e=Ye(t.workspacePath),o=go(e);if(!await R__default.pathExists(o))return [];let r=await R__default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=w.join(o,i.name);try{n.push({...await dr(a),snapshotPath:a});}catch{}}return n.sort((i,a)=>a.createdAt.localeCompare(i.createdAt))}async function Es(t){let e=Ye(t.workspacePath),o=w.join(go(e),ir(t.name));if(!await R__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await dr(o),n=cr(o),i=r.mode==="full"?["."]:Array.from(new Set(r.copiedPaths.map(l=>l.startsWith(".rapidkit/")?".rapidkit":l)));if(t.dryRun)return await Je(e,{action:"snapshot.restore",target:r.name,status:"planned",reason:t.reason,details:{restoredPaths:i}}),{workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await fo(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let a;if(t.safetySnapshot!==false&&(a=(await vt({workspacePath:e,name:`pre-restore-${r.name}-${kt()}`,reason:`Automatic safety snapshot before restoring ${r.name}`,includeProjects:false})).snapshotPath),r.mode==="full")await R__default.copy(n,e,{overwrite:true,errorOnExist:false,filter:l=>lr(n,l)});else for(let l of r.copiedPaths)await R__default.copy(w.join(n,l),w.join(e,l),{overwrite:true,errorOnExist:false});let c={workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:false,safetySnapshotPath:a};return await Je(e,{action:"snapshot.restore",target:r.name,status:"succeeded",reason:t.reason,details:{restoredPaths:i,safetySnapshotPath:a}}),c}function _s(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function As(t,e){let o=_s(e),r=w.isAbsolute(o)?w.resolve(o):w.resolve(t,o);if(r.startsWith(`${w.resolve(t)}${w.sep}`)&&await R__default.pathExists(r))return r;let i=(await a$b(t,{descendIntoMatchedProjects:false})).filter(a=>{let c=w.relative(t,a);return w.basename(a)===o||c===o});if(i.length===0)throw new Error(`Project not found in workspace: ${e}`);if(i.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return i[0]}async function pr(t){try{let{syncWorkspaceProjects:e}=await import('./workspace-FDMJD5XI.js');await e(t,true);}catch{}}function Ba(t,e){let o=sr.randomBytes(4).toString("hex");return w.join(Tt(t),`${e}-${kt()}-${o}`)}async function Is(t){let e=w.join(t,"rapidkit-archive.json"),o=await R__default.readJson(e);if(!o||typeof o!="object"||o.schema!==Cs)throw new Error(`Invalid RapidKit archive manifest: ${e}`);return o}async function ur(t={}){let e=Ye(t.workspacePath),o=Tt(e);if(!await R__default.pathExists(o))return [];let r=await R__default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=w.join(o,i.name),c=w.join(a,"rapidkit-archive.json");try{n.push({...await Is(a),archivePath:a,manifestPath:c});}catch{}}return n.sort((i,a)=>a.archivedAt.localeCompare(i.archivedAt))}async function Ua(t,e){let o=_s(e),r=w.isAbsolute(o)?w.resolve(o):w.resolve(Tt(t),o);if(r.startsWith(`${w.resolve(Tt(t))}${w.sep}`)&&await R__default.pathExists(w.join(r,"rapidkit-archive.json")))return r;let i=(await ur({workspacePath:t})).filter(a=>w.basename(a.archivePath)===o||a.projectName===o||w.relative(Tt(t),a.archivePath)===o);if(i.length===0)throw new Error(`Archived project not found: ${e}`);if(i.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return i[0].archivePath}async function mr(t){let e=Ye(t.workspacePath),o=await As(e,t.project),r=w.basename(o),n=Ba(e,r),i=w.join(n,"rapidkit-archive.json");if(t.dryRun)return await Je(e,{action:"project.archive",target:r,status:"planned",reason:t.reason,details:{projectPath:o,archivePath:n}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,dryRun:true};await fo(e,"project.archive",{reason:t.reason,safetySnapshot:true});let a=await vt({workspacePath:e,name:`pre-archive-${r}-${kt()}`,reason:t.reason||`Automatic safety snapshot before archiving ${r}`,includeProjects:false});await R__default.ensureDir(w.dirname(n)),await R__default.move(o,n,{overwrite:false});let c={schema:Cs,projectName:r,originalPath:o,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:a.snapshotPath};return await R__default.writeJson(i,c,{spaces:2}),await c$3(e,[o]),await pr(e),await Je(e,{action:"project.archive",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath,dryRun:false}}async function $s(t){if(!t.permanent)return mr(t);let e=Ye(t.workspacePath),o=await As(e,t.project),r=w.basename(o);if(t.confirm!==r)throw new Error(`Permanent delete requires --confirm ${r}`);if(t.dryRun)return await Je(e,{action:"project.delete",target:r,status:"planned",reason:t.reason,details:{projectPath:o,permanent:true}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",dryRun:true};await fo(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await vt({workspacePath:e,name:`pre-delete-${r}-${kt()}`,reason:t.reason||`Automatic safety snapshot before deleting ${r}`,includeProjects:false});return await R__default.remove(o),await c$3(e,[o]),await pr(e),await Je(e,{action:"project.delete",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function Ms(t){let e=Ye(t.workspacePath),o=await Ua(e,t.archive),r=await Is(o),n=t.targetName?.trim()||r.projectName,i=w.join(e,n);if(!i.startsWith(`${w.resolve(e)}${w.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await R__default.pathExists(i)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${i}`);if(t.dryRun)return await Je(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:o,projectPath:i}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:w.join(o,"rapidkit-archive.json"),dryRun:true};await fo(e,"project.restore",{reason:t.reason,safetySnapshot:true});let a=await vt({workspacePath:e,name:`pre-restore-project-${n}-${kt()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false});return await R__default.move(o,i,{overwrite:t.force===true}),await pr(e),await Je(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:o,projectPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:w.join(i,"rapidkit-archive.json"),safetySnapshotPath:a.snapshotPath,dryRun:false}}var qa="rapidkit.infra-stack.v1",Ns="rapidkit.infra-plan.v1",Pt=".rapidkit/infra/docker-compose.yml",bt=".rapidkit/reports/infra-plan.json",hr=".rapidkit/infra/.env.example";function za(){let t=w.dirname(fileURLToPath(import.meta.url)),e=[w.join(t,"../../contracts/infra-stack.v1.json"),w.join(t,"../contracts/infra-stack.v1.json")];for(let o of e)if(b$3.existsSync(o))return o;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var gr=null;function it(t){if(gr)return gr;let e=za(),o=b$3.readFileSync(e,"utf-8"),r=JSON.parse(o);if(r.schemaVersion!==qa)throw new Error(`Unsupported infra stack schema: ${r.schemaVersion}`);return Ya(r),(gr=r),r}function Ya(t){let e=new Set(Object.keys(t.services));for(let[o,r]of Object.entries(t.moduleMappings)){if(!Array.isArray(r))throw new Error(`Invalid moduleMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`moduleMappings/${o} references unknown service '${n}'`)}for(let[o,r]of Object.entries(t.envVarMappings)){if(!Array.isArray(r))throw new Error(`Invalid envVarMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`envVarMappings/${o} references unknown service '${n}'`)}}function Ds(t,e){let o=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[o]||[]}function jt(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Ts(t,e){let o={};for(let r of e){let n=t.services[r];n&&Object.assign(o,n.connectionEnv);}return o}async function Qa(t){let e=w.join(t,"registry.json");if(!await R__default.pathExists(e))return [];try{let r=(await R__default.readJson(e)).installed_modules||[];return [...new Set(r.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function Xa(t){let e=w.join(t,".env.example");if(!await R__default.pathExists(e))return [];try{let o=await R__default.readFile(e,"utf-8"),r=[];for(let n of o.split(`
|
|
116
|
+
`)){let i=n.trim();if(!i||i.startsWith("#"))continue;let a=i.match(/^([A-Z0-9_]+)=/);a?.[1]&&r.push(a[1]);}return r}catch{return []}}async function Za(t){let e=w.join(t,".rapidkit","infra","overrides.json");if(!await R__default.pathExists(e))return [];try{let o=await R__default.readJson(e);return Array.isArray(o.services)?[...new Set(o.services.filter(r=>typeof r=="string"&&r.trim().length>0))]:[]}catch{return []}}async function ec(t){let e=w.join(t,".rapidkit","workspace.contract.json");if(!await R__default.pathExists(e))return [];try{let o=await R__default.readJson(e),r=[];for(let n of o.projects||[]){let i=typeof n.slug=="string"?n.slug:"unknown";for(let a of n.contracts?.env||[])typeof a=="string"&&a.trim()&&r.push({project:i,env:a.trim().toUpperCase()});}return r}catch{return []}}function ho(t,e,o,r){t.add(o),e.push(r);}async function Ws(t){let e=w.resolve(t.workspacePath),o=t.contract||it(),r=new Set,n=[],i=new Set,a=new Set,c=new Set,l=await f$7(e);for(let g of l){let m=w.dirname(w.dirname(g)),p=w.basename(m);for(let d of await Qa(m)){i.add(d);for(let f of Ds(o,d))ho(r,n,f,{kind:"module",value:d,project:p});}for(let d of await Xa(m)){a.add(d);for(let f of jt(o,d))ho(r,n,f,{kind:"env-var",value:d,project:p});}}for(let g of await ec(e)){a.add(g.env);for(let m of jt(o,g.env))ho(r,n,m,{kind:"contract-env",value:g.env,project:g.project});}for(let g of await Za(e))c.add(g),ho(r,n,g,{kind:"override",value:g});return {modules:[...i].sort(),envVars:[...a].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...r].sort()}}function tc(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let o=e.indexOf("=");if(o<=0)return null;let r=e.slice(0,o).trim();if(!/^[A-Z0-9_]+$/.test(r))return null;let n=e.slice(o+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let i=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),a=(i?i[1]:n).trim();return a?{key:r,value:a}:null}async function oc(t){if(!await R__default.pathExists(t))return {};try{let e=await R__default.readFile(t,"utf-8"),o={};for(let r of e.split(`
|
|
117
|
+
`)){let n=tc(r);n&&(o[n.key]=n.value);}return o}catch{return {}}}async function Ls(t){let e={},o=await f$7(t.workspacePath);for(let r of o){let n=w.dirname(w.dirname(r)),i=await oc(w.join(n,".env.example"));for(let[a,c]of Object.entries(i))jt(t.contract,a).length>0&&(e[a]=c);}return e}function Js(t,e){return t.filter(o=>jt(e,o).length>0).sort()}function Ks(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let o=new URL(e),r=o.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(o.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(o.password||"postgres"),POSTGRES_DB:r||"postgres"}}catch{return}}function Gs(t){let e=t.POSTGRES_USER||"postgres",o=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${o}`]}function rc(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
|
|
118
|
+
`)?JSON.stringify(t):t}function Vs(t,e){return Object.entries(t).map(([o,r])=>`${e}${o}: ${rc(r)}`).join(`
|
|
119
|
+
`)}function nc(t,e){let o=t.test.map(r=>JSON.stringify(r)).join(", ");return [`${e}healthcheck:`,`${e} test: [${o}]`,`${e} interval: ${t.interval}`,`${e} timeout: ${t.timeout}`,`${e} retries: ${t.retries}`].join(`
|
|
120
|
+
`)}function Bs(t){let e=["# Generated by RapidKit infra plan \u2014 do not edit manually.",`# Workspace: ${t.workspaceName}`,`# Generated at: ${t.plan.generatedAt}`,"name: rapidkit-infra"],o=new Set;if(t.plan.services.length===0)return e.push("services: {}"),e.push(""),e.join(`
|
|
121
|
+
`);e.push("services:");for(let r of t.plan.services){let n=t.contract.services[r.id];if(n){if(e.push(` ${r.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: rapidkit-${r.id}`),n.command?.length){let i=n.command.map(a=>JSON.stringify(a)).join(", ");e.push(` command: [${i}]`);}if(n.env&&Object.keys(n.env).length>0){e.push(" environment:");let i={...n.env,...t.plan.serviceEnvOverrides?.[r.id]||{}};e.push(Vs(i," "));}else t.plan.serviceEnvOverrides?.[r.id]&&(e.push(" environment:"),e.push(Vs(t.plan.serviceEnvOverrides[r.id]," ")));if(n.ports.length>0){e.push(" ports:");for(let i of n.ports)e.push(` - "${i.host}:${i.container}"`);}if(n.volumes?.length){e.push(" volumes:");for(let i of n.volumes){e.push(` - ${i}`);let a=i.split(":")[0];a&&!a.startsWith("/")&&o.add(a);}}if(n.healthcheck){let i=t.plan.serviceEnvOverrides?.[r.id];if(r.id==="postgres"&&i){let a=Gs(i).map(c=>JSON.stringify(c)).join(", ");e.push(" healthcheck:"),e.push(` test: [${a}]`),e.push(` interval: ${n.healthcheck.interval}`),e.push(` timeout: ${n.healthcheck.timeout}`),e.push(` retries: ${n.healthcheck.retries}`);}else e.push(nc(n.healthcheck," "));}e.push(" restart: unless-stopped");}}if(o.size>0){e.push("volumes:");for(let r of [...o].sort())e.push(` ${r}:`),e.push(" driver: local");}return e.push(""),e.join(`
|
|
122
|
+
`)}function sc(t,e,o){return t.kind==="override"?t.value===e:t.kind==="module"?o.moduleMappings[t.value]?.includes(e)??false:o.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function ic(t){let e=new Map,o=[];for(let r of t)for(let n of r.ports){let i=e.get(n.host);i&&i!==r.id?o.push(`Port collision on host ${n.host} between services '${i}' and '${r.id}'`):e.set(n.host,r.id);}return o}async function ac(t){let e=w.join(t,".rapidkit","workspace.json");if(await R__default.pathExists(e))try{let o=await R__default.readJson(e);return o.workspace_name||o.name}catch{return}}async function wr(t){let e=w.resolve(t.workspacePath),o=it(),r=await Ws({workspacePath:e,contract:o}),n=r.serviceIds.map(d=>{let f=o.services[d];return f?{id:d,displayName:f.displayName,category:f.category,image:f.image,ports:f.ports,sources:r.sources.filter(u=>sc(u,d,o))}:null}).filter(d=>d!==null),i=ic(n);n.length===0&&i.push("No infrastructure services detected. Install modules with infra dependencies or add .rapidkit/infra/overrides.json");for(let d of r.overrides)o.services[d]||i.push(`Override references unknown service '${d}'`);let a=await R__default.pathExists(w.join(e,".rapidkit","workspace.contract.json"))?".rapidkit/workspace.contract.json":void 0,c=Ts(o,r.serviceIds),l=await Ls({workspacePath:e,contract:o}),g={...c,...l};l.RAPIDKIT_DB_POSTGRES_URL&&(g.DATABASE_URL=l.RAPIDKIT_DB_POSTGRES_URL);let m={},p=Ks(g);return p&&r.serviceIds.includes("postgres")&&(m.postgres=p),{schemaVersion:Ns,generatedAt:(t.now||(()=>new Date))().toISOString(),workspacePath:e,workspaceName:await ac(e),contractPath:a,strategy:"sidecar",composePath:Pt,envExamplePath:hr,services:n,connectionEnv:g,serviceEnvOverrides:Object.keys(m).length>0?m:void 0,sources:{modules:r.modules,envVars:r.envVars,overrides:r.overrides},warnings:i}}async function kr(t){let e=w.resolve(t.workspacePath),o=w.join(e,Pt),r=w.join(e,bt),n=w.join(e,hr),i=it(),a=Bs({plan:t.plan,contract:i,workspaceName:t.plan.workspaceName||w.basename(e)}),c=["# Generated by: npx rapidkit infra plan","# Copy values into project .env files as needed.",...Object.entries(t.plan.connectionEnv).map(([l,g])=>`${l}=${g}`),""].join(`
|
|
123
123
|
`);return t.dryRun?{composePath:o,planPath:r,envExamplePath:n}:(await R__default.ensureDir(w.dirname(o)),await R__default.ensureDir(w.dirname(r)),await R__default.writeFile(o,a,"utf-8"),await R__default.writeFile(r,`${JSON.stringify(t.plan,null,2)}
|
|
124
|
-
`,"utf-8"),await R__default.writeFile(n,c,"utf-8"),{composePath:o,planPath:r,envExamplePath:n})}function
|
|
124
|
+
`,"utf-8"),await R__default.writeFile(n,c,"utf-8"),{composePath:o,planPath:r,envExamplePath:n})}function cc(t){return w.resolve(t).split(w.sep).join("/")}async function Hs(){if((await execa("docker",["compose","version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker",prefixArgs:["compose"]};if((await execa("docker-compose",["version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker-compose",prefixArgs:[]};throw new Error("Docker Compose is not available. Install Docker Desktop or the docker-compose plugin, then verify with: docker compose version")}async function lc(){if((await execa("docker",["version"],{reject:false,timeout:5e3})).exitCode!==0)throw new Error("Docker is not available in PATH. Install Docker and ensure the daemon is running before using rapidkit infra.");await Hs();}function qs(t){let e=t.toLowerCase();return e.includes("no space left on device")?"Docker failed because the disk is full. Free space with: docker system prune -f (or docker system prune -a --volumes -f).":e.includes("address already in use")||e.includes("bind")?"Docker failed to bind a host port. Stop the conflicting service or adjust ports in contracts/infra-stack.v1.json via .rapidkit/infra/overrides.json.":e.includes("cannot connect to the docker daemon")?"Docker daemon is not running. Start Docker Desktop or the docker service, then retry.":null}async function zs(t){await lc();let e=await Hs(),o=cc(t.composePath),r=await execa(e.command,[...e.prefixArgs,"-f",o,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:r.exitCode??1,stdout:r.stdout,stderr:r.stderr}}function wo(t){let e=t?w.resolve(t):ar(process.cwd());if(!e)throw new Error("Not inside a RapidKit workspace. Run from workspace root or pass --workspace.");return a$a(e)}function dc(t){return w.join(t,Pt)}async function vr(t){let e=w.join(t,bt);if(!await R__default.pathExists(e))throw new Error(`Infra plan not found at ${bt}. Run: npx rapidkit infra plan`);return await R__default.readJson(e)}async function Pr(t){let e=dc(t.workspacePath);if(!await R__default.pathExists(e))throw new Error(`Compose file not found at ${Pt}. Run: npx rapidkit infra plan`);return zs({composePath:e,workspacePath:t.workspacePath,args:t.args})}function pc(t,e={}){if(console.log(s.bold(`
|
|
125
125
|
RapidKit infra plan
|
|
126
|
-
`)),console.log(s.gray(`Workspace: ${t.workspacePath}`)),t.workspaceName&&console.log(s.gray(`Name: ${t.workspaceName}`)),console.log(s.gray(`Strategy: ${t.strategy} (sidecar compose)`)),console.log(s.gray(`Compose: ${t.composePath}`)),console.log(s.gray(`Plan report: ${bt}`)),console.log(s.gray(`Env example: ${t.envExamplePath}`)),console.log(""),t.services.length===0)console.log(s.yellow("No infrastructure services detected."));else {console.log(s.bold("Services:"));for(let o of t.services){let r=o.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${o.id}`),s.gray(`(${o.displayName})`),r?s.white(`ports ${r}`):"");}}if(t.sources.modules.length>0&&(console.log(""),console.log(s.bold("Detected from modules:")),console.log(s.gray(` ${t.sources.modules.join(", ")}`))),t.sources.envVars.length>0){let o=it(),r=
|
|
126
|
+
`)),console.log(s.gray(`Workspace: ${t.workspacePath}`)),t.workspaceName&&console.log(s.gray(`Name: ${t.workspaceName}`)),console.log(s.gray(`Strategy: ${t.strategy} (sidecar compose)`)),console.log(s.gray(`Compose: ${t.composePath}`)),console.log(s.gray(`Plan report: ${bt}`)),console.log(s.gray(`Env example: ${t.envExamplePath}`)),console.log(""),t.services.length===0)console.log(s.yellow("No infrastructure services detected."));else {console.log(s.bold("Services:"));for(let o of t.services){let r=o.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${o.id}`),s.gray(`(${o.displayName})`),r?s.white(`ports ${r}`):"");}}if(t.sources.modules.length>0&&(console.log(""),console.log(s.bold("Detected from modules:")),console.log(s.gray(` ${t.sources.modules.join(", ")}`))),t.sources.envVars.length>0){let o=it(),r=Js(t.sources.envVars,o);console.log(s.bold("Detected from env vars (infra-mapped):")),r.length>0?console.log(s.gray(` ${r.join(", ")}`)):console.log(s.gray(" none"));let n=t.sources.envVars.length-r.length;if(n>0&&!e.verbose)console.log(s.gray(` (${n} other project env vars scanned \u2014 use --verbose to list all)`));else if(e.verbose){let i=t.sources.envVars.filter(a=>!r.includes(a));i.length>0&&console.log(s.gray(` Other scanned env vars: ${i.join(", ")}`));}}if(t.sources.overrides.length>0&&(console.log(s.bold("Overrides:")),console.log(s.gray(` ${t.sources.overrides.join(", ")}`))),Object.keys(t.connectionEnv).length>0){console.log(""),console.log(s.bold("Connection env (preview):"));for(let[o,r]of Object.entries(t.connectionEnv))console.log(s.gray(` ${o}=${r}`));}if(t.warnings.length>0){console.log(""),console.log(s.yellow("Warnings:"));for(let o of t.warnings)console.log(s.yellow(` - ${o}`));}console.log("");}function Ys(t){let e=t.command("infra").description("Plan and manage workspace infrastructure (Docker sidecar stack)");e.command("plan").description("Discover infra needs and generate compose plan artifacts").option("--workspace <path>","Workspace root path").option("--json","Print plan as JSON").option("--dry-run","Compute plan without writing artifacts").option("--verbose","Show all scanned project env vars").action(async o=>{try{let r=wo(o.workspace),n=await wr({workspacePath:r}),i=await kr({workspacePath:r,plan:n,dryRun:o.dryRun});if(o.json){console.log(JSON.stringify({...n,artifacts:o.dryRun?{composePath:i.composePath,planPath:i.planPath,envExamplePath:i.envExamplePath,dryRun:true}:{composePath:i.composePath,planPath:i.planPath,envExamplePath:i.envExamplePath}},null,2));return}pc(n,{verbose:o.verbose}),o.dryRun?console.log(s.yellow(`Dry run \u2014 no files written.
|
|
127
127
|
`)):(console.log(s.green("Artifacts written:")),console.log(s.gray(` ${i.composePath}`)),console.log(s.gray(` ${i.planPath}`)),console.log(s.gray(` ${i.envExamplePath}
|
|
128
128
|
`)));}catch(r){console.error(s.red(`
|
|
129
129
|
\u274C ${r instanceof Error?r.message:String(r)}
|
|
130
|
-
`)),process.exit(1);}}),e.command("up").description("Start planned infrastructure services via Docker Compose").option("--workspace <path>","Workspace root path").option("--detach","Run containers in background",true).option("--build","Build images before starting").option("--no-plan","Skip refreshing plan artifacts before starting").action(async o=>{try{let r=wo(o.workspace);if(o.plan!==false){let c=await
|
|
130
|
+
`)),process.exit(1);}}),e.command("up").description("Start planned infrastructure services via Docker Compose").option("--workspace <path>","Workspace root path").option("--detach","Run containers in background",true).option("--build","Build images before starting").option("--no-plan","Skip refreshing plan artifacts before starting").action(async o=>{try{let r=wo(o.workspace);if(o.plan!==false){let c=await wr({workspacePath:r});await kr({workspacePath:r,plan:c});}if((await vr(r)).services.length===0)throw new Error("Infra plan has no services. Run: npx rapidkit infra plan (from a workspace with .env.example, core modules, or .rapidkit/infra/overrides.json)");let i=["up"];o.detach!==false&&i.push("-d"),o.build&&i.push("--build");let a=await Pr({workspacePath:r,args:i});if(a.stdout&&process.stdout.write(a.stdout),a.stderr&&process.stderr.write(a.stderr),a.exitCode!==0){let c=qs(a.stderr);c&&console.error(s.yellow(`
|
|
131
131
|
\u26A0\uFE0F ${c}
|
|
132
132
|
`)),process.exit(a.exitCode);}o.detach!==false&&(console.log(s.green(`
|
|
133
133
|
\u2705 Infrastructure stack started.
|
|
134
134
|
`)),console.log(s.gray(`Check status: npx rapidkit infra status
|
|
135
135
|
`)));}catch(r){console.error(s.red(`
|
|
136
136
|
\u274C ${r instanceof Error?r.message:String(r)}
|
|
137
|
-
`)),process.exit(1);}}),e.command("down").description("Stop planned infrastructure services").option("--workspace <path>","Workspace root path").option("--volumes","Remove named volumes").action(async o=>{try{let r=wo(o.workspace);await
|
|
137
|
+
`)),process.exit(1);}}),e.command("down").description("Stop planned infrastructure services").option("--workspace <path>","Workspace root path").option("--volumes","Remove named volumes").action(async o=>{try{let r=wo(o.workspace);await vr(r);let n=["down"];o.volumes&&n.push("-v");let i=await Pr({workspacePath:r,args:n});i.stdout&&process.stdout.write(i.stdout),i.stderr&&process.stderr.write(i.stderr),i.exitCode!==0&&process.exit(i.exitCode),console.log(s.green(`
|
|
138
138
|
\u2705 Infrastructure stack stopped.
|
|
139
139
|
`));}catch(r){console.error(s.red(`
|
|
140
140
|
\u274C ${r instanceof Error?r.message:String(r)}
|
|
141
|
-
`)),process.exit(1);}}),e.command("status").description("Show Docker Compose status for planned infrastructure").option("--workspace <path>","Workspace root path").option("--json","Print docker compose ps JSON output").option("--strict","Exit non-zero when any container is not healthy/running").action(async o=>{try{let r=wo(o.workspace),n=await
|
|
141
|
+
`)),process.exit(1);}}),e.command("status").description("Show Docker Compose status for planned infrastructure").option("--workspace <path>","Workspace root path").option("--json","Print docker compose ps JSON output").option("--strict","Exit non-zero when any container is not healthy/running").action(async o=>{try{let r=wo(o.workspace),n=await vr(r),i=o.json?["ps","--format","json"]:["ps"],a=await Pr({workspacePath:r,args:i});if(o.json){a.stdout&&process.stdout.write(a.stdout),a.exitCode!==0&&process.exit(a.exitCode);return}console.log(s.bold(`
|
|
142
142
|
RapidKit infra status
|
|
143
143
|
`)),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Planned services: ${n.services.map(c=>c.id).join(", ")||"none"}`)),console.log(""),a.stdout.trim()?process.stdout.write(a.stdout):(console.log(s.yellow("No running containers found for the infra stack.")),console.log(s.gray(`Start with: npx rapidkit infra up
|
|
144
144
|
`))),a.exitCode!==0&&(a.stderr&&process.stderr.write(a.stderr),process.exit(a.exitCode)),o.strict&&/Restarting|Exit|unhealthy/i.test(a.stdout)&&(console.log(""),console.log(s.red("One or more infra containers are not healthy.")),console.log(s.gray(`Inspect logs with: docker logs rapidkit-postgres (or redis/mailpit)
|
|
145
145
|
`)),process.exit(1));}catch(r){console.error(s.red(`
|
|
146
146
|
\u274C ${r instanceof Error?r.message:String(r)}
|
|
147
|
-
`)),process.exit(1);}});}function
|
|
147
|
+
`)),process.exit(1);}});}function mc(t){try{let e=w.join(t,"Makefile");return b$3.existsSync(e)?b$3.readFileSync(e,"utf8"):""}catch{return ""}}function Ge(t,e){let o=mc(t);return o?new RegExp(`^${e}\\s*:`,"m").test(o):false}var vo=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureDotnetInstalled(e){return (await this.run("dotnet",["--version"],e)).exitCode===0?null:{exitCode:1,message:".NET SDK is not installed or not available on PATH. Install .NET 8+ from https://dotnet.microsoft.com/download and retry."}}findFilesBySuffix(e,o,r=3){let n=[],i=[{dir:e,depth:0}],a=new Set(["bin","obj",".git","node_modules",".rapidkit"]);for(;i.length>0;){let c=i.shift();if(!c||c.depth>r)continue;let l=[];try{l=b$3.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let g of l){let m=w.join(c.dir,g.name);if(g.isDirectory()){a.has(g.name)||i.push({dir:m,depth:c.depth+1});continue}g.name.toLowerCase().endsWith(o.toLowerCase())&&n.push(m);}}return n.sort()}findProjectFile(e){let o=this.findFilesBySuffix(e,".csproj");return o.find(r=>!r.toLowerCase().includes(".tests.csproj"))||o[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(r=>r.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let o=await this.ensureDotnetInstalled(e);return o||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=await this.run("dotnet",r?["restore",r]:["restore"],e);return n.exitCode===0?n:{exitCode:n.exitCode,message:"dotnet restore failed. Check NuGet connectivity, package references, and .NET SDK workload availability, then retry."}}async runDev(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=r?["watch","--project",r,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",r?["test",r]:["test"],e)}async runBuild(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["build",r,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["run","--project",r]:["run"],e)}async runLint(e){if(Ge(e,"lint"))return this.run("make",["lint"],e);let o=w.join(e,"Directory.Build.props");if(b$3.existsSync(o)&&b$3.readFileSync(o,"utf-8").includes("EnforceCodeStyleInBuild")){let r=await this.ensureDotnetInstalled(e);if(r)return r;let n=this.findProjectFile(e);return this.run("dotnet",n?["build",n,"-warnaserror"]:["build","-warnaserror"],e)}return {exitCode:1,message:"No .NET lint tooling detected. Add a Makefile lint target or enable EnforceCodeStyleInBuild in Directory.Build.props."}}async runFormat(e){if(Ge(e,"format"))return this.run("make",["format"],e);let o=await this.ensureDotnetInstalled(e);return o||(b$3.existsSync(w.join(e,".editorconfig"))?this.run("dotnet",["format","--verify-no-changes"],e):{exitCode:1,message:"No .NET format tooling detected. Add a Makefile format target or an .editorconfig file for dotnet format."})}async doctorHints(e){return ["Install .NET 8+ SDK and ensure dotnet is on PATH.","Run dotnet restore after changing package references.","Use dotnet format --verify-no-changes in CI for deterministic code style."]}};var Po=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureGoInstalled(e){return (await this.run("go",["version"],e)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findGoRunTarget(e){let o=w.join(e,"main.go");if(b$3.existsSync(o))return "./main.go";let r=w.join(e,"cmd");try{let n=b$3.readdirSync(r,{withFileTypes:true}).filter(i=>i.isDirectory()).map(i=>i.name).sort();for(let i of n)if(b$3.existsSync(w.join(r,i,"main.go")))return `./cmd/${i}`}catch{}return "./."}findWorkspaceRoot(e){let o=e;for(;;){if(b$3.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$3.existsSync(n))return "isolated";try{let c=b$3.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withGoCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","go"):w.join(e,".rapidkit","cache","go"),a=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=w.join(i,"mod"),process.env.GOCACHE=w.join(i,"build"),o().finally(()=>{typeof a>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=a,typeof c>"u"?delete process.env.GOCACHE:process.env.GOCACHE=c;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(e){return this.withGoCacheEnv(e,async()=>{try{return process.env.GOMODCACHE&&b$3.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&b$3.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let o=await this.ensureGoInstalled(e);if(o)return o;let r=w.join(e,"Makefile");return b$3.existsSync(r)?this.run("make",["run"],e):this.run("go",["run",this.findGoRunTarget(e)],e)})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let r=(a()?[w.join(e,"server.exe"),w.join(e,"server")]:[w.join(e,"server")]).find(i=>b$3.existsSync(i));if(r)return this.run(r,[],e);let n=await this.ensureGoInstalled(e);return n||this.run("go",["run",this.findGoRunTarget(e)],e)})}async runLint(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(Ge(e,"lint")?this.run("make",["lint"],e):b$3.existsSync(w.join(e,".golangci.yml"))||b$3.existsSync(w.join(e,".golangci.yaml"))?this.run("golangci-lint",["run","./..."],e):{exitCode:1,message:"No Go lint tooling detected. Add a Makefile lint target or .golangci.yml configuration."})})}async runFormat(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(Ge(e,"fmt")?this.run("make",["fmt"],e):Ge(e,"format")?this.run("make",["format"],e):this.run("go",["fmt","./..."],e))})}async doctorHints(e){return ["Install Go from https://go.dev/dl/ if missing.","Run go mod tidy when dependencies are out of sync.","Use make run for hot-reload if Makefile exists."]}};var bo=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return (b$3.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return b$3.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let o=process.env.JAVA_HOME?.trim();if(!o)return "java";let r=w.join(o,"bin",process.platform==="win32"?"java.exe":"java");return b$3.existsSync(r)?r:"java"}parseMajorJavaVersion(e){if(!e)return null;let r=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(r,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let o=w.join(e,"pom.xml");if(!b$3.existsSync(o))return 21;try{let n=b$3.readFileSync(o,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,o){try{let r=await execa(e,["-version"],{cwd:o,timeout:5e3,reject:false});if(r.exitCode!==0)return null;let n=`${r.stdout||""}
|
|
148
148
|
${r.stderr||""}`,i=n.match(/version\s+"([^"]+)"/i);if(i?.[1])return this.parseMajorJavaVersion(i[1]);let a=n.match(/(?:openjdk|java)\s+(\d+(?:[._]\d+)?)/i);return a?.[1]?this.parseMajorJavaVersion(a[1]):null}catch{return null}}parseMavenVersion(e){if(!e)return null;let o=e.match(/Apache Maven\s+(\d+)\.(\d+)\.(\d+)/i);return o?[Number.parseInt(o[1],10),Number.parseInt(o[2],10),Number.parseInt(o[3],10)]:null}isMavenVersionAtLeast(e,o){for(let r=0;r<3;r+=1){if(e[r]>o[r])return true;if(e[r]<o[r])return false}return true}async checkSystemMavenVersion(e){try{let o=await execa("mvn",["-version"],{cwd:e,timeout:5e3,reject:false});if(o.exitCode!==0)return {exitCode:o.exitCode||1,message:"Maven is required and must be available on PATH (3.9+)."};let r=this.parseMavenVersion(`${o.stdout||""}
|
|
149
|
-
${o.stderr||""}`);return r?this.isMavenVersionAtLeast(r,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${r.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let o=b$3.existsSync(w.join(e,"pom.xml")),r=b$3.existsSync(w.join(e,"mvnw"))||b$3.existsSync(w.join(e,"mvnw.cmd")),n=b$3.existsSync(w.join(e,"build.gradle"))||b$3.existsSync(w.join(e,"build.gradle.kts"))||b$3.existsSync(w.join(e,"settings.gradle"))||b$3.existsSync(w.join(e,"settings.gradle.kts")),i=b$3.existsSync(w.join(e,"gradlew"))||b$3.existsSync(w.join(e,"gradlew.bat"));return {hasMavenProject:o||r,hasMavenWrapper:r,hasGradleProject:n||i,hasGradleWrapper:i}}findWorkspaceRoot(e){let o=e;for(;;){if(b$3.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$3.existsSync(n))return "isolated";try{let c=b$3.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let o=w.join(e,"mvnw.cmd");if(process.platform==="win32"&&b$3.existsSync(o))return {command:o,baseArgs:[]};let r=w.join(e,"mvnw");return b$3.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let o=w.join(e,"gradlew.bat");if(process.platform==="win32"&&b$3.existsSync(o))return {command:o,baseArgs:[]};let r=w.join(e,"gradlew");return b$3.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let o=[],r=new Set,n=[e];for(;n.length>0;){let i=n.shift();if(!i||r.has(i))continue;r.add(i);let a=[];try{a=b$3.readdirSync(i,{withFileTypes:true});}catch{continue}for(let c of a){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let l=w.join(i,c.name),g=this.inspectJavaProject(l);(g.hasMavenProject||g.hasGradleProject)&&o.push(l),n.push(l);}}return o}withJavaCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","java","m2"):w.join(e,".rapidkit","cache","java","m2"),a=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","java","gradle"):w.join(e,".rapidkit","cache","java","gradle"),c=process.env.MAVEN_OPTS,l=process.env.GRADLE_USER_HOME,g=`-Dmaven.repo.local=${i}`;return process.env.MAVEN_OPTS=c?`${c} ${g}`:g,process.env.GRADLE_USER_HOME=a,o().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof l>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=l;})}async runBuildTool(e,o,r=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:i}=this.buildToolCommand(e),a=await this.runCommand(n,[...i,...o],e);if(a===0||!r)return {exitCode:a};let c=b$3.existsSync(w.join(e,"pom.xml")),l=b$3.existsSync(w.join(e,"build.gradle"))||b$3.existsSync(w.join(e,"build.gradle.kts"));return {exitCode:a,message:c||l?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let o=[w.join(e,"target"),w.join(e,"build","libs")];for(let r of o){if(!b$3.existsSync(r))continue;let i=b$3.readdirSync(r).filter(a=>a.toLowerCase().endsWith(".jar")).find(a=>!a.toLowerCase().endsWith("-sources.jar")&&!a.toLowerCase().endsWith("-javadoc.jar")&&!a.toLowerCase().endsWith("-plain.jar"));if(i)return w.join(r,i)}return null}commandArgsFor(e,o){if(e==="gradle"){let r=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return o==="init"?[...r,"dependencies"]:o==="dev"?[...r,"bootRun"]:o==="test"?[...r,"test"]:[...r,"bootJar"]}return o==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:o==="dev"?["spring-boot:run"]:o==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),o=this.resolveJavaCommand(e),r=await this.runCommand(o,["-version"],e);if(r!==0)return {exitCode:r,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),l=await this.detectInstalledJavaMajor(o,e);if(l!==null&&l<c)return {exitCode:1,message:`Detected Java ${l}, but project requires Java ${c}+.`};let g=w.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&b$3.existsSync(g))try{let p=b$3.readFileSync(g,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),d=this.parseMajorJavaVersion(p?.[1]);if(d!==null&&d<c)return {exitCode:1,message:`Detected JAVA_HOME version ${d}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),l=c==="gradle"?["--version"]:["-version"],g=await this.runBuildTool(e,l);return g.exitCode!==0?g:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):g}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let l=c.reduce((p,d)=>Math.max(p,this.readRequiredJavaMajor(d)),0);if(l>0){let p=await this.detectInstalledJavaMajor(o,e);if(p!==null&&p<l){let d=c.filter(u=>this.readRequiredJavaMajor(u)>p).map(u=>w.relative(e,u)).join(", ");return {exitCode:1,message:`Detected Java ${p}, but workspace project(s) [${d}] require Java ${l}+.`}}}let g=false,m=false;for(let p of c){let d=this.inspectJavaProject(p);d.hasMavenProject&&!d.hasMavenWrapper&&(g=true),d.hasGradleProject&&!d.hasGradleWrapper&&(m=true);}if(g){let p=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(p!==0)return {exitCode:p,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let d=await this.checkSystemMavenVersion(e);if(d.exitCode!==0)return d}if(m){let p=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(p!==0)return {exitCode:p,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(i===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return a===0?{exitCode:0}:{exitCode:i||a||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let o=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return o&&b$3.mkdirSync(o,{recursive:true}),process.env.GRADLE_USER_HOME&&b$3.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let o=this.resolveJarPath(e);if(o)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",o],e)};let r=await this.runBuild(e);if(r.exitCode!==0)return r;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(Ge(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let o=w.join(e,"pom.xml");return b$3.existsSync(o)&&b$3.readFileSync(o,"utf-8").includes("checkstyle")?this.runBuildTool(e,["checkstyle:check"]):{exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){return Ge(e,"format")?{exitCode:await this.runCommand("make",["format"],e)}:["build.gradle","build.gradle.kts"].map(r=>w.join(e,r)).filter(r=>b$3.existsSync(r)).some(r=>b$3.readFileSync(r,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure spotless in Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run rapidkit init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var jo=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}findWorkspaceRoot(e){let o=e;for(;;){if(b$3.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$3.existsSync(n))return "isolated";try{let c=b$3.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,o,r){let n=this.resolveDependencyMode(e),i=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=n==="isolated"?w.join(e,".rapidkit","cache","node"):w.join(i||e,".rapidkit","cache","node"),c=process.env.npm_config_cache,l=process.env.npm_config_store_dir,g=process.env.RAPIDKIT_DEP_SHARING_MODE,m=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,i&&(process.env.RAPIDKIT_WORKSPACE_PATH=i),o==="pnpm"?(process.env.npm_config_store_dir=w.join(a,"pnpm-store"),process.env.npm_config_cache=w.join(a,"pnpm-cache")):o==="yarn"?process.env.npm_config_cache=w.join(a,"yarn-cache"):process.env.npm_config_cache=w.join(a,"npm-cache"),r().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof l>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=l,typeof g>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=g,typeof m>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=m;})}detectPackageManager(e){if(b$3.existsSync(w.join(e,"package-lock.json")))return "npm";if(b$3.existsSync(w.join(e,"pnpm-lock.yaml")))return "pnpm";if(b$3.existsSync(w.join(e,"yarn.lock")))return "yarn";if(!this.commandAvailable("npm")){if(this.commandAvailable("pnpm"))return "pnpm";if(this.commandAvailable("yarn"))return "yarn"}return "npm"}hasPinnedPackageManager(e){return b$3.existsSync(w.join(e,"package-lock.json"))||b$3.existsSync(w.join(e,"pnpm-lock.yaml"))||b$3.existsSync(w.join(e,"yarn.lock"))}availablePackageManagers(e){let o=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[o]:[o,...["npm","pnpm","yarn"].filter(n=>n!==o&&this.commandAvailable(n))]}commandAvailable(e){return spawnSync(e,["--version"],{stdio:"ignore",shell:process.platform==="win32"}).status===0}scriptArgs(e,o){return e==="npm"?["run",o]:["run",o]}async runScriptWithFallback(e,o){let r={exitCode:1};for(let n of this.availablePackageManagers(e))if(r=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,o),e)),r.exitCode===0)return r;return r}async runLifecycle(e,o){let r=a$5(e),n=i$2(e,r),i=g$1(e,o,{framework:n.key});return i?this.runScriptWithFallback(e,i.scriptName):{exitCode:1,message:`No npm script available for \`${o}\`. Add a "${o}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let o=this.detectPackageManager(e);return this.withDependencyEnv(e,o,async()=>{try{return process.env.npm_config_cache&&b$3.mkdirSync(process.env.npm_config_cache,{recursive:true}),o==="pnpm"&&process.env.npm_config_store_dir&&b$3.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let o=this.detectPackageManager(e),r=this.resolveDependencyMode(e),n=r==="shared-runtime-caches"||r==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,o,()=>this.run(o,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var xo=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,o){return {exitCode:await this.withPythonCacheEnv(o,()=>this.runCore(e,o))}}findWorkspaceRoot(e){let o=e;for(;;){if(b$3.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$3.existsSync(n))return "isolated";try{let c=b$3.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","python"):w.join(e,".rapidkit","cache","python"),a=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=w.join(i,"pip"),process.env.POETRY_CACHE_DIR=w.join(i,"poetry"),o().finally(()=>{typeof a>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=a,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),o=await this.run(["doctor","check"],e);return o.exitCode===0?o:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx rapidkit doctor workspace" for a full workspace scan.','Use "npx rapidkit init" after adding or changing modules.','Use workspace launcher "./rapidkit" to avoid environment drift.']}};function rc(){let t={...process.env},e=t.PATH||"";if(e){let o=e.split(w.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(w.delimiter);t.PATH=o;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||c$6(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ve(t,e){return t==="go"?new Po((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="node"?new jo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="java"?new bo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="dotnet"?new vo((o,r,n)=>e.runCommandInCwd(o,r,n)):new xo((o,r)=>e.runCoreRapidkit(o,{cwd:r,env:rc()}))}var Js=w.join(Wn.homedir(),".rapidkit","cache"),Ks=1440*60*1e3;function Cr(){let t=process.env.RAPIDKIT_CACHE_DIR?.trim();if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?w.join(Js,`vitest-${e}`):Js}var So=class t{static instance;memoryCache=new Map;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getCacheKey(e){return createHash("md5").update(e).digest("hex")}getCachePath(e){return w.join(Cr(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let o=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${o}.tmp`}async get(e,o="1.0"){let r=this.memoryCache.get(e);if(r&&r.version===o&&Date.now()-r.timestamp<Ks)return f.debug(`Cache hit (memory): ${e}`),r.data;try{let n=this.getCachePath(e),i=await promises.readFile(n,"utf-8"),a=JSON.parse(i);if(a.version===o&&Date.now()-a.timestamp<Ks)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,a),a.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,o,r="1.0"){let n={data:o,timestamp:Date.now(),version:r};this.memoryCache.set(e,n);try{await promises.mkdir(Cr(),{recursive:true});let i=this.getCachePath(e),a=this.getTempCachePath(i);await promises.writeFile(a,JSON.stringify(n),"utf-8"),await promises.rename(a,i),f.debug(`Cache set: ${e}`);}catch(i){f.debug(`Cache write failed: ${e}`,i);}}async invalidate(e){this.memoryCache.delete(e);try{let o=this.getCachePath(e);await promises.unlink(o),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=Cr(),o=await promises.readdir(e);await Promise.all(o.map(r=>promises.unlink(w.join(e,r)))),f.debug("Cache cleared");}catch{}}};var Ro=["list","sync","registry","foundation","model","snapshot","diff","impact","verify","graph","watch","context","agent-sync","policy","contract","share","export","archive","hydrate","import","run","init"],Eo=["model","snapshot","diff","impact","verify","context","agent-sync"];function Gs(t){return Eo.includes(t)}var Vs="rapidkit-runtime-command-surface-v1";var ac=["catalog","pulse","nova","orbit","atlas","vertex","summit","beacon","ledger","flux","nexus","apex","harbor","forge","spark","portal","studio","canvas","quantum","vault","zenith","compass","vector","catalyst","saas","commerce","radar","stellar","prism","cedar","momentum","signal","cipher","lumen","trail","ridge"],cc={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},lc={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"};function dc(t){return t[Math.floor(Math.random()*t.length)]}function Sr(t){let e=dc(ac),o=k$1(t);if(o){let i=lc[o.id]??"app";return `${e}-${i}`}let r=p(t),n=r?cc[r.id]??"service":"app";return `${e}-${n}`}async function fc(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function Bs(t,e){await R.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
150
|
-
`,"utf-8");}function De(t,e){return w.isAbsolute(e)?e:w.join(t,e)}function
|
|
151
|
-
`,"utf-8"),n}function vc(t,e){if(!e?.enabled)return {headers:{}};let o=process.env[e.hmacKeyEnv];if(!o)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let r=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",i=createHmac(r,o).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:i,"x-rapidkit-evidence-signature-alg":r}}}async function Pc(t,e,o){let r=(o.algorithm||"sha256").toLowerCase(),n=De(t,o.publicKeyPath);if(!await R.pathExists(n))return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Public key not found: ${n}`};try{let i=await promises.readFile(n,"utf-8"),a=await promises.readFile(e),c=createVerify(r);c.update(a),c.end();let l=Buffer.from(o.signature,"base64"),g=c.verify(i,l),m=createHash("sha256").update(i).digest("hex");return {verified:g,algorithm:r,publicKeyPath:n,publicKeyFingerprint:m,signature:o.signature,message:g?"Attestation verified.":"Attestation signature verification failed."}}catch(i){return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Attestation verification error: ${i.message}`}}}async function bc(t,e,o,r){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};let i=o.signaturePath?De(t,o.signaturePath):null;if(!i||!await R.pathExists(i))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:i};let a=["verify-blob",e,"--signature",i],c=o.certificatePath?De(t,o.certificatePath):null;c&&a.push("--certificate",c);let l=o.bundlePath?De(t,o.bundlePath):null;l&&a.push("--bundle",l);let g=o.keyPath?De(t,o.keyPath):null;g&&a.push("--key",g),o.identity&&a.push("--certificate-identity",o.identity),o.issuer&&a.push("--certificate-oidc-issuer",o.issuer),o.rekorUrl&&a.push("--rekor-url",o.rekorUrl),r.requireTransparencyLog||a.push("--insecure-ignore-tlog");try{let m=await execa("cosign",a,{reject:false});return m.exitCode===0?{verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:i}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${m.stderr||m.stdout||"unknown error"}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:i}}catch(m){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${m.message}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:i}}}async function jc(t,e){let o=e.algorithm||"sha256",r=De(t,e.policyPath),n=De(t,e.signaturePath),i=De(t,e.publicKeyPath);if(!await R.pathExists(r))return {verified:false,message:`Governance policy bundle not found: ${r}`,policies:null};if(!await R.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await R.pathExists(i))return {verified:false,message:`Governance policy public key not found: ${i}`,policies:null};try{let a=await promises.readFile(r,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),l=await promises.readFile(i,"utf-8"),g=createVerify(o);return g.update(a),g.end(),g.verify(l,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(a).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(a){return {verified:false,message:`Governance policy bundle verification error: ${a.message}`,policies:null}}}async function Rr(t,e){let o=[],r={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=w.join(t,".rapidkit"),i=w.join(n,"mirror-config.json"),a=w.join(n,"mirror.lock"),c=w.join(n,"mirror","artifacts"),l=w.join(n,"reports"),g=await hc(t);if(!await R.pathExists(i))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .rapidkit/mirror-config.json not found."}),{checks:o,details:r};let m={};try{m=JSON.parse(await promises.readFile(i,"utf-8"));}catch{return o.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:o,details:r}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||m.mode==="offline-only"))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:o,details:r};await R.ensureDir(c);let d=Math.max(0,m.prefetch?.retries??2),u=Math.max(0,m.prefetch?.backoffMs??250),f=Math.max(1e3,m.prefetch?.timeoutMs??15e3),y=m.security?.requireAttestation===true,v=m.security?.requireSigstore===true,P=m.security?.requireTransparencyLog===true,k=m.security?.requireSignedGovernance===true,h=m.security?.evidenceExport,S=(process.env.RAPIDKIT_ENV||m.security?.governance?.environment||"dev").toLowerCase(),x=m.security?.governance?.policies||{};if(m.security?.governanceBundle){let N=await jc(t,m.security.governanceBundle);if(o.push({id:"governance.bundle.verify",status:N.verified?"passed":"failed",message:N.message}),N.verified&&N.policies)x=N.policies,r.governanceBundleVerified=true;else if(k)return {checks:o,details:r}}let I=x[S],Y=P||I?.requireTransparencyLog===true,H=[],ae=Array.isArray(m.artifacts)?m.artifacts:[],O=[];for(let N=0;N<ae.length;N+=1){let J=ae[N],C=J.id||`artifact-${N+1}`,ee=J.source?De(t,J.source):null,Re=gc(J,C),q=w.join(c,Re),Z=false,ke={sourceType:"path",source:ee||J.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(ee&&await R.pathExists(ee))await R.ensureDir(w.dirname(q)),await R.copyFile(ee,q),r.syncedArtifacts+=1,Z=true,ke={sourceType:"path",source:ee,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},o.push({id:`mirror.sync.${C}`,status:"passed",message:`Mirrored artifact ${C} from source path.`});else if(J.url){let _e="";try{_e=new URL(J.url).hostname.toLowerCase();}catch{o.push({id:`mirror.prefetch.${C}`,status:"failed",message:`Invalid URL for ${C}: ${J.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||g.has(_e))){o.push({id:`mirror.prefetch.trust.${C}`,status:"failed",message:`Untrusted mirror host for ${C}: ${_e}. Add host to .rapidkit/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await R.pathExists(q)?(Z=true,ke={sourceType:"url",source:J.url,host:_e,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},o.push({id:`mirror.prefetch.${C}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${C}.`})):o.push({id:`mirror.prefetch.${C}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${C} without an existing mirrored copy.`}),!Z))continue;if(!Z){let W=null,$e=0;for(let we=1;we<=d+1;we+=1){$e=we;try{await yc(J.url,q,f),r.syncedArtifacts+=1,Z=true,ke={sourceType:"url",source:J.url,host:_e,fetchedAt:new Date().toISOString(),attempts:$e,trusted:true},o.push({id:`mirror.prefetch.${C}`,status:"passed",message:$e>1?`Prefetched artifact ${C} from ${_e} after ${$e} attempts.`:`Prefetched artifact ${C} from ${_e}.`});break}catch(Fe){if(W=Fe,we<=d){await Us(u*we);continue}}}if(!Z){o.push({id:`mirror.prefetch.${C}`,status:"failed",message:`Failed to prefetch ${C} after ${d+1} attempt(s): ${W?.message||"unknown error"}`});continue}}if(!Z){o.push({id:`mirror.prefetch.${C}`,status:"failed",message:`Failed to prefetch ${C}.`});continue}}if(!Z){J.required||e.offlineMode?o.push({id:`mirror.sync.${C}`,status:"failed",message:`Mirror source missing for ${C}${ee?`: ${ee}`:""}`}):o.push({id:`mirror.sync.${C}`,status:"skipped",message:`Mirror source not found for optional artifact ${C}.`});continue}let Ee=await fc(q);if(J.sha256&&J.sha256.toLowerCase()!==Ee.toLowerCase()){o.push({id:`mirror.verify.${C}`,status:"failed",message:`Checksum mismatch for ${C}.`});continue}r.verifiedArtifacts+=1,o.push({id:`mirror.verify.${C}`,status:"passed",message:`Checksum verified for ${C}.`});let Pe=J.attestation?await Pc(t,q,J.attestation):null;if(J.attestation){if(o.push({id:`mirror.attest.${C}`,status:Pe?.verified?"passed":"failed",message:Pe?.message||"Attestation verification failed."}),!Pe?.verified)continue}else if(y){o.push({id:`mirror.attest.${C}`,status:"failed",message:`Attestation is required but missing for ${C}.`});continue}else o.push({id:`mirror.attest.${C}`,status:"skipped",message:`No attestation provided for ${C}.`});let xe=J.attestation?.sigstore,V=xe?await bc(t,q,xe,{requireTransparencyLog:Y}):null;if(xe){if(o.push({id:`mirror.sigstore.${C}`,status:V?.verified?"passed":"failed",message:V?.message||"Sigstore verification failed."}),H.push({artifactId:C,verified:!!V?.verified,tlogVerified:!!V?.tlogVerified,identity:V?.identity||null,issuer:V?.issuer||null,rekorUrl:V?.rekorUrl||null,timestamp:new Date().toISOString(),environment:S}),!V?.verified)continue}else if(v){o.push({id:`mirror.sigstore.${C}`,status:"failed",message:`Sigstore attestation is required but missing for ${C}.`});continue}else o.push({id:`mirror.sigstore.${C}`,status:"skipped",message:`No Sigstore attestation provided for ${C}.`});if(xe&&V?.verified&&I){let _e=I.allowedIdentities||[];if(_e.length>0){let W=!!V.identity&&_e.includes(V.identity);if(o.push({id:`mirror.sigstore.policy.identity.${C}`,status:W?"passed":"failed",message:W?`Sigstore identity policy passed for ${C} in ${S}.`:`Sigstore identity policy failed for ${C} in ${S}.`}),!W)continue}let E=I.allowedIssuers||[];if(E.length>0){let W=!!V.issuer&&E.includes(V.issuer);if(o.push({id:`mirror.sigstore.policy.issuer.${C}`,status:W?"passed":"failed",message:W?`Sigstore issuer policy passed for ${C} in ${S}.`:`Sigstore issuer policy failed for ${C} in ${S}.`}),!W)continue}let M=I.allowedRekorUrls||[];if(M.length>0){let W=!!V.rekorUrl&&M.includes(V.rekorUrl);if(o.push({id:`mirror.sigstore.policy.rekor.${C}`,status:W?"passed":"failed",message:W?`Sigstore Rekor policy passed for ${C} in ${S}.`:`Sigstore Rekor policy failed for ${C} in ${S}.`}),!W)continue}}else I&&o.push({id:`mirror.sigstore.policy.${C}`,status:"skipped",message:`Sigstore governance policy configured for ${S} but no verified Sigstore attestation for ${C}.`});let Ct=await promises.stat(q);O.push({id:C,path:w.relative(t,q),sha256:Ee,size:Ct.size,provenance:ke,attestation:{detached:{provided:!!J.attestation,verified:Pe?.verified||false,algorithm:Pe?.algorithm||null,publicKeyPath:Pe?.publicKeyPath||null,publicKeyFingerprint:Pe?.publicKeyFingerprint||null,signature:Pe?.signature||null,verifiedAt:Pe?.verified?new Date().toISOString():null},sigstore:{provided:!!xe,verified:V?.verified||false,tlogVerified:V?.tlogVerified||false,identity:V?.identity||null,issuer:V?.issuer||null,rekorUrl:V?.rekorUrl||null,bundlePath:V?.bundlePath||null,certificatePath:V?.certificatePath||null,signaturePath:V?.signaturePath||null,verifiedAt:V?.verified?new Date().toISOString():null}}});}let T=m.retention?.keepLast;if(typeof T=="number"&&T>0){let J=(await promises.readdir(c,{withFileTypes:true})).filter(C=>C.isFile()).map(C=>w.join(c,C.name));if(J.length>T){let C=await Promise.all(J.map(async Re=>({filePath:Re,stat:await promises.stat(Re)})));C.sort((Re,q)=>q.stat.mtimeMs-Re.stat.mtimeMs);let ee=C.slice(T);for(let Re of ee)await promises.unlink(Re.filePath),r.rotatedFiles+=1;}}o.push({id:"mirror.rotate",status:"passed",message:r.rotatedFiles>0?`Mirror retention rotation removed ${r.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let je={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:m.mode||null,environment:S,artifacts:O};if(await promises.writeFile(a,`${JSON.stringify(je,null,2)}
|
|
152
|
-
`,"utf-8"),r.lockWritten=true,o.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${w.relative(t,a)}.`}),r.transparencyEvidenceRecords=H.length,H.length>0){let
|
|
153
|
-
`,"utf-8"),r.evidenceExported=true,r.evidenceExportTarget=q,o.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${q}.`});}catch(q){o.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${q.message}`});}else if(h.target==="http")if(!h.endpoint)o.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let q=Math.max(0,h.retries??0),Z=Math.max(0,h.backoffMs??500),ke=vc(N,h.signing);ke.error&&o.push({id:"sigstore.evidence.export.http",status:"failed",message:ke.error});try{let Ee=h.authTokenEnv?process.env[h.authTokenEnv]:void 0,Pe=false,xe=null;for(let V=1;V<=q+1;V+=1)try{if(ke.error)throw new Error(ke.error);await wc(h.endpoint,N,Re,Ee,ke.headers),r.evidenceExported=true,r.evidenceExportTarget=h.endpoint,o.push({id:"sigstore.evidence.export.http",status:"passed",message:V>1?`Transparency evidence exported to HTTP endpoint ${h.endpoint} after ${V} attempts.`:`Transparency evidence exported to HTTP endpoint ${h.endpoint}.`}),Pe=true;break}catch(Ct){xe=Ct,V<=q&&await Us(Z*V);}if(!Pe)throw xe||new Error("unknown evidence export error")}catch(Ee){let Pe=`Evidence HTTP export failed: ${Ee.message}`;o.push({id:"sigstore.evidence.export.http",status:"failed",message:Pe});try{let xe=await kc(t,h.deadLetterPath,N,Pe);o.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${xe}.`});}catch(xe){o.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${xe.message}`});}}}if(h.failOnError&&o.some(Z=>Z.status==="failed"&&(Z.id==="sigstore.evidence.export.file"||Z.id==="sigstore.evidence.export.http")))return {checks:o,details:r}}else o.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else o.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),o.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:o,details:r}}function _o(t){let e=k$2(t.detection.runtime),o=o$1({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),r=[];r.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"RapidKit could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .rapidkit/project.json metadata or import a project with recognizable runtime manifests.":void 0}),r.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),r.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit module mutation is enabled for this project.":"RapidKit module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),r.push({id:"lifecycle-commands",status:o.lifecycleCommands.length>1?"pass":"warn",message:o.lifecycleCommands.length>1?`Lifecycle commands available: ${o.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:o.lifecycleCommands.length>1?void 0:"Add runtime scripts or a RapidKit runtime adapter before relying on dev/test/build/start."});let n=r.some(a=>a.status==="fail"),i=r.some(a=>a.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":i?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:o.lifecycleCommands,unsupportedLifecycleCommands:o.unsupportedLifecycleCommands,moduleCommands:o.moduleCommands},checks:r}}function Ao(t){return t.existingProjectJson?.module_support===true?true:t.enableModules!==true?false:k$2(t.detection.runtime).moduleCommands}function Qs(t){return t.replace(/\\/g,"/")}function xc(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function Cc(t,e){let o=Qs(w.relative(t,e));return !o||o.startsWith("..")?true:o.split("/").filter(Boolean).some(r=>r==="..")}function Wt(t){let e=Qs(w.relative(t.workspacePath,t.projectPath)),o=Cc(t.workspacePath,t.projectPath),r=xc(t.projectName,w.basename(t.projectPath)),n=o?`external/${r}`:e||r;return {relativePath:e||n,contractRelativePath:n,isExternal:o}}function Zs(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Rc(t){let e=t.trim();if(!e)return "imported-project";let o=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),r=o[o.length-1]||e,n=r.split(":"),i=(n[n.length-1]||r).replace(/\.git$/i,"");return Zs(i)||"imported-project"}function _r(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function Ec(t){return _r(t)?"git-url":"local-folder"}async function _c(t,e){let o=Zs(e)||"imported-project",r=0;for(;;){let n=r===0?o:r===1?`${o}-imported`:`${o}-imported-${r}`,i=w.join(t,n);if(!await R__default.pathExists(i))return i;r+=1;}}function Ac(t,e){let o=w.resolve(t),r=w.resolve(e),n=w.relative(o,r);return n===""||n.length>0&&!n.startsWith("..")&&!w.isAbsolute(n)}function Ic(t,e){if(Ac(t,e))throw new Error("Import source must be outside the current workspace root.")}function $c(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}function Mc(t){let e=w.basename(t);return !([".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor","packages"].includes(e)||$c(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Nc(t){let e=w.join(t,".rapidkit","project.json");if(!await R__default.pathExists(e))return null;try{return await R__default.readJson(e)}catch{return null}}async function Oc(t){let e=new Date().toISOString(),o=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:w.basename(t.projectPath),r=Wt({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:o}),n=r.contractRelativePath,i=w.join(t.projectPath,".rapidkit","project.json"),a=w.join(t.projectPath,".rapidkit","import.json"),c=w.join(t.projectPath,".rapidkit","import-readiness.json"),l=Ao({existingProjectJson:t.existingProjectJson,detection:t.detection,enableModules:t.enableModules}),g=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],m=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},p={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:w.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:w.basename(t.projectPath),kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:l,modules:g,contracts:m,import:{managed_by:"rapidkit-npm",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:r.relativePath,is_external:r.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},d={schema_version:"1.0",kind:"rapidkit.imported_project",imported_at:e,managed_by:"rapidkit-npm",source:{type:t.sourceType,name:w.basename(t.projectPath)},project:{name:p.name,slug:p.slug,relative_path:n,kind:t.projectKind,module_support:l},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:l}},u=_o({projectName:String(p.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:l,projectPath:t.projectPath,generatedAt:new Date(e)});return await R__default.ensureDir(w.dirname(i)),await R__default.writeJson(i,p,{spaces:2}),await R__default.writeJson(a,d,{spaces:2}),await R__default.writeJson(c,u,{spaces:2}),{projectJsonPath:i,importJsonPath:a,importReadinessPath:c,moduleSupport:l}}async function Dc(t,e){let o={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,importedAt:new Date().toISOString()};await b$a(t,[o]);}async function Xs(t){await R__default.pathExists(t)&&await R__default.remove(t);}async function ei(t,e){await Xs(e),await c$3(t,[e]);}async function ti(t){let e=w.resolve(t.workspacePath),o=t.source.trim(),r=t.sourceType??Ec(o),n=t.name??(r==="git-url"?Rc(o):w.basename(o)),i=await _c(e,n),a=false;try{if(r==="local-folder"){let u=w.resolve(o),f=await R__default.stat(u).catch(()=>null);if(!f||!f.isDirectory())throw new Error("Import source is not a directory.");Ic(e,u),a=true,await R__default.copy(u,i,{overwrite:false,errorOnExist:true,filter:Mc});}else a=true,await execa("git",["clone","--depth","1",o,i],{timeout:12e4});let c=await Nc(i),l=i$2(i,c),g=await e$2(i,c),m=await Oc({workspacePath:e,projectPath:i,sourceType:r,detection:l,existingProjectJson:c,projectKind:g,enableModules:t.enableModules}),p=Wt({workspacePath:e,projectPath:i,projectName:w.basename(i)}),d={name:w.basename(i),path:i,relativePath:p.contractRelativePath,stack:l.importStack,runtime:l.runtime,framework:l.key,frameworkDisplayName:l.displayName,supportTier:l.supportTier,moduleSupport:m.moduleSupport,confidence:l.confidence,source:r,projectJsonPath:m.projectJsonPath,importJsonPath:m.importJsonPath,importReadinessPath:m.importReadinessPath};return await Dc(e,d),d}catch(c){if(a)try{await Xs(i);}catch(l){let g=c instanceof Error?c.message:String(c),m=l instanceof Error?l.message:String(l);throw new Error(`Import failed: ${g}. Rollback also failed: ${m}`)}throw c}}function Tc(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Wc(t,e){return w.resolve(t)===w.resolve(e)}async function Fc(t){let e=w.join(t,".rapidkit","project.json");if(!await R__default.pathExists(e))return null;try{return await R__default.readJson(e)}catch{return null}}function Lc(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],o=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:o,adoption:{managed_by:"rapidkit-npm",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,discovered_relative_path:t.discoveredRelativePath,is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function oi(t,e,o){let r=w.join(e,".rapidkit","project.json"),n=w.join(e,".rapidkit","adopt.json"),i=w.join(e,".rapidkit","adopt-readiness.json");o?await R__default.writeJson(r,o,{spaces:2}):await R__default.pathExists(r)&&await R__default.remove(r),await R__default.pathExists(n)&&await R__default.remove(n),await R__default.pathExists(i)&&await R__default.remove(i);let{removeImportedProjectsRegistryEntries:a}=await import('./imported-projects-registry-ZOCHFWMK.js');await a(t,[e]);}async function ri(t){let e=w.resolve(t.workspacePath),o=w.resolve(t.source),r=await R__default.stat(o).catch(()=>null);if(!r||!r.isDirectory())throw new Error("Adopt source is not a directory.");if(Wc(e,o))throw new Error("Adopt source cannot be the workspace root itself.");let n=await Fc(o),i=i$2(o,n),a=await e$2(o,n),c=Tc(t.name||(typeof n?.name=="string"?n.name:"")||w.basename(o))||"adopted-project",l=Wt({workspacePath:e,projectPath:o,projectName:c}),g=(t.now??new Date).toISOString(),m=w.join(o,".rapidkit","project.json"),p=w.join(o,".rapidkit","adopt.json"),d=w.join(o,".rapidkit","adopt-readiness.json"),u=Ao({existingProjectJson:n,detection:i,enableModules:t.enableModules}),f=Lc({projectName:c,contractRelativePath:l.contractRelativePath,isExternal:l.isExternal,discoveredRelativePath:l.relativePath,detection:i,existingProjectJson:n,projectKind:a,moduleSupport:u,adoptedAt:g}),y={schema_version:"1.0",kind:"rapidkit.adopted_project",adopted_at:g,managed_by:"rapidkit-npm",mode:"linked",workspace:{path:e},project:{name:c,path:o,relative_path:l.contractRelativePath,discovered_relative_path:l.relativePath,is_external:l.isExternal,kind:a,module_support:u},detection:{framework:i.key,framework_display_name:i.displayName,runtime:i.runtime,kind:a,confidence:i.confidence,support_tier:i.supportTier,import_stack:i.importStack,source:i.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:u,workspace_contract:"linked-project"}},v=_o({projectName:c,relativePath:l.contractRelativePath,projectKind:a,source:"adopted-local",detection:i,moduleSupport:u,projectPath:o,generatedAt:new Date(g)});if(t.dryRun!==true){await R__default.ensureDir(w.dirname(m)),await R__default.writeJson(m,f,{spaces:2}),await R__default.writeJson(p,y,{spaces:2}),await R__default.writeJson(d,v,{spaces:2});let P={name:c,path:o,relativePath:l.contractRelativePath,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:u,confidence:i.confidence,source:"adopted-local",importedAt:g};await b$a(e,[P]);}return {name:c,path:o,relativePath:l.relativePath,contractRelativePath:l.contractRelativePath,isExternal:l.isExternal,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:u,confidence:i.confidence,projectJsonPath:m,adoptJsonPath:p,adoptReadinessPath:d,wroteFiles:t.dryRun!==true}}function Ar(t){if(!t||typeof t!="object")return null;let e=t.code;return e==="PYTHON_NOT_FOUND"||e==="BRIDGE_VENV_BOOTSTRAP_FAILED"||e==="BRIDGE_VENV_CREATE_FAILED"||e==="BRIDGE_PIP_BOOTSTRAP_FAILED"?e:null}function Kc(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Ne(t,e){let o=t.indexOf(e);if(o>=0&&o+1<t.length)return t[o+1];let r=t.find(n=>n.startsWith(`${e}=`));if(r)return r.slice(e.length+1)}function Kr(){return d$6()}function si(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(w.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(w.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=c$6()),t.RAPIDKIT_SKIP_LOCK_SYNC||(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t.POETRY_KEYRING_ENABLED||(t.POETRY_KEYRING_ENABLED="false"),t.PYTHON_KEYRING_BACKEND||(t.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),t.POETRY_NO_INTERACTION||(t.POETRY_NO_INTERACTION="1"),t}function Gc(t){return f$3(w.join(t,".venv"))}async function ji(t,e){return await z(t,["--version"],e)===0}async function dt(t){let e=w.join(t,"go.mod");if(await R__default.pathExists(e))return "go";let o=w.join(t,"pom.xml"),r=w.join(t,"build.gradle"),n=w.join(t,"build.gradle.kts");if(await R__default.pathExists(o)||await R__default.pathExists(r)||await R__default.pathExists(n))return "java";if((await R__default.pathExists(t)?await b$3.promises.readdir(t,{withFileTypes:true}):[]).some(p=>p.isFile()&&p.name.toLowerCase().endsWith(".sln")))return "dotnet";let a=w.join(t,"src");if(await R__default.pathExists(a)&&(await b$3.promises.readdir(a,{withFileTypes:true})).some(d=>d.isFile()&&d.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=w.join(t,"package.json");if(await R__default.pathExists(c))return "node";let l=w.join(t,"pyproject.toml"),g=w.join(t,"requirements.txt"),m=w.join(t,"poetry.lock");return await R__default.pathExists(l)||await R__default.pathExists(g)||await R__default.pathExists(m)?"python":null}async function Vc(t){for(let e of Kr())if(await z(e,e==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function xi(t){for(let e of Kr())if(await z(e,e==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Bc(t){let e=f$3(w.join(t,".venv"));if(!await R__default.pathExists(e)){let i=await xi(t);if(i!==0)return i}if(!await ji("poetry",t))return 0;let r=await z("poetry",["config","virtualenvs.in-project","true","--local"],t);if(r!==0)return r;let n=await z("poetry",["env","use",e],t);return n!==0?n:0}async function Uc(t){let e=f$3(w.join(t,".venv"));if(!await R__default.pathExists(e)){let n=await xi(t);if(n!==0)return n}await z(e,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let o=w.join(t,"requirements.txt");if(await R__default.pathExists(o)&&await z(e,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let r=w.join(t,"pyproject.toml");return await R__default.pathExists(r)&&(await z(e,["-m","pip","install","-e","."],t)===0||await z(e,["-m","pip","install","."],t)===0)?0:1}async function Ir(t,e){return await Bc(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await R__default.pathExists(w.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await Uc(t))}async function $r(t){let e=await ct("init",t);if(e===0)return 0;let o=["npm","pnpm","yarn"];for(let r of o){if(!await ji(r,t))continue;if(await z(r,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${r} install`)),0}return e}function Hc(t,e){let o=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),r=Ne([...e],"--port");if(r&&!/^\d+$/.test(r.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Ne([...e],"--java-version"),i=Ne([...e],"--spring-boot-version"),a=Ne([...e],"--springdoc-version"),c=Ne([...e],"--group-id"),l=Ne([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(i&&!o(i.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(a&&!o(a.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(l&&!/^[A-Za-z0-9_.-]+$/.test(l.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Ne([...e],"--target-framework"),i=Ne([...e],"--root-namespace");if(n&&!/^net\d+\.\d+$/.test(n.trim()))return "Invalid --target-framework. Expected .NET target framework, e.g. net8.0";if(i&&!/^[A-Za-z0-9_.]+$/.test(i.trim()))return "Invalid --root-namespace. Use dot-separated .NET namespace identifiers only."}return null}async function Dr(t$1){if(t$1[0]!=="create"||t$1[1]!=="project")return 1;let e=t$1[2],o=p(e),r=t$1[3];if(!o||o.owner!=="npm")return 1;if(!r)return process.stderr.write(`Usage: ${o.createUsage??"rapidkit create project <kit> <name> [--output <dir>]"}
|
|
149
|
+
${o.stderr||""}`);return r?this.isMavenVersionAtLeast(r,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${r.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let o=b$3.existsSync(w.join(e,"pom.xml")),r=b$3.existsSync(w.join(e,"mvnw"))||b$3.existsSync(w.join(e,"mvnw.cmd")),n=b$3.existsSync(w.join(e,"build.gradle"))||b$3.existsSync(w.join(e,"build.gradle.kts"))||b$3.existsSync(w.join(e,"settings.gradle"))||b$3.existsSync(w.join(e,"settings.gradle.kts")),i=b$3.existsSync(w.join(e,"gradlew"))||b$3.existsSync(w.join(e,"gradlew.bat"));return {hasMavenProject:o||r,hasMavenWrapper:r,hasGradleProject:n||i,hasGradleWrapper:i}}findWorkspaceRoot(e){let o=e;for(;;){if(b$3.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$3.existsSync(n))return "isolated";try{let c=b$3.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let o=w.join(e,"mvnw.cmd");if(process.platform==="win32"&&b$3.existsSync(o))return {command:o,baseArgs:[]};let r=w.join(e,"mvnw");return b$3.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let o=w.join(e,"gradlew.bat");if(process.platform==="win32"&&b$3.existsSync(o))return {command:o,baseArgs:[]};let r=w.join(e,"gradlew");return b$3.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let o=[],r=new Set,n=[e];for(;n.length>0;){let i=n.shift();if(!i||r.has(i))continue;r.add(i);let a=[];try{a=b$3.readdirSync(i,{withFileTypes:true});}catch{continue}for(let c of a){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let l=w.join(i,c.name),g=this.inspectJavaProject(l);(g.hasMavenProject||g.hasGradleProject)&&o.push(l),n.push(l);}}return o}withJavaCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","java","m2"):w.join(e,".rapidkit","cache","java","m2"),a=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","java","gradle"):w.join(e,".rapidkit","cache","java","gradle"),c=process.env.MAVEN_OPTS,l=process.env.GRADLE_USER_HOME,g=`-Dmaven.repo.local=${i}`;return process.env.MAVEN_OPTS=c?`${c} ${g}`:g,process.env.GRADLE_USER_HOME=a,o().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof l>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=l;})}async runBuildTool(e,o,r=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:i}=this.buildToolCommand(e),a=await this.runCommand(n,[...i,...o],e);if(a===0||!r)return {exitCode:a};let c=b$3.existsSync(w.join(e,"pom.xml")),l=b$3.existsSync(w.join(e,"build.gradle"))||b$3.existsSync(w.join(e,"build.gradle.kts"));return {exitCode:a,message:c||l?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let o=[w.join(e,"target"),w.join(e,"build","libs")];for(let r of o){if(!b$3.existsSync(r))continue;let i=b$3.readdirSync(r).filter(a=>a.toLowerCase().endsWith(".jar")).find(a=>!a.toLowerCase().endsWith("-sources.jar")&&!a.toLowerCase().endsWith("-javadoc.jar")&&!a.toLowerCase().endsWith("-plain.jar"));if(i)return w.join(r,i)}return null}commandArgsFor(e,o){if(e==="gradle"){let r=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return o==="init"?[...r,"dependencies"]:o==="dev"?[...r,"bootRun"]:o==="test"?[...r,"test"]:[...r,"bootJar"]}return o==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:o==="dev"?["spring-boot:run"]:o==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),o=this.resolveJavaCommand(e),r=await this.runCommand(o,["-version"],e);if(r!==0)return {exitCode:r,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),l=await this.detectInstalledJavaMajor(o,e);if(l!==null&&l<c)return {exitCode:1,message:`Detected Java ${l}, but project requires Java ${c}+.`};let g=w.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&b$3.existsSync(g))try{let p=b$3.readFileSync(g,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),d=this.parseMajorJavaVersion(p?.[1]);if(d!==null&&d<c)return {exitCode:1,message:`Detected JAVA_HOME version ${d}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),l=c==="gradle"?["--version"]:["-version"],g=await this.runBuildTool(e,l);return g.exitCode!==0?g:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):g}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let l=c.reduce((p,d)=>Math.max(p,this.readRequiredJavaMajor(d)),0);if(l>0){let p=await this.detectInstalledJavaMajor(o,e);if(p!==null&&p<l){let d=c.filter(f=>this.readRequiredJavaMajor(f)>p).map(f=>w.relative(e,f)).join(", ");return {exitCode:1,message:`Detected Java ${p}, but workspace project(s) [${d}] require Java ${l}+.`}}}let g=false,m=false;for(let p of c){let d=this.inspectJavaProject(p);d.hasMavenProject&&!d.hasMavenWrapper&&(g=true),d.hasGradleProject&&!d.hasGradleWrapper&&(m=true);}if(g){let p=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(p!==0)return {exitCode:p,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let d=await this.checkSystemMavenVersion(e);if(d.exitCode!==0)return d}if(m){let p=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(p!==0)return {exitCode:p,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(i===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return a===0?{exitCode:0}:{exitCode:i||a||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let o=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return o&&b$3.mkdirSync(o,{recursive:true}),process.env.GRADLE_USER_HOME&&b$3.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let o=this.resolveJarPath(e);if(o)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",o],e)};let r=await this.runBuild(e);if(r.exitCode!==0)return r;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(Ge(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let o=w.join(e,"pom.xml");return b$3.existsSync(o)&&b$3.readFileSync(o,"utf-8").includes("checkstyle")?this.runBuildTool(e,["checkstyle:check"]):{exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){return Ge(e,"format")?{exitCode:await this.runCommand("make",["format"],e)}:["build.gradle","build.gradle.kts"].map(r=>w.join(e,r)).filter(r=>b$3.existsSync(r)).some(r=>b$3.readFileSync(r,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure spotless in Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run rapidkit init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var jo=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}findWorkspaceRoot(e){let o=e;for(;;){if(b$3.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$3.existsSync(n))return "isolated";try{let c=b$3.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,o,r){let n=this.resolveDependencyMode(e),i=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=n==="isolated"?w.join(e,".rapidkit","cache","node"):w.join(i||e,".rapidkit","cache","node"),c=process.env.npm_config_cache,l=process.env.npm_config_store_dir,g=process.env.RAPIDKIT_DEP_SHARING_MODE,m=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,i&&(process.env.RAPIDKIT_WORKSPACE_PATH=i),o==="pnpm"?(process.env.npm_config_store_dir=w.join(a,"pnpm-store"),process.env.npm_config_cache=w.join(a,"pnpm-cache")):o==="yarn"?process.env.npm_config_cache=w.join(a,"yarn-cache"):process.env.npm_config_cache=w.join(a,"npm-cache"),r().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof l>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=l,typeof g>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=g,typeof m>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=m;})}detectPackageManager(e){if(b$3.existsSync(w.join(e,"package-lock.json")))return "npm";if(b$3.existsSync(w.join(e,"pnpm-lock.yaml")))return "pnpm";if(b$3.existsSync(w.join(e,"yarn.lock")))return "yarn";if(!this.commandAvailable("npm")){if(this.commandAvailable("pnpm"))return "pnpm";if(this.commandAvailable("yarn"))return "yarn"}return "npm"}hasPinnedPackageManager(e){return b$3.existsSync(w.join(e,"package-lock.json"))||b$3.existsSync(w.join(e,"pnpm-lock.yaml"))||b$3.existsSync(w.join(e,"yarn.lock"))}availablePackageManagers(e){let o=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[o]:[o,...["npm","pnpm","yarn"].filter(n=>n!==o&&this.commandAvailable(n))]}commandAvailable(e){return spawnSync(e,["--version"],{stdio:"ignore",shell:process.platform==="win32"}).status===0}scriptArgs(e,o){return e==="npm"?["run",o]:["run",o]}async runScriptWithFallback(e,o){let r={exitCode:1};for(let n of this.availablePackageManagers(e))if(r=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,o),e)),r.exitCode===0)return r;return r}async runLifecycle(e,o){let r=a$5(e),n=i$2(e,r),i=g$1(e,o,{framework:n.key});return i?this.runScriptWithFallback(e,i.scriptName):{exitCode:1,message:`No npm script available for \`${o}\`. Add a "${o}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let o=this.detectPackageManager(e);return this.withDependencyEnv(e,o,async()=>{try{return process.env.npm_config_cache&&b$3.mkdirSync(process.env.npm_config_cache,{recursive:true}),o==="pnpm"&&process.env.npm_config_store_dir&&b$3.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let o=this.detectPackageManager(e),r=this.resolveDependencyMode(e),n=r==="shared-runtime-caches"||r==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,o,()=>this.run(o,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var xo=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,o){return {exitCode:await this.withPythonCacheEnv(o,()=>this.runCore(e,o))}}findWorkspaceRoot(e){let o=e;for(;;){if(b$3.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$3.existsSync(n))return "isolated";try{let c=b$3.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","python"):w.join(e,".rapidkit","cache","python"),a=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=w.join(i,"pip"),process.env.POETRY_CACHE_DIR=w.join(i,"poetry"),o().finally(()=>{typeof a>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=a,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),o=await this.run(["doctor","check"],e);return o.exitCode===0?o:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx rapidkit doctor workspace" for a full workspace scan.','Use "npx rapidkit init" after adding or changing modules.','Use workspace launcher "./rapidkit" to avoid environment drift.']}};function gc(){let t={...process.env},e=t.PATH||"";if(e){let o=e.split(w.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(w.delimiter);t.PATH=o;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||c$6(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ve(t,e){return t==="go"?new Po((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="node"?new jo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="java"?new bo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="dotnet"?new vo((o,r,n)=>e.runCommandInCwd(o,r,n)):new xo((o,r)=>e.runCoreRapidkit(o,{cwd:r,env:gc()}))}var ei=w.join(Qn.homedir(),".rapidkit","cache"),ti=1440*60*1e3;function Sr(){let t=process.env.RAPIDKIT_CACHE_DIR?.trim();if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?w.join(ei,`vitest-${e}`):ei}var So=class t{static instance;memoryCache=new Map;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getCacheKey(e){return createHash("md5").update(e).digest("hex")}getCachePath(e){return w.join(Sr(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let o=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${o}.tmp`}async get(e,o="1.0"){let r=this.memoryCache.get(e);if(r&&r.version===o&&Date.now()-r.timestamp<ti)return f.debug(`Cache hit (memory): ${e}`),r.data;try{let n=this.getCachePath(e),i=await promises.readFile(n,"utf-8"),a=JSON.parse(i);if(a.version===o&&Date.now()-a.timestamp<ti)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,a),a.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,o,r="1.0"){let n={data:o,timestamp:Date.now(),version:r};this.memoryCache.set(e,n);try{await promises.mkdir(Sr(),{recursive:true});let i=this.getCachePath(e),a=this.getTempCachePath(i);await promises.writeFile(a,JSON.stringify(n),"utf-8"),await promises.rename(a,i),f.debug(`Cache set: ${e}`);}catch(i){f.debug(`Cache write failed: ${e}`,i);}}async invalidate(e){this.memoryCache.delete(e);try{let o=this.getCachePath(e);await promises.unlink(o),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=Sr(),o=await promises.readdir(e);await Promise.all(o.map(r=>promises.unlink(w.join(e,r)))),f.debug("Cache cleared");}catch{}}};var Ro=["list","sync","registry","foundation","model","snapshot","diff","impact","verify","graph","watch","context","agent-sync","explain","why","trace","feedback","mcp","policy","contract","share","export","archive","hydrate","import","run","init"],Eo=["model","snapshot","diff","impact","verify","context","agent-sync","explain"];function oi(t){return Eo.includes(t)}var ri="rapidkit-runtime-command-surface-v1";function _o(){return {runtimeCommandSurface:ri,cliLogEvent:c$5,freshnessMetadata:a$i,blockerResolution:a$h,workspaceModel:g$2,workspaceImpact:e$3,workspaceVerify:b$c,workspaceContext:a$g,workspaceDependencyGraph:f$4,workspaceIntelligenceHistory:a$f,agentCustomizationPack:l$2,workspaceOperationalSkill:a$e,workspaceSkillsIndex:b$b,workspaceExplain:a$d,agentActionOutcome:a$c}}var kc=["catalog","pulse","nova","orbit","atlas","vertex","summit","beacon","ledger","flux","nexus","apex","harbor","forge","spark","portal","studio","canvas","quantum","vault","zenith","compass","vector","catalyst","saas","commerce","radar","stellar","prism","cedar","momentum","signal","cipher","lumen","trail","ridge"],vc={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},Pc={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"};function bc(t){return t[Math.floor(Math.random()*t.length)]}function Rr(t){let e=bc(kc),o=k$1(t);if(o){let i=Pc[o.id]??"app";return `${e}-${i}`}let r=p(t),n=r?vc[r.id]??"service":"app";return `${e}-${n}`}async function Sc(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function ni(t,e){await R.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
150
|
+
`,"utf-8");}function De(t,e){return w.isAbsolute(e)?e:w.join(t,e)}function Rc(t,e){if(t.target)return t.target;if(t.source)return w.basename(t.source);if(t.url)try{let o=new URL(t.url).pathname,r=w.basename(o);if(r&&r!=="/")return r}catch{}return `${e}.artifact`}async function Ec(t){let e=w.join(t,".rapidkit","trusted-sources.lock"),o=new Set(["localhost","127.0.0.1"]);if(!await R.pathExists(e))return o;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0&&!i.startsWith("#"));for(let i of n)o.add(i.toLowerCase());}catch{}return o}async function _c(t,e,o){await R.ensureDir(w.dirname(e)),await new Promise((r,n)=>{let a=(t.startsWith("https://")?li:ci).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let l=createWriteStream(e);c.pipe(l),l.on("finish",()=>{l.close(),r();}),l.on("error",g=>{n(g);});});a.setTimeout(o,()=>{a.destroy(new Error(`Request timeout after ${o}ms`));}),a.on("error",c=>{n(c);});});}async function Ac(t,e,o,r,n){let i=new URL(t),a=JSON.stringify(e),c=i.protocol==="https:"?li:ci;await new Promise((l,g)=>{let m=c.request({method:"POST",hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:`${i.pathname}${i.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(a),...r?{Authorization:`Bearer ${r}`}:{},...n||{}}},p=>{if(!p.statusCode||p.statusCode<200||p.statusCode>=300){g(new Error(`HTTP ${p.statusCode||"unknown"}`)),p.resume();return}p.resume(),l();});m.setTimeout(o,()=>{m.destroy(new Error(`Request timeout after ${o}ms`));}),m.on("error",p=>{g(p);}),m.write(a),m.end();});}function si(t){return new Promise(e=>setTimeout(e,t))}async function Ic(t,e,o,r){let n=De(t,e||".rapidkit/reports/evidence-export-dead-letter.ndjson");return await R.ensureDir(w.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:r,payload:o})}
|
|
151
|
+
`,"utf-8"),n}function $c(t,e){if(!e?.enabled)return {headers:{}};let o=process.env[e.hmacKeyEnv];if(!o)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let r=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",i=createHmac(r,o).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:i,"x-rapidkit-evidence-signature-alg":r}}}async function Mc(t,e,o){let r=(o.algorithm||"sha256").toLowerCase(),n=De(t,o.publicKeyPath);if(!await R.pathExists(n))return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Public key not found: ${n}`};try{let i=await promises.readFile(n,"utf-8"),a=await promises.readFile(e),c=createVerify(r);c.update(a),c.end();let l=Buffer.from(o.signature,"base64"),g=c.verify(i,l),m=createHash("sha256").update(i).digest("hex");return {verified:g,algorithm:r,publicKeyPath:n,publicKeyFingerprint:m,signature:o.signature,message:g?"Attestation verified.":"Attestation signature verification failed."}}catch(i){return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Attestation verification error: ${i.message}`}}}async function Oc(t,e,o,r){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};let i=o.signaturePath?De(t,o.signaturePath):null;if(!i||!await R.pathExists(i))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:i};let a=["verify-blob",e,"--signature",i],c=o.certificatePath?De(t,o.certificatePath):null;c&&a.push("--certificate",c);let l=o.bundlePath?De(t,o.bundlePath):null;l&&a.push("--bundle",l);let g=o.keyPath?De(t,o.keyPath):null;g&&a.push("--key",g),o.identity&&a.push("--certificate-identity",o.identity),o.issuer&&a.push("--certificate-oidc-issuer",o.issuer),o.rekorUrl&&a.push("--rekor-url",o.rekorUrl),r.requireTransparencyLog||a.push("--insecure-ignore-tlog");try{let m=await execa("cosign",a,{reject:false});return m.exitCode===0?{verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:i}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${m.stderr||m.stdout||"unknown error"}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:i}}catch(m){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${m.message}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:i}}}async function Nc(t,e){let o=e.algorithm||"sha256",r=De(t,e.policyPath),n=De(t,e.signaturePath),i=De(t,e.publicKeyPath);if(!await R.pathExists(r))return {verified:false,message:`Governance policy bundle not found: ${r}`,policies:null};if(!await R.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await R.pathExists(i))return {verified:false,message:`Governance policy public key not found: ${i}`,policies:null};try{let a=await promises.readFile(r,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),l=await promises.readFile(i,"utf-8"),g=createVerify(o);return g.update(a),g.end(),g.verify(l,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(a).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(a){return {verified:false,message:`Governance policy bundle verification error: ${a.message}`,policies:null}}}async function Er(t,e){let o=[],r={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=w.join(t,".rapidkit"),i=w.join(n,"mirror-config.json"),a=w.join(n,"mirror.lock"),c=w.join(n,"mirror","artifacts"),l=w.join(n,"reports"),g=await Ec(t);if(!await R.pathExists(i))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .rapidkit/mirror-config.json not found."}),{checks:o,details:r};let m={};try{m=JSON.parse(await promises.readFile(i,"utf-8"));}catch{return o.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:o,details:r}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||m.mode==="offline-only"))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:o,details:r};await R.ensureDir(c);let d=Math.max(0,m.prefetch?.retries??2),f=Math.max(0,m.prefetch?.backoffMs??250),u=Math.max(1e3,m.prefetch?.timeoutMs??15e3),h=m.security?.requireAttestation===true,k=m.security?.requireSigstore===true,P=m.security?.requireTransparencyLog===true,v=m.security?.requireSignedGovernance===true,y=m.security?.evidenceExport,C=(process.env.RAPIDKIT_ENV||m.security?.governance?.environment||"dev").toLowerCase(),x=m.security?.governance?.policies||{};if(m.security?.governanceBundle){let O=await Nc(t,m.security.governanceBundle);if(o.push({id:"governance.bundle.verify",status:O.verified?"passed":"failed",message:O.message}),O.verified&&O.policies)x=O.policies,r.governanceBundleVerified=true;else if(v)return {checks:o,details:r}}let I=x[C],Y=P||I?.requireTransparencyLog===true,H=[],ae=Array.isArray(m.artifacts)?m.artifacts:[],N=[];for(let O=0;O<ae.length;O+=1){let G=ae[O],S=G.id||`artifact-${O+1}`,ee=G.source?De(t,G.source):null,Re=Rc(G,S),q=w.join(c,Re),X=false,ke={sourceType:"path",source:ee||G.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(ee&&await R.pathExists(ee))await R.ensureDir(w.dirname(q)),await R.copyFile(ee,q),r.syncedArtifacts+=1,X=true,ke={sourceType:"path",source:ee,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},o.push({id:`mirror.sync.${S}`,status:"passed",message:`Mirrored artifact ${S} from source path.`});else if(G.url){let _e="";try{_e=new URL(G.url).hostname.toLowerCase();}catch{o.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Invalid URL for ${S}: ${G.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||g.has(_e))){o.push({id:`mirror.prefetch.trust.${S}`,status:"failed",message:`Untrusted mirror host for ${S}: ${_e}. Add host to .rapidkit/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await R.pathExists(q)?(X=true,ke={sourceType:"url",source:G.url,host:_e,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},o.push({id:`mirror.prefetch.${S}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${S}.`})):o.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${S} without an existing mirrored copy.`}),!X))continue;if(!X){let W=null,$e=0;for(let we=1;we<=d+1;we+=1){$e=we;try{await _c(G.url,q,u),r.syncedArtifacts+=1,X=true,ke={sourceType:"url",source:G.url,host:_e,fetchedAt:new Date().toISOString(),attempts:$e,trusted:true},o.push({id:`mirror.prefetch.${S}`,status:"passed",message:$e>1?`Prefetched artifact ${S} from ${_e} after ${$e} attempts.`:`Prefetched artifact ${S} from ${_e}.`});break}catch(Fe){if(W=Fe,we<=d){await si(f*we);continue}}}if(!X){o.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S} after ${d+1} attempt(s): ${W?.message||"unknown error"}`});continue}}if(!X){o.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S}.`});continue}}if(!X){G.required||e.offlineMode?o.push({id:`mirror.sync.${S}`,status:"failed",message:`Mirror source missing for ${S}${ee?`: ${ee}`:""}`}):o.push({id:`mirror.sync.${S}`,status:"skipped",message:`Mirror source not found for optional artifact ${S}.`});continue}let Ee=await Sc(q);if(G.sha256&&G.sha256.toLowerCase()!==Ee.toLowerCase()){o.push({id:`mirror.verify.${S}`,status:"failed",message:`Checksum mismatch for ${S}.`});continue}r.verifiedArtifacts+=1,o.push({id:`mirror.verify.${S}`,status:"passed",message:`Checksum verified for ${S}.`});let Pe=G.attestation?await Mc(t,q,G.attestation):null;if(G.attestation){if(o.push({id:`mirror.attest.${S}`,status:Pe?.verified?"passed":"failed",message:Pe?.message||"Attestation verification failed."}),!Pe?.verified)continue}else if(h){o.push({id:`mirror.attest.${S}`,status:"failed",message:`Attestation is required but missing for ${S}.`});continue}else o.push({id:`mirror.attest.${S}`,status:"skipped",message:`No attestation provided for ${S}.`});let xe=G.attestation?.sigstore,V=xe?await Oc(t,q,xe,{requireTransparencyLog:Y}):null;if(xe){if(o.push({id:`mirror.sigstore.${S}`,status:V?.verified?"passed":"failed",message:V?.message||"Sigstore verification failed."}),H.push({artifactId:S,verified:!!V?.verified,tlogVerified:!!V?.tlogVerified,identity:V?.identity||null,issuer:V?.issuer||null,rekorUrl:V?.rekorUrl||null,timestamp:new Date().toISOString(),environment:C}),!V?.verified)continue}else if(k){o.push({id:`mirror.sigstore.${S}`,status:"failed",message:`Sigstore attestation is required but missing for ${S}.`});continue}else o.push({id:`mirror.sigstore.${S}`,status:"skipped",message:`No Sigstore attestation provided for ${S}.`});if(xe&&V?.verified&&I){let _e=I.allowedIdentities||[];if(_e.length>0){let W=!!V.identity&&_e.includes(V.identity);if(o.push({id:`mirror.sigstore.policy.identity.${S}`,status:W?"passed":"failed",message:W?`Sigstore identity policy passed for ${S} in ${C}.`:`Sigstore identity policy failed for ${S} in ${C}.`}),!W)continue}let E=I.allowedIssuers||[];if(E.length>0){let W=!!V.issuer&&E.includes(V.issuer);if(o.push({id:`mirror.sigstore.policy.issuer.${S}`,status:W?"passed":"failed",message:W?`Sigstore issuer policy passed for ${S} in ${C}.`:`Sigstore issuer policy failed for ${S} in ${C}.`}),!W)continue}let M=I.allowedRekorUrls||[];if(M.length>0){let W=!!V.rekorUrl&&M.includes(V.rekorUrl);if(o.push({id:`mirror.sigstore.policy.rekor.${S}`,status:W?"passed":"failed",message:W?`Sigstore Rekor policy passed for ${S} in ${C}.`:`Sigstore Rekor policy failed for ${S} in ${C}.`}),!W)continue}}else I&&o.push({id:`mirror.sigstore.policy.${S}`,status:"skipped",message:`Sigstore governance policy configured for ${C} but no verified Sigstore attestation for ${S}.`});let Ct=await promises.stat(q);N.push({id:S,path:w.relative(t,q),sha256:Ee,size:Ct.size,provenance:ke,attestation:{detached:{provided:!!G.attestation,verified:Pe?.verified||false,algorithm:Pe?.algorithm||null,publicKeyPath:Pe?.publicKeyPath||null,publicKeyFingerprint:Pe?.publicKeyFingerprint||null,signature:Pe?.signature||null,verifiedAt:Pe?.verified?new Date().toISOString():null},sigstore:{provided:!!xe,verified:V?.verified||false,tlogVerified:V?.tlogVerified||false,identity:V?.identity||null,issuer:V?.issuer||null,rekorUrl:V?.rekorUrl||null,bundlePath:V?.bundlePath||null,certificatePath:V?.certificatePath||null,signaturePath:V?.signaturePath||null,verifiedAt:V?.verified?new Date().toISOString():null}}});}let T=m.retention?.keepLast;if(typeof T=="number"&&T>0){let G=(await promises.readdir(c,{withFileTypes:true})).filter(S=>S.isFile()).map(S=>w.join(c,S.name));if(G.length>T){let S=await Promise.all(G.map(async Re=>({filePath:Re,stat:await promises.stat(Re)})));S.sort((Re,q)=>q.stat.mtimeMs-Re.stat.mtimeMs);let ee=S.slice(T);for(let Re of ee)await promises.unlink(Re.filePath),r.rotatedFiles+=1;}}o.push({id:"mirror.rotate",status:"passed",message:r.rotatedFiles>0?`Mirror retention rotation removed ${r.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let je={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:m.mode||null,environment:C,artifacts:N};if(await promises.writeFile(a,`${JSON.stringify(je,null,2)}
|
|
152
|
+
`,"utf-8"),r.lockWritten=true,o.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${w.relative(t,a)}.`}),r.transparencyEvidenceRecords=H.length,H.length>0){let O={schemaVersion:"1.0",generatedAt:new Date().toISOString(),environment:C,records:H},G=new Date().toISOString().replace(/[:.]/g,"-"),S=w.join(l,`transparency-evidence-${G}.json`),ee=w.join(l,"transparency-evidence.latest.json");if(await R.ensureDir(l),await ni(S,O),await ni(ee,O),r.transparencyEvidenceWritten=true,o.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${w.relative(t,ee)}.`}),y?.enabled){let Re=Math.max(1e3,y.timeoutMs??1e4);if(y.target==="file")if(!y.filePath)o.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let q=De(t,y.filePath);await R.ensureDir(w.dirname(q)),await promises.appendFile(q,`${JSON.stringify(O)}
|
|
153
|
+
`,"utf-8"),r.evidenceExported=true,r.evidenceExportTarget=q,o.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${q}.`});}catch(q){o.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${q.message}`});}else if(y.target==="http")if(!y.endpoint)o.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let q=Math.max(0,y.retries??0),X=Math.max(0,y.backoffMs??500),ke=$c(O,y.signing);ke.error&&o.push({id:"sigstore.evidence.export.http",status:"failed",message:ke.error});try{let Ee=y.authTokenEnv?process.env[y.authTokenEnv]:void 0,Pe=false,xe=null;for(let V=1;V<=q+1;V+=1)try{if(ke.error)throw new Error(ke.error);await Ac(y.endpoint,O,Re,Ee,ke.headers),r.evidenceExported=true,r.evidenceExportTarget=y.endpoint,o.push({id:"sigstore.evidence.export.http",status:"passed",message:V>1?`Transparency evidence exported to HTTP endpoint ${y.endpoint} after ${V} attempts.`:`Transparency evidence exported to HTTP endpoint ${y.endpoint}.`}),Pe=true;break}catch(Ct){xe=Ct,V<=q&&await si(X*V);}if(!Pe)throw xe||new Error("unknown evidence export error")}catch(Ee){let Pe=`Evidence HTTP export failed: ${Ee.message}`;o.push({id:"sigstore.evidence.export.http",status:"failed",message:Pe});try{let xe=await Ic(t,y.deadLetterPath,O,Pe);o.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${xe}.`});}catch(xe){o.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${xe.message}`});}}}if(y.failOnError&&o.some(X=>X.status==="failed"&&(X.id==="sigstore.evidence.export.file"||X.id==="sigstore.evidence.export.http")))return {checks:o,details:r}}else o.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else o.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),o.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:o,details:r}}function Ao(t){let e=k$2(t.detection.runtime),o=o$1({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),r=[];r.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"RapidKit could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .rapidkit/project.json metadata or import a project with recognizable runtime manifests.":void 0}),r.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),r.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit module mutation is enabled for this project.":"RapidKit module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),r.push({id:"lifecycle-commands",status:o.lifecycleCommands.length>1?"pass":"warn",message:o.lifecycleCommands.length>1?`Lifecycle commands available: ${o.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:o.lifecycleCommands.length>1?void 0:"Add runtime scripts or a RapidKit runtime adapter before relying on dev/test/build/start."});let n=r.some(a=>a.status==="fail"),i=r.some(a=>a.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":i?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:o.lifecycleCommands,unsupportedLifecycleCommands:o.unsupportedLifecycleCommands,moduleCommands:o.moduleCommands},checks:r}}function Io(t){return t.existingProjectJson?.module_support===true?true:t.enableModules!==true?false:k$2(t.detection.runtime).moduleCommands}function di(t){return t.replace(/\\/g,"/")}function Dc(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function Tc(t,e){let o=di(w.relative(t,e));return !o||o.startsWith("..")?true:o.split("/").filter(Boolean).some(r=>r==="..")}function Wt(t){let e=di(w.relative(t.workspacePath,t.projectPath)),o=Tc(t.workspacePath,t.projectPath),r=Dc(t.projectName,w.basename(t.projectPath)),n=o?`external/${r}`:e||r;return {relativePath:e||n,contractRelativePath:n,isExternal:o}}function pi(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Fc(t){let e=t.trim();if(!e)return "imported-project";let o=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),r=o[o.length-1]||e,n=r.split(":"),i=(n[n.length-1]||r).replace(/\.git$/i,"");return pi(i)||"imported-project"}function Ar(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function Lc(t){return Ar(t)?"git-url":"local-folder"}async function Jc(t,e){let o=pi(e)||"imported-project",r=0;for(;;){let n=r===0?o:r===1?`${o}-imported`:`${o}-imported-${r}`,i=w.join(t,n);if(!await R__default.pathExists(i))return i;r+=1;}}function Kc(t,e){let o=w.resolve(t),r=w.resolve(e),n=w.relative(o,r);return n===""||n.length>0&&!n.startsWith("..")&&!w.isAbsolute(n)}function Gc(t,e){if(Kc(t,e))throw new Error("Import source must be outside the current workspace root.")}function Vc(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}function Bc(t){let e=w.basename(t);return !([".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor","packages"].includes(e)||Vc(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Uc(t){let e=w.join(t,".rapidkit","project.json");if(!await R__default.pathExists(e))return null;try{return await R__default.readJson(e)}catch{return null}}async function Hc(t){let e=new Date().toISOString(),o=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:w.basename(t.projectPath),r=Wt({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:o}),n=r.contractRelativePath,i=w.join(t.projectPath,".rapidkit","project.json"),a=w.join(t.projectPath,".rapidkit","import.json"),c=w.join(t.projectPath,".rapidkit","import-readiness.json"),l=Io({existingProjectJson:t.existingProjectJson,detection:t.detection,enableModules:t.enableModules}),g=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],m=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},p={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:w.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:w.basename(t.projectPath),kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:l,modules:g,contracts:m,import:{managed_by:"rapidkit-npm",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:r.relativePath,is_external:r.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},d={schema_version:"1.0",kind:"rapidkit.imported_project",imported_at:e,managed_by:"rapidkit-npm",source:{type:t.sourceType,name:w.basename(t.projectPath)},project:{name:p.name,slug:p.slug,relative_path:n,kind:t.projectKind,module_support:l},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:l}},f=Ao({projectName:String(p.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:l,projectPath:t.projectPath,generatedAt:new Date(e)});return await R__default.ensureDir(w.dirname(i)),await R__default.writeJson(i,p,{spaces:2}),await R__default.writeJson(a,d,{spaces:2}),await R__default.writeJson(c,f,{spaces:2}),{projectJsonPath:i,importJsonPath:a,importReadinessPath:c,moduleSupport:l}}async function qc(t,e){let o={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,importedAt:new Date().toISOString()};await b$9(t,[o]);}async function ui(t){await R__default.pathExists(t)&&await R__default.remove(t);}async function mi(t,e){await ui(e),await c$3(t,[e]);}async function fi(t){let e=w.resolve(t.workspacePath),o=t.source.trim(),r=t.sourceType??Lc(o),n=t.name??(r==="git-url"?Fc(o):w.basename(o)),i=await Jc(e,n),a=false;try{if(r==="local-folder"){let f=w.resolve(o),u=await R__default.stat(f).catch(()=>null);if(!u||!u.isDirectory())throw new Error("Import source is not a directory.");Gc(e,f),a=true,await R__default.copy(f,i,{overwrite:false,errorOnExist:true,filter:Bc});}else a=true,await execa("git",["clone","--depth","1",o,i],{timeout:12e4});let c=await Uc(i),l=i$2(i,c),g=await e$2(i,c),m=await Hc({workspacePath:e,projectPath:i,sourceType:r,detection:l,existingProjectJson:c,projectKind:g,enableModules:t.enableModules}),p=Wt({workspacePath:e,projectPath:i,projectName:w.basename(i)}),d={name:w.basename(i),path:i,relativePath:p.contractRelativePath,stack:l.importStack,runtime:l.runtime,framework:l.key,frameworkDisplayName:l.displayName,supportTier:l.supportTier,moduleSupport:m.moduleSupport,confidence:l.confidence,source:r,projectJsonPath:m.projectJsonPath,importJsonPath:m.importJsonPath,importReadinessPath:m.importReadinessPath};return await qc(e,d),d}catch(c){if(a)try{await ui(i);}catch(l){let g=c instanceof Error?c.message:String(c),m=l instanceof Error?l.message:String(l);throw new Error(`Import failed: ${g}. Rollback also failed: ${m}`)}throw c}}function zc(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Yc(t,e){return w.resolve(t)===w.resolve(e)}async function Qc(t){let e=w.join(t,".rapidkit","project.json");if(!await R__default.pathExists(e))return null;try{return await R__default.readJson(e)}catch{return null}}function Xc(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],o=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:o,adoption:{managed_by:"rapidkit-npm",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,discovered_relative_path:t.discoveredRelativePath,is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function gi(t,e,o){let r=w.join(e,".rapidkit","project.json"),n=w.join(e,".rapidkit","adopt.json"),i=w.join(e,".rapidkit","adopt-readiness.json");o?await R__default.writeJson(r,o,{spaces:2}):await R__default.pathExists(r)&&await R__default.remove(r),await R__default.pathExists(n)&&await R__default.remove(n),await R__default.pathExists(i)&&await R__default.remove(i);let{removeImportedProjectsRegistryEntries:a}=await import('./imported-projects-registry-ZOCHFWMK.js');await a(t,[e]);}async function hi(t){let e=w.resolve(t.workspacePath),o=w.resolve(t.source),r=await R__default.stat(o).catch(()=>null);if(!r||!r.isDirectory())throw new Error("Adopt source is not a directory.");if(Yc(e,o))throw new Error("Adopt source cannot be the workspace root itself.");let n=await Qc(o),i=i$2(o,n),a=await e$2(o,n),c=zc(t.name||(typeof n?.name=="string"?n.name:"")||w.basename(o))||"adopted-project",l=Wt({workspacePath:e,projectPath:o,projectName:c}),g=(t.now??new Date).toISOString(),m=w.join(o,".rapidkit","project.json"),p=w.join(o,".rapidkit","adopt.json"),d=w.join(o,".rapidkit","adopt-readiness.json"),f=Io({existingProjectJson:n,detection:i,enableModules:t.enableModules}),u=Xc({projectName:c,contractRelativePath:l.contractRelativePath,isExternal:l.isExternal,discoveredRelativePath:l.relativePath,detection:i,existingProjectJson:n,projectKind:a,moduleSupport:f,adoptedAt:g}),h={schema_version:"1.0",kind:"rapidkit.adopted_project",adopted_at:g,managed_by:"rapidkit-npm",mode:"linked",workspace:{path:e},project:{name:c,path:o,relative_path:l.contractRelativePath,discovered_relative_path:l.relativePath,is_external:l.isExternal,kind:a,module_support:f},detection:{framework:i.key,framework_display_name:i.displayName,runtime:i.runtime,kind:a,confidence:i.confidence,support_tier:i.supportTier,import_stack:i.importStack,source:i.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:f,workspace_contract:"linked-project"}},k=Ao({projectName:c,relativePath:l.contractRelativePath,projectKind:a,source:"adopted-local",detection:i,moduleSupport:f,projectPath:o,generatedAt:new Date(g)});if(t.dryRun!==true){await R__default.ensureDir(w.dirname(m)),await R__default.writeJson(m,u,{spaces:2}),await R__default.writeJson(p,h,{spaces:2}),await R__default.writeJson(d,k,{spaces:2});let P={name:c,path:o,relativePath:l.contractRelativePath,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:f,confidence:i.confidence,source:"adopted-local",importedAt:g};await b$9(e,[P]);}return {name:c,path:o,relativePath:l.relativePath,contractRelativePath:l.contractRelativePath,isExternal:l.isExternal,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:f,confidence:i.confidence,projectJsonPath:m,adoptJsonPath:p,adoptReadinessPath:d,wroteFiles:t.dryRun!==true}}function Ir(t){if(!t||typeof t!="object")return null;let e=t.code;return e==="PYTHON_NOT_FOUND"||e==="BRIDGE_VENV_BOOTSTRAP_FAILED"||e==="BRIDGE_VENV_CREATE_FAILED"||e==="BRIDGE_PIP_BOOTSTRAP_FAILED"?e:null}function el(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Oe(t,e){let o=t.indexOf(e);if(o>=0&&o+1<t.length)return t[o+1];let r=t.find(n=>n.startsWith(`${e}=`));if(r)return r.slice(e.length+1)}function Gr(){return d$7()}function wi(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(w.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(w.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=c$6()),t.RAPIDKIT_SKIP_LOCK_SYNC||(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t.POETRY_KEYRING_ENABLED||(t.POETRY_KEYRING_ENABLED="false"),t.PYTHON_KEYRING_BACKEND||(t.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),t.POETRY_NO_INTERACTION||(t.POETRY_NO_INTERACTION="1"),t}function tl(t){return f$3(w.join(t,".venv"))}async function Di(t,e){return await z(t,["--version"],e)===0}async function dt(t){let e=w.join(t,"go.mod");if(await R__default.pathExists(e))return "go";let o=w.join(t,"pom.xml"),r=w.join(t,"build.gradle"),n=w.join(t,"build.gradle.kts");if(await R__default.pathExists(o)||await R__default.pathExists(r)||await R__default.pathExists(n))return "java";if((await R__default.pathExists(t)?await b$3.promises.readdir(t,{withFileTypes:true}):[]).some(p=>p.isFile()&&p.name.toLowerCase().endsWith(".sln")))return "dotnet";let a=w.join(t,"src");if(await R__default.pathExists(a)&&(await b$3.promises.readdir(a,{withFileTypes:true})).some(d=>d.isFile()&&d.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=w.join(t,"package.json");if(await R__default.pathExists(c))return "node";let l=w.join(t,"pyproject.toml"),g=w.join(t,"requirements.txt"),m=w.join(t,"poetry.lock");return await R__default.pathExists(l)||await R__default.pathExists(g)||await R__default.pathExists(m)?"python":null}async function ol(t){for(let e of Gr())if(await z(e,e==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Ti(t){for(let e of Gr())if(await z(e,e==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function rl(t){let e=f$3(w.join(t,".venv"));if(!await R__default.pathExists(e)){let i=await Ti(t);if(i!==0)return i}if(!await Di("poetry",t))return 0;let r=await z("poetry",["config","virtualenvs.in-project","true","--local"],t);if(r!==0)return r;let n=await z("poetry",["env","use",e],t);return n!==0?n:0}async function nl(t){let e=f$3(w.join(t,".venv"));if(!await R__default.pathExists(e)){let n=await Ti(t);if(n!==0)return n}await z(e,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let o=w.join(t,"requirements.txt");if(await R__default.pathExists(o)&&await z(e,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let r=w.join(t,"pyproject.toml");return await R__default.pathExists(r)&&(await z(e,["-m","pip","install","-e","."],t)===0||await z(e,["-m","pip","install","."],t)===0)?0:1}async function $r(t,e){return await rl(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await R__default.pathExists(w.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await nl(t))}async function Mr(t){let e=await ct("init",t);if(e===0)return 0;let o=["npm","pnpm","yarn"];for(let r of o){if(!await Di(r,t))continue;if(await z(r,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${r} install`)),0}return e}function sl(t,e){let o=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),r=Oe([...e],"--port");if(r&&!/^\d+$/.test(r.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Oe([...e],"--java-version"),i=Oe([...e],"--spring-boot-version"),a=Oe([...e],"--springdoc-version"),c=Oe([...e],"--group-id"),l=Oe([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(i&&!o(i.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(a&&!o(a.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(l&&!/^[A-Za-z0-9_.-]+$/.test(l.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Oe([...e],"--target-framework"),i=Oe([...e],"--root-namespace");if(n&&!/^net\d+\.\d+$/.test(n.trim()))return "Invalid --target-framework. Expected .NET target framework, e.g. net8.0";if(i&&!/^[A-Za-z0-9_.]+$/.test(i.trim()))return "Invalid --root-namespace. Use dot-separated .NET namespace identifiers only."}return null}async function Tr(t$1){if(t$1[0]!=="create"||t$1[1]!=="project")return 1;let e=t$1[2],o=p(e),r=t$1[3];if(!o||o.owner!=="npm")return 1;if(!r)return process.stderr.write(`Usage: ${o.createUsage??"rapidkit create project <kit> <name> [--output <dir>]"}
|
|
154
154
|
`),1;try{h(r);}catch(g){let m=g instanceof Error?g.message:String(g);return process.stderr.write(`${m}
|
|
155
|
-
`),1}let n=
|
|
156
|
-
`),1;let i=
|
|
157
|
-
`),1;await g.ensureDir(a),await t(o,{projectName:r,projectPath:a,args:t$1,skipGit:c,skipInstall:l});let m=re(process.cwd());if(m){let{syncWorkspaceProjects:p}=await import('./workspace-
|
|
158
|
-
`),1}}async function
|
|
155
|
+
`),1}let n=sl(o.id,t$1);if(n)return process.stderr.write(`${n}
|
|
156
|
+
`),1;let i=Oe(t$1,"--output")||process.cwd(),a=w.resolve(i,r),c=t$1.includes("--skip-git")||t$1.includes("--no-git"),l=t$1.includes("--skip-install");try{let{default:g}=await import('fs-extra');if(await g.ensureDir(w.dirname(a)),await g.pathExists(a))return process.stderr.write(`\u274C Directory "${a}" already exists
|
|
157
|
+
`),1;await g.ensureDir(a),await t(o,{projectName:r,projectPath:a,args:t$1,skipGit:c,skipInstall:l});let m=re(process.cwd());if(m){let{syncWorkspaceProjects:p}=await import('./workspace-FDMJD5XI.js');await p(m,true);}return 0}catch(g){return process.stderr.write(`RapidKit ${o.id} generator failed: ${g?.message??g}
|
|
158
|
+
`),1}}async function ki(t){let e=k$1(t[2]);if(!e)return 1;try{let o$1=await o({args:t});if(!o$1.dryRun){let r=re(process.cwd()),n=false;r||(r=(await Br()).workspacePath,n=true);let{registerProjectInWorkspace:i,registerWorkspace:a,syncWorkspaceProjects:c}=await import('./workspace-FDMJD5XI.js'),l=i$4({workspacePath:r,result:o$1});await a(r,w.basename(r)),await b$9(r,[l]),await i(r,o$1.projectName,o$1.projectPath),await c(r,true),await Ue(r,{silent:true}),n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a RapidKit workspace \u2014 linked to managed workspace "${f$6}" (${l.relationship}).`)),console.log(s.gray(` Registry: ${w.join(j$2(),"workspaces.json")}`)),console.log(s.gray(" Tip: run from inside a workspace next time, or create one with `rapidkit create workspace`.")));}return 0}catch(o){return process.stderr.write(`RapidKit ${e.kitId} generator failed: ${o?.message??o}
|
|
159
159
|
`),t[3]||process.stderr.write(`Usage: ${n(e.id)}
|
|
160
|
-
`),1}}async function
|
|
160
|
+
`),1}}async function Or(t,e){if(t.includes("--json"))return process.stderr.write("RapidKit (npm) offline fallback does not support --json for `create` commands.\nInstall Python 3.10+ and retry the same command.\n"),1;if(t[0]!=="create")return 1;if(t[1]!=="project")return process.stderr.write(`RapidKit (npm) could not run the Python core engine for \`create\`.
|
|
161
161
|
Reason: ${e}.
|
|
162
162
|
Install Python 3.10+ to use the interactive wizard and full kit catalog.
|
|
163
163
|
`),1;let n=t[2],i=t[3];if(!n||!i)return process.stderr.write(`Usage: rapidkit create project <kit> <name> [--output <dir>]
|
|
164
164
|
Tip: offline fallback supports only fastapi* and nestjs* kits.
|
|
165
|
-
`),1;let a=
|
|
165
|
+
`),1;let a=el(n);if(!a)return process.stderr.write(`RapidKit (npm) could not run the Python core engine to create this kit.
|
|
166
166
|
Reason: ${e}.
|
|
167
167
|
Requested kit: ${n}
|
|
168
168
|
Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
|
|
169
169
|
Install Python 3.10+ to access all kits.
|
|
170
|
-
`),1;let c=
|
|
171
|
-
`),1;let p="pip",d=re(process.cwd());if(d)try{let{readWorkspaceMarker:
|
|
172
|
-
`),1}}function
|
|
170
|
+
`),1;let c=Oe(t,"--output")||process.cwd(),l=w.resolve(c,i),g=t.includes("--skip-git")||t.includes("--no-git"),m=t.includes("--skip-install");try{if(await R__default.ensureDir(w.dirname(l)),await R__default.pathExists(l))return process.stderr.write(`\u274C Directory "${l}" already exists
|
|
171
|
+
`),1;let p="pip",d=re(process.cwd());if(d)try{let{readWorkspaceMarker:u}=await import('./workspace-marker-IOPQ42A7.js'),h=await u(d);h?.metadata?.npm?.installMethod&&(p=h.metadata.npm.installMethod,f.debug(`Detected workspace engine: ${p}`));}catch(u){f.debug("Failed to read workspace marker",u);}else f.debug("No workspace found, using default engine: pip");await R__default.ensureDir(l);let{generateDemoKit:f$1}=await import('./demo-kit-2VI4H6OJ.js');if(await f$1(l,{project_name:i,template:a,kit_name:n,skipGit:g,skipInstall:m,engine:p}),d){let{syncWorkspaceProjects:u}=await import('./workspace-FDMJD5XI.js');await u(d,true),await Ue(d,{silent:true});}return 0}catch(p){return process.stderr.write(`RapidKit (npm) offline fallback failed: ${p?.message??p}
|
|
172
|
+
`),1}}function il(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("RapidKit native create is not available for this request yet.")}
|
|
173
173
|
`),process.stderr.write(s.gray(`Requested: ${e}
|
|
174
174
|
`)),process.stderr.write(s.gray(`Lane: ${t.lane} (${t.status})
|
|
175
175
|
`)),process.stderr.write(s.gray(`Reason: ${t.reason}
|
|
176
176
|
`)),t.officialCommands?.length){process.stderr.write(s.gray(`External generator candidates:
|
|
177
177
|
`));for(let o of t.officialCommands)process.stderr.write(s.gray(` - ${o}
|
|
178
|
-
`));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx rapidkit adopt <project-path>` to add Workspace Intelligence.\n"));}async function
|
|
178
|
+
`));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx rapidkit adopt <project-path>` to add Workspace Intelligence.\n"));}async function Wi(t){let e$1=t[0]==="create"&&t[1]==="frontend",o=m$2(t);if(o&&(t=o),e$1&&!l$1(t[2]))return process.stderr.write(`Unknown frontend generator: ${t[2]?.replace(/^frontend\./,"")}
|
|
179
179
|
`),process.stderr.write(`Usage: ${n()}
|
|
180
|
-
`),1;let r=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace","--here","--output"]);if(t[0]==="create"&&(!t[1]||t[1].startsWith("-"))){let n=t.includes("--yes")||t.includes("-y"),i=t.slice(1),a;!process.stdin.isTTY||n?(a="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."))):(process.stdin.isTTY&&a$2("create"),a=(await b$2([{type:"rawlist",name:"createTarget",message:"What do you want to create?",choices:[{name:"workspace",value:"workspace"},{name:"project",value:"project"}]}])).createTarget);let c=["create",a,...i];return await
|
|
181
|
-
`),1;try{h(d);}catch(
|
|
182
|
-
`),1;throw
|
|
183
|
-
`),
|
|
184
|
-
`),1;let
|
|
185
|
-
`),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))try{return await d$4(),await e(["create","project","--help"],{cwd:process.cwd()})}catch(
|
|
186
|
-
`),1}if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a$2("create project");let{kitChoice:
|
|
187
|
-
`),f.debug(`Synced Python version ${T.trim()} from workspace to ${x}`);}}}catch(x){f.debug("Could not sync Python version from workspace:",x);}let{syncWorkspaceProjects:
|
|
188
|
-
`),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$4();let n=await e(t,{cwd:process.cwd()});if(n===0){let i=re(process.cwd());if(i){let{syncWorkspaceProjects:a}=await import('./workspace-
|
|
189
|
-
`),1)}return await d$4(),await e(t,{cwd:process.cwd()})}catch(n){let i=
|
|
190
|
-
`),1)}}var
|
|
180
|
+
`),1;let r=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace","--here","--output"]);if(t[0]==="create"&&(!t[1]||t[1].startsWith("-"))){let n=t.includes("--yes")||t.includes("-y"),i=t.slice(1),a;!process.stdin.isTTY||n?(a="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."))):(process.stdin.isTTY&&a$2("create"),a=(await b$2([{type:"rawlist",name:"createTarget",message:"What do you want to create?",choices:[{name:"workspace",value:"workspace"},{name:"project",value:"project"}]}])).createTarget);let c=["create",a,...i];return await Wi(c)}if(t[0]==="create"&&t[1]==="workspace")try{let n=t.includes("--yes")||t.includes("-y"),i=t.includes("--skip-git")||t.includes("--no-git"),a=t.includes("--dry-run"),c=t[2]&&!t[2].startsWith("-")?t[2]:void 0,l$1=Oe(t,"--install-method"),g=l$1==="poetry"||l$1==="venv"||l$1==="pipx"?l$1:void 0,m$1=Oe(t,"--profile"),p=m$1==="minimal"||m$1==="java-only"||m$1==="go-only"||m$1==="dotnet-only"||m$1==="python-only"||m$1==="node-only"||m$1==="polyglot"||m$1==="enterprise"?m$1:void 0,d=c;if(d||(n?d="my-workspace":(process.stdin.isTTY&&a$2("create workspace"),d=(await b$2([{type:"input",name:"workspaceName",message:"Workspace name:",default:"my-workspace"}])).workspaceName)),!d||!d.trim())return process.stderr.write(`Workspace name is required.
|
|
181
|
+
`),1;try{h(d);}catch(y){if(y instanceof a$3)return process.stderr.write(`${y.message}
|
|
182
|
+
`),1;throw y}let f=await m(t,{hasYes:n}),u=l(d.trim(),{argv:t,outputParent:f});a||await R__default.ensureDir(w.dirname(u));let h$2=h$1(d.trim());if(!a&&(h$2&&await R__default.pathExists(h$2)||await R__default.pathExists(u)))return process.stderr.write(`\u274C Workspace "${d}" already exists
|
|
183
|
+
`),h$2&&h$2!==u&&process.stderr.write(` Found at: ${h$2}
|
|
184
|
+
`),1;let k$1=await b$1(),P=k$1.author||process.env.USER||"RapidKit User";if(!n){let y=await b$2([{type:"input",name:"author",message:"Author name:",default:P}]);y.author?.trim()&&(P=y.author.trim());}let{createProject:v}=await import('./create-UGXMC4CT.js');return await v(d,{skipGit:i,yes:n,dryRun:a,userConfig:{...k$1,author:P},installMethod:g,profile:p,parentDirectory:w.dirname(u)}),a||(console.log(s.gray(`\u2139\uFE0F Workspace root: ${u}`)),console.log(s.gray(` Next: ${k(u)} && npx rapidkit create project`))),0}catch(n){return process.stderr.write(`RapidKit (npm) failed to create workspace: ${n?.message??n}
|
|
185
|
+
`),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))try{return await d$4(),await e(["create","project","--help"],{cwd:process.cwd()})}catch(v){return process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${v?.message??v}
|
|
186
|
+
`),1}if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a$2("create project");let{kitChoice:v}=await b$2([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$8()}]);if(s$1(v)||l$1(v)){let x=Rr(v),{projectName:I}=await b$2([{type:"input",name:"projectName",message:"Project name:",default:x,validate:T=>T.trim().length>0||"Project name is required"}]),Y=t.slice(2).filter(T=>T.startsWith("-")),H=["create","project",v,I.trim(),...Y],ae=l$1(v)?await ki(H):await Tr(H),N=re(process.cwd());return ae===0&&N&&await Ue(N),ae}let y=Rr(v),{projectName:C}=await b$2([{type:"input",name:"projectName",message:"Project name:",default:y,validate:x=>x.trim().length>0||"Project name is required"}]);t.splice(2,0,v,C.trim());}let i=t[2],a=c$4({kitId:i,framework:i,runtime:i});if(d$5(a))return il(a),1;{let v=re(process.cwd()),y=(t[2]||"").toLowerCase();if(v&&y){let C=w.join(v,".rapidkit","workspace.json"),x=w.join(v,".rapidkit","policies.yml");try{let[I,Y]=await Promise.all([R__default.pathExists(C).then(ke=>ke?b$3.promises.readFile(C,"utf-8"):"{}"),R__default.pathExists(x).then(ke=>ke?b$3.promises.readFile(x,"utf-8"):"")]),H=JSON.parse(I).profile,N=Y.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]??"warn",T=p(y),O=k$1(y)?"node":T?.runtime,G=O==="go",S=O==="java",ee=O==="dotnet",Re=O==="node",q=O==="python"||!O,X=null;if(H==="python-only"&&!q?X=`Kit "${y}" is not a Python kit, but workspace profile is "python-only".`:H==="node-only"&&!Re?X=`Kit "${y}" is not a Node kit, but workspace profile is "node-only".`:H==="go-only"&&!G?X=`Kit "${y}" is not a Go kit, but workspace profile is "go-only".`:H==="java-only"&&!S?X=`Kit "${y}" is not a Java kit, but workspace profile is "java-only".`:H==="dotnet-only"&&!ee&&(X=`Kit "${y}" is not a .NET kit, but workspace profile is "dotnet-only".`),X){if(N==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${X}`)),console.log(s.gray("\u{1F4A1} Change workspace profile or use --no-workspace to skip enforcement.")),1;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${X}`)),console.log(s.gray('\u{1F4A1} Consider using a "polyglot" workspace profile for multi-language projects.'));}}catch{}}}if(s$1(t[2])){let v=await Tr(t),y=re(process.cwd());return v===0&&y&&await Ue(y),v}if(l$1(t[2]))return await ki(t);let c=t.includes("--create-workspace"),l=t.includes("--no-workspace"),g=t.includes("--yes")||t.includes("-y"),m=t.includes("--skip-git")||t.includes("--no-git");if(!!!Lr(process.cwd())){let{registerWorkspaceAtPath:v}=await import('./create-UGXMC4CT.js');if(c)await v(process.cwd(),{skipGit:m,yes:g,userConfig:await b$1()});else if(!l)if(g)await v(process.cwd(),{skipGit:m,yes:true,userConfig:await b$1()});else {let{createWs:y}=await b$2([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);y&&await v(process.cwd(),{skipGit:m,yes:false,userConfig:await b$1()});}}let f$1=[...t.filter(v=>{let y=v.split("=")[0];return !r.has(v)&&!r.has(y)})],u=re(process.cwd()),P=t.includes("--skip-install")||!!u?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$4();let v=await e(f$1,{cwd:process.cwd(),env:P});if(v===0&&u&&!t.includes("--skip-install")&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx rapidkit init"))),v===0){let y=u||re(process.cwd());if(y){try{let x=t[3];if(x){let I=t.indexOf("--output"),Y=I>=0?t[I+1]:".",H=w.resolve(process.cwd(),Y,x),ae=w.join(y,".python-version"),N=w.join(H,".python-version");if(b$3.existsSync(ae)&&b$3.existsSync(H)){let T=b$3.readFileSync(ae,"utf-8");b$3.writeFileSync(N,T.trim()+`
|
|
187
|
+
`),f.debug(`Synced Python version ${T.trim()} from workspace to ${x}`);}}}catch(x){f.debug("Could not sync Python version from workspace:",x);}let{syncWorkspaceProjects:C}=await import('./workspace-FDMJD5XI.js');await C(y,true),await Ue(y);}}return v}catch(v){let y=Ir(v);return y?await Or(f$1,y):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${v?.message??v}
|
|
188
|
+
`),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$4();let n=await e(t,{cwd:process.cwd()});if(n===0){let i=re(process.cwd());if(i){let{syncWorkspaceProjects:a}=await import('./workspace-FDMJD5XI.js');await a(i,true);}}return n}catch(n){let i=Ir(n);return i?await Or(t,i):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${n?.message??n}
|
|
189
|
+
`),1)}return await d$4(),await e(t,{cwd:process.cwd()})}catch(n){let i=Ir(n);return i?await Or(t,i):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${n?.message??n}
|
|
190
|
+
`),1)}}var vi=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],Fi=["analyze","readiness","doctor","autopilot","pipeline","import","adopt","snapshot","workspace","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands"],al=["analyze","readiness","doctor","autopilot","pipeline","import","adopt","snapshot","workspace","ai","config","product","infra","shell","commands"],cl=["bootstrap","setup","cache","mirror"],ll=[["project","commands"],["project","archives"],["project","archive"],["project","restore"],["project","delete"]],dl=["init"],pl=h$3,Pi=[...pl,...i$1];function ul(t){return !!t&&Fi.includes(t)}function Li(t){let e=t[0],o=t[1];return ll.some(([r,n])=>e!==r?false:o?o===n:true)}function Lt(t){return ul(t[0])||Li(t)}function ml(t){return !!t&&al.includes(t)}function bi(t){return ml(t[0])||Li(t)}function ji(t){return !!t&&cl.includes(t)}function fl(t=process.env){let e=t.npm_config_user_agent||"",o=t.npm_execpath||"",r=t.npm_command||"";return e.startsWith("npm/")||e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(o)||/(?:^|[/\\])npm(?:\.cmd)?$/i.test(o)||r==="exec"||r==="x"||r==="run-script"}function Ji(t={}){let e=q$1(process.cwd());if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("RapidKit project command capabilities")),console.log(s.gray(`Project: ${e.projectRoot??"not detected"}`)),console.log(s.gray(`Runtime: ${e.runtime} (${e.runtimeSupportTier}) | Framework: ${e.frameworkDisplayName} (${e.frameworkSupportTier}) | Module support: ${e.moduleSupport?"yes":"no"}`)),console.log(s.gray(`Doctor support: ${e.runtimeDoctorSupport}`)),console.log(""),console.log(s.green(`Supported: ${e.supportedCommands.join(", ")||"none"}`)),console.log(s.yellow(`Global: ${e.globalCommands.join(", ")||"none"}`)),console.log(s.red(`Unsupported: ${e.unsupportedCommands.join(", ")||"none"}`));}var Ki="rapidkit-command-capabilities-v1",gl="rapidkit-version-v1";function hl(){return {schemaVersion:gl,cli:"rapidkit-npm",version:b(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:Ki,contracts:_o()}}function yl(){let t=[...Fi,"project"],e=["version","create","add","list","info","upgrade","diff","merge","optimize","license","checkpoint","reconcile","rollback","uninstall","frameworks","modules"],o=["init","dev","start","build","test","lint","format","help"],r=[...Ro],n=[...Eo];return {schemaVersion:Ki,scope:"global",cli:"rapidkit-npm",version:b(),cwd:process.cwd(),contracts:_o(),commands:{npmOwned:t,coreBacked:e,projectScoped:o},workspace:{command:"workspace",subcommands:r,intelligenceSubcommands:n},commandMap:Object.fromEntries([...t.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...e.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...o.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])])}}function wl(t={}){let e=yl();if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("RapidKit command capabilities")),console.log(s.gray(`CLI: ${e.cli} v${e.version}`)),console.log(""),console.log(s.green(`npm wrapper: ${e.commands.npmOwned.join(", ")}`)),console.log(s.cyan(`Python core: ${e.commands.coreBacked.join(", ")}`)),console.log(s.yellow(`Project runtime: ${e.commands.projectScoped.join(", ")}`)),console.log(s.magenta(`Workspace intelligence: ${e.workspace.intelligenceSubcommands.join(", ")}`)),console.log(""),console.log(s.gray("Tip: run `rapidkit project commands --json` inside a project."));}function Wr(t){return s$2(t)?(Ji({json:t.includes("--json")||t.includes("--ci")}),true):false}function Fr(t){let e=q$1(process.cwd());if(!e.projectRoot)return false;let o=r(t,process.cwd());if(!o||o.status!=="unsupported")return false;console.error(s.red(t$1(o,e))),process.exit(1);}function We(t){return b$3.existsSync(w.join(t,".rapidkit-workspace"))||b$3.existsSync(w.join(t,".rapidkit","workspace.json"))}function Gi(t){let e=t;for(;;){let o=w.join(e,".rapidkit","context.json");if(b$3.existsSync(o))return o;let r=w.dirname(e);if(r===e)break;e=r;}return null}function Lr(t){let e=t,o=w.resolve(tmpdir());for(;;){let r=w.join(e,".rapidkit-workspace");if(b$3.existsSync(r)&&w.resolve(e)!==o)return r;let n=w.dirname(e);if(n===e)break;e=n;}return null}function re(t){let e=t,o=w.resolve(tmpdir());for(;;){let r=w.join(e,".rapidkit-workspace");if(b$3.existsSync(r)&&w.resolve(e)!==o)return e;let n=w.dirname(e);if(n===e)break;e=n;}return null}async function Ue(t,e){try{let{syncWorkspaceContract:o}=await import('./workspace-contract-ITFCJCHI.js'),r=await o({workspacePath:t});if(!e?.silent&&(r.addedProjects.length>0||r.updatedProjects.length>0)&&console.log(s.gray(`\u2139\uFE0F Workspace contract synced (${r.contract.projects.length} project(s)).`)),r.verification.status!=="passed"){console.log(s.yellow("\u26A0\uFE0F Workspace contract verification failed after project sync."));for(let n of r.verification.violations)console.log(s.gray(` Violation: ${n}`));console.log(s.white(" Next: npx rapidkit workspace contract inspect"));}}catch(o){e?.silent||console.log(s.yellow(`\u26A0\uFE0F Workspace contract sync skipped: ${o.message}`));}}async function kl(t,e=process.cwd(),o=process.platform){if(!(t.workspaceFlag||t.scope==="workspace")||!a(o))return {detected:false};let n=i(e,o);for(let i of n){if(!await R__default.pathExists(i))continue;let a=i.toLowerCase();if(a.endsWith("rapidkit.cmd")||a.endsWith("rapidkit.exe"))return {detected:true,candidatePath:i,reason:"Found workspace-local rapidkit launcher on Windows."}}return {detected:false}}function vl(t){let e=t;for(;;){let o=w.join(e,".rapidkit-workspace"),r=w.join(e,".rapidkit","workspace.json");if(!b$3.existsSync(o)&&b$3.existsSync(r))return e;let n=w.dirname(e);if(n===e)break;e=n;}return null}var Vi={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function Pl(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Ft(t,e){let o=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return o?o[1]==="true":Vi[e]}function xi(t){let e=t??"";return {mode:Pl(e),dependency_sharing_mode:Bi(e),rules:{enforce_workspace_marker:Ft(e,"enforce_workspace_marker"),enforce_toolchain_lock:Ft(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Ft(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Ft(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Ft(e,"require_mirror_lock_for_offline")}}}function Ci(t,e,o){let r=`${e}: ${o}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(i.test(t))return t.replace(i,r);let a=/^[\t ]*rules:\s*(?:#.*)?$/m;return a.test(t)?t.replace(a,`${r}
|
|
191
191
|
rules:`):`${t.endsWith(`
|
|
192
192
|
`)?t:`${t}
|
|
193
193
|
`}${r}
|
|
194
|
-
`}function
|
|
194
|
+
`}function bl(t,e,o){let r=` ${e}: ${o?"true":"false"}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^[\\t ]+${n}:\\s*.*$`,"m");if(i.test(t))return t.replace(i,r);let a=/^[\t ]*rules:\s*(?:#.*)?$/m;return a.test(t)?t.replace(a,`rules:
|
|
195
195
|
${r}`):`${t.endsWith(`
|
|
196
196
|
`)?t:`${t}
|
|
197
197
|
`}rules:
|
|
198
198
|
${r}
|
|
199
|
-
`}function
|
|
200
|
-
`)}async function
|
|
199
|
+
`}function jl(){return ['version: "1.0"','mode: warn # "warn" or "strict"','dependency_sharing_mode: isolated # "isolated" or "shared-runtime-caches" or "shared-node-deps"',"# change profile (recommended): npx rapidkit bootstrap --profile polyglot","# change mode/dependency manually: edit this file and rerun npx rapidkit init","rules:"," enforce_workspace_marker: true"," enforce_toolchain_lock: false"," disallow_untrusted_tool_sources: false"," enforce_compatibility_matrix: false"," require_mirror_lock_for_offline: true",""].join(`
|
|
200
|
+
`)}async function Si(t){let e=w.join(t,".rapidkit","policies.yml");return await R__default.pathExists(e)?b$3.promises.readFile(e,"utf-8"):jl()}async function xl(t,e){let o=w.join(t,".rapidkit"),r=w.join(o,"policies.yml");await R__default.ensureDir(o);let n=e.endsWith(`
|
|
201
201
|
`)?e:`${e}
|
|
202
|
-
`;await b$3.promises.writeFile(r,n,"utf-8");}function
|
|
203
|
-
`,"utf-8");}async function fl(t,e,o){let r=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?w.resolve(e.workspace):null,i=n??re(process.cwd()),a=false,c=false;if(n){if(!We(n)){let p=`Workspace path is not a valid RapidKit workspace: ${n}`;return e.json?console.log(JSON.stringify({error:p},null,2)):console.log(s.red(`\u274C ${p}`)),1}}else if(!i||!We(i)){let p=await Vr();i=p.workspacePath,a=true,c=p.created;}if(!i||!We(i)){let p="Not inside a RapidKit workspace";return e.json?console.log(JSON.stringify({error:p},null,2)):(console.log(s.red(`\u274C ${p}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let l=`cd ${i}`,g=o?.syncWorkspaceProjects??(async p=>{if(r)throw new Error("forced sync failure for command-level import rollback test");let{syncWorkspaceProjects:d}=await import('./workspace-L4ITCKMM.js');await d(p,true),await Ue(p,{silent:true});}),m=o?.rollbackImportedProjectImport??ei;try{let p=await ti({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,enableModules:e.enableModules});try{await g(i);}catch(d){await m(i,p.path);try{await g(i);}catch{}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${d instanceof Error?d.message:String(d)}`)}return e.json?(console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?c:false,suggestedCdCommand:l,importedProject:p},null,2)),0):(a&&console.log(s.yellow(`\u2139 Imported outside a workspace, so RapidKit used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${p.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${p.path}`)),console.log(s.gray(` Stack: ${p.stack} (${p.confidence})`)),console.log(s.gray(` Source: ${e.git===true||_r(t)?"git-url":"local-folder"}`)),console.log(s.gray(` Next shell step: ${l}`)),0)}catch(p){let d=p instanceof Error?p.message:String(p);return e.json?console.log(JSON.stringify({error:d},null,2)):console.log(s.red(`\u274C Import failed: ${d}`)),1}}async function gl(t,e,o){let r=w.resolve(t||process.cwd()),n=e.workspace?w.resolve(e.workspace):null,i=n??re(process.cwd()),a=false,c=false;if(n){if(!We(n)){let u=`Workspace path is not a valid RapidKit workspace: ${n}`;return e.json?console.log(JSON.stringify({error:u},null,2)):console.log(s.red(`\u274C ${u}`)),1}}else if(!i||!We(i)){let u=await Vr();i=u.workspacePath,a=true,c=u.created;}if(!i||!We(i)){let u="Not inside a RapidKit workspace";return e.json?console.log(JSON.stringify({error:u},null,2)):(console.log(s.red(`\u274C ${u}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let l=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),g=o?.syncWorkspaceProjects??(async u=>{if(l)throw new Error("forced sync failure for command-level adopt rollback test");let{syncWorkspaceProjects:f}=await import('./workspace-L4ITCKMM.js');await f(u,true),await Ue(u,{silent:true});}),m=o?.registerProjectInWorkspace??(async(u,f,y)=>{let{registerProjectInWorkspace:v}=await import('./workspace-L4ITCKMM.js');await v(u,f,y);}),p=o?.registerWorkspace??(async(u,f)=>{let{registerWorkspace:y}=await import('./workspace-L4ITCKMM.js');await y(u,f);}),d=o?.rollbackAdoptedProjectImport??oi;try{let u=w.join(r,".rapidkit","project.json"),f=await R__default.pathExists(u)?await R__default.readJson(u):null,y=await ri({workspacePath:i,source:r,name:e.name,dryRun:e.dryRun===true,enableModules:e.enableModules});if(e.dryRun!==true)try{await p(i,w.basename(i)),await m(i,y.name,y.path),await g(i);}catch(v){throw await d(i,y.path,f),new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${v instanceof Error?v.message:String(v)}`)}return e.json?(console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?c:false,dryRun:e.dryRun===true,adoptedProject:y},null,2)),0):(a&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so RapidKit used the default workspace: ${i}`)),e.dryRun===true&&console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.green(`\u2714 Adopted project: ${y.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${y.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${y.stack} (${y.confidence})`)),console.log(s.gray(` Report: ${y.adoptReadinessPath}`)),console.log(s.gray(" Next: npx rapidkit workspace model --json")),0)}catch(u){let f=u instanceof Error?u.message:String(u);return e.json?console.log(JSON.stringify({error:f},null,2)):console.log(s.red(`\u274C Adopt failed: ${f}`)),1}}async function Lr(t){let e=new Set(["python-only","polyglot","enterprise"]),o="minimal";try{let i=w.join(t,".rapidkit","workspace.json");o=JSON.parse(await b$3.promises.readFile(i,"utf-8")).profile??"minimal";}catch{o="minimal";}if(!await(async()=>{if(e.has(o))return true;let i=await Gr(t);if(i.length===0)return false;for(let a of i){let c=a$5(a),l=c?.module_support;if(!(b$6(c,a)||d$3(c,a)||e$1(c,a))&&l!==false)return f$2(c,a)||c$2(c,a),true}return false})())return 0;let n="poetry";try{let{readWorkspaceMarker:i}=await import('./workspace-marker-IOPQ42A7.js'),c=(await i(t))?.metadata?.npm?.installMethod;(c==="poetry"||c==="venv"||c==="pipx"||c==="pip")&&(n=c);}catch{}if(n==="poetry"||n==="venv"){let i=w.join(t,"pyproject.toml"),a=false;try{a=(await b$3.promises.readFile(i,"utf-8")).includes("rapidkit-core");}catch{a=false;}let c=process.env.RAPIDKIT_DEV_PATH,l=c?await R__default.pathExists(c):false;if(a){let g=Gc(t);if(!await R__default.pathExists(g)){let d=await Vc(t);if(d!==0)return d}let p=await z(g,l&&c?["-m","pip","install",c,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"],t);if(p!==0)return p}else {let g=await z("poetry",["install","--no-root"],t);if(g!==0)return g;let m=await z("poetry",["add","rapidkit-core"],t);if(m!==0)return m}try{let{writeWorkspaceLauncher:g}=await import('./create-XVDDQA42.js');await g(t,n==="venv"?"venv":"poetry");}catch{}return 0}return 0}async function Gr(t){let e=[],o=new Set,r=[t];for(;r.length>0;){let n=r.pop();if(!n||o.has(n))continue;o.add(n);let i=[];try{i=await b$3.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){if(!a.isDirectory()||a.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(a.name))continue;let c=w.join(n,a.name),l=w.join(c,".rapidkit","context.json"),g=w.join(c,".rapidkit","project.json");if(await R__default.pathExists(l)||await R__default.pathExists(g)){e.push(c);continue}r.push(c);}}return e}function hl(t){return i$5(t)}async function Vr(){let t=j$1(),e=w.basename(t),o=We(t);await R__default.ensureDir(w.join(t,".rapidkit")),await b$9(t,d$5(e,b()));let r=w.join(t,".rapidkit","workspace.json");return await R__default.pathExists(r)||await lt(r,{name:e,workspace_name:e,profile:"minimal",createdAt:new Date().toISOString(),createdBy:"rapidkit-npm-import-fallback"}),{workspacePath:t,created:!o}}async function Nr(t){let o=await Ve("go",{runCommandInCwd:z,runCoreRapidkit:e}).initProject(t);return X(o)}function X(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function ct(t,e$1){let o=Ve("node",{runCommandInCwd:z,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return X(n)}if(t==="dev"){let n=await o.runDev(e$1);return X(n)}if(t==="test"){let n=await o.runTest(e$1);return X(n)}if(t==="build"){let n=await o.runBuild(e$1);return X(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return X(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return X(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return X(r)}async function Be(t,e$1){let o=Ve("java",{runCommandInCwd:z,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return X(n)}if(t==="dev"){let n=await o.runDev(e$1);return X(n)}if(t==="test"){let n=await o.runTest(e$1);return X(n)}if(t==="build"){let n=await o.runBuild(e$1);return X(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return X(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return X(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return X(r)}function fi(t,e,o){let r=o.filter(n=>n.status==="failed").map(n=>{let i=n.id||"check";return n.message?`${i}: ${n.message}`:i}).slice(0,12);return f$4(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:r,runId:e$3()})}async function gi(t,e=Jr){let o=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let i=function(E){if(!E)return null;let M=E.trim().toLowerCase();return M==="minimal"||M==="java-only"||M==="go-only"||M==="dotnet-only"||M==="python-only"||M==="node-only"||M==="polyglot"||M==="enterprise"?M:null},a=function(E){let $e=E.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",we=(Fe,rt)=>{let St=E.match(new RegExp(`^\\s*${Fe}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return St?St[1].toLowerCase()==="true":rt};return {mode:$e,dependency_sharing_mode:Mi(E),rules:{enforce_workspace_marker:we("enforce_workspace_marker",true),enforce_toolchain_lock:we("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:we("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:we("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:we("require_mirror_lock_for_offline",true)}}};let c=["init"],l,g=false,m=false,p=false,d=false;for(let E=1;E<t.length;E+=1){let M=t[E];if(M==="--ci"){g=true;continue}if(M==="--offline"){m=true;continue}if(M==="--json"){p=true;continue}if(M==="--compliance-only"){d=true;continue}if(M==="--profile"){let W=t[E+1];if(!W||W.startsWith("-"))return console.log(s.yellow("Usage: rapidkit bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;l=W,E+=1;continue}if(M.startsWith("--profile=")){l=M.slice(10);continue}c.push(M);}let u=i(l);if(l&&!u)return console.log(s.red(`Invalid profile: ${l}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let f=process.cwd(),y=c.slice(1).filter(E=>!E.startsWith("-"));if(y.length>0){let E=w.resolve(f,y[0]),M=a$5(E),W=b$3.existsSync(E)?await dt(E):"unknown";if(!We(E)&&(b$6(M,E)||d$3(M,E)||e$1(M,E)||c$2(M,E)||f$2(M,E)||W!=="unknown"))return await e(c)}let v=w.join(f,".rapidkit-workspace"),P=w.join(f,".rapidkit","workspace.json"),k;!b$3.existsSync(v)&&b$3.existsSync(P)?k=f:(k=re(f),k||(k=cl(f)));let h=[],S=null,x=null;if(k)try{let E=w.join(k,".rapidkit","workspace.json"),M=await b$3.promises.readFile(E,"utf-8"),W=JSON.parse(M);x=i(W.profile);}catch{x=null;}let I=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],Y={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},H=u;if(!!k&&!u&&!g&&!p&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let E=x||"minimal",{chosenProfile:M}=await b$2([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${E})`,choices:I.map(W=>({name:W===E?`${Y[W]} \u2190 current`:Y[W],value:W})),default:I.indexOf(E)}]);H=M;}let O=H||x||"minimal";if(k)try{let M=O==="python-only"||O==="polyglot"||O==="enterprise"?"poetry":"venv",W;try{let rt=(await b$3.promises.readFile(w.join(k,".python-version"),"utf-8")).trim();rt&&(W=rt);}catch{}let{syncWorkspaceFoundationFiles:$e}=await import('./create-XVDDQA42.js'),we=await $e(k,{workspaceName:w.basename(k),installMethod:M,pythonVersion:W,profile:O,writeMarker:true,writeGitignore:true,onlyIfMissing:true});h.push({id:"workspace.legacy.sync",status:we.length>0?"passed":"skipped",message:we.length>0?`Legacy workspace foundation synchronized: ${we.join(", ")}`:"Workspace foundation files are already up to date."});}catch(E){h.push({id:"workspace.legacy.sync",status:"failed",message:`Failed to synchronize legacy workspace foundation files: ${E.message}`});}if(k&&H&&H!==x)try{let E=w.join(k,".rapidkit","workspace.json"),M=await b$3.promises.readFile(E,"utf-8"),W=JSON.parse(M);W.profile=H,await b$3.promises.writeFile(E,JSON.stringify(W,null,2)+`
|
|
204
|
-
`,"utf-8");}catch{}let T={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},je=null;if(
|
|
205
|
-
`):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${q}`))),1}let Ee=0;p&&d||(Ee=await e(c));let xe=
|
|
206
|
-
`);else {let E=
|
|
207
|
-
${I.stderr||""}`.match(/version\s+"([^"]+)"/i);
|
|
208
|
-
${je.stderr||""}`.match(/Apache Maven\s+(\S+)/i);P=
|
|
209
|
-
${je.stderr||""}`.match(/Gradle\s+(\S+)/i);P=
|
|
202
|
+
`;await b$3.promises.writeFile(r,n,"utf-8");}function Cl(t){let e=t.trim().toLowerCase();return e==="true"||e==="1"||e==="on"?true:e==="false"||e==="0"||e==="off"?false:null}function Bi(t){if(!t)return "isolated";let o=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated"?o:"isolated"}function Ui(t){if(!t)return {mode:"isolated",status:"skipped",message:"No policies.yml found; dependency_sharing_mode defaults to isolated."};let e=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m);if(!e)return {mode:"isolated",status:"skipped",message:"dependency_sharing_mode is not set; defaulting to isolated."};let o=e[1].toLowerCase();return o==="isolated"||o==="shared-runtime-caches"||o==="shared-node-deps"?{mode:o,status:"passed",message:`dependency_sharing_mode is valid: ${o}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${o}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function Hi(t,e){let o=re(t),r=o?w.join(o,".rapidkit","policies.yml"):null,n="isolated";if(r&&await R__default.pathExists(r))try{let c=await b$3.promises.readFile(r,"utf-8"),l=Ui(c);if(l.status==="failed")return console.log(s.red(`\u274C ${l.message}`)),{ok:false,code:1};n=l.mode;}catch{return console.log(s.red("\u274C Failed to read workspace policy file (.rapidkit/policies.yml).")),{ok:false,code:1}}let i=process.env.RAPIDKIT_DEP_SHARING_MODE,a=process.env.RAPIDKIT_WORKSPACE_PATH;process.env.RAPIDKIT_DEP_SHARING_MODE=n,o&&(process.env.RAPIDKIT_WORKSPACE_PATH=o);try{return {ok:true,value:await e()}}finally{typeof i>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=i,typeof a>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=a;}}async function z(t,e,o){return await new Promise(r=>{let n=spawn(t,e,{stdio:["ignore","pipe","pipe"],cwd:o,shell:b$a()});n.stdout?.on("data",i=>{process.stdout.write(i);}),n.stderr?.on("data",i=>{process.stderr.write(i);}),n.on("close",i=>r(i??1)),n.on("error",()=>r(1));})}async function lt(t,e){await R__default.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
203
|
+
`,"utf-8");}async function Sl(t,e,o){let r=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?w.resolve(e.workspace):null,i=n??re(process.cwd()),a=false,c=false;if(n){if(!We(n)){let p=`Workspace path is not a valid RapidKit workspace: ${n}`;return e.json?console.log(JSON.stringify({error:p},null,2)):console.log(s.red(`\u274C ${p}`)),1}}else if(!i||!We(i)){let p=await Br();i=p.workspacePath,a=true,c=p.created;}if(!i||!We(i)){let p="Not inside a RapidKit workspace";return e.json?console.log(JSON.stringify({error:p},null,2)):(console.log(s.red(`\u274C ${p}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let l=`cd ${i}`,g=o?.syncWorkspaceProjects??(async p=>{if(r)throw new Error("forced sync failure for command-level import rollback test");let{syncWorkspaceProjects:d}=await import('./workspace-FDMJD5XI.js');await d(p,true),await Ue(p,{silent:true});}),m=o?.rollbackImportedProjectImport??mi;try{let p=await fi({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,enableModules:e.enableModules});try{await g(i);}catch(d){await m(i,p.path);try{await g(i);}catch{}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${d instanceof Error?d.message:String(d)}`)}return e.json?(console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?c:false,suggestedCdCommand:l,importedProject:p},null,2)),0):(a&&console.log(s.yellow(`\u2139 Imported outside a workspace, so RapidKit used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${p.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${p.path}`)),console.log(s.gray(` Stack: ${p.stack} (${p.confidence})`)),console.log(s.gray(` Source: ${e.git===true||Ar(t)?"git-url":"local-folder"}`)),console.log(s.gray(` Next shell step: ${l}`)),0)}catch(p){let d=p instanceof Error?p.message:String(p);return e.json?console.log(JSON.stringify({error:d},null,2)):console.log(s.red(`\u274C Import failed: ${d}`)),1}}async function Rl(t,e,o){let r=w.resolve(t||process.cwd()),n=e.workspace?w.resolve(e.workspace):null,i=n??re(process.cwd()),a=false,c=false;if(n){if(!We(n)){let f=`Workspace path is not a valid RapidKit workspace: ${n}`;return e.json?console.log(JSON.stringify({error:f},null,2)):console.log(s.red(`\u274C ${f}`)),1}}else if(!i||!We(i)){let f=await Br();i=f.workspacePath,a=true,c=f.created;}if(!i||!We(i)){let f="Not inside a RapidKit workspace";return e.json?console.log(JSON.stringify({error:f},null,2)):(console.log(s.red(`\u274C ${f}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let l=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),g=o?.syncWorkspaceProjects??(async f=>{if(l)throw new Error("forced sync failure for command-level adopt rollback test");let{syncWorkspaceProjects:u}=await import('./workspace-FDMJD5XI.js');await u(f,true),await Ue(f,{silent:true});}),m=o?.registerProjectInWorkspace??(async(f,u,h)=>{let{registerProjectInWorkspace:k}=await import('./workspace-FDMJD5XI.js');await k(f,u,h);}),p=o?.registerWorkspace??(async(f,u)=>{let{registerWorkspace:h}=await import('./workspace-FDMJD5XI.js');await h(f,u);}),d=o?.rollbackAdoptedProjectImport??gi;try{let f=w.join(r,".rapidkit","project.json"),u=await R__default.pathExists(f)?await R__default.readJson(f):null,h=await hi({workspacePath:i,source:r,name:e.name,dryRun:e.dryRun===true,enableModules:e.enableModules});if(e.dryRun!==true)try{await p(i,w.basename(i)),await m(i,h.name,h.path),await g(i);}catch(k){throw await d(i,h.path,u),new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${k instanceof Error?k.message:String(k)}`)}return e.json?(console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?c:false,dryRun:e.dryRun===true,adoptedProject:h},null,2)),0):(a&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so RapidKit used the default workspace: ${i}`)),e.dryRun===true&&console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.green(`\u2714 Adopted project: ${h.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${h.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${h.stack} (${h.confidence})`)),console.log(s.gray(` Report: ${h.adoptReadinessPath}`)),console.log(s.gray(" Next: npx rapidkit workspace model --json")),0)}catch(f){let u=f instanceof Error?f.message:String(f);return e.json?console.log(JSON.stringify({error:u},null,2)):console.log(s.red(`\u274C Adopt failed: ${u}`)),1}}async function Jr(t){let e=new Set(["python-only","polyglot","enterprise"]),o="minimal";try{let i=w.join(t,".rapidkit","workspace.json");o=JSON.parse(await b$3.promises.readFile(i,"utf-8")).profile??"minimal";}catch{o="minimal";}if(!await(async()=>{if(e.has(o))return true;let i=await Vr(t);if(i.length===0)return false;for(let a of i){let c=a$5(a),l=c?.module_support;if(!(b$6(c,a)||d$3(c,a)||e$1(c,a))&&l!==false)return f$2(c,a)||c$2(c,a),true}return false})())return 0;let n="poetry";try{let{readWorkspaceMarker:i}=await import('./workspace-marker-IOPQ42A7.js'),c=(await i(t))?.metadata?.npm?.installMethod;(c==="poetry"||c==="venv"||c==="pipx"||c==="pip")&&(n=c);}catch{}if(n==="poetry"||n==="venv"){let i=w.join(t,"pyproject.toml"),a=false;try{a=(await b$3.promises.readFile(i,"utf-8")).includes("rapidkit-core");}catch{a=false;}let c=process.env.RAPIDKIT_DEV_PATH,l=c?await R__default.pathExists(c):false;if(a){let g=tl(t);if(!await R__default.pathExists(g)){let d=await ol(t);if(d!==0)return d}let p=await z(g,l&&c?["-m","pip","install",c,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"],t);if(p!==0)return p}else {let g=await z("poetry",["install","--no-root"],t);if(g!==0)return g;let m=await z("poetry",["add","rapidkit-core"],t);if(m!==0)return m}try{let{writeWorkspaceLauncher:g}=await import('./create-UGXMC4CT.js');await g(t,n==="venv"?"venv":"poetry");}catch{}return 0}return 0}async function Vr(t){let e=[],o=new Set,r=[t];for(;r.length>0;){let n=r.pop();if(!n||o.has(n))continue;o.add(n);let i=[];try{i=await b$3.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){if(!a.isDirectory()||a.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(a.name))continue;let c=w.join(n,a.name),l=w.join(c,".rapidkit","context.json"),g=w.join(c,".rapidkit","project.json");if(await R__default.pathExists(l)||await R__default.pathExists(g)){e.push(c);continue}r.push(c);}}return e}function El(t){return i$5(t)}async function Br(){let t=j$1(),e=w.basename(t),o=We(t);await R__default.ensureDir(w.join(t,".rapidkit")),await b$8(t,d$6(e,b()));let r=w.join(t,".rapidkit","workspace.json");return await R__default.pathExists(r)||await lt(r,{name:e,workspace_name:e,profile:"minimal",createdAt:new Date().toISOString(),createdBy:"rapidkit-npm-import-fallback"}),{workspacePath:t,created:!o}}async function Nr(t){let o=await Ve("go",{runCommandInCwd:z,runCoreRapidkit:e}).initProject(t);return Z(o)}function Z(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function ct(t,e$1){let o=Ve("node",{runCommandInCwd:z,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return Z(n)}if(t==="dev"){let n=await o.runDev(e$1);return Z(n)}if(t==="test"){let n=await o.runTest(e$1);return Z(n)}if(t==="build"){let n=await o.runBuild(e$1);return Z(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return Z(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return Z(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return Z(r)}async function Be(t,e$1){let o=Ve("java",{runCommandInCwd:z,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return Z(n)}if(t==="dev"){let n=await o.runDev(e$1);return Z(n)}if(t==="test"){let n=await o.runTest(e$1);return Z(n)}if(t==="build"){let n=await o.runBuild(e$1);return Z(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return Z(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return Z(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return Z(r)}function Ri(t,e,o){let r=o.filter(n=>n.status==="failed").map(n=>{let i=n.id||"check";return n.message?`${i}: ${n.message}`:i}).slice(0,12);return f$5(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:r,runId:e$4()})}async function Ei(t,e=Kr){let o=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let i=function(E){if(!E)return null;let M=E.trim().toLowerCase();return M==="minimal"||M==="java-only"||M==="go-only"||M==="dotnet-only"||M==="python-only"||M==="node-only"||M==="polyglot"||M==="enterprise"?M:null},a=function(E){let $e=E.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",we=(Fe,rt)=>{let St=E.match(new RegExp(`^\\s*${Fe}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return St?St[1].toLowerCase()==="true":rt};return {mode:$e,dependency_sharing_mode:Bi(E),rules:{enforce_workspace_marker:we("enforce_workspace_marker",true),enforce_toolchain_lock:we("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:we("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:we("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:we("require_mirror_lock_for_offline",true)}}};let c=["init"],l,g=false,m=false,p=false,d=false;for(let E=1;E<t.length;E+=1){let M=t[E];if(M==="--ci"){g=true;continue}if(M==="--offline"){m=true;continue}if(M==="--json"){p=true;continue}if(M==="--compliance-only"){d=true;continue}if(M==="--profile"){let W=t[E+1];if(!W||W.startsWith("-"))return console.log(s.yellow("Usage: rapidkit bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;l=W,E+=1;continue}if(M.startsWith("--profile=")){l=M.slice(10);continue}c.push(M);}let f=i(l);if(l&&!f)return console.log(s.red(`Invalid profile: ${l}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let u=process.cwd(),h=c.slice(1).filter(E=>!E.startsWith("-"));if(h.length>0){let E=w.resolve(u,h[0]),M=a$5(E),W=b$3.existsSync(E)?await dt(E):"unknown";if(!We(E)&&(b$6(M,E)||d$3(M,E)||e$1(M,E)||c$2(M,E)||f$2(M,E)||W!=="unknown"))return await e(c)}let k=w.join(u,".rapidkit-workspace"),P=w.join(u,".rapidkit","workspace.json"),v;!b$3.existsSync(k)&&b$3.existsSync(P)?v=u:(v=re(u),v||(v=vl(u)));let y=[],C=null,x=null;if(v)try{let E=w.join(v,".rapidkit","workspace.json"),M=await b$3.promises.readFile(E,"utf-8"),W=JSON.parse(M);x=i(W.profile);}catch{x=null;}let I=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],Y={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},H=f;if(!!v&&!f&&!g&&!p&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let E=x||"minimal",{chosenProfile:M}=await b$2([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${E})`,choices:I.map(W=>({name:W===E?`${Y[W]} \u2190 current`:Y[W],value:W})),default:I.indexOf(E)}]);H=M;}let N=H||x||"minimal";if(v)try{let M=N==="python-only"||N==="polyglot"||N==="enterprise"?"poetry":"venv",W;try{let rt=(await b$3.promises.readFile(w.join(v,".python-version"),"utf-8")).trim();rt&&(W=rt);}catch{}let{syncWorkspaceFoundationFiles:$e}=await import('./create-UGXMC4CT.js'),we=await $e(v,{workspaceName:w.basename(v),installMethod:M,pythonVersion:W,profile:N,writeMarker:true,writeGitignore:true,onlyIfMissing:true});y.push({id:"workspace.legacy.sync",status:we.length>0?"passed":"skipped",message:we.length>0?`Legacy workspace foundation synchronized: ${we.join(", ")}`:"Workspace foundation files are already up to date."});}catch(E){y.push({id:"workspace.legacy.sync",status:"failed",message:`Failed to synchronize legacy workspace foundation files: ${E.message}`});}if(v&&H&&H!==x)try{let E=w.join(v,".rapidkit","workspace.json"),M=await b$3.promises.readFile(E,"utf-8"),W=JSON.parse(M);W.profile=H,await b$3.promises.writeFile(E,JSON.stringify(W,null,2)+`
|
|
204
|
+
`,"utf-8");}catch{}let T={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},je=null;if(v)try{let E=await b$3.promises.readFile(w.join(v,".rapidkit","policies.yml"),"utf-8");je=E,T=a(E);}catch{y.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else y.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(v){let E=Ui(je);T.dependency_sharing_mode=E.mode,y.push({id:"policy.schema.dependency_sharing_mode",status:E.status,message:E.message}),y.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:T.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":T.dependency_sharing_mode==="shared-node-deps"?"Effective dependency mode: shared-node-deps (Node projects share workspace-level caches).":"Effective dependency mode: shared-runtime-caches (Node/Python/Go share workspace-level caches)."});let M=b$3.existsSync(w.join(v,".rapidkit-workspace"));y.push({id:"policy.enforce_workspace_marker",status:!T.rules.enforce_workspace_marker||M?"passed":"failed",message:!T.rules.enforce_workspace_marker||M?"Workspace marker policy satisfied.":"Workspace marker policy failed: .rapidkit-workspace is missing."});let W=b$3.existsSync(w.join(v,".rapidkit","toolchain.lock"));y.push({id:"policy.enforce_toolchain_lock",status:!T.rules.enforce_toolchain_lock||W?"passed":"failed",message:!T.rules.enforce_toolchain_lock||W?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .rapidkit/toolchain.lock is missing."});let $e=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||b$3.existsSync(w.join(v,".rapidkit","trusted-sources.lock"));y.push({id:"policy.disallow_untrusted_tool_sources",status:!T.rules.disallow_untrusted_tool_sources||$e?"passed":"failed",message:!T.rules.disallow_untrusted_tool_sources||$e?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .rapidkit/trusted-sources.lock."});let we=w.join(v,".rapidkit","compatibility-matrix.json"),Fe=b$3.existsSync(we),rt=T.rules.enforce_compatibility_matrix;if(y.push({id:"policy.enforce_compatibility_matrix",status:!rt||Fe?"passed":"failed",message:!rt||Fe?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .rapidkit/compatibility-matrix.json is missing."}),Fe)try{let B=await b$3.promises.readFile(we,"utf-8"),te=JSON.parse(B),Kt=!!te&&typeof te=="object";y.push({id:"compatibility.matrix.parse",status:Kt?"passed":"failed",message:Kt?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{y.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let St=w.join(v,".rapidkit","mirror-config.json"),zi=w.join(v,".rapidkit","mirror.lock"),Oo=b$3.existsSync(St),No=b$3.existsSync(zi),Ur={};if(Oo)try{Ur=JSON.parse(await b$3.promises.readFile(St,"utf-8")),y.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{y.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .rapidkit/mirror-config.json."});}let Do=await Er(v,{ciMode:g,offlineMode:m});if(y.push(...Do.checks.map(B=>({id:B.id,status:B.status,message:B.message}))),C=Do.details,Do.details.lockWritten&&(No=true),m){let B=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||Ur.enabled===true;y.push({id:"offline.mirror.enabled",status:B?"passed":"failed",message:B?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .rapidkit/mirror-config.json {"enabled": true}).'});let te=T.rules.require_mirror_lock_for_offline;y.push({id:"offline.mirror.lock",status:!te||No?"passed":"failed",message:!te||No?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .rapidkit/mirror.lock is missing."});}else y.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Yi=await Vr(v),se=new Set;for(let B of Yi){let te=a$5(B);if(b$6(te,B)){se.add("go");continue}if(d$3(te,B)){se.add("java");continue}if(e$1(te,B)){se.add("dotnet");continue}if(c$2(te,B)){se.add("node");continue}if(f$2(te,B)){se.add("python");continue}se.add("unknown");}if(N==="go-only"){let B=se.size===0||[...se].every(te=>te==="go");y.push({id:"profile.go-only",status:B?"passed":"failed",message:B?"go-only profile validated for discovered projects.":`go-only profile mismatch: detected runtimes [${[...se].join(", ")}].`});}else if(N==="java-only"){let B=se.size===0||[...se].every(te=>te==="java");y.push({id:"profile.java-only",status:B?"passed":"failed",message:B?"java-only profile validated for discovered projects.":`java-only profile mismatch: detected runtimes [${[...se].join(", ")}].`});}else if(N==="dotnet-only"){let B=se.size===0||[...se].every(te=>te==="dotnet");y.push({id:"profile.dotnet-only",status:B?"passed":"failed",message:B?"dotnet-only profile validated for discovered projects.":`dotnet-only profile mismatch: detected runtimes [${[...se].join(", ")}].`});}else if(N==="python-only"){let B=se.size===0||[...se].every(te=>te==="python");y.push({id:"profile.python-only",status:B?"passed":"failed",message:B?"python-only profile validated for discovered projects.":`python-only profile mismatch: detected runtimes [${[...se].join(", ")}].`});}else if(N==="node-only"){let B=se.size===0||[...se].every(te=>te==="node");y.push({id:"profile.node-only",status:B?"passed":"failed",message:B?"node-only profile validated for discovered projects.":`node-only profile mismatch: detected runtimes [${[...se].join(", ")}].`});}else if(N==="minimal"){let B=[...se].filter(Kt=>Kt!=="unknown"),te=B.length<=1;y.push({id:"profile.minimal",status:te?"passed":"failed",message:te?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${B.join(", ")}].`});}else N==="enterprise"&&(y.push({id:"profile.enterprise.ci",status:g?"passed":"failed",message:g?"enterprise profile running with --ci.":"enterprise profile expects --ci for deterministic non-interactive mode."}),y.push({id:"profile.enterprise.compatibility-matrix",status:Fe?"passed":"failed",message:Fe?"enterprise profile has compatibility matrix.":"enterprise profile requires .rapidkit/compatibility-matrix.json."}),y.push({id:"profile.enterprise.mirror-config",status:Oo?"passed":"failed",message:Oo?"enterprise profile has mirror configuration.":"enterprise profile requires .rapidkit/mirror-config.json."}));}g&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),m&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let G=y.some(E=>E.id.startsWith("policy.schema.")&&E.status==="failed")||T.mode==="strict"&&y.some(E=>E.status==="failed"),S=v||u,ee=w.join(S,".rapidkit","reports"),Re=new Date().toISOString().replace(/[:.]/g,"-"),q=w.join(ee,`bootstrap-compliance-${Re}.json`),X=w.join(ee,"bootstrap-compliance.latest.json"),ke={command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:v,profile:N,options:{ci:g,offline:m,strict:T.mode==="strict"},policyMode:T.mode,policyRules:T.rules,mirrorLifecycle:C,checks:y};if(G){let E=Ri({...ke,result:"blocked",initExitCode:null},1,y);return await R__default.ensureDir(ee),await lt(q,E),await lt(X,E),p?process.stdout.write(`${JSON.stringify(E,null,2)}
|
|
205
|
+
`):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${q}`))),1}let Ee=0;p&&d||(Ee=await e(c));let xe=y.filter(E=>E.status==="failed").length,V=Ee!==0?"failed":xe>0?"ok_with_warnings":"ok",Ct=Ee!==0?Ee:xe>0?1:0,_e=Ri({...ke,result:V,initExitCode:Ee,complianceOnly:p&&d},Ct,y);if(await R__default.ensureDir(ee),await lt(q,_e),await lt(X,_e),v&&Ee===0)try{let{syncWorkspaceProjects:E}=await import('./workspace-FDMJD5XI.js');await E(v,p),await Ue(v,{silent:p});}catch{}if(p)process.stdout.write(`${JSON.stringify(_e,null,2)}
|
|
206
|
+
`);else {let E=y.filter(M=>M.status==="failed").length;E>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${E} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${q}`));}return Ee}finally{typeof o>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=o;}}async function _i(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: rapidkit setup <python|node|go|java|dotnet> [--warm-deps]")),0;let e$1=(t[1]||"").toLowerCase(),o=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!e$1||!["python","node","go","java","dotnet"].includes(e$1))return console.log(s.yellow("Usage: rapidkit setup <python|node|go|java|dotnet> [--warm-deps]")),1;let r=async(p,d)=>{if(p==="node"){if(!b$3.existsSync(w.join(d,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let u=b$3.existsSync(w.join(d,"pnpm-lock.yaml")),h=b$3.existsSync(w.join(d,"yarn.lock"));return u?{exitCode:await z("pnpm",["install","--lockfile-only","--ignore-scripts"],d)}:h?{exitCode:await z("yarn",["install","--ignore-scripts"],d)}:{exitCode:await z("npm",["install","--package-lock-only","--ignore-scripts"],d)}}if(p==="go")return b$3.existsSync(w.join(d,"go.mod"))?{exitCode:await z("go",["mod","download"],d)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(p==="java"){let f=b$3.existsSync(w.join(d,"pom.xml")),u=b$3.existsSync(w.join(d,"build.gradle"))||b$3.existsSync(w.join(d,"build.gradle.kts")),h=w.join(d,process.platform==="win32"?"gradlew.bat":"gradlew"),k=b$3.existsSync(h);return !f&&!u?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:f?{exitCode:await z("mvn",["-B","-q","-DskipTests","dependency:go-offline"],d)}:{exitCode:await z(k?h:"gradle",["--no-daemon","dependencies"],d)}}return p==="dotnet"?(()=>{let u=[{dir:d,depth:0}],h=new Set(["bin","obj",".git","node_modules",".rapidkit"]);for(;u.length>0;){let k=u.shift();if(!k||k.depth>3)continue;let P=[];try{P=b$3.readdirSync(k.dir,{withFileTypes:true});}catch{continue}for(let v of P)if(v.isFile()){let y=v.name.toLowerCase();if(y.endsWith(".sln")||y.endsWith(".csproj"))return true}else v.isDirectory()&&!h.has(v.name)&&u.push({dir:w.join(k.dir,v.name),depth:k.depth+1});}return false})()?{exitCode:await z("dotnet",["restore"],d)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:{exitCode:0,message:"Dependency warm-up currently applies to node/go/java/dotnet runtimes."}},n=Ve(e$1,{runCommandInCwd:z,runCoreRapidkit:(p,d)=>e(p,{...d,cwd:void 0})}),i=await n.checkPrereqs(),a=await n.doctorHints(process.cwd()),c=re(process.cwd()),l=c||process.cwd(),g=null,m=async()=>e$1!=="java"||!c?[]:g||(g=(await Vr(c)).filter(d=>{let f=a$5(d);return d$3(f,d)}),g);if(i.exitCode===0){console.log(s.green(`\u2705 ${e$1} prerequisites look good.`));let p=["python","node","go","java","dotnet"].filter(d=>d!==e$1).join("/");if(console.log(s.gray(` Scope: validated ${e$1} runtime only. ${p} checks are optional unless your workspace profile uses them.`)),e$1==="python"&&console.log(s.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),n.warmSetupCache&&((await n.warmSetupCache(l)).exitCode===0?console.log(s.gray(` ${e$1} cache warm-up completed.`)):console.log(s.yellow(` ${e$1} cache warm-up skipped (non-fatal).`))),o)if(e$1==="java"&&c){let d=await m();if(d.length>0){let f=0,u=0,h=0;for(let k of d){let P=await r("java",k),v=/skipped/i.test(P.message||""),y=w.relative(c,k)||w.basename(k);P.message&&console.log(s.gray(` [${y}] ${P.message}`)),P.exitCode===0&&!v?f+=1:P.exitCode===0&&v?h+=1:u+=1;}f>0&&console.log(s.gray(` java dependency warm-up completed for ${f} project(s) (--warm-deps).`)),u>0&&console.log(s.yellow(` java dependency warm-up failed for ${u} project(s) (non-fatal).`)),f===0&&u===0&&h>0&&console.log(s.gray(" java dependency warm-up skipped for discovered workspace projects."));}else {let f=await r("java",l),u=/skipped/i.test(f.message||"");f.message&&console.log(s.gray(` ${f.message}`)),f.exitCode===0&&!u?console.log(s.gray(` ${e$1} dependency warm-up completed (--warm-deps).`)):f.exitCode!==0&&console.log(s.yellow(` ${e$1} dependency warm-up failed (non-fatal).`));}}else {let d=await r(e$1,l),f=/skipped/i.test(d.message||"");d.message&&console.log(s.gray(` ${d.message}`)),d.exitCode===0&&!f?console.log(s.gray(` ${e$1} dependency warm-up completed (--warm-deps).`)):d.exitCode!==0&&console.log(s.yellow(` ${e$1} dependency warm-up failed (non-fatal).`));}if(c)try{let d=w.join(c,".rapidkit","toolchain.lock"),f={};try{f=JSON.parse(await b$3.promises.readFile(d,"utf-8"));}catch{}(!f.runtime||typeof f.runtime!="object")&&(f.runtime={});let u=f.runtime;if(e$1==="python"){let h=null;try{let{execa:k}=await import('execa');for(let P of Gr()){let y=await k(P,P==="py"?["-3","--version"]:["--version"],{cwd:c,stdio:"pipe",reject:false,timeout:3e3});if(y.exitCode===0){let x=(y.stdout||y.stderr||"").match(/Python\s+(\S+)/);if(h=x?x[1]:null,h)break}}}catch{}u.python={...u.python||{},version:h,last_setup:new Date().toISOString()};}else if(e$1==="node")u.node={...u.node||{},version:process.version,last_setup:new Date().toISOString()};else if(e$1==="go"){let h=null;try{let{execa:k}=await import('execa'),v=((await k("go",["version"],{cwd:c,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);h=v?v[1]:null;}catch{}u.go={...u.go||{},version:h,last_setup:new Date().toISOString()};}else if(e$1==="java"){let h=null,k=null,P=null,v=await m(),C=b$3.existsSync(w.join(l,"pom.xml"))||b$3.existsSync(w.join(l,"build.gradle"))||b$3.existsSync(w.join(l,"build.gradle.kts"))?l:v[0]||l;try{let{execa:x}=await import('execa'),I=await x("java",["-version"],{cwd:c,stdio:"pipe",reject:false,timeout:3e3}),H=`${I.stdout||""}
|
|
207
|
+
${I.stderr||""}`.match(/version\s+"([^"]+)"/i);h=H?H[1]:null;let ae=b$3.existsSync(w.join(C,"pom.xml")),N=b$3.existsSync(w.join(C,"build.gradle"))||b$3.existsSync(w.join(C,"build.gradle.kts"));if(ae){k="maven";let T=(()=>{let S=w.join(C,"mvnw.cmd");if(process.platform==="win32"&&b$3.existsSync(S))return S;let ee=w.join(C,"mvnw");return b$3.existsSync(ee)?ee:"mvn"})(),je=await x(T,["-version"],{cwd:C,stdio:"pipe",reject:false,timeout:3e3}),G=`${je.stdout||""}
|
|
208
|
+
${je.stderr||""}`.match(/Apache Maven\s+(\S+)/i);P=G?G[1]:null;}else if(N){k="gradle";let T=(()=>{let S=w.join(C,"gradlew.bat");if(process.platform==="win32"&&b$3.existsSync(S))return S;let ee=w.join(C,"gradlew");return b$3.existsSync(ee)?ee:"gradle"})(),je=await x(T,["--version"],{cwd:C,stdio:"pipe",reject:false,timeout:3e3}),G=`${je.stdout||""}
|
|
209
|
+
${je.stderr||""}`.match(/Gradle\s+(\S+)/i);P=G?G[1]:null;}}catch{}u.java={...u.java||{},version:h,build_tool:k,build_tool_version:P,last_setup:new Date().toISOString()};}else if(e$1==="dotnet"){let h=null;try{let{execa:k}=await import('execa'),v=((await k("dotnet",["--version"],{cwd:c,stdio:"pipe",reject:false,timeout:3e3})).stdout||"").trim();h=v.length>0?v:null;}catch{}u.dotnet={...u.dotnet||{},version:h,sdk:h,last_setup:new Date().toISOString()};}f.updated_at=new Date().toISOString(),await b$3.promises.writeFile(d,JSON.stringify(f,null,2)+`
|
|
210
210
|
`,"utf-8"),console.log(s.gray(" toolchain.lock updated (.rapidkit/toolchain.lock)"));}catch{}}else console.log(s.red(`\u274C ${e$1} prerequisites check failed.`));if(a.length>0){console.log(s.gray(`
|
|
211
|
-
Hints:`));for(let p of a)console.log(s.gray(`- ${p}`));}return i.exitCode}function
|
|
212
|
-
`)){let r=o.trim(),n=r.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]]/g,""));let i=r.match(/^prune_on_bootstrap:\s*(true|false)/);i&&(e.prune_on_bootstrap=i[1]==="true");let a=r.match(/^self_heal:\s*(true|false)/);a&&(e.self_heal=a[1]==="true");let c=r.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function
|
|
213
|
-
`,"utf-8"),console.log(s.gray(" mirror-config.json created with defaults (.rapidkit/mirror-config.json)"));}catch{}let d=await R__default.pathExists(i),
|
|
214
|
-
`),0):(console.log(s.cyan("RapidKit mirror status")),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Config: ${d?"present":"missing"} (${i})`)),console.log(s.gray(`Lock: ${
|
|
215
|
-
`),1;console.log(s.red("\u274C Mirror verify failed."));for(let
|
|
216
|
-
`),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${d.length} issue(s).`));for(let
|
|
217
|
-
`),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${p.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${p.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${p.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),1}async function
|
|
218
|
-
`).toLowerCase(),I=x.includes("\\.rapidkit\\rapidkit"),Y=x.includes("\\.rapidkit\\rapidkit.cmd")||x.includes("\\.rapidkit\\rapidkit.exe")||x.includes("\\.venv\\scripts\\rapidkit.exe");return I&&!Y}catch{return false}},e$2=process.cwd(),o=process.argv.slice(2),r=o[0],n=r==="init",i$1=new Set(h$3),a$1=!r||r==="--help"||r==="-h"||r==="help",c=We(e$2),l=b$3.existsSync(w.join(e$2,".rapidkit","project.json")),g=a$5(e$2),m=await dt(e$2),p=b$6(g,e$2)||c$2(g,e$2)||f$2(g,e$2)||d$3(g,e$2)||e$1(g,e$2)||m$1(m??void 0),d=!!r&&i$1.has(r)&&p,
|
|
211
|
+
Hints:`));for(let p of a)console.log(s.gray(`- ${p}`));}return i.exitCode}function _l(t){let e={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let o of t.split(`
|
|
212
|
+
`)){let r=o.trim(),n=r.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]]/g,""));let i=r.match(/^prune_on_bootstrap:\s*(true|false)/);i&&(e.prune_on_bootstrap=i[1]==="true");let a=r.match(/^self_heal:\s*(true|false)/);a&&(e.self_heal=a[1]==="true");let c=r.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function Ai(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: rapidkit cache <status|clear|prune|repair>")),0;let e=(t[1]||"status").toLowerCase(),o=So.getInstance(),r=re(process.cwd()),n={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(r)try{let i=await b$3.promises.readFile(w.join(r,".rapidkit","cache-config.yml"),"utf-8");n=_l(i);}catch{}return e==="status"?(console.log(s.cyan("RapidKit cache is enabled")),console.log(s.cyan("RapidKit cache status")),r?(console.log(s.gray(` Workspace: ${r}`)),console.log(s.gray(` Strategy: ${n.strategy}`)),console.log(s.gray(` Self-heal: ${n.self_heal}`)),console.log(s.gray(` Prune on bootstrap:${n.prune_on_bootstrap}`)),console.log(s.gray(` Verify integrity: ${n.verify_integrity}`))):console.log(s.gray(" (not inside a workspace \u2014 showing in-memory cache only)")),console.log(s.gray(" In-memory cache: enabled")),console.log(s.gray(" Use: rapidkit cache clear|prune|repair")),0):e==="clear"?(await o.clear(),console.log(s.green("Cache clear completed")),console.log(s.green("\u2705 Cache cleared (all entries removed).")),0):e==="prune"?(await o.clear(),console.log(s.green("\u2705 Cache pruned (stale entries removed).")),n.prune_on_bootstrap||console.log(s.gray(" Tip: set prune_on_bootstrap: true in .rapidkit/cache-config.yml to auto-prune on every bootstrap.")),0):e==="repair"?n.self_heal?(await o.clear(),console.log(s.green("\u2705 Cache repaired (self-heal applied, stale entries evicted).")),n.verify_integrity&&console.log(s.gray(" Integrity verification is enabled in cache-config.yml.")),0):(console.log(s.yellow("\u26A0\uFE0F self_heal is disabled in .rapidkit/cache-config.yml \u2014 skipping repair.")),0):(console.log(s.yellow("Usage: rapidkit cache <status|clear|prune|repair>")),1)}async function Al(t,e,o,r){let n=(e||"show").toLowerCase(),i=w.join(t,".rapidkit","policies.yml");if(n==="show"||n==="status"||n==="get"){let m=await Si(t),p=xi(m);return console.log(s.cyan(`Policy file: ${i}`)),console.log(s.gray(` mode: ${p.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${p.dependency_sharing_mode}`)),console.log(s.gray(" rules:")),console.log(s.gray(` enforce_workspace_marker: ${p.rules.enforce_workspace_marker}`)),console.log(s.gray(` enforce_toolchain_lock: ${p.rules.enforce_toolchain_lock}`)),console.log(s.gray(` disallow_untrusted_tool_sources: ${p.rules.disallow_untrusted_tool_sources}`)),console.log(s.gray(` enforce_compatibility_matrix: ${p.rules.enforce_compatibility_matrix}`)),console.log(s.gray(` require_mirror_lock_for_offline: ${p.rules.require_mirror_lock_for_offline}`)),console.log(s.gray("Examples:")),console.log(s.gray(" npx rapidkit workspace policy set mode strict")),console.log(s.gray(" npx rapidkit workspace policy set dependency_sharing_mode shared-runtime-caches")),console.log(s.gray(" npx rapidkit workspace policy set rules.enforce_toolchain_lock true")),0}if(n!=="set")return console.log(s.red(`Unknown workspace policy action: ${e||""}`)),console.log(s.gray("Available: show, set")),1;if(!o||typeof r>"u")return console.log(s.yellow("Usage: rapidkit workspace policy set <key> <value>")),console.log(s.gray("Allowed keys:")),console.log(s.gray(" mode (warn|strict)")),console.log(s.gray(" dependency_sharing_mode (isolated|shared-runtime-caches|shared-node-deps)")),console.log(s.gray(" rules.enforce_workspace_marker (true|false)")),console.log(s.gray(" rules.enforce_toolchain_lock (true|false)")),console.log(s.gray(" rules.disallow_untrusted_tool_sources (true|false)")),console.log(s.gray(" rules.enforce_compatibility_matrix (true|false)")),console.log(s.gray(" rules.require_mirror_lock_for_offline (true|false)")),1;let a=o.trim(),l=await Si(t);if(a==="mode"){let m=r.trim().toLowerCase();if(m!=="warn"&&m!=="strict")return console.log(s.red("\u274C Invalid mode. Use: warn | strict")),1;l=Ci(l,"mode",`${m} # "warn" or "strict"`);}else if(a==="dependency_sharing_mode"){let m=r.trim().toLowerCase();if(m!=="isolated"&&m!=="shared-runtime-caches"&&m!=="shared-node-deps")return console.log(s.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1;l=Ci(l,"dependency_sharing_mode",`${m} # "isolated" or "shared-runtime-caches" or "shared-node-deps"`);}else if(a.startsWith("rules.")){let m=a.slice(6);if(!(m in Vi))return console.log(s.red(`\u274C Unknown policy rule: ${m}`)),1;let p=Cl(r);if(p===null)return console.log(s.red("\u274C Rule values must be boolean: true | false")),1;l=bl(l,m,p);}else return console.log(s.red(`\u274C Unknown policy key: ${a}`)),1;await xl(t,l);let g=xi(l);return console.log(s.green(`\u2705 Updated ${a} in .rapidkit/policies.yml`)),console.log(s.gray(` mode: ${g.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${g.dependency_sharing_mode}`)),console.log(s.gray(" Tip: run `npx rapidkit workspace policy show` to inspect all values.")),0}async function Ii(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),0;let e=(t[1]||"status").toLowerCase(),o=t.includes("--json"),r=re(process.cwd());if(!r)return console.log(s.red("\u274C Not inside a RapidKit workspace")),console.log(s.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let n=w.join(r,".rapidkit"),i=w.join(n,"mirror-config.json"),a=w.join(n,"mirror.lock"),c=w.join(n,"mirror","artifacts"),l=w.join(n,"reports");async function g(p){let d=new Date().toISOString().replace(/[:.]/g,"-"),f=w.join(l,`mirror-ops-${d}.json`),u=w.join(l,"mirror-ops.latest.json");await R__default.ensureDir(l),await lt(f,p),await lt(u,p);}async function m(){let p=await R__default.pathExists(i),d=await R__default.pathExists(a),f=0;return await R__default.pathExists(c)&&(f=(await b$3.promises.readdir(c,{withFileTypes:true})).filter(u=>u.isFile()).length),{configExists:p,lockExists:d,artifactsCount:f}}if(e==="status"){if(!await R__default.pathExists(i))try{let P={schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:new Date().toISOString(),note:"Auto-generated by rapidkit mirror status. Set enabled: true and add artifact entries to activate mirroring."};await R__default.ensureDir(n),await b$3.promises.writeFile(i,JSON.stringify(P,null,2)+`
|
|
213
|
+
`,"utf-8"),console.log(s.gray(" mirror-config.json created with defaults (.rapidkit/mirror-config.json)"));}catch{}let d=await R__default.pathExists(i),f=await R__default.pathExists(c),u=await R__default.pathExists(a),h=f?(await b$3.promises.readdir(c,{withFileTypes:true})).filter(P=>P.isFile()).length:0,k={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:{configExists:d,lockExists:u,artifactsCount:h}};return await g(k),o?(process.stdout.write(`${JSON.stringify(k,null,2)}
|
|
214
|
+
`),0):(console.log(s.cyan("RapidKit mirror status")),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Config: ${d?"present":"missing"} (${i})`)),console.log(s.gray(`Lock: ${u?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${h}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let p=await Er(r,{ciMode:true,offlineMode:e==="verify",forceRun:true}),d=p.checks.filter(h=>h.status==="failed"),f=p.checks.some(h=>h.id.startsWith("mirror.verify.")&&h.status==="failed");if(e==="verify"&&f){let h={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:p.details,checks:p.checks};if(await g(h),o)return process.stdout.write(`${JSON.stringify(h,null,2)}
|
|
215
|
+
`),1;console.log(s.red("\u274C Mirror verify failed."));for(let k of p.checks.filter(P=>P.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${k.id}: ${k.message}`));return 1}if(d.length>0){let h={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:p.details,checks:p.checks};if(await g(h),o)return process.stdout.write(`${JSON.stringify(h,null,2)}
|
|
216
|
+
`),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${d.length} issue(s).`));for(let k of d)console.log(s.gray(`- ${k.id}: ${k.message}`));return 1}let u={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:p.details,checks:p.checks};return await g(u),o?(process.stdout.write(`${JSON.stringify(u,null,2)}
|
|
217
|
+
`),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${p.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${p.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${p.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),1}async function Kr(t){let e$2=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$2>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let o=process.cwd(),r=await Hi(o,async()=>{let n=re(o),i=Ve("python",{runCommandInCwd:z,runCoreRapidkit:e}),a=Ve("dotnet",{runCommandInCwd:z,runCoreRapidkit:e}),c=t.slice(1).filter(u=>!u.startsWith("-"));if(c.length>0){let u=w.resolve(o,c[0]),h=a$5(u),k=await dt(u);return b$6(h,u)||k==="go"?await Nr(u):d$3(h,u)||k==="java"?await Be("init",u):e$1(h,u)||k==="dotnet"?Z(await a.initProject(u)):c$2(h,u)||k==="node"?await Mr(u):f$2(h,u)||k==="python"?await $r(u,i):await e(t,{cwd:o})}let l=a$5(o),g$1=!!re(o)&&o===re(o);if(!g$1&&b$6(l,o))return await Nr(o);let m=await dt(o);if(!g$1&&(d$3(l,o)||m==="java"))return await Be("init",o);if(!g$1&&(e$1(l,o)||m==="dotnet"))return Z(await a.initProject(o));if(!g$1&&(c$2(l,o)||m==="node"))return await Mr(o);if(!g$1&&(f$2(l,o)||m==="python"))return await $r(o,i);let p=n||re(o),d=Gi(o),f=d?w.dirname(w.dirname(d)):null;if(f&&f!==p){let u=a$5(f),h=await dt(f);return b$6(u,f)||h==="go"?await Nr(f):d$3(u,f)||h==="java"?await Be("init",f):e$1(u,f)||h==="dotnet"?Z(await a.initProject(f)):c$2(u,f)||h==="node"?await Mr(f):f$2(u,f)||h==="python"?await $r(f,i):await e(["init"],{cwd:f})}if(p&&o===p){console.log(s.yellow("\u26A0\uFE0F Running `npx rapidkit init` at workspace root.")),console.log(s.gray(" Root `init`, `workspace init`, and `workspace run init` now share the same full-init flow:\n workspace-profile dependencies first, then project dependency initialization.\n"));let u=await Jr(p);if(u!==0)return u;let{runWorkspaceStage:h}=await import('./workspace-run-IHB2TPMD.js');return (await h({workspacePath:p,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!p){let u=await b$1(),h=g(),{name:k}=El(h);await R__default.ensureDir(h);let{createProject:P}=await import('./create-UGXMC4CT.js');return await P(k,{yes:true,userConfig:u,parentDirectory:h}),0}return await e(t,{cwd:o})});return r.ok?r.value:r.code}finally{typeof e$2>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$2;}}async function $i(t){let e=re(t);if(!e)return [];let o="warn";try{let l=await b$3.promises.readFile(w.join(e,".rapidkit","policies.yml"),"utf-8");(l.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??l.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(o="strict");}catch{return []}if(o!=="strict")return [];let r=[],n=w.join(e,".rapidkit","toolchain.lock");if(!b$3.existsSync(n))return r.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain)."),r;let i={};try{i=JSON.parse(await b$3.promises.readFile(n,"utf-8"));}catch{return r.push("toolchain.lock is invalid JSON \u2014 regenerate it with `rapidkit bootstrap` before running commands in strict mode."),r}let a=i.runtime??{},c=a$5(t);b$6(c,t)&&!a.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."):c$2(c,t)&&!a.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."):d$3(c,t)&&!a.java?.version?r.push("java.version is not pinned in toolchain.lock \u2014 run `rapidkit setup java` first."):e$1(c,t)&&!a.dotnet?.version?r.push("dotnet.version is not pinned in toolchain.lock \u2014 run `rapidkit setup dotnet` first."):f$2(c,t)&&!a.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");try{let g=JSON.parse(await b$3.promises.readFile(w.join(e,".rapidkit","workspace.json"),"utf-8")).profile??"";g==="python-only"&&(b$6(c,t)||c$2(c,t)||d$3(c,t)||e$1(c,t))?r.push('Workspace profile is "python-only" but this project is not Python.'):g==="node-only"&&(b$6(c,t)||f$2(c,t)||d$3(c,t)||e$1(c,t))?r.push('Workspace profile is "node-only" but this project is not Node.'):g==="go-only"&&(c$2(c,t)||f$2(c,t)||d$3(c,t)||e$1(c,t))?r.push('Workspace profile is "go-only" but this project is not Go.'):g==="java-only"&&(f$2(c,t)||c$2(c,t)||b$6(c,t)||e$1(c,t))?r.push('Workspace profile is "java-only" but this project is not Java.'):g==="dotnet-only"&&(f$2(c,t)||c$2(c,t)||b$6(c,t)||d$3(c,t))&&r.push('Workspace profile is "dotnet-only" but this project is not .NET.');}catch{}return r}async function Il(){let t=async y=>{if(!a()||!y.toLowerCase().endsWith(".cmd"))return false;try{let x=(await R__default.readFile(y,"utf8")).replace(/\r\n/g,`
|
|
218
|
+
`).toLowerCase(),I=x.includes("\\.rapidkit\\rapidkit"),Y=x.includes("\\.rapidkit\\rapidkit.cmd")||x.includes("\\.rapidkit\\rapidkit.exe")||x.includes("\\.venv\\scripts\\rapidkit.exe");return I&&!Y}catch{return false}},e$2=process.cwd(),o=process.argv.slice(2),r=o[0],n=r==="init",i$1=new Set(h$3),a$1=!r||r==="--help"||r==="-h"||r==="help",c=We(e$2),l=b$3.existsSync(w.join(e$2,".rapidkit","project.json")),g=a$5(e$2),m=await dt(e$2),p=b$6(g,e$2)||c$2(g,e$2)||f$2(g,e$2)||d$3(g,e$2)||e$1(g,e$2)||m$1(m??void 0),d=!!r&&i$1.has(r)&&p,f$1=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Lt(o)||o[0]==="create")return false;if(Wr(o))return true;if(o[0]==="init"&&c&&!l)return false;if(Fr(o))return true;try{let y=r==="shell"&&o[1]==="activate",C=r==="create",x=await Un(e$2,{cwd:e$2,timeoutMs:1200});if(x.ok&&x.data?.isRapidkitProject&&x.data.engine==="python"){let I=C||Lt(o);if(!a$1&&!y&&!I&&!n&&!d&&zo(o)){if(r&&Pi.includes(r)){let H=await $i(e$2).catch(()=>[]);if(H.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
|
|
219
219
|
`);for(let ae of H)process.stderr.write(s.red(` \u2022 ${ae}`)+`
|
|
220
|
-
`);process.exit(1);}}let Y=await e(process.argv.slice(2),{cwd:e$2});process.exit(Y);}}}catch{}let
|
|
221
|
-
`);for(let
|
|
222
|
-
`);process.exit(1);}}if(P&&r&&
|
|
220
|
+
`);process.exit(1);}}let Y=await e(process.argv.slice(2),{cwd:e$2});process.exit(Y);}}}catch{}let u=Gi(e$2),h=a(),k=f$1?[]:i(e$2),P=null;for(let y of k)if(await R__default.pathExists(y)){if(await t(y)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${y}. Falling back to core bridge.`);continue}P=y;break}let v=r==="create";if(r==="init"&&c&&!l)return false;if(r&&Pi.includes(r)){let y=await $i(e$2);if(y.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
|
|
221
|
+
`);for(let C of y)process.stderr.write(s.red(` \u2022 ${C}`)+`
|
|
222
|
+
`);process.exit(1);}}if(P&&r&&vi.includes(r)&&!v&&!n&&!d){f.debug(`Delegating to local CLI: ${P} ${o.join(" ")}`);let y=r==="init"?wi():process.env,C=spawn(P,o,{stdio:"inherit",cwd:e$2,shell:h,env:y});return C.on("close",x=>{process.exit(x??0);}),C.on("error",x=>{f.error(`Failed to run local rapidkit: ${x.message}`),process.exit(1);}),true}if(u&&await R__default.pathExists(u))try{let y=await R__default.readJson(u);if(qn(y.engine)){let C=o[0],x=f$1?[]:i(e$2),I=null;for(let Y of x)if(await R__default.pathExists(Y)){if(await t(Y)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${Y}. Falling back to core bridge.`);continue}I=Y;break}if(I&&C&&vi.includes(C)&&C!=="init"&&!d){f.debug(`Delegating to local CLI (early detection): ${I} ${o.join(" ")}`);let Y=C==="init"?wi():process.env,H=spawn(I,o,{stdio:"inherit",cwd:e$2,env:Y});return H.on("close",ae=>process.exit(ae??0)),H.on("error",ae=>{f.error(`Failed to run local rapidkit: ${ae.message}`),process.exit(1);}),true}if(C==="shell"&&o[1]==="activate"){let Y=a()?`# RapidKit: activation snippet (PowerShell)
|
|
223
223
|
$venv = ".venv"
|
|
224
224
|
if (Test-Path "$venv\\Scripts\\Activate.ps1") { . "$venv\\Scripts\\Activate.ps1" }
|
|
225
225
|
$env:RAPIDKIT_PROJECT_ROOT = (Get-Location).Path
|
|
@@ -241,7 +241,7 @@ export PATH="$(pwd)/.rapidkit:$(pwd):$PATH"
|
|
|
241
241
|
\u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
|
|
242
242
|
`)),console.log(Y),console.log(s.gray(`
|
|
243
243
|
\u{1F4A1} After activation you can run: rapidkit dev
|
|
244
|
-
`)),process.exit(0);}if(!a$1&&!Lt(o)&&
|
|
244
|
+
`)),process.exit(0);}if(!a$1&&!Lt(o)&&C!=="init"&&!d&&zo(o)){let Y=await e(o,{cwd:e$2});process.exit(Y);}}}catch{}return false}var ot=null,$o=false,ne=new Command,$l=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function Ml(t){if(t.length===0)return false;let e=t[0],o=t[1];if(s$2(t)||dl.includes(e))return false;if(i$1.includes(e)){if(e==="lint"||e==="format"){let n=a$5(process.cwd()),i=await dt(process.cwd());if(c$2(n,process.cwd())||i==="node"){let a=i$2(process.cwd(),n);if(g$1(process.cwd(),e,{framework:a.key})!==null)return false}if(f$2(n,process.cwd())||i==="python")return true;if(p$1(process.cwd()))return false}return true}if(Lt(t)||e==="shell"&&o==="activate")return false;if(t.includes("--tui"))return true;if(e==="--help"||e==="-h"||e==="help"||e==="--version"||e==="-V"||e==="-v"||t.includes("--template")||t.includes("-t"))return false;let r=await i$3();return qo(e,r)?true:t.some(n=>Ho.has(n))?false:r?r.has(e):!!(a$9.has(e)||t.length>1)}ne.name("rapidkit").description("Create RapidKit workspaces and projects").version(b());var Ol=a()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev",Nl=w.join(g(),"my-workspace");ne.addHelpText("beforeAll",`RapidKit NPM CLI
|
|
245
245
|
|
|
246
246
|
Create workspaces, scaffold projects, and manage your development toolchain.
|
|
247
247
|
`);ne.addHelpText("afterAll",`
|
|
@@ -274,9 +274,9 @@ Quick start:
|
|
|
274
274
|
npx rapidkit my-workspace # Create workspace in ~/rapidkit/workspaces
|
|
275
275
|
npx rapidkit my-workspace --here # Create workspace in the current directory
|
|
276
276
|
npx rapidkit create workspace --output .
|
|
277
|
-
cd ${
|
|
277
|
+
cd ${Nl} # Or cd my-workspace when using --here
|
|
278
278
|
npx rapidkit create project # Interactive kit picker
|
|
279
|
-
${
|
|
279
|
+
${Ol} # Install deps + run
|
|
280
280
|
|
|
281
281
|
Notes:
|
|
282
282
|
--here Create workspace in the current directory (alias for --output .)
|
|
@@ -285,7 +285,7 @@ Notes:
|
|
|
285
285
|
It is different from core --skip-essentials (essential module installation).
|
|
286
286
|
|
|
287
287
|
Use "rapidkit help <command>" for more information.
|
|
288
|
-
`);ne.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, java-only, python-only, node-only, go-only, dotnet-only, polyglot, enterprise").choices(["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not create a workspace").hideHelp()).option("--no-update-check","Skip checking for updates").action(async(t,e$1)=>{try{e$1.debug&&(f.setDebug(true),f.debug("Debug mode enabled"));let o=await b$1();f.debug("User config loaded",o);let r=await c();f.debug("RapidKit config loaded",r);let n=d(o,r,{author:e$1.author,pythonVersion:void 0,skipGit:e$1.skipGit});f.debug("Merged config",n),e$1.updateCheck!==false&&await a$1(),a$2("workspace"),t||(
|
|
288
|
+
`);ne.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, java-only, python-only, node-only, go-only, dotnet-only, polyglot, enterprise").choices(["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not create a workspace").hideHelp()).option("--no-update-check","Skip checking for updates").action(async(t,e$1)=>{try{e$1.debug&&(f.setDebug(true),f.debug("Debug mode enabled"));let o=await b$1();f.debug("User config loaded",o);let r=await c();f.debug("RapidKit config loaded",r);let n=d(o,r,{author:e$1.author,pythonVersion:void 0,skipGit:e$1.skipGit});f.debug("Merged config",n),e$1.updateCheck!==false&&await a$1(),a$2("workspace"),t||(qi(),process.exit(0));try{h(t);}catch(l){throw l instanceof a$3&&(f.error(`
|
|
289
289
|
\u274C ${l.message}`),l.details&&f.warn(`\u{1F4A1} ${l.details}
|
|
290
290
|
`),process.exit(1)),l}let i=!!e$1.template,a;i||(e$1.here?a=process.cwd():e$1.output?a=w.resolve(e$1.output):a=await m([],{hasYes:e$1.yes}));let c$1=i?w.resolve(process.cwd(),t):l(t,{outputParent:a});if(ot=c$1,!e$1.dryRun){i||await R__default.ensureDir(w.dirname(c$1));let l=i?void 0:h$1(t);(l&&await R__default.pathExists(l)||await R__default.pathExists(c$1))&&(f.error(`
|
|
291
291
|
\u274C Directory "${t}" already exists`),l&&l!==c$1&&console.log(s.gray(` Found at: ${l}`)),console.log(s.cyan(`
|
|
@@ -293,15 +293,22 @@ Use "rapidkit help <command>" for more information.
|
|
|
293
293
|
`)),process.exit(1));}if(e$1.dryRun){console.log(s.cyan(`
|
|
294
294
|
\u{1F50D} Dry-run mode - showing what would be created:
|
|
295
295
|
`)),console.log(s.white("\u{1F4C2} Path:"),c$1),console.log(s.white("\u{1F4E6} Type:"),i?`Project (${e$1.template})`:"Workspace"),console.log();return}if(!e$1.yes&&!i?await b$2([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"RapidKit User"}]):e$1.yes&&console.log(s.gray(`Using default values (--yes flag)
|
|
296
|
-
`)),i){let l=String(e$1.template||"").trim(),g=q(l);if(s$1(g)){let
|
|
297
|
-
`),f.debug(`Synced Python version ${x.trim()} from workspace to project`);}}catch(x){f.debug("Could not sync Python version from workspace:",x);}}if(!e$1.skipInstall){let
|
|
298
|
-
`),f.debug(`Re-synced Python version ${I.trim()} after init`);}}catch(I){f.debug("Could not re-sync Python version after init:",I);}}}}else {let{createProject:l}=await import('./create-
|
|
296
|
+
`)),i){let l=String(e$1.template||"").trim(),g=q(l);if(s$1(g)){let v=await Tr(["create","project",g,t,...e$1.skipGit?["--skip-git"]:[]]);v!==0&&process.exit(v);return}if(!!!Lr(process.cwd())){let{registerWorkspaceAtPath:v}=await import('./create-UGXMC4CT.js');if(e$1.createWorkspace)await v(process.cwd(),{skipGit:e$1.skipGit,yes:e$1.yes,userConfig:o});else if(!e$1.noWorkspace)if(e$1.yes)await v(process.cwd(),{skipGit:e$1.skipGit,yes:true,userConfig:o});else {let{createWs:y}=await b$2([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);y&&await v(process.cwd(),{skipGit:e$1.skipGit,yes:false,userConfig:o});}}let p=["create","project",g,t,"--output",process.cwd()];e$1.yes&&p.push("--yes");let d=re(process.cwd()),f$2=!!e$1.skipInstall,u=f$2||!!d;f$2&&p.push("--skip-essentials");let h=u?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,k=await f$1(p,{cwd:process.cwd(),env:h});k!==0&&process.exit(k),d&&!e$1.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx rapidkit init")));let P=Lr(process.cwd());if(P){let v=w.dirname(P),y=w.join(v,".python-version"),C=w.join(c$1,".python-version");try{if(await R__default.pathExists(y)){let x=b$3.readFileSync(y,"utf-8");b$3.writeFileSync(C,x.trim()+`
|
|
297
|
+
`),f.debug(`Synced Python version ${x.trim()} from workspace to project`);}}catch(x){f.debug("Could not sync Python version from workspace:",x);}}if(!e$1.skipInstall){let v=await e(["init",c$1],{cwd:process.cwd()});if(v!==0&&process.exit(v),P){let y=w.dirname(P),C=w.join(y,".python-version"),x=w.join(c$1,".python-version");try{if(await R__default.pathExists(C)){let I=b$3.readFileSync(C,"utf-8");b$3.writeFileSync(x,I.trim()+`
|
|
298
|
+
`),f.debug(`Re-synced Python version ${I.trim()} after init`);}}catch(I){f.debug("Could not re-sync Python version after init:",I);}}}}else {let{createProject:l}=await import('./create-UGXMC4CT.js');await l(t,{skipGit:e$1.skipGit,dryRun:e$1.dryRun,yes:e$1.yes,userConfig:n,installMethod:e$1.installMethod,profile:e$1.profile,parentDirectory:w.dirname(c$1)}),console.log(s.gray(`\u2139\uFE0F Workspace root: ${c$1}`)),console.log(s.gray(` Next: ${k(c$1)} && npx rapidkit create project`));}}catch(o){o instanceof a$3?(f.error(`
|
|
299
299
|
\u274C ${o.message}`),o.details&&f.warn(`\u{1F4A1} ${o.details}`),f.debug("Error code:",o.code)):(f.error(`
|
|
300
|
-
\u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{ot=null;}});ns(ne);ls(ne);Ts(ne);ne.command("commands").description("Show effective RapidKit command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{il({json:t.json});});ne.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:o}=await import('./analyze-RHQM4AB2.js'),r=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(r,null,2)):o(r),r.summary.verdict==="blocked"&&process.exit(2);}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify({schemaVersion:"rapidkit-analyze-error-v1",ok:false,error:{message:o}},null,2)):console.error(s.red(`Analyze failed: ${o}`)),process.exit(1);}});Ln(ne);ne.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(l){let g=l;for(;;){let m=w.join(g,".rapidkit","context.json");if(b$3.existsSync(m))return m;let p=w.dirname(g);if(p===g)break;g=p;}return null}let r=o(e);function n(l){let g=l;for(;;){let m=w.join(g,".venv"),p=w.join(g,".rapidkit","activate");if(b$3.existsSync(p)||b$3.existsSync(m))return {venv:m,activateFile:p};let d=w.dirname(g);if(d===g)break;g=d;}return null}let i=n(e);!r&&!i&&(console.log(s.yellow("No RapidKit project found in this directory")),process.exit(1));let a$1;i&&b$3.existsSync(i.activateFile)?a$1=i.activateFile:i&&b$3.existsSync(i.venv)?a$1=h$2(i.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=a();console.log(c?`call "${a$1}"`:`. "${a$1}"`);});ne.command("readiness").description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$4({json:t.json,strict:t.strict,skipVerify:t.skipVerify});});ne.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:o}=await import('./pipeline-XK62WL4D.js');await o({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.noAgentSync===true,agentSync:t.agentSync===true?true:t.noAgentSync?false:void 0});});ne.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let o=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(o)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let r=Number(e.maxWorkers??""),n=Number.isFinite(r)?Math.max(1,Math.trunc(r)):void 0,{runAutopilotRelease:i}=await import('./autopilot-release-OJTLXPMX.js'),a;try{a=await i({workspacePath:process.cwd(),mode:o,since:e.since,parallel:e.parallel===true,maxWorkers:n,json:e.json===true,output:e.output});}catch(c){let l=c instanceof Error?c.message:String(c);console.log(s.red(`Autopilot release failed: ${l}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});ne.command("import <source>").description("Import a local backend project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Enable Core module/template commands for supported runtimes").option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await fl(t,e);o!==0&&process.exit(o);});ne.command("adopt [source]").description("Adopt an existing local project into a RapidKit workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Enable Core module/template commands for supported runtimes").option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await gl(t,e);o!==0&&process.exit(o);});var $o=ne.command("snapshot").description("Create, list, and restore RapidKit workspace snapshots");$o.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await vt({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot create failed: ${o.message}`)),process.exit(1);}});$o.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await fs({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let o of e)console.log(s.cyan(o.name)),console.log(s.gray(` ${o.createdAt} | ${o.mode} | ${o.projects.length} project(s)`)),console.log(s.gray(` ${o.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});$o.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await ms({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.cyan(`Snapshot: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Created: ${o.manifest.createdAt}`)),console.log(s.gray(` Projects: ${o.manifest.projects.length}`)),console.log(s.gray(` Files: ${o.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${o.estimatedBytes}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot inspect failed: ${o.message}`)),process.exit(1);}});$o.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await gs({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(o,null,2));return}o.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${o.snapshotPath}`)),console.log(s.gray(` Restored paths: ${o.restoredPaths.join(", ")}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot restore failed: ${o.message}`)),process.exit(1);}});var Jt=ne.command("project").description("Safe workspace project lifecycle operations");Jt.command("commands").description("Show effective commands supported by the current RapidKit project").option("--json","Emit machine-readable JSON output").action(async t=>{Ei({json:t.json});});Jt.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await pr({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let o of e)console.log(s.cyan(o.projectName)),console.log(s.gray(` Archived: ${o.archivedAt}`)),console.log(s.gray(` Path: ${o.archivePath}`)),o.reason&&console.log(s.gray(` Reason: ${o.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Jt.command("archive <project>").description("Move a project into .rapidkit/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await ur({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project archive dry-run: ${o.projectName}`):s.green(`\u2714 Project archived: ${o.projectName}`)),console.log(s.gray(` From: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` To: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project archive failed: ${o.message}`)),process.exit(1);}});Jt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await vs({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project restore dry-run: ${o.projectName}`):s.green(`\u2714 Project restored: ${o.projectName}`)),console.log(s.gray(` From: ${o.archivePath}`)),console.log(s.gray(` To: ${o.projectPath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project restore failed: ${o.message}`)),process.exit(1);}});Jt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await ks({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}let r=o.action==="archive"?"archived":"deleted";console.log(o.dryRun?s.cyan(`Project ${r} dry-run: ${o.projectName}`):s.green(`\u2714 Project ${r}: ${o.projectName}`)),console.log(s.gray(` Path: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` Archive: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project delete failed: ${o.message}`)),process.exit(1);}});ne.command("doctor [scope]").description("\u{1FA7A} Check RapidKit system health by default; use workspace or project for scoped checks").option("--workspace","Check entire workspace (including all projects)").option("--project","Check only the current project (or nearest parent project)").option("--json","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx rapidkit doctor | npx rapidkit doctor workspace | npx rapidkit doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let o=await al({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package rapidkit rapidkit doctor workspace")));let{runDoctor:r}=await import('./doctor-UOLOGJ2Z.js'),n=await r({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true});n!==0&&process.exit(n);});ne.command("workspace <action> [subaction] [key] [value]").description(`Manage RapidKit workspaces (list, sync, policy, share, export, hydrate, run)
|
|
300
|
+
\u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{ot=null;}});ys(ne);bs(ne);Ys(ne);ne.command("commands").description("Show effective RapidKit command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{wl({json:t.json});});ne.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:o}=await import('./analyze-JVMUCQ22.js'),r=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(r,null,2)):o(r),r.summary.verdict==="blocked"&&process.exit(2);}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify({schemaVersion:"rapidkit-analyze-error-v1",ok:false,error:{message:o}},null,2)):console.error(s.red(`Analyze failed: ${o}`)),process.exit(1);}});Zn(ne);ne.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(l){let g=l;for(;;){let m=w.join(g,".rapidkit","context.json");if(b$3.existsSync(m))return m;let p=w.dirname(g);if(p===g)break;g=p;}return null}let r=o(e);function n(l){let g=l;for(;;){let m=w.join(g,".venv"),p=w.join(g,".rapidkit","activate");if(b$3.existsSync(p)||b$3.existsSync(m))return {venv:m,activateFile:p};let d=w.dirname(g);if(d===g)break;g=d;}return null}let i=n(e);!r&&!i&&(console.log(s.yellow("No RapidKit project found in this directory")),process.exit(1));let a$1;i&&b$3.existsSync(i.activateFile)?a$1=i.activateFile:i&&b$3.existsSync(i.venv)?a$1=h$2(i.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=a();console.log(c?`call "${a$1}"`:`. "${a$1}"`);});ne.command("readiness").description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$4({json:t.json,strict:t.strict,skipVerify:t.skipVerify});});ne.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:o}=await import('./pipeline-MKNYPNGD.js');await o({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.noAgentSync===true,agentSync:t.agentSync===true?true:t.noAgentSync?false:void 0});});ne.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let o=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(o)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let r=Number(e.maxWorkers??""),n=Number.isFinite(r)?Math.max(1,Math.trunc(r)):void 0,{runAutopilotRelease:i}=await import('./autopilot-release-GM5ALPWO.js'),a;try{a=await i({workspacePath:process.cwd(),mode:o,since:e.since,parallel:e.parallel===true,maxWorkers:n,json:e.json===true,output:e.output});}catch(c){let l=c instanceof Error?c.message:String(c);console.log(s.red(`Autopilot release failed: ${l}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});ne.command("import <source>").description("Import a local backend project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Enable Core module/template commands for supported runtimes").option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await Sl(t,e);o!==0&&process.exit(o);});ne.command("adopt [source]").description("Adopt an existing local project into a RapidKit workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Enable Core module/template commands for supported runtimes").option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await Rl(t,e);o!==0&&process.exit(o);});var Mo=ne.command("snapshot").description("Create, list, and restore RapidKit workspace snapshots");Mo.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await vt({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot create failed: ${o.message}`)),process.exit(1);}});Mo.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Rs({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let o of e)console.log(s.cyan(o.name)),console.log(s.gray(` ${o.createdAt} | ${o.mode} | ${o.projects.length} project(s)`)),console.log(s.gray(` ${o.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});Mo.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Ss({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.cyan(`Snapshot: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Created: ${o.manifest.createdAt}`)),console.log(s.gray(` Projects: ${o.manifest.projects.length}`)),console.log(s.gray(` Files: ${o.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${o.estimatedBytes}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot inspect failed: ${o.message}`)),process.exit(1);}});Mo.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Es({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(o,null,2));return}o.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${o.snapshotPath}`)),console.log(s.gray(` Restored paths: ${o.restoredPaths.join(", ")}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot restore failed: ${o.message}`)),process.exit(1);}});var Jt=ne.command("project").description("Safe workspace project lifecycle operations");Jt.command("commands").description("Show effective commands supported by the current RapidKit project").option("--json","Emit machine-readable JSON output").action(async t=>{Ji({json:t.json});});Jt.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await ur({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let o of e)console.log(s.cyan(o.projectName)),console.log(s.gray(` Archived: ${o.archivedAt}`)),console.log(s.gray(` Path: ${o.archivePath}`)),o.reason&&console.log(s.gray(` Reason: ${o.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Jt.command("archive <project>").description("Move a project into .rapidkit/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await mr({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project archive dry-run: ${o.projectName}`):s.green(`\u2714 Project archived: ${o.projectName}`)),console.log(s.gray(` From: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` To: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project archive failed: ${o.message}`)),process.exit(1);}});Jt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Ms({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project restore dry-run: ${o.projectName}`):s.green(`\u2714 Project restored: ${o.projectName}`)),console.log(s.gray(` From: ${o.archivePath}`)),console.log(s.gray(` To: ${o.projectPath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project restore failed: ${o.message}`)),process.exit(1);}});Jt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await $s({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}let r=o.action==="archive"?"archived":"deleted";console.log(o.dryRun?s.cyan(`Project ${r} dry-run: ${o.projectName}`):s.green(`\u2714 Project ${r}: ${o.projectName}`)),console.log(s.gray(` Path: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` Archive: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project delete failed: ${o.message}`)),process.exit(1);}});ne.command("doctor [scope]").description("\u{1FA7A} Check RapidKit system health by default; use workspace or project for scoped checks").option("--workspace","Check entire workspace (including all projects)").option("--project","Check only the current project (or nearest parent project)").option("--json","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx rapidkit doctor | npx rapidkit doctor workspace | npx rapidkit doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let o=await kl({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package rapidkit rapidkit doctor workspace")));let{runDoctor:r}=await import('./doctor-LCKG5S76.js'),n=await r({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true});n!==0&&process.exit(n);});ne.command("workspace <action> [subaction] [key] [value]").description(`Manage RapidKit workspaces (list, sync, policy, share, export, run, intelligence)
|
|
301
301
|
workspace run <stage> \u2014 fleet stage execution across discovered projects
|
|
302
|
-
stages: init | test | build | start (dev excluded by design)`).option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--output <file>","Output file path for workspace share bundle").option("--from <file>","Input workspace model snapshot/report for workspace diff").option("--from-impact <file>","Input workspace impact report for workspace verify (defaults to last-run impact)").option("--include-paths","Include absolute paths in workspace share bundle").option("--write","Write workspace intelligence artifact to .rapidkit/reports").option("--include-evidence","Read status metadata from referenced evidence reports").option("--scan-depth <count>","Observable project discovery depth for large monorepos").option("--cache","Reuse cached workspace model when inputs are unchanged (keyed by inputsHash)").option("--incremental","Rebuild only changed projects and re-infer only their incident graph edges (graph-aware)").option("--once","For workspace watch: do the initial in-memory build and exit (no watcher)").option("--for-agent [agent]","Build an agent-ready workspace context pack").option("--agent-sync","After --write on context, sync cross-tool agent grounding files (AGENTS.md, Copilot, Cursor, Claude)").option("--no-agent-sync","Skip automatic agent grounding sync after context --write").option("--target <targets>","Agent customization targets for agent-sync (all|vscode|agents,copilot,cursor,claude,codex,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").option("--refresh-context","Rebuild workspace-context-agent.json during agent-sync").option("--experimental-hooks","Generate advisory VS Code agent hook design files during enterprise agent-sync").option("--scope <scope>","Scope workspace intelligence output, e.g. project:<name>").option("--no-doctor","Exclude doctor evidence in workspace share bundle").option("--no-blueprint","Exclude reproducibility blueprint from workspace share bundle").option("--include-env","Include .env/private key files in workspace export archive").option("--force","Overwrite an existing hydrate output directory").option("--refresh","Publish workspace registry summary before reading status").option("--dry-run","Preview hydrate without writing files").option("--affected","Run only affected projects (requires git diff context)").option("--blast-radius","Include downstream dependents from workspace dependency graph").option("--since <ref>","Git ref for affected calculation (default: HEAD~1)").option("--parallel","Run project stages in parallel").option("--max-workers <count>","Maximum parallel workers (default: min(4, selected))").option("--continue-on-error","Continue running remaining projects after a failure").option("--json","Emit machine-readable JSON output").option("--strict","Return non-zero exit on warn/fail gate outcomes").option("--no-gates","Skip doctor/readiness pre-run gates").action(async function(t,e,o,r){let n=this.opts(),i=l=>{let m=(n.workspace?w.resolve(n.workspace):null)??a$7(process.cwd())??re(process.cwd());(!m||!We(m))&&(console.log(s.red("\u274C Not inside a RapidKit workspace")),console.log(s.gray("\u{1F4A1} Run from a workspace directory or pass --workspace <path>.")),process.exit(1));let p=w.resolve(process.cwd()),d=w.resolve(m);return p!==d&&console.log(s.gray(`\u2139 Using workspace root ${m} for "${l}" (current directory: ${p}).`)),m},a=l=>process.argv.includes(l),c=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0};if(Gs(t)&&d$1({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||a("--json"),strict:n.strict===true||a("--strict")}}),t==="list"){let{listWorkspaces:l}=await import('./workspace-L4ITCKMM.js');await l();}else if(t==="model"){let l=i("model"),{buildWorkspaceModelCached:g,buildWorkspaceModelIncremental:m,writeWorkspaceModel:p}=await import('./workspace-model-SDHH5RBC.js'),d=n.incremental===true||a("--incremental"),u=n.cache===true||a("--cache")||d,f={workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c(),strict:n.strict===true||a("--strict")},y,v;if(d){let h=await m(f);y=h.model,v=h.mode;}else {let h=await g({...f,cache:u});y=h.model,v=h.cache;}let P;(n.write===true||a("--write"))&&(P=await p(y,l));let k=(n.strict===true||a("--strict"))&&y.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...y,...P?{outputPath:P}:{}},null,2)),k&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${y.workspace.name}`)),d?console.log(s.gray(` Build: ${v} (incremental)`)):u&&console.log(s.gray(` Cache: ${v}`)),console.log(s.gray(` Projects: ${y.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${y.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${y.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${y.identity.workspaceType}`)),console.log(s.gray(` Validation: ${y.validation?.status??"unknown"} (${y.validation?.errors??0} error, ${y.validation?.warnings??0} warning)`)),console.log(P?s.gray(` Written: ${P}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-model.json")),k&&process.exit(1);}else if(t==="agent-sync"){let l=i("agent-sync"),{syncWorkspaceAgentGrounding:g,parseAgentGroundingTargets:m}=await import('./workspace-agent-sync-G7JU77IK.js'),p=n.strict===true||a("--strict"),d=n.write===true||a("--write"),u=a("--dry-run"),f=await g({workspacePath:l,scope:n.scope,agent:n.forAgent,write:d&&!u,dryRun:u,strict:p,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||a("--refresh-context")||a("--refresh"),targets:m(n.target),experimentalHooks:n.experimentalHooks===true||a("--experimental-hooks"),staleAfterHours:24});if(n.json)console.log(JSON.stringify(f,null,2));else {console.log(s.green(`\u2714 Agent grounding ${d&&!u?"synced":"planned"}`)),console.log(s.gray(` Index: ${f.indexPath}`)),f.contextPath&&console.log(s.gray(` Context: ${f.contextPath}`)),f.blockers.length>0&&console.log(s.yellow(` Blockers: ${f.blockers.slice(0,3).join(" \xB7 ")}`));let y=d&&!u?f.writtenFiles:f.skippedFiles;if(y.length>0&&console.log(s.gray(` Files: ${y.join(", ")}`)),f.strictViolations.length>0)for(let v of f.strictViolations)console.log(s.red(`\u274C ${v}`));}p&&f.strictViolations.length>0&&process.exit(1);}else if(t==="context"){let l=i("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx rapidkit workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:g,writeWorkspaceAgentContext:m}=await import('./workspace-context-NMMQMHNU.js'),p=n.strict===true||a("--strict"),d=await g({workspacePath:l,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c(),strict:p&&!n.json}),u,f;if((n.write===true||a("--write"))&&(u=await m(d,l),(n.agentSync===true||a("--agent-sync")||n.noAgentSync!==true)&&!a("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:k}=await import('./workspace-agent-sync-G7JU77IK.js');if(f=await P({workspacePath:l,scope:n.scope,agent:d.agent,write:true,refreshContext:false,strict:p,preset:n.preset==="minimal"?"minimal":"enterprise",targets:k(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${f.writtenFiles.length} file(s) updated`)),p&&f.strictViolations.length>0){for(let h of f.strictViolations)console.log(s.red(`\u274C ${h}`));process.exit(1);}}let y=p&&d.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...d,...u?{outputPath:u}:{},...f?{agentGroundingSync:f}:{}},null,2)),y&&process.exit(1);return}console.log(s.green(`\u2714 Workspace context: ${d.workspace.name}`)),console.log(s.gray(` Agent: ${d.agent}`)),console.log(s.gray(` Scope: ${d.scope.activeProject??d.scope.requested}`)),console.log(s.gray(` Projects included: ${d.projects.length}`)),console.log(s.gray(` Safe commands: ${d.safeCommands.length}`)),console.log(s.gray(` Validation: ${d.validation.status} (${d.validation.errors} error, ${d.validation.warnings} warning)`)),console.log(u?s.gray(` Written: ${u}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-context-agent.json"));}else if(t==="snapshot"){let l=i("snapshot"),{buildWorkspaceModelSnapshot:g,writeWorkspaceModelSnapshot:m}=await import('./workspace-intelligence-64IWAYHS.js'),p=await g({workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),d=await m(p,l);if(n.json){console.log(JSON.stringify({...p,outputPath:d},null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${p.model.workspace.name}`)),console.log(s.gray(` Hash: ${p.modelHash}`)),console.log(s.gray(` Projects: ${p.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${p.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${d}`));}else if(t==="diff"){let l=i("diff"),g=n.from||e;g||(console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx rapidkit workspace diff --from .rapidkit/reports/workspace-model.json --json")),console.log(s.gray(" npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx rapidkit workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:m,writeWorkspaceModelDiff:p}=await import('./workspace-intelligence-64IWAYHS.js'),d=await m({workspacePath:l,fromPath:g,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),u=await p(d,l);if(n.json){console.log(JSON.stringify({...d,outputPath:u},null,2));return}let f=d.summary.changed?s.yellow:s.green;console.log(f(`\u2714 Workspace model diff: ${d.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${d.fromRef}`)),console.log(s.gray(` Added projects: ${d.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${d.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${d.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${d.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${d.summary.validationChanges}`)),d.git?.available&&console.log(s.gray(` Git: ${d.git.dirty?"dirty":"clean"} (${d.summary.gitChangedFiles} mapped change(s))`));for(let y of d.changes.slice(0,12))console.log(s.gray(` \u2022 ${y.type} ${y.target}: ${y.message}`));d.changes.length>12&&console.log(s.gray(` \u2026 ${d.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${u}`));}else if(t==="impact"){let l=i("impact"),g=n.from||e;g||(console.log(s.red("\u274C workspace impact requires --from <snapshot-model-or-diff-report>")),console.log(s.gray(" npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:m,writeWorkspaceImpact:p}=await import('./workspace-intelligence-64IWAYHS.js'),d=await m({workspacePath:l,fromPath:g,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),u=await p(d,l);if(n.json){console.log(JSON.stringify({...d,outputPath:u},null,2));return}let f=d.summary.risk==="critical"||d.summary.risk==="high"?s.red:d.summary.risk==="medium"?s.yellow:s.green;console.log(f(`\u2714 Workspace impact: ${d.summary.risk}`)),console.log(s.gray(` From: ${d.fromRef}`)),console.log(s.gray(` Affected projects: ${d.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${d.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${d.summary.recommendedCommands}`));for(let y of d.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${y.title}: ${y.summary}`));d.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${d.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${u}`));}else if(t==="verify"){let l=i("verify"),{buildWorkspaceVerify:g,writeWorkspaceVerify:m,evaluateWorkspaceVerifyGate:p}=await import('./workspace-verify-6Q6MGRG6.js'),d=await g({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),u=await m(d,l),f=p(d,{strict:n.strict===true||a("--strict")}),y=f.exitCode,{recordWorkspaceHistory:v,historyEntryFromVerify:P}=await import('./workspace-history-LHUTLE3S.js');if(await v(l,P(d,f.passed)),n.json){console.log(JSON.stringify({...d,gate:f,outputPath:u},null,2)),y!==0&&process.exit(y);return}let k=d.summary.verdict==="ready"?s.green:d.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(k(`\u2714 Workspace verify: ${d.summary.verdict}`)),console.log(s.gray(` Freshness: ${d.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${d.impact.risk}`)),console.log(s.gray(` Steps: ${d.steps.length}`)),console.log(s.gray(` Passed ${d.summary.stepsPassed}, warn ${d.summary.stepsWarn}, failed ${d.summary.stepsFailed}, missing ${d.summary.stepsMissing}`));for(let h of d.steps.slice(0,10))console.log(s.gray(` \u2022 ${h.id}: ${h.status} \u2014 ${h.message}`));if(d.steps.length>10&&console.log(s.gray(` \u2026 ${d.steps.length-10} more step(s)`)),d.policyViolations.length>0){console.log(s.gray(` Policy (${d.policyMode}): ${d.policyViolations.length} violation(s)`));for(let h of d.policyViolations.slice(0,5)){let S=h.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${S} [${h.source}] ${h.code}: ${h.message}`);}}console.log(s.gray(` Gate (${f.mode}): ${f.passed?"passed":"blocked"}`));for(let h of f.reasons.slice(0,5))console.log(s.red(` \u2717 ${h}`));console.log(s.gray(` Written: ${u}`)),y!==0&&process.exit(y);}else if(t==="graph"){let l=i("graph"),{buildWorkspaceModel:g}=await import('./workspace-model-SDHH5RBC.js'),{buildGraphEmit:m,renderGraphDot:p,renderGraphMermaid:d,explainGraphNode:u}=await import('./workspace-graph-ICB7OVAZ.js'),y=(await g({workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()})).graph;y||(console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let v=(e||"emit").toLowerCase();if(v==="dot"){console.log(p(y));return}if(v==="mermaid"){console.log(d(y));return}if(v==="explain"){let k=(n.scope?.replace(/^project:/,"")||o||"").trim();k||(console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx rapidkit workspace graph explain <project> --json")),console.log(s.gray(" npx rapidkit workspace graph explain --scope project:<name>")),process.exit(1));let h=u(y,k);if(n.json){console.log(JSON.stringify(h,null,2)),h.found||process.exit(1);return}h.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${k}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${h.project}`)),h.centrality&&console.log(s.gray(` Centrality: fanIn ${h.centrality.fanIn}, fanOut ${h.centrality.fanOut}, reach ${h.centrality.reach}, betweenness ${h.centrality.betweenness}${h.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${h.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${h.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${h.transitiveDependents.length}`));for(let S of h.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${S.id} (d${S.distance}, via ${S.via??"\u2014"})`));return}let P=m(y);if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${P.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${P.graph.stats.edgeCount} (inferred ${P.graph.stats.inferredEdges}, contract ${P.graph.stats.contractEdges}, manual ${P.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${P.integrity.ok?"ok":"issues"} (cycles ${P.integrity.stats.cycleCount}, dangling ${P.integrity.stats.danglingCount}, orphans ${P.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${P.hotspots.join(", ")||"none"}`)),console.log(s.gray(" Render: workspace graph dot | workspace graph mermaid"));}else if(t==="watch"){let l=i("watch"),{runWorkspaceWatch:g}=await import('./workspace-watch-JDXVGW4H.js'),m=n.once===true||a("--once"),p=n.json===true,d=new AbortController,u=()=>d.abort();process.once("SIGINT",u),process.once("SIGTERM",u),p||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await g({workspacePath:l,once:m,signal:d.signal,buildOptions:{workspacePath:l,observableScanDepth:c()},onProgress:f=>{p||console.error(s.gray(` ${f}`));},emit:f=>{if(p){console.log(JSON.stringify(f));return}if(f.kind==="ready"){console.log(s.gray(` Ready: ${f.graph.nodeCount} nodes, ${f.graph.edgeCount} edges (hash ${f.modelHash.slice(0,12)})`));return}if(f.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${f.error??"unknown error"}`));return}if(f.kind==="unchanged"){console.log(s.gray(` No structural change (${f.mode}, ${f.durationMs}ms)`));return}let y=[];f.changedProjects.length>0&&y.push(`changed: ${f.changedProjects.join(", ")}`),f.addedProjects.length>0&&y.push(`added: ${f.addedProjects.join(", ")}`),f.removedProjects.length>0&&y.push(`removed: ${f.removedProjects.join(", ")}`),f.graph.edgesAdded.length>0&&y.push(`+${f.graph.edgesAdded.length} edges`),f.graph.edgesRemoved.length>0&&y.push(`-${f.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${f.mode}, ${f.durationMs}ms): ${y.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u),!p&&!m&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=i("sync"),{syncWorkspaceProjects:g}=await import('./workspace-L4ITCKMM.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${w.basename(l)}`));let m=await g(l,n.json===true);await Ue(l,{silent:n.json===true});let{readWorkspaceRegistrySummary:p}=await import('./workspace-registry-summary-MIPHVB56.js'),d=await p(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:m,contractSynced:true,registrySummary:d},null,2));}else if(t==="registry"){let l=i("registry"),g=e||"status";g!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${g}`)),console.log(s.gray(" npx rapidkit workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:m,readWorkspaceRegistrySummary:p,resolveWorkspaceRegisteredProjects:d}=await import('./workspace-registry-summary-MIPHVB56.js'),f=n.refresh===true||a("--refresh")||n.force===true||a("--force")?await m(l):await p(l)||await m(l);if(n.json){console.log(JSON.stringify(f,null,2));return}let y=await d(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${f.authority}`)),console.log(s.gray(` Projects: ${f.projectCount}`)),console.log(s.gray(` Summary: ${f.registrySummaryPath}`)),y.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=i("foundation"),g=e||"ensure";g!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${g}`)),console.log(s.gray(" npx rapidkit workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:m}=await import('./workspace-foundation-HNIRAIBF.js'),p=await m(l,{force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(p,null,2));return}p.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${p.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=i("policy"),g=await wl(l,e,o,r);g!==0&&process.exit(g);}else if(t==="contract"){let l=i("contract"),{buildWorkspaceContractGraph:g,readWorkspaceContract:m,verifyWorkspaceContract:p,writeWorkspaceContract:d,WORKSPACE_CONTRACT_PATH:u}=await import('./workspace-contract-D5O4OZD5.js'),f=e||"inspect",y=n.output;try{if(f==="init"){let v=await d({workspacePath:l,outputPath:y,force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${v.contractPath}`)),console.log(s.gray(` Projects: ${v.contract.projects.length}`));return}if(f==="inspect"){let v=await m({workspacePath:l,contractPath:y});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${v.contractPath}`)),console.log(s.gray(` Workspace: ${v.contract.workspace.name}`)),console.log(s.gray(` Projects: ${v.contract.projects.length}`)),console.log(s.gray(` Schema: v${v.contract.schemaVersion}`));return}if(f==="verify"){let v=await p({workspacePath:l,contractPath:y,strict:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(v,null,2));else {let P=v.status==="passed"?s.green:s.red;console.log(P(`\u2714 Workspace contract verification ${v.status}: ${v.contractPath}`)),console.log(s.gray(` Projects: ${v.projectCount}`));for(let k of v.checks){let h=k.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${h} ${k.id}: ${k.message}`));}for(let k of v.violations)console.log(s.gray(` Violation: ${k}`));}(v.status==="failed"||v.status!=="passed"&&n.strict)&&process.exit(1);return}if(f==="graph"){let v=await g({workspacePath:l,contractPath:y});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${v.contractPath}`)),console.log(s.gray(` Workspace: ${v.graph.workspace.name}`)),console.log(s.gray(` Projects: ${v.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${v.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${v.graph.summary.eventEdges}`)),console.log(s.gray(` Ports: ${v.graph.summary.portCount}`));for(let P of v.graph.nodes){let k=P.ports.map(h=>`${h.name}:${h.port}`).join(", ")||"none";console.log(s.gray(` \u2022 ${P.id} (${P.runtime||"unknown"}${P.framework?`/${P.framework}`:""}) ports=${k}`));}for(let P of v.graph.edges){let k=P.type==="event"?`event:${P.label}`:P.label;console.log(s.gray(` ${P.from} -> ${P.to} [${k}]`));}return}console.log(s.red(`\u274C Unknown workspace contract action: ${f}`)),console.log(s.white(` npx rapidkit workspace contract init|inspect|verify|graph [--output ${u}]`)),process.exit(1);}catch(v){console.log(s.red(`\u274C Workspace contract ${f} failed: ${v.message}`)),process.exit(1);}}else if(t==="share"){let l=i("share"),g=n.output||e,{createWorkspaceShareBundle:m}=await import('./workspace-L4ITCKMM.js'),p=await m(l,{outputPath:g,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});console.log(s.green(`\u2714 Workspace share bundle exported: ${p}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=i("export"),{exportWorkspaceArchive:g}=await import('./workspace-archive-EJIGYKSR.js'),m=await g({workspacePath:l,outputPath:n.output||e,includeEnv:n.includeEnv===true||a("--include-env")});if(n.json){console.log(JSON.stringify(m,null,2));return}let p=(m.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${m.archivePath}`)),console.log(s.gray(` Files: ${m.manifest.files.length}`)),console.log(s.gray(` Size: ${p} MB`)),m.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let l=o;l||(console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx rapidkit workspace archive ${e} team.rapidkit-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:g,inspectWorkspaceArchive:m,verifyWorkspaceArchive:p}=await import('./workspace-archive-EJIGYKSR.js');try{if(e==="inspect"){let u=await m({archivePathOrUrl:l});if(n.json){console.log(JSON.stringify(u,null,2));return}let f=(u.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${u.archivePath}`)),console.log(s.gray(` Workspace: ${u.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${u.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${u.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${u.fileCount}`)),console.log(s.gray(` Payload: ${f} MB`));return}if(e==="doctor"){let u=await g({archivePathOrUrl:l,strict:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(u,null,2));else {let f=u.status==="passed"?s.green:u.status==="warning"?s.yellow:s.red;console.log(f(`\u2714 Workspace archive doctor ${u.status}: ${u.archivePath}`)),console.log(s.gray(` Workspace: ${u.workspaceName}`)),console.log(s.gray(` Files: ${u.fileCount}`));for(let y of u.checks){let v=y.status==="passed"?"\u2714":y.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${v} ${y.id}: ${y.message}`));}for(let y of u.recommendedActions)console.log(s.gray(` Next: ${y}`));}(u.status==="failed"||u.status==="warning"&&n.strict)&&process.exit(1);return}let d=await p({archivePathOrUrl:l,requireChecksums:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(d,null,2));else if(d.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${d.archivePath}`)),console.log(s.gray(` Files: ${d.verifiedFiles}/${d.fileCount}`));else {let u=d.status==="failed"?s.red:s.yellow;console.log(u(`\u274C Workspace archive verification ${d.status}: ${d.archivePath}`)),d.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${d.missingArchiveEntries.join(", ")}`)),d.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${d.extraArchiveEntries.join(", ")}`)),d.mismatches.length&&console.log(s.gray(` Mismatches: ${d.mismatches.map(f=>f.path).join(", ")}`)),d.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${d.missingChecksumFiles.join(", ")}`));}(d.status==="failed"||d.status==="warning"&&n.strict)&&process.exit(1);}catch(d){console.log(s.red(`\u274C Workspace archive ${e} failed: ${d.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx rapidkit workspace ${t} team.rapidkit-archive.zip --output ./team`)),process.exit(1));let{hydrateWorkspaceArchive:g}=await import('./workspace-archive-EJIGYKSR.js');try{let m=await g({archivePathOrUrl:l,outputPath:n.output,force:n.force===true||a("--force"),dryRun:n.dryRun===true||a("--dry-run"),strict:n.strict===true||a("--strict")});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.dryRun?`\u2714 Workspace archive hydrate preview: ${m.outputPath}`:`\u2714 Workspace archive hydrated: ${m.outputPath}`)),console.log(s.gray(` Files: ${m.files.length}`)),m.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${m.manifest.workspaceName}`));}catch(m){console.log(s.red(`\u274C Workspace ${t} failed: ${m.message}`)),process.exit(1);}}else if(t==="run"){let l=i(`run ${e||""}`.trim());(!e||!["init","test","build","start"].includes(e))&&(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let g=Number(n.maxWorkers??""),m=Number.isFinite(g)?Math.max(1,Math.trunc(g)):void 0;if(e==="init"){let u=await Lr(l);u!==0&&process.exit(u);}let{runWorkspaceStage:p}=await import('./workspace-run-SPP32MPV.js'),d=await p({workspacePath:l,stage:e,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:m,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(d,null,2)),d.summary.exitCode!==0&&process.exit(d.summary.exitCode);}else if(t==="init"){console.log(s.yellow("\u2139 workspace init is an alias of: npx rapidkit workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
|
|
302
|
+
stages: init | test | build | start | <custom-from-context>
|
|
303
|
+
workspace explain|why \u2014 blocker/project narrative (--write for artifact)
|
|
304
|
+
workspace trace \u2014 diff \u2192 blast radius \u2192 gates narrative (--from <diff>)
|
|
305
|
+
workspace mcp serve \u2014 read-mostly stdio MCP bridge over workspace evidence`).option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--output <file>","Output file path for workspace share bundle").option("--from <file>","Input workspace model snapshot/report for workspace diff").option("--from-impact <file>","Input workspace impact report for workspace verify (defaults to last-run impact)").option("--include-paths","Include absolute paths in workspace share bundle").option("--write","Write workspace intelligence artifact to .rapidkit/reports").option("--include-evidence","Read status metadata from referenced evidence reports").option("--scan-depth <count>","Observable project discovery depth for large monorepos").option("--cache","Reuse cached workspace model when inputs are unchanged (keyed by inputsHash)").option("--incremental","Rebuild only changed projects and re-infer only their incident graph edges (graph-aware)").option("--once","For workspace watch: do the initial in-memory build and exit (no watcher)").option("--for-agent [agent]","Build an agent-ready workspace context pack").option("--agent-sync","After --write on context, sync cross-tool agent grounding files (AGENTS.md, Copilot, Cursor, Claude)").option("--no-agent-sync","Skip automatic agent grounding sync after context --write").option("--target <targets>","Agent customization targets for agent-sync (all|vscode|agents,copilot,cursor,claude,codex,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").option("--refresh-context","Rebuild workspace-context-agent.json during agent-sync").option("--experimental-hooks","Generate advisory VS Code agent hook design files during enterprise agent-sync").option("--hydrate-prompts","Hydrate matching Copilot prompt files with workspace-specific verification steps during agent-sync").option("--scope <scope>","Scope workspace intelligence output, e.g. project:<name>").option("--no-doctor","Exclude doctor evidence in workspace share bundle").option("--no-blueprint","Exclude reproducibility blueprint from workspace share bundle").option("--include-env","Include .env/private key files in workspace export archive").option("--force","Overwrite an existing hydrate output directory").option("--refresh","Publish workspace registry summary before reading status").option("--dry-run","Preview hydrate without writing files").option("--affected","Run only affected projects (requires git diff context)").option("--blast-radius","Include downstream dependents from workspace dependency graph").option("--since <ref>","Git ref for affected calculation (default: HEAD~1)").option("--parallel","Run project stages in parallel").option("--max-workers <count>","Maximum parallel workers (default: min(4, selected))").option("--continue-on-error","Continue running remaining projects after a failure").option("--reuse-passed","Skip projects that already passed this stage in workspace-run-last.json").option("--json","Emit machine-readable JSON output").option("--strict","Return non-zero exit on warn/fail gate outcomes").option("--no-gates","Skip doctor/readiness pre-run gates").action(async function(t,e,o,r){let n=this.opts(),i=l=>{let m=(n.workspace?w.resolve(n.workspace):null)??a$7(process.cwd())??re(process.cwd());(!m||!We(m))&&(console.log(s.red("\u274C Not inside a RapidKit workspace")),console.log(s.gray("\u{1F4A1} Run from a workspace directory or pass --workspace <path>.")),process.exit(1));let p=w.resolve(process.cwd()),d=w.resolve(m);return p!==d&&console.log(s.gray(`\u2139 Using workspace root ${m} for "${l}" (current directory: ${p}).`)),m},a=l=>process.argv.includes(l),c=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0};if((oi(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$1({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||a("--json"),strict:n.strict===true||a("--strict")}}),t==="list"){let{listWorkspaces:l}=await import('./workspace-FDMJD5XI.js');await l();}else if(t==="model"){let l=i("model"),{buildWorkspaceModelCached:g,buildWorkspaceModelIncremental:m,writeWorkspaceModel:p}=await import('./workspace-model-VMMLHJWI.js'),d=n.incremental===true||a("--incremental"),f=n.cache===true||a("--cache")||d,u={workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c(),strict:n.strict===true||a("--strict")},h,k;if(d){let y=await m(u);h=y.model,k=y.mode;}else {let y=await g({...u,cache:f});h=y.model,k=y.cache;}let P;(n.write===true||a("--write"))&&(P=await p(h,l));let v=(n.strict===true||a("--strict"))&&h.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...h,...P?{outputPath:P}:{}},null,2)),v&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${h.workspace.name}`)),d?console.log(s.gray(` Build: ${k} (incremental)`)):f&&console.log(s.gray(` Cache: ${k}`)),console.log(s.gray(` Projects: ${h.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${h.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${h.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${h.identity.workspaceType}`)),console.log(s.gray(` Validation: ${h.validation?.status??"unknown"} (${h.validation?.errors??0} error, ${h.validation?.warnings??0} warning)`)),console.log(P?s.gray(` Written: ${P}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-model.json")),v&&process.exit(1);}else if(t==="agent-sync"){let l=i("agent-sync"),{syncWorkspaceAgentGrounding:g,parseAgentGroundingTargets:m}=await import('./workspace-agent-sync-WJIZCZX5.js'),p=n.strict===true||a("--strict"),d=n.write===true||a("--write"),f=a("--dry-run"),u=await g({workspacePath:l,scope:n.scope,agent:n.forAgent,write:d&&!f,dryRun:f,strict:p,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||a("--refresh-context")||a("--refresh"),targets:m(n.target),experimentalHooks:n.experimentalHooks===true||a("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||a("--hydrate-prompts"),staleAfterHours:24});if(n.json)console.log(JSON.stringify(u,null,2));else {console.log(s.green(`\u2714 Agent grounding ${d&&!f?"synced":"planned"}`)),console.log(s.gray(` Index: ${u.indexPath}`)),u.contextPath&&console.log(s.gray(` Context: ${u.contextPath}`)),u.blockers.length>0&&console.log(s.yellow(` Blockers: ${u.blockers.slice(0,3).join(" \xB7 ")}`));let h=d&&!f?u.writtenFiles:u.skippedFiles;if(h.length>0&&console.log(s.gray(` Files: ${h.join(", ")}`)),u.strictViolations.length>0)for(let k of u.strictViolations)console.log(s.red(`\u274C ${k}`));}p&&u.strictViolations.length>0&&process.exit(1);}else if(t==="context"){let l=i("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx rapidkit workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:g,writeWorkspaceAgentContext:m}=await import('./workspace-context-RYOQYGOP.js'),p=n.strict===true||a("--strict"),d=await g({workspacePath:l,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c(),strict:false}),f,u;if((n.write===true||a("--write"))&&(f=await m(d,l),(n.agentSync===true||a("--agent-sync")||n.noAgentSync!==true)&&!a("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:v}=await import('./workspace-agent-sync-WJIZCZX5.js');if(u=await P({workspacePath:l,scope:n.scope,agent:d.agent,write:true,refreshContext:false,strict:p,preset:n.preset==="minimal"?"minimal":"enterprise",targets:v(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${u.writtenFiles.length} file(s) updated`)),p&&u.strictViolations.length>0){for(let y of u.strictViolations)console.log(s.red(`\u274C ${y}`));process.exit(1);}}let h=p&&d.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...d,...f?{outputPath:f}:{},...u?{agentGroundingSync:u}:{}},null,2)),h&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${d.workspace.name}`)),console.log(s.gray(` Agent: ${d.agent}`)),console.log(s.gray(` Scope: ${d.scope.activeProject??d.scope.requested}`)),console.log(s.gray(` Projects included: ${d.projects.length}`)),console.log(s.gray(` Safe commands: ${d.safeCommands.length}`)),console.log(s.gray(` Validation: ${d.validation.status} (${d.validation.errors} error, ${d.validation.warnings} warning)`)),console.log(f?s.gray(` Written: ${f}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-context-agent.json")),h){for(let k of d.validation.issues)console.log(s.red(`\u274C ${k.severity}:${k.code}:${k.target}`));process.exit(1);}}else if(t==="snapshot"){let l=i("snapshot"),{buildWorkspaceModelSnapshot:g,writeWorkspaceModelSnapshot:m}=await import('./workspace-intelligence-YOZQBAK5.js'),p=await g({workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),d=await m(p,l);if(n.json){console.log(JSON.stringify({...p,outputPath:d},null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${p.model.workspace.name}`)),console.log(s.gray(` Hash: ${p.modelHash}`)),console.log(s.gray(` Projects: ${p.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${p.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${d}`));}else if(t==="diff"){let l=i("diff"),g=n.from||e;g||(console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx rapidkit workspace diff --from .rapidkit/reports/workspace-model.json --json")),console.log(s.gray(" npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx rapidkit workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:m,writeWorkspaceModelDiff:p}=await import('./workspace-intelligence-YOZQBAK5.js'),d=await m({workspacePath:l,fromPath:g,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),f=await p(d,l);if(n.json){console.log(JSON.stringify({...d,outputPath:f},null,2));return}let u=d.summary.changed?s.yellow:s.green;console.log(u(`\u2714 Workspace model diff: ${d.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${d.fromRef}`)),console.log(s.gray(` Added projects: ${d.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${d.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${d.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${d.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${d.summary.validationChanges}`)),d.git?.available&&console.log(s.gray(` Git: ${d.git.dirty?"dirty":"clean"} (${d.summary.gitChangedFiles} mapped change(s))`));for(let h of d.changes.slice(0,12))console.log(s.gray(` \u2022 ${h.type} ${h.target}: ${h.message}`));d.changes.length>12&&console.log(s.gray(` \u2026 ${d.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="impact"){let l=i("impact"),g=n.from||e;g||(console.log(s.red("\u274C workspace impact requires --from <snapshot-model-or-diff-report>")),console.log(s.gray(" npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:m,writeWorkspaceImpact:p}=await import('./workspace-intelligence-YOZQBAK5.js'),d=await m({workspacePath:l,fromPath:g,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),f=await p(d,l);if(n.json){console.log(JSON.stringify({...d,outputPath:f},null,2));return}let u=d.summary.risk==="critical"||d.summary.risk==="high"?s.red:d.summary.risk==="medium"?s.yellow:s.green;console.log(u(`\u2714 Workspace impact: ${d.summary.risk}`)),console.log(s.gray(` From: ${d.fromRef}`)),console.log(s.gray(` Affected projects: ${d.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${d.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${d.summary.recommendedCommands}`));for(let h of d.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${h.title}: ${h.summary}`));d.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${d.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="verify"){let l=i("verify"),{buildWorkspaceVerify:g,writeWorkspaceVerify:m,evaluateWorkspaceVerifyGate:p}=await import('./workspace-verify-3CAKAZIL.js'),d=await g({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),f=await m(d,l),u=p(d,{strict:n.strict===true||a("--strict")}),h=u.exitCode,{recordWorkspaceHistory:k,historyEntryFromVerify:P}=await import('./workspace-history-VPDADQKG.js');if(await k(l,P(d,u.passed)),n.json){console.log(JSON.stringify({...d,gate:u,outputPath:f},null,2)),h!==0&&process.exit(h);return}let v=d.summary.verdict==="ready"?s.green:d.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(v(`\u2714 Workspace verify: ${d.summary.verdict}`)),console.log(s.gray(` Freshness: ${d.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${d.impact.risk}`)),console.log(s.gray(` Steps: ${d.steps.length}`)),console.log(s.gray(` Passed ${d.summary.stepsPassed}, warn ${d.summary.stepsWarn}, failed ${d.summary.stepsFailed}, missing ${d.summary.stepsMissing}`));for(let y of d.steps.slice(0,10))console.log(s.gray(` \u2022 ${y.id}: ${y.status} \u2014 ${y.message}`));if(d.steps.length>10&&console.log(s.gray(` \u2026 ${d.steps.length-10} more step(s)`)),d.policyViolations.length>0){console.log(s.gray(` Policy (${d.policyMode}): ${d.policyViolations.length} violation(s)`));for(let y of d.policyViolations.slice(0,5)){let C=y.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${C} [${y.source}] ${y.code}: ${y.message}`);}}console.log(s.gray(` Gate (${u.mode}): ${u.passed?"passed":"blocked"}`));for(let y of u.reasons.slice(0,5))console.log(s.red(` \u2717 ${y}`));console.log(s.gray(` Written: ${f}`)),h!==0&&process.exit(h);}else if(t==="graph"){let l=i("graph"),{buildWorkspaceModel:g}=await import('./workspace-model-VMMLHJWI.js'),{buildGraphEmit:m,renderGraphDot:p,renderGraphMermaid:d,explainGraphNode:f}=await import('./workspace-graph-2A5THUCI.js'),h=(await g({workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()})).graph;h||(console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let k=(e||"emit").toLowerCase();if(k==="dot"){console.log(p(h));return}if(k==="mermaid"){console.log(d(h));return}if(k==="explain"){let v=(n.scope?.replace(/^project:/,"")||o||"").trim();v||(console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx rapidkit workspace graph explain <project> --json")),console.log(s.gray(" npx rapidkit workspace graph explain --scope project:<name>")),process.exit(1));let y=f(h,v);if(n.json){console.log(JSON.stringify(y,null,2)),y.found||process.exit(1);return}y.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${v}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${y.project}`)),y.centrality&&console.log(s.gray(` Centrality: fanIn ${y.centrality.fanIn}, fanOut ${y.centrality.fanOut}, reach ${y.centrality.reach}, betweenness ${y.centrality.betweenness}${y.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${y.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${y.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${y.transitiveDependents.length}`));for(let C of y.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${C.id} (d${C.distance}, via ${C.via??"\u2014"})`));return}let P=m(h);if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${P.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${P.graph.stats.edgeCount} (inferred ${P.graph.stats.inferredEdges}, contract ${P.graph.stats.contractEdges}, manual ${P.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${P.integrity.ok?"ok":"issues"} (cycles ${P.integrity.stats.cycleCount}, dangling ${P.integrity.stats.danglingCount}, orphans ${P.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${P.hotspots.join(", ")||"none"}`)),console.log(s.gray(" Render: workspace graph dot | workspace graph mermaid"));}else if(t==="watch"){let l=i("watch"),{runWorkspaceWatch:g}=await import('./workspace-watch-3MEZRSEE.js'),m=n.once===true||a("--once"),p=n.json===true,d=new AbortController,f=()=>d.abort();process.once("SIGINT",f),process.once("SIGTERM",f),p||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await g({workspacePath:l,once:m,signal:d.signal,buildOptions:{workspacePath:l,observableScanDepth:c()},onProgress:u=>{p||console.error(s.gray(` ${u}`));},emit:u=>{if(p){console.log(JSON.stringify(u));return}if(u.kind==="ready"){console.log(s.gray(` Ready: ${u.graph.nodeCount} nodes, ${u.graph.edgeCount} edges (hash ${u.modelHash.slice(0,12)})`));return}if(u.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${u.error??"unknown error"}`));return}if(u.kind==="unchanged"){console.log(s.gray(` No structural change (${u.mode}, ${u.durationMs}ms)`));return}let h=[];u.changedProjects.length>0&&h.push(`changed: ${u.changedProjects.join(", ")}`),u.addedProjects.length>0&&h.push(`added: ${u.addedProjects.join(", ")}`),u.removedProjects.length>0&&h.push(`removed: ${u.removedProjects.join(", ")}`),u.graph.edgesAdded.length>0&&h.push(`+${u.graph.edgesAdded.length} edges`),u.graph.edgesRemoved.length>0&&h.push(`-${u.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${u.mode}, ${u.durationMs}ms): ${h.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",f),process.removeListener("SIGTERM",f),!p&&!m&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=i("sync"),{syncWorkspaceProjects:g}=await import('./workspace-FDMJD5XI.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${w.basename(l)}`));let m=await g(l,n.json===true);await Ue(l,{silent:n.json===true});let{readWorkspaceRegistrySummary:p}=await import('./workspace-registry-summary-ZXGKL2NT.js'),d=await p(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:m,contractSynced:true,registrySummary:d},null,2));}else if(t==="registry"){let l=i("registry"),g=e||"status";g!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${g}`)),console.log(s.gray(" npx rapidkit workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:m,readWorkspaceRegistrySummary:p,resolveWorkspaceRegisteredProjects:d}=await import('./workspace-registry-summary-ZXGKL2NT.js'),u=n.refresh===true||a("--refresh")||n.force===true||a("--force")?await m(l):await p(l)||await m(l);if(n.json){console.log(JSON.stringify(u,null,2));return}let h=await d(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${u.authority}`)),console.log(s.gray(` Projects: ${u.projectCount}`)),console.log(s.gray(` Summary: ${u.registrySummaryPath}`)),h.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=i("foundation"),g=e||"ensure";g!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${g}`)),console.log(s.gray(" npx rapidkit workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:m}=await import('./workspace-foundation-SILFUKL5.js'),p=await m(l,{force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(p,null,2));return}p.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${p.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=i("policy"),g=await Al(l,e,o,r);g!==0&&process.exit(g);}else if(t==="contract"){let l=i("contract"),{buildWorkspaceContractGraph:g,readWorkspaceContract:m,verifyWorkspaceContract:p,writeWorkspaceContract:d,WORKSPACE_CONTRACT_PATH:f}=await import('./workspace-contract-ITFCJCHI.js'),u=e||"inspect",h=n.output;try{if(u==="init"){let k=await d({workspacePath:l,outputPath:h,force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(k,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${k.contractPath}`)),console.log(s.gray(` Projects: ${k.contract.projects.length}`));return}if(u==="inspect"){let k=await m({workspacePath:l,contractPath:h});if(n.json){console.log(JSON.stringify(k,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${k.contractPath}`)),console.log(s.gray(` Workspace: ${k.contract.workspace.name}`)),console.log(s.gray(` Projects: ${k.contract.projects.length}`)),console.log(s.gray(` Schema: v${k.contract.schemaVersion}`));return}if(u==="verify"){let k=await p({workspacePath:l,contractPath:h,strict:n.strict===true||a("--strict")}),{writeWorkspaceContractVerifyEvidence:P}=await import('./workspace-contract-ITFCJCHI.js'),v=await P({workspacePath:l,result:k});if(n.json)console.log(JSON.stringify({...k,evidencePath:v},null,2));else {let y=k.status==="passed"?s.green:s.red;console.log(y(`\u2714 Workspace contract verification ${k.status}: ${k.contractPath}`)),console.log(s.gray(` Projects: ${k.projectCount}`));for(let C of k.checks){let x=C.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${x} ${C.id}: ${C.message}`));}for(let C of k.violations)console.log(s.gray(` Violation: ${C}`));}(k.status==="failed"||k.status!=="passed"&&n.strict)&&process.exit(1);return}if(u==="graph"){let k=await g({workspacePath:l,contractPath:h});if(n.json){console.log(JSON.stringify(k,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${k.contractPath}`)),console.log(s.gray(` Workspace: ${k.graph.workspace.name}`)),console.log(s.gray(` Projects: ${k.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${k.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${k.graph.summary.eventEdges}`)),console.log(s.gray(` Ports: ${k.graph.summary.portCount}`));for(let P of k.graph.nodes){let v=P.ports.map(y=>`${y.name}:${y.port}`).join(", ")||"none";console.log(s.gray(` \u2022 ${P.id} (${P.runtime||"unknown"}${P.framework?`/${P.framework}`:""}) ports=${v}`));}for(let P of k.graph.edges){let v=P.type==="event"?`event:${P.label}`:P.label;console.log(s.gray(` ${P.from} -> ${P.to} [${v}]`));}return}console.log(s.red(`\u274C Unknown workspace contract action: ${u}`)),console.log(s.white(` npx rapidkit workspace contract init|inspect|verify|graph [--output ${f}]`)),process.exit(1);}catch(k){console.log(s.red(`\u274C Workspace contract ${u} failed: ${k.message}`)),process.exit(1);}}else if(t==="share"){let l=i("share"),g=n.output||e,{createWorkspaceShareBundle:m}=await import('./workspace-FDMJD5XI.js'),p=await m(l,{outputPath:g,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});console.log(s.green(`\u2714 Workspace share bundle exported: ${p}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=i("export"),{exportWorkspaceArchive:g}=await import('./workspace-archive-EJIGYKSR.js'),m=await g({workspacePath:l,outputPath:n.output||e,includeEnv:n.includeEnv===true||a("--include-env")});if(n.json){console.log(JSON.stringify(m,null,2));return}let p=(m.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${m.archivePath}`)),console.log(s.gray(` Files: ${m.manifest.files.length}`)),console.log(s.gray(` Size: ${p} MB`)),m.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let l=o;l||(console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx rapidkit workspace archive ${e} team.rapidkit-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:g,inspectWorkspaceArchive:m,verifyWorkspaceArchive:p}=await import('./workspace-archive-EJIGYKSR.js');try{if(e==="inspect"){let f=await m({archivePathOrUrl:l});if(n.json){console.log(JSON.stringify(f,null,2));return}let u=(f.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${f.archivePath}`)),console.log(s.gray(` Workspace: ${f.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${f.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${f.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${f.fileCount}`)),console.log(s.gray(` Payload: ${u} MB`));return}if(e==="doctor"){let f=await g({archivePathOrUrl:l,strict:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(f,null,2));else {let u=f.status==="passed"?s.green:f.status==="warning"?s.yellow:s.red;console.log(u(`\u2714 Workspace archive doctor ${f.status}: ${f.archivePath}`)),console.log(s.gray(` Workspace: ${f.workspaceName}`)),console.log(s.gray(` Files: ${f.fileCount}`));for(let h of f.checks){let k=h.status==="passed"?"\u2714":h.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${k} ${h.id}: ${h.message}`));}for(let h of f.recommendedActions)console.log(s.gray(` Next: ${h}`));}(f.status==="failed"||f.status==="warning"&&n.strict)&&process.exit(1);return}let d=await p({archivePathOrUrl:l,requireChecksums:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(d,null,2));else if(d.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${d.archivePath}`)),console.log(s.gray(` Files: ${d.verifiedFiles}/${d.fileCount}`));else {let f=d.status==="failed"?s.red:s.yellow;console.log(f(`\u274C Workspace archive verification ${d.status}: ${d.archivePath}`)),d.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${d.missingArchiveEntries.join(", ")}`)),d.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${d.extraArchiveEntries.join(", ")}`)),d.mismatches.length&&console.log(s.gray(` Mismatches: ${d.mismatches.map(u=>u.path).join(", ")}`)),d.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${d.missingChecksumFiles.join(", ")}`));}(d.status==="failed"||d.status==="warning"&&n.strict)&&process.exit(1);}catch(d){console.log(s.red(`\u274C Workspace archive ${e} failed: ${d.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx rapidkit workspace ${t} team.rapidkit-archive.zip --output ./team`)),process.exit(1));let{hydrateWorkspaceArchive:g}=await import('./workspace-archive-EJIGYKSR.js');try{let m=await g({archivePathOrUrl:l,outputPath:n.output,force:n.force===true||a("--force"),dryRun:n.dryRun===true||a("--dry-run"),strict:n.strict===true||a("--strict")});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.dryRun?`\u2714 Workspace archive hydrate preview: ${m.outputPath}`:`\u2714 Workspace archive hydrated: ${m.outputPath}`)),console.log(s.gray(` Files: ${m.files.length}`)),m.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${m.manifest.workspaceName}`));}catch(m){console.log(s.red(`\u274C Workspace ${t} failed: ${m.message}`)),process.exit(1);}}else if(t==="run"){let l=i(`run ${e||""}`.trim()),g=new Set(["init","test","build","start"]),m=e?.trim()??"";m||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .rapidkit/context.json commands")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2)),g.has(m)||(!/^[a-z][a-z0-9_-]*$/i.test(m)||m==="dev"||m==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${m}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),process.exit(2));let p=Number(n.maxWorkers??""),d=Number.isFinite(p)?Math.max(1,Math.trunc(p)):void 0;if(m==="init"){let h=await Jr(l);h!==0&&process.exit(h);}let{runWorkspaceStage:f}=await import('./workspace-run-IHB2TPMD.js'),u=await f({workspacePath:l,stage:m,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:d,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(u,null,2)),u.summary.exitCode!==0&&process.exit(u.summary.exitCode);}else if(t==="explain"||t==="why"){let l=i(t),{parseWorkspaceExplainTarget:g}=await import('./workspace-explain-contract-CLHQ3XEH.js'),{buildWorkspaceExplain:m,writeWorkspaceExplainReport:p}=await import('./workspace-explain-VKSUKP3O.js'),d=(e??o??"").trim();!d&&n.scope&&(d=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),d||(console.log(s.red(`\u274C workspace ${t} requires a target.`)),console.log(s.gray(" npx rapidkit workspace explain project:<name>|release-blocked [--json] [--write]")),console.log(s.gray(" npx rapidkit workspace why <project>|release-blocked [--json]")),process.exit(1));let f=g(d);f||(console.log(s.red(`\u274C Invalid explain target: ${d}`)),process.exit(1));let u=await m({workspacePath:l,target:f}),h=n.write===true||a("--write"),k;if(h&&(k=await p(u,l)),n.json){console.log(JSON.stringify({...u,outputPath:k},null,2));return}console.log(s.green(`\u2714 Workspace explain: ${u.summary}`));for(let P of u.sections)console.log(s.bold(`
|
|
306
|
+
${P.title}`)),console.log(P.body);k&&console.log(s.gray(`
|
|
307
|
+
Written: ${k}`));}else if(t==="trace"){let l=i("trace"),g=n.from||e;g||(console.log(s.red("\u274C workspace trace requires --from <diff-ref>")),console.log(s.gray(" npx rapidkit workspace trace --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{parseWorkspaceExplainTarget:m}=await import('./workspace-explain-contract-CLHQ3XEH.js'),{buildWorkspaceExplain:p,writeWorkspaceExplainReport:d}=await import('./workspace-explain-VKSUKP3O.js'),f=m(g)??m(`trace:${g}`)??{kind:"trace",diffRef:g};f.kind!=="trace"&&(console.log(s.red(`\u274C Invalid trace ref: ${g}`)),process.exit(1));let u=await p({workspacePath:l,target:f}),h=n.write===true||a("--write"),k;if(h&&(k=await d(u,l)),n.json){console.log(JSON.stringify({...u,outputPath:k},null,2));return}console.log(s.green(`\u2714 Workspace trace: ${u.summary}`));for(let P of u.sections)console.log(s.bold(`
|
|
308
|
+
${P.title}`)),console.log(P.body);k&&console.log(s.gray(`
|
|
309
|
+
Written: ${k}`));}else if(t==="feedback"){let l=i("feedback"),g=(e||"record").toLowerCase();g!=="record"&&(console.log(s.red(`Unknown feedback action: ${g}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!a("--json")&&(console.log(s.red("\u274C workspace feedback record requires --json (stdin payload)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx rapidkit workspace feedback record --json`)),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace feedback record requires piped JSON on stdin (not a TTY)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx rapidkit workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:m,parseFeedbackStdinPayload:p,readStdinAll:d}=await import('./workspace-feedback-65NR3EZH.js'),f=await d(),u=p(f);u||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let h=await m({workspacePath:l,payload:u});n.json?console.log(JSON.stringify(h,null,2)):h.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${h.historyPath}`))):console.log(s.red(`\u274C ${h.error??"Failed to record feedback"}`)),h.ok||process.exit(1);}else if(t==="mcp"){let l=i("mcp"),g=(e||"serve").toLowerCase();g!=="serve"&&(console.log(s.red(`Unknown mcp action: ${g}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:m}=await import('./workspace-mcp-serve-OOLITFCK.js');n.json||console.error(s.gray("\u2139 RapidKit MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await m({workspacePath:l});}else if(t==="init"){console.log(s.yellow("\u2139 workspace init is an alias of: npx rapidkit workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
|
|
303
310
|
npx rapidkit init | npx rapidkit workspace init | npx rapidkit workspace run init
|
|
304
|
-
`));let l=i("init"),g=Number(n.maxWorkers??""),m=Number.isFinite(g)?Math.max(1,Math.trunc(g)):void 0,p=await
|
|
311
|
+
`));let l=i("init"),g=Number(n.maxWorkers??""),m=Number.isFinite(g)?Math.max(1,Math.trunc(g)):void 0,p=await Jr(l);p!==0&&process.exit(p);let{runWorkspaceStage:d}=await import('./workspace-run-IHB2TPMD.js'),f=await d({workspacePath:l,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:m,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(f,null,2)),f.summary.exitCode!==0&&process.exit(f.summary.exitCode);}else console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${Ro.join(", ")}`)),process.exit(1);});function xt(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function qi(){let t=a()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev";console.log(s.white(`Usage:
|
|
305
312
|
`)),console.log(s.cyan(` npx rapidkit <workspace-name> [options]
|
|
306
313
|
`)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems
|
|
307
314
|
`)),console.log(s.white("Most AI tools understand files.")),console.log(s.white("RapidKit helps developers, CI pipelines, IDEs, and AI agents share the same understanding of a software system.")),console.log(s.dim(`One workspace. One truth. Humans and AI aligned.
|
|
@@ -316,6 +323,8 @@ Use "rapidkit help <command>" for more information.
|
|
|
316
323
|
`)),console.log(s.cyan(` npx rapidkit workspace impact --from <snapshot>
|
|
317
324
|
`)),console.log(s.white(`5. Verify release readiness
|
|
318
325
|
`)),console.log(s.cyan(" npx rapidkit workspace verify --strict")),console.log(s.cyan(` npx rapidkit pipeline --strict
|
|
326
|
+
`)),console.log(s.white(`6. Explain blockers and trace change impact
|
|
327
|
+
`)),console.log(s.cyan(" npx rapidkit workspace explain release-blocked --json --write")),console.log(s.cyan(` npx rapidkit workspace trace --from .rapidkit/reports/workspace-model-diff-last-run.json --json --write
|
|
319
328
|
`)),xt("Workspace Intelligence"),console.log(s.white(`
|
|
320
329
|
What projects exist?
|
|
321
330
|
`)),console.log(s.cyan(` npx rapidkit workspace model --json
|
|
@@ -325,8 +334,14 @@ What projects exist?
|
|
|
325
334
|
`)),console.log(s.cyan(` npx rapidkit workspace impact --from <snapshot>
|
|
326
335
|
`)),console.log(s.white(`Is this change safe?
|
|
327
336
|
`)),console.log(s.cyan(` npx rapidkit workspace verify --strict
|
|
337
|
+
`)),console.log(s.white(`Why is release blocked?
|
|
338
|
+
`)),console.log(s.cyan(` npx rapidkit workspace explain release-blocked --json --write
|
|
339
|
+
`)),console.log(s.white(`Trace a diff through blast radius and gates?
|
|
340
|
+
`)),console.log(s.cyan(` npx rapidkit workspace trace --from .rapidkit/reports/workspace-model-diff-last-run.json --json --write
|
|
328
341
|
`)),console.log(s.white(`How do I align AI tools and CI?
|
|
329
342
|
`)),console.log(s.cyan(` npx rapidkit workspace agent-sync --write
|
|
343
|
+
`)),console.log(s.white(`Expose evidence to MCP clients?
|
|
344
|
+
`)),console.log(s.cyan(` npx rapidkit workspace mcp serve
|
|
330
345
|
`)),xt("Workspace Operations"),console.log(s.white(`
|
|
331
346
|
Create workspace
|
|
332
347
|
`)),console.log(s.cyan(` npx rapidkit my-workspace
|
|
@@ -356,6 +371,8 @@ Generate context pack
|
|
|
356
371
|
`)),console.log(s.cyan(` npx rapidkit workspace context --for-agent
|
|
357
372
|
`)),console.log(s.white(`Sync agent surfaces
|
|
358
373
|
`)),console.log(s.cyan(` npx rapidkit workspace agent-sync --write
|
|
374
|
+
`)),console.log(s.white(`Serve read-mostly MCP bridge
|
|
375
|
+
`)),console.log(s.cyan(` npx rapidkit workspace mcp serve
|
|
359
376
|
`)),console.log(s.white(`Supported ecosystems:
|
|
360
377
|
`)),console.log(s.gray(` Copilot \xB7 Cursor \xB7 Claude Code \xB7 Codex \xB7 MCP-ready tools
|
|
361
378
|
`)),xt("Mental Model"),console.log(s.gray(`
|
|
@@ -363,17 +380,17 @@ Generate context pack
|
|
|
363
380
|
`)),console.log(s.dim(`RapidKit turns projects and repositories into a shared, evidence-backed understanding of a software system.
|
|
364
381
|
`)),console.log(s.bold("Quick start \u2014 workspace workflow:")),console.log(s.cyan(" npx rapidkit my-workspace ")+s.gray("# Create workspace (interactive profile picker)")),console.log(s.cyan(` cd ${w.join(g(),"my-workspace")}`)+s.gray(" # default managed location")),console.log(s.cyan(" npx rapidkit my-workspace --here ")+s.gray("# Create in current directory, then cd my-workspace")),console.log(s.cyan(" npx rapidkit bootstrap ")+s.gray("# Bootstrap all runtime toolchains")),console.log(s.cyan(" npx rapidkit create project ")+s.gray("# Interactive kit picker")),console.log(s.cyan(" npx rapidkit create frontend nextjs web ")+s.gray("# Create a frontend with the official generator")),console.log(s.cyan(" cd my-api")),console.log(s.cyan(` ${t}
|
|
365
382
|
`)),console.log(s.bold("Workspace profiles (asked during creation):")),console.log(s.gray(" minimal Foundation files only \u2014 fastest bootstrap (default)")),console.log(s.gray(" java-only Java runtime (Spring Boot services)")),console.log(s.gray(" python-only Python + Poetry (FastAPI, Django, ML)")),console.log(s.gray(" node-only Node.js runtime (NestJS, Express, Next.js)")),console.log(s.gray(" go-only Go runtime (Fiber, Gin, gRPC)")),console.log(s.gray(" dotnet-only .NET runtime (ASP.NET Core services)")),console.log(s.gray(" polyglot Python + Node.js + Go + Java + .NET multi-runtime")),console.log(s.gray(` enterprise Polyglot + governance + Sigstore
|
|
366
|
-
`)),console.log(s.bold("Workspace commands (inside a workspace):")),console.log(s.gray(" npx rapidkit bootstrap [--profile <p>] Re-bootstrap toolchains")),console.log(s.gray(" npx rapidkit analyze [--json --strict] Analyze workspace health and gaps")),console.log(s.gray(" npx rapidkit pipeline [--json --strict] Governance loop: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot")),console.log(s.gray(" npx rapidkit readiness [--json --strict] Release readiness gates (env/doctor/analyze/verify/deps)")),console.log(s.gray(" npx rapidkit doctor workspace [--ci] Workspace health with CI exit codes")),console.log(s.gray(" npx rapidkit workspace list List registered workspaces")),console.log(s.gray(" npx rapidkit workspace model --json Build workspace intelligence model")),console.log(s.gray(" npx rapidkit workspace context --for-agent --json --write Build agent context + sync grounding")),console.log(s.gray(" npx rapidkit workspace agent-sync --write --refresh-context Sync the Agent Customization Pack")),console.log(s.gray(" npx rapidkit workspace snapshot --json Persist workspace intelligence snapshot")),console.log(s.gray(" npx rapidkit workspace diff --from <file|git[:ref]> --json Diff current model against a snapshot")),console.log(s.gray(" npx rapidkit workspace impact --from <file> --json Build blast radius from model diff")),console.log(s.gray(" npx rapidkit workspace verify [--strict] --json Evaluate impact verification evidence")),console.log(s.gray(" npx rapidkit workspace run
|
|
383
|
+
`)),console.log(s.bold("Workspace commands (inside a workspace):")),console.log(s.gray(" npx rapidkit bootstrap [--profile <p>] Re-bootstrap toolchains")),console.log(s.gray(" npx rapidkit analyze [--json --strict] Analyze workspace health and gaps")),console.log(s.gray(" npx rapidkit pipeline [--json --strict] Governance loop: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot")),console.log(s.gray(" npx rapidkit readiness [--json --strict] Release readiness gates (env/doctor/analyze/verify/deps)")),console.log(s.gray(" npx rapidkit doctor workspace [--ci] Workspace health with CI exit codes")),console.log(s.gray(" npx rapidkit workspace list List registered workspaces")),console.log(s.gray(" npx rapidkit workspace model --json Build workspace intelligence model")),console.log(s.gray(" npx rapidkit workspace context --for-agent --json --write Build agent context + sync grounding")),console.log(s.gray(" npx rapidkit workspace agent-sync --write --refresh-context Sync the Agent Customization Pack")),console.log(s.gray(" npx rapidkit workspace snapshot --json Persist workspace intelligence snapshot")),console.log(s.gray(" npx rapidkit workspace diff --from <file|git[:ref]> --json Diff current model against a snapshot")),console.log(s.gray(" npx rapidkit workspace impact --from <file> --json Build blast radius from model diff")),console.log(s.gray(" npx rapidkit workspace verify [--strict] --json Evaluate impact verification evidence")),console.log(s.gray(" npx rapidkit workspace explain <target> [--write] --json Narrative for blockers/projects (alias: why)")),console.log(s.gray(" npx rapidkit workspace trace --from <diff> [--write] --json Diff \u2192 blast radius \u2192 gates narrative")),console.log(s.gray(" npx rapidkit workspace feedback record --json Append agent action outcome to intelligence history")),console.log(s.gray(" npx rapidkit workspace mcp serve Read-mostly stdio MCP over workspace evidence")),console.log(s.gray(" npx rapidkit workspace graph [emit|explain|dot|mermaid] Inspect/visualize dependency graph")),console.log(s.gray(" npx rapidkit workspace watch [--once] [--json] Keep model+graph in memory; stream change events")),console.log(s.gray(" npx rapidkit workspace run <stage> [--scope project:<name>] [--reuse-passed] Fleet init/test/build/start or custom stage")),console.log(s.gray(" npx rapidkit workspace sync [--json] Sync registry + contract from projects")),console.log(s.gray(" npx rapidkit workspace registry status [--refresh] [--json] Canonical project registry summary")),console.log(s.gray(" npx rapidkit import <path|git-url> Copy or clone a backend project into this workspace")),console.log(s.gray(" npx rapidkit adopt [path] Link an existing local project to a workspace")),console.log(s.gray(" npx rapidkit snapshot create [name] Create a recoverable workspace snapshot")),console.log(s.gray(" npx rapidkit snapshot restore <name> Restore snapshot metadata with safety guard")),console.log(s.gray(" npx rapidkit snapshot inspect <name> Inspect snapshot manifest and size")),console.log(s.gray(" npx rapidkit project archive <name> Archive a project with a safety snapshot")),console.log(s.gray(" npx rapidkit project restore <archive> Restore an archived project safely")),console.log(s.gray(" npx rapidkit workspace share [--output <file>] Export collaboration bundle")),console.log(s.gray(" npx rapidkit workspace foundation ensure Ensure workspace.json/policies/toolchain files")),console.log(s.gray(" npx rapidkit workspace contract init Create workspace service contract")),console.log(s.gray(" npx rapidkit workspace contract verify Verify service ports/dependencies")),console.log(s.gray(" npx rapidkit workspace contract graph Show service dependency graph")),console.log(s.gray(" npx rapidkit workspace export --output <file> Export portable workspace archive")),console.log(s.gray(" npx rapidkit workspace archive verify <file> Verify archive integrity")),console.log(s.gray(" npx rapidkit workspace archive doctor <file> Diagnose archive readiness")),console.log(s.gray(" npx rapidkit workspace hydrate <archive> --output <dir> Hydrate workspace archive")),console.log(s.gray(" npx rapidkit workspace policy show Show effective workspace policies")),console.log(s.gray(" npx rapidkit workspace policy set <k> <v> Update workspace policy values")),console.log(s.gray(" npx rapidkit setup python|node|go|java|dotnet [--warm-deps] Set up runtime (+ optional deps warm-up)")),console.log(s.gray(" npx rapidkit mirror [status|sync|verify|rotate] Registry mirror management")),console.log(s.gray(" npx rapidkit cache [status|clear|prune|repair] Package cache management")),console.log(s.gray(" npx rapidkit infra plan Discover and generate infra compose")),console.log(s.gray(` npx rapidkit infra up|down|status Manage Docker sidecar infrastructure
|
|
367
384
|
`)),console.log(s.bold("Options (workspace creation):")),console.log(s.gray(" -y, --yes Skip prompts and use defaults")),console.log(s.gray(" --author <name> Author/team name for workspace metadata")),console.log(s.gray(" --skip-git Skip git initialization")),console.log(s.gray(" --debug Enable debug logging")),console.log(s.gray(" --dry-run Show what would be created")),console.log(s.gray(" --create-workspace When creating a project outside a workspace: create and register a workspace in the current directory")),console.log(s.gray(" --no-workspace When creating a project outside a workspace: do not create a workspace")),console.log(s.gray(` --no-update-check Skip checking for updates
|
|
368
385
|
`)),console.log(s.bold("Project commands (inside a project):")),console.log(s.gray(" npx rapidkit create project Scaffold a new project")),console.log(s.gray(" cd my-api Change directory to the new project")),console.log(s.gray(" npx rapidkit init Install project dependencies")),console.log(s.gray(" npx rapidkit dev Start dev server")),console.log(s.gray(" npx rapidkit build Build for production")),console.log(s.gray(` npx rapidkit test Run tests
|
|
369
386
|
`)),console.log(s.bold("Flags clarification:")),console.log(s.gray(" --skip-install npm fast-path for lock/dependency steps")),console.log(s.gray(` --skip-essentials core flag for skipping essential module installation
|
|
370
|
-
`))
|
|
387
|
+
`)),$l?(console.log(s.bold("Legacy (shown because RAPIDKIT_SHOW_LEGACY=1):")),console.log(s.gray(" npx rapidkit my-project --template fastapi")),console.log(s.gray(" npx rapidkit my-project --template nestjs")),console.log(s.gray(" npx rapidkit my-project --template springboot")),console.log(s.gray(" npx rapidkit my-project --template gofiber")),console.log(s.gray(" npx rapidkit my-project --template gogin")),console.log(s.gray(" npx rapidkit my-project --template dotnet")),console.log(s.gray(` --skip-install Fast-path lock/deps (legacy template mode) \u2014 not same as --skip-essentials
|
|
371
388
|
`))):console.log(s.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
|
|
372
|
-
`));}var
|
|
389
|
+
`));}var Mi="__rapidkit_signal_handlers_registered__",Oi=globalThis;Oi[Mi]||(Oi[Mi]=true,process.on("SIGINT",async()=>{if(!$o){if($o=true,console.log(s.yellow(`
|
|
373
390
|
|
|
374
|
-
\u26A0\uFE0F Interrupted by user`)),ot&&await R__default.pathExists(ot)){console.log(s.gray("Cleaning up partial installation..."));try{await R__default.remove(ot),console.log(s.green("\u2713 Cleanup complete"));}catch(t){f.debug("Cleanup failed:",t);}}b$5(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(
|
|
391
|
+
\u26A0\uFE0F Interrupted by user`)),ot&&await R__default.pathExists(ot)){console.log(s.gray("Cleaning up partial installation..."));try{await R__default.remove(ot),console.log(s.green("\u2713 Cleanup complete"));}catch(t){f.debug("Cleanup failed:",t);}}b$5(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!$o){if($o=true,f.debug("Received SIGTERM"),ot&&await R__default.pathExists(ot))try{await R__default.remove(ot);}catch(t){f.debug("Cleanup failed:",t);}b$5(143,"Terminated"),process.exit(143);}}));var Dl=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Tl=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),o=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return b$3.realpathSync(t)===b$3.realpathSync(fileURLToPath(import.meta.url))||o}catch{return w.resolve(t)===w.resolve(fileURLToPath(import.meta.url))||o}})(),Wl=!Dl||Tl;function Fl(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}async function ge(t){b$5(t),await new Promise(e=>setImmediate(e)),await new Promise(e=>setTimeout(e,25)),await Promise.all([process.stdout,process.stderr].map(e=>new Promise(o=>{e.write("",()=>o());}))),process.exit(t);}if(Wl){Fl(),d$2(),a$4({argv:process.argv,cwd:process.cwd(),rapidkitVersion:b()}),c$1(process.argv);let t=process.argv.slice(2),e$2=t[0],o=process.cwd(),r=We(o),n=b$3.existsSync(w.join(o,".rapidkit","project.json")),i=fl(),a=bi(t),c=i&&Lt(t),l=e$2==="init"&&r&&!n;(t.length===0||t.length===1&&(e$2==="--help"||e$2==="-h"||e$2==="help"))&&(a$2("npm cli"),qi(),process.exit(0)),t.some(m=>m==="--version"||m==="-V"||m==="-v")&&!t.some(m=>m==="--help"||m==="-h"||m==="help")&&(t.includes("--json")?console.log(JSON.stringify(hl(),null,2)):console.log(b()),process.exit(0)),Wr(t)&&process.exit(0),c&&ji(e$2)?(async()=>{e$2==="bootstrap"&&await ge(await Ei(t)),e$2==="setup"&&await ge(await _i(t)),e$2==="cache"&&await ge(await Ai(t)),await ge(await Ii(t));})().catch(m=>{process.stderr.write(`RapidKit (npm) failed to run ${e$2}: ${m?.message??m}
|
|
375
392
|
`),process.exit(1);}):a||c?ne.parseAsync().then(()=>ge(0)).catch(m=>{process.stderr.write(`RapidKit (npm) failed: ${m?.message??m}
|
|
376
|
-
`),process.exit(1);}):l?
|
|
377
|
-
`),process.exit(1);}):
|
|
378
|
-
`),
|
|
379
|
-
`),d){let
|
|
393
|
+
`),process.exit(1);}):l?Kr(t).then(m=>ge(m)).catch(m=>{process.stderr.write(`RapidKit (npm) failed to run workspace init: ${m?.message??m}
|
|
394
|
+
`),process.exit(1);}):Il().then(async m=>{if(!m){let p=process.argv.slice(2);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] argv=${JSON.stringify(p)}
|
|
395
|
+
`),bi(p)){await ne.parseAsync();return}if(Wr(p)&&await ge(0),p[0]==="create"){let f=await Wi(p);await ge(f);}if(p[0]==="init"){let f=await Kr(p);await ge(f);}if(ji(p[0])){if(p[0]==="bootstrap"){let u=await Ei(p);await ge(u);}if(p[0]==="setup"){let u=await _i(p);await ge(u);}if(p[0]==="cache"){let u=await Ai(p);await ge(u);}let f=await Ii(p);await ge(f);}if(j(p[0])){if(Fr(p))return;let f=p[0],u=a$5(process.cwd()),h=await dt(process.cwd()),k=re(process.cwd()),P=false;if(k){let x=w.join(k,".rapidkit","policies.yml");if(await R__default.pathExists(x))try{let I=await b$3.promises.readFile(x,"utf-8");if(P=((I.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??I.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict",P){let ae=w.join(k,".rapidkit","toolchain.lock"),N=[];if(!await R__default.pathExists(ae))N.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain).");else try{let O=JSON.parse(await b$3.promises.readFile(ae,"utf-8")).runtime??{};b$6(u,process.cwd())&&!O.go?.version&&N.push("Go runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."),c$2(u,process.cwd())&&!O.node?.version&&N.push("Node runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."),d$3(u,process.cwd())&&!O.java?.version&&N.push("Java runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup java` first."),e$1(u,process.cwd())&&!O.dotnet?.version&&N.push(".NET runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup dotnet` first."),f$2(u,process.cwd())&&!O.python?.version&&N.push("Python runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");}catch{N.push("toolchain.lock is invalid JSON \u2014 regenerate it with `rapidkit bootstrap` before running commands in strict mode.");}let T=w.join(k,".rapidkit","workspace.json");if(await R__default.pathExists(T))try{let O=JSON.parse(await b$3.promises.readFile(T,"utf-8")).profile??"";O==="python-only"&&(b$6(u,process.cwd())||c$2(u,process.cwd())||d$3(u,process.cwd())||e$1(u,process.cwd()))&&N.push('Workspace profile is "python-only" but this project is not Python. Update the workspace profile or use a polyglot workspace.'),O==="node-only"&&(b$6(u,process.cwd())||f$2(u,process.cwd())||d$3(u,process.cwd())||e$1(u,process.cwd()))&&N.push('Workspace profile is "node-only" but this project is not Node. Update the workspace profile or use a polyglot workspace.'),O==="go-only"&&(f$2(u,process.cwd())||c$2(u,process.cwd())||d$3(u,process.cwd())||e$1(u,process.cwd()))&&N.push('Workspace profile is "go-only" but this project is not Go. Update the workspace profile or use a polyglot workspace.'),O==="java-only"&&(f$2(u,process.cwd())||c$2(u,process.cwd())||b$6(u,process.cwd())||e$1(u,process.cwd()))&&N.push('Workspace profile is "java-only" but this project is not Java. Update the workspace profile or use a polyglot workspace.'),O==="dotnet-only"&&(f$2(u,process.cwd())||c$2(u,process.cwd())||b$6(u,process.cwd())||d$3(u,process.cwd()))&&N.push('Workspace profile is "dotnet-only" but this project is not .NET. Update the workspace profile or use a polyglot workspace.');}catch{}if(N.length>0){console.log(s.red(`\u274C Strict policy violations block \`${f}\`:`));for(let je of N)console.log(s.red(` \u2022 ${je}`));console.log(s.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .rapidkit/policies.yml")),await ge(1);}}}catch{}}let v=await a$6({startPath:process.cwd(),action:f,writeReport:true}),y=P||process.env.RAPIDKIT_LIFECYCLE_ENFORCE_READINESS==="1"||process.env.RAPIDKIT_ENFORCE_READINESS==="1";if(v.blocking&&y){console.log(s.red(`\u274C Release readiness blocks \`${f}\`:`));for(let x of v.blockingReasons)console.log(s.red(` \u2022 ${x}`));v.evidencePath&&console.log(s.gray(`\u2139\uFE0F Readiness evidence: ${v.evidencePath}`)),await ge(1);}v.overallStatus!=="pass"&&!y&&(console.log(s.yellow(`\u26A0\uFE0F Release readiness is ${v.overallStatus}. Command continues in warn mode.`)),v.evidencePath&&console.log(s.gray(` Evidence: ${v.evidencePath} (set RAPIDKIT_LIFECYCLE_ENFORCE_READINESS=1 to block)`)));let C=await Hi(process.cwd(),async()=>{if(b$6(u,process.cwd())||h==="go"){let x=Ve("go",{runCommandInCwd:z,runCoreRapidkit:e});if(f==="lint")return Z(await x.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(f==="format")return Z(await x.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let I=f==="dev"?await x.runDev(process.cwd()):f==="test"?await x.runTest(process.cwd()):f==="build"?await x.runBuild(process.cwd()):await x.runStart(process.cwd());return I.message&&console.log(s.red(`\u274C ${I.message}`)),I.exitCode}if(d$3(u,process.cwd())||h==="java")return f==="dev"?await Be("dev",process.cwd()):f==="test"?await Be("test",process.cwd()):f==="build"?await Be("build",process.cwd()):f==="lint"?await Be("lint",process.cwd()):f==="format"?await Be("format",process.cwd()):await Be("start",process.cwd());if(e$1(u,process.cwd())||h==="dotnet"){let x=Ve("dotnet",{runCommandInCwd:z,runCoreRapidkit:e});if(f==="lint")return Z(await x.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(f==="format")return Z(await x.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let I=f==="dev"?await x.runDev(process.cwd()):f==="test"?await x.runTest(process.cwd()):f==="build"?await x.runBuild(process.cwd()):await x.runStart(process.cwd());return I.message&&console.log(s.red(`\u274C ${I.message}`)),I.exitCode}if(c$2(u,process.cwd())||h==="node")return f==="dev"?await ct("dev",process.cwd()):f==="test"?await ct("test",process.cwd()):f==="build"?await ct("build",process.cwd()):f==="lint"?await ct("lint",process.cwd()):f==="format"?await ct("format",process.cwd()):await ct("start",process.cwd());if(f$2(u,process.cwd())||h==="python"){if(f==="lint"||f==="format")return await e([f],{cwd:process.cwd()});let x=Ve("python",{runCommandInCwd:z,runCoreRapidkit:e});return Z(f==="dev"?await x.runDev(process.cwd()):f==="test"?await x.runTest(process.cwd()):f==="build"?await x.runBuild(process.cwd()):await x.runStart(process.cwd()))}return -1});if(!C.ok){await ge(C.code);return}if(C.ok&&C.value>=0){await ge(C.value);return}if(C.ok&&C.value===-1){console.error(s.red(`\u274C RapidKit cannot run \`${f}\` for this project runtime.`)),console.error(s.gray("Run `rapidkit project commands` to inspect supported commands.")),await ge(1);return}}if(p[0]==="add"||p[0]==="module"&&p[1]==="add"){let f=a$5(process.cwd());if(f?.module_support===false){let u=f?.runtime==="java"?"Spring Boot":f?.runtime==="dotnet"?"ASP.NET Core":"Go";console.error(s.red(`\u274C RapidKit modules are not available for ${u} npm-level kits.`)),console.error(s.gray(" The module system requires Python and is currently only supported for FastAPI and NestJS projects.")),await ge(1);}}if(Fr(p))return;let d=await Ml(p);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] shouldForwardToCore=${d}
|
|
396
|
+
`),d){let f=await e(p,{cwd:process.cwd()});await ge(f);}await ne.parseAsync();}});}export{Ki as COMMAND_CAPABILITIES_SCHEMA_VERSION,ll as NPM_ONLY_SCOPED_COMMANDS,Fi as NPM_ONLY_TOP_LEVEL_COMMANDS,gl as VERSION_CONTRACT_SCHEMA_VERSION,dl as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,kl as detectWindowsDoctorWorkspaceShadow,yl as getGlobalCommandCapabilities,_o as getPublishedContractVersions,hl as getVersionContract,Rl as handleAdoptCommand,Ei as handleBootstrapCommand,Ai as handleCacheCommand,Wi as handleCreateOrFallback,Sl as handleImportCommand,Kr as handleInitCommand,Ii as handleMirrorCommand,_i as handleSetupCommand,Jr as installWorkspaceDependencies,fl as isNpmExecInvocation,Ml as shouldForwardToCore};
|