workspai 0.59.1 → 0.60.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 +5 -0
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +4 -0
- package/contracts/workspace-intelligence/goal-agent-handoff.v1.json +89 -8
- package/contracts/workspace-intelligence/goal-index.v1.json +76 -7
- package/contracts/workspace-intelligence/goal-lifecycle-result.v1.json +49 -5
- package/contracts/workspace-intelligence/goal-pack.v1.json +182 -19
- package/contracts/workspace-intelligence/verified-goal.v1.json +44 -3
- package/dist/analyze-FYNMI5KT.js +1 -0
- package/dist/autopilot-release-O5PPB6HQ.js +1 -0
- package/dist/chunk-6YFCS2AI.js +1 -0
- package/dist/{chunk-QPE6VCDW.js → chunk-7COD67YY.js} +19 -19
- package/dist/{chunk-DGGTTRYE.js → chunk-7ITSLGPZ.js} +1 -1
- package/dist/{chunk-5NIZNXRS.js → chunk-A4BK7C7M.js} +1 -1
- package/dist/{chunk-Y4B55J5S.js → chunk-AHKXQRLX.js} +1 -1
- package/dist/{chunk-KVSYBHUR.js → chunk-B6FJ6RG6.js} +1 -1
- package/dist/{chunk-5PSKBJKJ.js → chunk-DIJGQUEV.js} +1 -1
- package/dist/{chunk-QMPFNXI7.js → chunk-E4LJ3PQD.js} +1 -1
- package/dist/{chunk-RVKMGKYL.js → chunk-FUCFNB3P.js} +1 -1
- package/dist/{chunk-6FBNSTUS.js → chunk-GPGEJVVO.js} +1 -1
- package/dist/chunk-ILIBOMYL.js +1 -0
- package/dist/chunk-J7G3YL4O.js +1 -0
- package/dist/{chunk-NOZ4JCH7.js → chunk-KCJ3VS6R.js} +1 -1
- package/dist/{chunk-SP5EHSWG.js → chunk-KG3TUTXU.js} +1 -1
- package/dist/{chunk-3CGR6435.js → chunk-KKAGBP4T.js} +1 -1
- package/dist/{chunk-P2WH7W2H.js → chunk-KPEVYWOC.js} +6 -6
- package/dist/{chunk-WSRUPDZN.js → chunk-NA2NXX5P.js} +1 -1
- package/dist/{chunk-OFWSZYUX.js → chunk-NBJ6AP7K.js} +1 -1
- package/dist/{chunk-7WUT5ZSO.js → chunk-NVQUBUTY.js} +1 -1
- package/dist/{chunk-YEEAWZWI.js → chunk-O6R7SE6Y.js} +1 -1
- package/dist/{chunk-7SFXADXO.js → chunk-OU7DF6MP.js} +1 -1
- package/dist/{chunk-WJVB6SSD.js → chunk-PTNLVI62.js} +5 -5
- package/dist/{chunk-U3MGJN7A.js → chunk-PZLHQEGC.js} +1 -1
- package/dist/{chunk-WP3CXMVA.js → chunk-SCP5LJNO.js} +1 -1
- package/dist/{chunk-QFBVQUKV.js → chunk-TFOOSYGO.js} +6 -6
- package/dist/chunk-UJXE4UAX.js +1 -0
- package/dist/{chunk-ENKGGWRX.js → chunk-VDFHUYAQ.js} +8 -8
- package/dist/chunk-VR6XMUF3.js +2 -0
- package/dist/{chunk-FLTIFYTJ.js → chunk-WJ7MZB3I.js} +1 -1
- package/dist/{chunk-ZJCM37KX.js → chunk-WLFJHRB3.js} +1 -1
- package/dist/chunk-X6TNBARH.js +6 -0
- package/dist/{chunk-RTDEFUTL.js → chunk-XXQRHS5I.js} +1 -1
- package/dist/chunk-XZ55OA4C.js +2 -0
- package/dist/{create-HUEDWYDM.js → create-IRNHMUEN.js} +1 -1
- package/dist/demo-kit-QHIDCSBI.js +149 -0
- package/dist/{doctor-NAZEKMGU.js → doctor-MAPZ2ZCD.js} +1 -1
- package/dist/{dotnet-webapi-clean-VXEF4SHM.js → dotnet-webapi-clean-AVHPJG7Y.js} +5 -5
- package/dist/goal-command-contract-43E22XQD.js +1 -0
- package/dist/goal-interactive-selection-6YJOK4WC.js +1 -0
- package/dist/goal-lifecycle-VQDUWZVG.js +1 -0
- package/dist/goal-pack-U3ZP7A2A.js +1 -0
- package/dist/{gofiber-standard-AQGSC7ON.js → gofiber-standard-47S2GYAO.js} +2 -2
- package/dist/{gogin-standard-7DU3OCBX.js → gogin-standard-EWB4XNOI.js} +3 -3
- package/dist/index.js +122 -122
- package/dist/{pipeline-62A2SDLC.js → pipeline-5O36G4ZV.js} +1 -1
- package/dist/{project-agent-entry-7SYHRY7J.js → project-agent-entry-CN4K6JNZ.js} +1 -1
- package/dist/{project-intelligence-lens-BSG5LK6N.js → project-intelligence-lens-N7REBQ3A.js} +1 -1
- package/dist/{project-test-coverage-HP37HUV2.js → project-test-coverage-E2Q4QL44.js} +1 -1
- package/dist/{rust-axum-4HXDICIB.js → rust-axum-M5X4ZC4Z.js} +4 -4
- package/dist/{springboot-standard-EK6GYN5T.js → springboot-standard-Y5ADLZMQ.js} +7 -7
- package/dist/verified-goal-CIYKNDOU.js +1 -0
- package/dist/{workspace-BNRSBWSL.js → workspace-UUU4VMZB.js} +1 -1
- package/dist/{workspace-agent-sync-ANBHBZ2H.js → workspace-agent-sync-LQNIMGLN.js} +1 -1
- package/dist/{workspace-context-RAO62QVU.js → workspace-context-YAK5XX27.js} +1 -1
- package/dist/{workspace-contract-ACSIHJIO.js → workspace-contract-3BWIRSVQ.js} +1 -1
- package/dist/{workspace-explain-RH27OQB4.js → workspace-explain-QH4FXQW5.js} +1 -1
- package/dist/{workspace-foundation-EWYJPPT6.js → workspace-foundation-AISQHJA3.js} +1 -1
- package/dist/{workspace-graph-stream-ZZZEQQTE.js → workspace-graph-stream-XTSDKRLM.js} +1 -1
- package/dist/{workspace-intelligence-3YERTBA3.js → workspace-intelligence-625UN27X.js} +1 -1
- package/dist/{workspace-intelligence-runner-QLLBUD6G.js → workspace-intelligence-runner-7KCGHRID.js} +1 -1
- package/dist/{workspace-knowledge-graph-HZZP6ZRB.js → workspace-knowledge-graph-3ZBPSAS7.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-ZI4W735H.js +1 -0
- package/dist/{workspace-mcp-serve-5TTAN243.js → workspace-mcp-serve-ALIZV72K.js} +1 -1
- package/dist/{workspace-model-EIQSKDX7.js → workspace-model-ETCLINRB.js} +1 -1
- package/dist/{workspace-onboarding-UW3CSURE.js → workspace-onboarding-XNBC6H2G.js} +1 -1
- package/dist/{workspace-registry-summary-OV5KX3WC.js → workspace-registry-summary-VSOBKAJG.js} +1 -1
- package/dist/workspace-repair-engine-7WGJWUBN.js +3 -0
- package/dist/workspace-run-I6E6VI6N.js +1 -0
- package/dist/{workspace-verify-W4P6LBIH.js → workspace-verify-7ENGIY4S.js} +1 -1
- package/dist/{workspace-watch-EZ4D4VCF.js → workspace-watch-2YFSB2WL.js} +1 -1
- package/docs/ci-workflows.md +1 -1
- package/docs/commands-reference.md +12 -2
- package/docs/goal-packs.md +41 -5
- package/package.json +1 -1
- package/dist/analyze-52TEGLDR.js +0 -1
- package/dist/autopilot-release-NFLAKBA3.js +0 -1
- package/dist/chunk-DQ6VXTDE.js +0 -1
- package/dist/chunk-MZKKRAAJ.js +0 -2
- package/dist/chunk-RO73VVHW.js +0 -2
- package/dist/chunk-T3GJ7YVG.js +0 -1
- package/dist/chunk-VRW6KXNK.js +0 -6
- package/dist/demo-kit-KHH63TNA.js +0 -149
- package/dist/goal-command-contract-CHE7U6YY.js +0 -1
- package/dist/goal-lifecycle-NUKWVUAL.js +0 -1
- package/dist/goal-pack-TWOXHXN6.js +0 -1
- package/dist/verified-goal-B6HQOZWA.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-7DWHMEM2.js +0 -1
- package/dist/workspace-repair-engine-DHH2UUJN.js +0 -3
- package/dist/workspace-run-BLHRXT2N.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {c as c$
|
|
2
|
+
import {c as c$8,b as b$f,a as a$p}from'./chunk-QCKWQFCD.js';import {a as a$l}from'./chunk-ICGWHIMK.js';import {a as a$s}from'./chunk-FB7SCXAZ.js';import {b,c,d,j as j$1,h as h$2,i,a as a$F}from'./chunk-NVQUBUTY.js';import {a as a$h}from'./chunk-AHKXQRLX.js';import {a as a$q}from'./chunk-5SFCBZOH.js';import {d as d$3,c as c$3,p as p$2,b as b$j,a as a$D}from'./chunk-KTN2ARZJ.js';import {a as a$j,f as f$5,d as d$9,i as i$5}from'./chunk-S4CWUZ4K.js';import {c as c$1,b as b$6,a as a$E}from'./chunk-LPCWROQ3.js';import {b as b$4,a as a$7}from'./chunk-GPGEJVVO.js';import {c as c$5,d as d$5,e as e$5,b as b$d,g as g$3}from'./chunk-KPEVYWOC.js';import {b as b$e,a as a$n,c as c$7}from'./chunk-XXQRHS5I.js';import {b as b$8,a as a$a}from'./chunk-THIOE2PB.js';import {f as f$3}from'./chunk-WJ7MZB3I.js';import {b as b$b,g as g$2,c as c$c,a as a$C}from'./chunk-XZ55OA4C.js';import {g as g$6,e as e$8,c as c$a,b as b$h,a as a$y}from'./chunk-6YFCS2AI.js';import {a as a$i,e as e$9,d as d$a}from'./chunk-J3X56S7L.js';import {a,b as b$1}from'./chunk-B6FJ6RG6.js';import {a as a$r}from'./chunk-4PUJVYRM.js';import {b as b$7,d as d$6,a as a$6,c as c$6,f as f$8,e as e$a}from'./chunk-ILIBOMYL.js';import {b as b$5,a as a$2,d as d$2}from'./chunk-GPOZILMY.js';import {a as a$m}from'./chunk-PXWKMPPI.js';import {e as e$3,d as d$4}from'./chunk-KBR4Y4RW.js';import {a as a$u}from'./chunk-OU7DF6MP.js';import {a as a$x}from'./chunk-WQX3JYEP.js';import {c as c$9,a as a$v}from'./chunk-O6R7SE6Y.js';import {a as a$B,b as b$i}from'./chunk-HCFWT42C.js';import {a as a$A}from'./chunk-NS53IPAC.js';import {f as f$6}from'./chunk-NBJ6AP7K.js';import {a as a$k}from'./chunk-PVXSIYLP.js';import {a as a$o}from'./chunk-N4QQADXX.js';import {a as a$c}from'./chunk-KCJ3VS6R.js';import {a as a$9}from'./chunk-A5FBGRJA.js';import {a as a$t}from'./chunk-TFOOSYGO.js';import {b as b$a,a as a$e,j as j$5,g as g$5,e as e$7,c as c$d,d as d$b}from'./chunk-NA2NXX5P.js';import {h as h$1,a as a$1,l as l$1,k as k$2,m as m$2,q as q$1,j as j$6,p as p$4,n as n$1,s as s$3,r as r$2}from'./chunk-PTNLVI62.js';import {a as a$g}from'./chunk-27UR373Z.js';import {d as d$8,b as b$g,i as i$7}from'./chunk-KG3TUTXU.js';import {b as b$2,d as d$1,a as a$3,e as e$4,w,i as i$2,p as p$3,j as j$3,l,m as m$1,n,k as k$1,s as s$2,o as o$2,y,q as q$2,h as h$5,r as r$1,x,z,t as t$1,v as v$1,f as f$7,u as u$1}from'./chunk-SCP5LJNO.js';export{r as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-SCP5LJNO.js';import {c as c$4,b as b$c,a as a$H}from'./chunk-T5YRFRJV.js';import {j as j$4,i as i$4}from'./chunk-ZCPT6KC3.js';import {a as a$f}from'./chunk-GR6442P7.js';import {d as d$7,a as a$b,b as b$9}from'./chunk-CCDGHPEJ.js';import {b as b$l}from'./chunk-D65FCQIO.js';import {a as a$4}from'./chunk-AFIFZTOY.js';import {k,i as i$1,e as e$2,f as f$2,h as h$3,g as g$4,c as c$b,a as a$z,l as l$2}from'./chunk-NZ3WZYD5.js';import {h,e,g,c as c$2,a as a$8,f as f$4}from'./chunk-X6TNBARH.js';import {a as a$d}from'./chunk-TQEMLBAG.js';import {a as a$w}from'./chunk-VR6XMUF3.js';import {f,e as e$1,a as a$5,d as d$c,i as i$6,g as g$7}from'./chunk-W3HXTCSY.js';import {m,f as f$1,t,o as o$1,v,p,j as j$2,s as s$1,u,i as i$3,g as g$1,h as h$4,e as e$6,a as a$G,b as b$k,k as k$3,n as n$2}from'./chunk-MOSXTVPU.js';import {o,b as b$3,p as p$1,q,r,m as m$3,i as i$8,j as j$7,e as e$b,g as g$8,c as c$e}from'./chunk-RJIYCDVC.js';import {c as c$f}from'./chunk-2FIX2MDC.js';import {Command,Option}from'commander';import s from'chalk';import j from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Zu from'vm';import*as O from'fs-extra';import O__default from'fs-extra';import _,{existsSync,promises,createWriteStream}from'fs';import Tn,{tmpdir,homedir}from'os';import {execa}from'execa';import Pt,{randomUUID,createVerify,createHash,createHmac}from'crypto';import bl from'http';import Cl from'https';function yp(){return j$7()}function wp(t,e){return t==="py"?["-3",...e]:e}function kp(t){return typeof t=="object"&&t!==null}async function vp(t,e,r,o=c$f()){try{let n=await execa(t,e,{cwd:r,timeout:o,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 Pp(t,e){let r=["-m","rapidkit",...t],o=yp();for(let n of o){let a=await vp(n,wp(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return kp(c)?{ok:true,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr,data:c}:{ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}catch{return {ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}}return {ok:false}}async function Gi(t,e){let r=await Pp(["project","detect","--path",t,"--json"],e);return !r.ok||!r.data||r.data.schema_version!==1?{ok:false,command:r.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:r}var Ji=new Set(["create"]),_n=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),jp=new Set(["pip","poetry","venv","pipx","python"]);function Vi(t){return typeof t=="string"&&jp.has(t)}function In(t,e){return !t||Ji.has(t)?false:a$5.has(t)?true:e?.has(t)??false}function On(t,e=null){let r=t[0];return !r||r.startsWith("-")||Ji.has(r)||r==="init"?false:In(r,e)?true:t.filter(n=>!n.startsWith("-")&&!_n.has(n)).length<=1?false:t.length>1}var Ht=j.join(Tn.homedir(),".workspairc.json"),bp=j.join(Tn.homedir(),".rapidkitrc.json"),Cp=j.join(Tn.homedir(),".rapidkit","config.json");function $n(t){try{if(!_.existsSync(t))return {};let e=_.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Ki(t){if(process.platform!=="win32")try{_.chmodSync(t,384);}catch{}}function Bt(){let t=$n(Ht),e=$n(bp),r=$n(Cp);return _.existsSync(Ht)&&Ki(Ht),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function ho(t){let r={...Bt(),...t};_.writeFileSync(Ht,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Ki(Ht);}function jr(){return process.env.OPENAI_API_KEY||Bt().openaiApiKey||null}function Mn(){return Bt().aiEnabled!==false}function Wn(){return Ht}function Ui(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async r=>{let o=r.key;o?o.startsWith("sk-")||(console.log(s.red(`
|
|
3
3
|
\u274C Invalid API key format (should start with sk-)
|
|
4
4
|
`)),process.exit(1)):o=(await b$1([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:a=>a?a.startsWith("sk-")?a.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,ho({openaiApiKey:o}),console.log(s.green(`
|
|
5
5
|
\u2705 OpenAI API key saved successfully!
|
|
@@ -20,7 +20,7 @@ Cancelled
|
|
|
20
20
|
\u274C Invalid action: ${r}`)),console.log(s.gray(`Use: workspai config ai enable|disable
|
|
21
21
|
`)),process.exit(1));let o=r==="enable";ho({aiEnabled:o}),console.log(s.green(`
|
|
22
22
|
\u2705 AI features ${o?"enabled":"disabled"}
|
|
23
|
-
`));});}var br=null,yo=false,Dn=null;async function Sp(){return Dn||(Dn=(await import('openai')).default),Dn}function Hi(){yo=true;}function Bi(t){let r=new Array(1536),o=0;for(let a=0;a<t.length;a++)o=(o<<5)-o+t.charCodeAt(a),o=o&o;for(let a=0;a<1536;a++)o=o*1664525+1013904223&4294967295,r[a]=o/4294967295*2-1;let n=Math.sqrt(r.reduce((a,i)=>a+i*i,0));return r.map(a=>a/n)}async function wo(t){if(!t.trim()){br=null;return}let e=await Sp();br=new e({apiKey:t});}function qi(){if(!br)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return br}async function Ln(t){return yo?Bi(t):(await qi().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function zi(t){return yo?t.map(Bi):(await qi().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(o=>o.embedding)}function Yi(){return br!==null}function qt(){return yo}function Fn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function xp(t){return !t||typeof t!="object"?{}:t}var Jn=[{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"]}],kt=null,Gn=0,Ep=300*1e3;function Rp(t){let e=xp(t),r=e.slug||e.name||e.id||e.module_id||"",o=Fn(e.keywords??e.tags);return {id:r,name:e.display_name||e.name||"",category:Ap(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:o.map(n=>n.toLowerCase()),framework:_p(e.framework),dependencies:Fn(e.dependencies),useCases:Fn(e.use_cases??e.useCases)}}function Ap(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function _p(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 Ip(){try{let t=await g$7(["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.trim(),r;try{r=JSON.parse(e);}catch{let n=e.indexOf("{"),a=e.indexOf("["),i=[n,a].filter(f=>f>=0);if(i.length===0)throw new Error("Python Core modules response did not contain JSON");let c=Math.min(...i),p=e[c]==="["?"]":"}",d=e.lastIndexOf(p);if(d<c)throw new Error("Python Core modules response contained incomplete JSON");r=JSON.parse(e.slice(c,d+1));}let o=[];if(Array.isArray(r))o=r;else if(r&&typeof r=="object"){let n=r;Array.isArray(n.modules)?o=n.modules:Array.isArray(n.data)&&(o=n.data);}return o.map(Rp).filter(n=>n.id&&n.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)"),Jn}}async function ko(){let t=Date.now();return qt()?(kt=Jn,Gn=t,kt):(kt&&t-Gn<Ep||(kt=await Ip(),Gn=t,kt.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),kt=Jn)),kt)}var $p=fileURLToPath(import.meta.url),Qi=j.dirname($p),zt=null,Zi=new Map;function Np(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function Tp(t){let e=Zi.get(t.id);if(e)return e;let r=await Ln(Np(t));return Zi.set(t.id,r),r}function Mp(){if(zt)return zt;let t=[j.join(Qi,"../../data/modules-embeddings.json"),j.join(Qi,"../data/modules-embeddings.json"),j.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(_.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let r=_.readFileSync(e,"utf-8"),o=JSON.parse(r);if(Array.isArray(o)?zt={model:"mock-or-text-embedding-3-small",dimension:o[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:o}:zt=o,!zt)throw new Error("failed to load embeddings data");return zt}function ec(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let r=0,o=0,n=0;for(let i=0;i<t.length;i++)r+=t[i]*e[i],o+=t[i]*t[i],n+=e[i]*e[i];let a=Math.sqrt(o)*Math.sqrt(n);return a===0?0:r/a}function tc(t,e){let r=e.toLowerCase(),o=t.keywords.filter(n=>r.includes(n)||n.includes(r));return o.length>0?`Matches: ${o.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function rc(t,e=5){let r=await ko(),o=await Ln(t);if(qt()){let i=await Promise.all(r.map(async c=>{let p=await Tp(c);return {module:c,score:ec(o,p),reason:tc(c,t)}}));return i.sort((c,p)=>p.score-c.score),i.slice(0,e)}let a=Mp().modules.map(i=>{let c=r.find(d=>d.id===i.id);if(!c)return null;let p=ec(o,i.embedding);return {module:c,score:p,reason:tc(c,t)}}).filter(i=>i!==null);return a.sort((i,c)=>c.score-i.score),a.slice(0,e)}var Dp=fileURLToPath(import.meta.url),oc=j.dirname(Dp);function nc(t){return t instanceof Error?t.message:String(t)}function Lp(){return [j.join(oc,"../../data/modules-embeddings.json"),j.join(oc,"../data/modules-embeddings.json"),j.join(process.cwd(),"data/modules-embeddings.json")]}function sc(){let t=Lp();for(let e of t)if(_.existsSync(e))try{let r=JSON.parse(_.readFileSync(e,"utf-8")),o=Array.isArray(r)?r:r.modules||[];return {exists:true,path:e,moduleCount:o.length,generatedAt:r.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function Po(t=true,e){try{if(!Yi()&&!qt())return console.log(s.red(`
|
|
23
|
+
`));});}var br=null,yo=false,Dn=null;async function Sp(){return Dn||(Dn=(await import('openai')).default),Dn}function Hi(){yo=true;}function Bi(t){let r=new Array(1536),o=0;for(let a=0;a<t.length;a++)o=(o<<5)-o+t.charCodeAt(a),o=o&o;for(let a=0;a<1536;a++)o=o*1664525+1013904223&4294967295,r[a]=o/4294967295*2-1;let n=Math.sqrt(r.reduce((a,i)=>a+i*i,0));return r.map(a=>a/n)}async function wo(t){if(!t.trim()){br=null;return}let e=await Sp();br=new e({apiKey:t});}function qi(){if(!br)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return br}async function Ln(t){return yo?Bi(t):(await qi().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function zi(t){return yo?t.map(Bi):(await qi().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(o=>o.embedding)}function Yi(){return br!==null}function qt(){return yo}function Fn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function xp(t){return !t||typeof t!="object"?{}:t}var Jn=[{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"]}],kt=null,Gn=0,Ep=300*1e3;function Rp(t){let e=xp(t),r=e.slug||e.name||e.id||e.module_id||"",o=Fn(e.keywords??e.tags);return {id:r,name:e.display_name||e.name||"",category:Ap(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:o.map(n=>n.toLowerCase()),framework:_p(e.framework),dependencies:Fn(e.dependencies),useCases:Fn(e.use_cases??e.useCases)}}function Ap(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function _p(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 Ip(){try{let t=await g$7(["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.trim(),r;try{r=JSON.parse(e);}catch{let n=e.indexOf("{"),a=e.indexOf("["),i=[n,a].filter(f=>f>=0);if(i.length===0)throw new Error("Python Core modules response did not contain JSON");let c=Math.min(...i),d=e[c]==="["?"]":"}",l=e.lastIndexOf(d);if(l<c)throw new Error("Python Core modules response contained incomplete JSON");r=JSON.parse(e.slice(c,l+1));}let o=[];if(Array.isArray(r))o=r;else if(r&&typeof r=="object"){let n=r;Array.isArray(n.modules)?o=n.modules:Array.isArray(n.data)&&(o=n.data);}return o.map(Rp).filter(n=>n.id&&n.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)"),Jn}}async function ko(){let t=Date.now();return qt()?(kt=Jn,Gn=t,kt):(kt&&t-Gn<Ep||(kt=await Ip(),Gn=t,kt.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),kt=Jn)),kt)}var $p=fileURLToPath(import.meta.url),Qi=j.dirname($p),zt=null,Zi=new Map;function Np(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function Tp(t){let e=Zi.get(t.id);if(e)return e;let r=await Ln(Np(t));return Zi.set(t.id,r),r}function Mp(){if(zt)return zt;let t=[j.join(Qi,"../../data/modules-embeddings.json"),j.join(Qi,"../data/modules-embeddings.json"),j.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(_.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let r=_.readFileSync(e,"utf-8"),o=JSON.parse(r);if(Array.isArray(o)?zt={model:"mock-or-text-embedding-3-small",dimension:o[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:o}:zt=o,!zt)throw new Error("failed to load embeddings data");return zt}function ec(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let r=0,o=0,n=0;for(let i=0;i<t.length;i++)r+=t[i]*e[i],o+=t[i]*t[i],n+=e[i]*e[i];let a=Math.sqrt(o)*Math.sqrt(n);return a===0?0:r/a}function tc(t,e){let r=e.toLowerCase(),o=t.keywords.filter(n=>r.includes(n)||n.includes(r));return o.length>0?`Matches: ${o.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function rc(t,e=5){let r=await ko(),o=await Ln(t);if(qt()){let i=await Promise.all(r.map(async c=>{let d=await Tp(c);return {module:c,score:ec(o,d),reason:tc(c,t)}}));return i.sort((c,d)=>d.score-c.score),i.slice(0,e)}let a=Mp().modules.map(i=>{let c=r.find(l=>l.id===i.id);if(!c)return null;let d=ec(o,i.embedding);return {module:c,score:d,reason:tc(c,t)}}).filter(i=>i!==null);return a.sort((i,c)=>c.score-i.score),a.slice(0,e)}var Dp=fileURLToPath(import.meta.url),oc=j.dirname(Dp);function nc(t){return t instanceof Error?t.message:String(t)}function Lp(){return [j.join(oc,"../../data/modules-embeddings.json"),j.join(oc,"../data/modules-embeddings.json"),j.join(process.cwd(),"data/modules-embeddings.json")]}function sc(){let t=Lp();for(let e of t)if(_.existsSync(e))try{let r=JSON.parse(_.readFileSync(e,"utf-8")),o=Array.isArray(r)?r:r.modules||[];return {exists:true,path:e,moduleCount:o.length,generatedAt:r.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function Po(t=true,e){try{if(!Yi()&&!qt())return console.log(s.red(`
|
|
24
24
|
\u274C OpenAI not initialized`)),console.log(s.yellow("Please set your API key:")),console.log(s.white(" workspai 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 Workspai modules...
|
|
@@ -28,8 +28,8 @@ Cancelled
|
|
|
28
28
|
`));let o=r.length*50/1e6*.02;if(console.log(s.cyan(`\u{1F4B0} Estimated cost: ~$${o.toFixed(3)}`)),console.log(s.gray(` (Based on ${r.length} modules at $0.02/1M tokens)
|
|
29
29
|
`)),t){let{confirm:i}=await b$1([{type:"confirm",name:"confirm",message:"Generate embeddings now?",default:true}]);if(!i)return console.log(s.yellow(`
|
|
30
30
|
\u26A0\uFE0F Embeddings generation cancelled
|
|
31
|
-
`)),false}let n=r.map(i=>`${i.name}. ${i.description}. ${i.longDescription}. Keywords: ${i.keywords.join(", ")}. Use cases: ${i.useCases.join(", ")}.`),a=
|
|
32
|
-
\u2705 Embeddings generated successfully!`)),console.log(s.gray(`\u{1F4C1} Saved to: ${
|
|
31
|
+
`)),false}let n=r.map(i=>`${i.name}. ${i.description}. ${i.longDescription}. Keywords: ${i.keywords.join(", ")}. Use cases: ${i.useCases.join(", ")}.`),a=a$8(`Generating embeddings for ${r.length} modules...`,{component:"ai",phase:"embeddings.generate"});try{let i=await zi(n);a.succeed(`Generated embeddings for ${r.length} modules`);let c={model:"text-embedding-3-small",dimension:i[0].length,generated_at:new Date().toISOString(),modules:r.map((f,u)=>({id:f.id,name:f.name,embedding:i[u]}))},d=e||j.join(process.cwd(),"data","modules-embeddings.json"),l=j.dirname(d);return _.existsSync(l)||_.mkdirSync(l,{recursive:true}),_.writeFileSync(d,JSON.stringify(c,null,2)),console.log(s.green(`
|
|
32
|
+
\u2705 Embeddings generated successfully!`)),console.log(s.gray(`\u{1F4C1} Saved to: ${d}`)),console.log(s.gray(`\u{1F4CA} Size: ${r.length} modules, ${i[0].length} dimensions
|
|
33
33
|
`)),true}catch(i){a.fail("Failed to generate embeddings");let c=nc(i);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(`
|
|
@@ -50,7 +50,7 @@ Cancelled
|
|
|
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 Po(true,t.path):false):(console.log(s.yellow(`
|
|
52
52
|
\u26A0\uFE0F No existing embeddings found`)),console.log(s.gray(`Use: workspai ai generate-embeddings
|
|
53
|
-
`)),false)}function Vn(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 cc(t,e=0){console.log(JSON.stringify(t,null,2)),e!==0&&process.exit(e);}function lc(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(r,o)=>{try{Mn()||(o.json&&cc({ok:false,error:{code:"AI_DISABLED",message:"AI features are disabled",remediation:"workspai config ai enable"}},1),console.log(s.yellow(`
|
|
53
|
+
`)),false)}function Vn(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 cc(t,e=0){console.log(JSON.stringify(t,null,2)),e!==0&&process.exit(e);}function lc(t){let e$1=t.command("ai").description("AI-powered features");e$1.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(r,o)=>{try{Mn()||(o.json&&cc({ok:false,error:{code:"AI_DISABLED",message:"AI features are disabled",remediation:"workspai config ai enable"}},1),console.log(s.yellow(`
|
|
54
54
|
\u26A0\uFE0F AI features are disabled`)),console.log(s.gray(`Enable with: workspai config ai enable
|
|
55
55
|
`)),process.exit(1));let n=jr();n?await wo(n):(o.json||(console.log(s.yellow(`
|
|
56
56
|
\u26A0\uFE0F OpenAI API key not configured - using MOCK MODE for testing
|
|
@@ -60,31 +60,31 @@ Cancelled
|
|
|
60
60
|
\u{1F916} Analyzing your request...
|
|
61
61
|
`)),!n||await ac(!o.json)||(o.json&&cc({ok:false,query:a,error:{code:"EMBEDDINGS_MISSING",message:"Module embeddings are not available",remediation:"workspai ai generate-embeddings"}},1),console.log(s.yellow(`
|
|
62
62
|
\u26A0\uFE0F Cannot proceed without embeddings
|
|
63
|
-
`)),process.exit(1));let c=parseInt(o.number,10),
|
|
63
|
+
`)),process.exit(1));let c=parseInt(o.number,10),d=await rc(a,c);if(d.length===0||d[0].score<.3)if(console.log(s.yellow(`
|
|
64
64
|
\u26A0\uFE0F No matching modules found in RapidKit Core registry.
|
|
65
65
|
`)),console.log(s.cyan(`\u{1F4A1} Options:
|
|
66
66
|
`)),console.log(s.white("1. Create custom module:")),console.log(s.gray(" npx workspai modules scaffold <name> --category <category>")),console.log(s.gray(` Example: npx workspai modules scaffold blockchain-integration --category integrations
|
|
67
67
|
`)),console.log(s.white("2. Search with different keywords")),console.log(s.gray(` Try more general terms (e.g., "storage" instead of "blockchain")
|
|
68
68
|
`)),console.log(s.white("3. Request feature:")),console.log(s.gray(` https://github.com/chistiq/workspai/issues
|
|
69
|
-
`)),
|
|
70
|
-
`));else return;if(o.json){console.log(JSON.stringify({query:a,recommendations:
|
|
71
|
-
`)),
|
|
72
|
-
`));let{shouldInstall:f}=await b$1([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(f){let{selectedModules:
|
|
69
|
+
`)),d.length>0)console.log(s.yellow(`\u26A0\uFE0F Low confidence matches found:
|
|
70
|
+
`));else return;if(o.json){console.log(JSON.stringify({query:a,recommendations:d},null,2));return}console.log(s.green.bold(`\u{1F4E6} Recommended Modules:
|
|
71
|
+
`)),d.forEach((u,w)=>{let y=(u.score*100).toFixed(1),P=u.score>.8?" \u2B50":"";console.log(s.bold(`${w+1}. ${u.module.name}${P}`)),console.log(s.gray(` ${u.module.description}`)),console.log(s.cyan(` Match: ${y}%`)+s.gray(` - ${u.reason}`)),console.log(s.yellow(` Category: ${u.module.category}`)),u.module.dependencies.length>0&&console.log(s.magenta(` Requires: ${u.module.dependencies.join(", ")}`)),console.log();});let l=d.slice(0,3).map(u=>u.module.id);console.log(s.cyan("\u{1F4A1} Quick install (top 3):")),console.log(s.white(` npx workspai add module ${l.join(" ")}
|
|
72
|
+
`));let{shouldInstall:f$1}=await b$1([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(f$1){let{selectedModules:u}=await b$1([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:d.map(y=>({name:`${y.module.name} - ${y.module.description}`,value:y.module.id,checked:y.score>.7}))}]),w$1=u;if(w$1.length>0){console.log(s.blue(`
|
|
73
73
|
\u{1F4E6} Installing ${w$1.length} modules...
|
|
74
74
|
`)),console.log(s.gray(`Command: npx workspai add module ${w$1.join(" ")}`));let P=w(process.cwd()).commandMap.add;if(!P||P.status!=="supported"){console.log(s.red(`
|
|
75
75
|
\u274C RapidKit Core modules are not available for this project.`)),console.log(s.gray(` ${P?.reason??"Module commands require RapidKit Core module-enabled project metadata."}
|
|
76
|
-
`));return}let S=await f
|
|
76
|
+
`));return}let S=await f(["add","module",...w$1],{cwd:process.cwd()});console.log(S===0?s.green(`
|
|
77
77
|
\u2705 Selected modules installed successfully
|
|
78
78
|
`):s.red(`
|
|
79
79
|
\u274C Module installation failed (exit code: ${S})
|
|
80
80
|
`));}else console.log(s.gray(`
|
|
81
81
|
No modules selected
|
|
82
|
-
`));}}catch(n){let a=Vn(n);
|
|
82
|
+
`));}}catch(n){let a=Vn(n);e.error(`
|
|
83
83
|
\u274C Error:`,a.message),a.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: workspai config set-api-key
|
|
85
85
|
`))):a.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 packages/cli")),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 r=jr(),o=Mn();console.log(s.bold(`
|
|
87
|
+
`))),process.exit(1);}}),e$1.command("info").description("Show AI features information").action(()=>{let r=jr(),o=Mn();console.log(s.bold(`
|
|
88
88
|
\u{1F916} Workspai AI Features
|
|
89
89
|
`)),console.log(s.cyan("Status:"),o?s.green("Enabled"):s.red("Disabled")),console.log(s.cyan("API Key:"),r?s.green("Configured \u2713"):s.red("Not configured \u2717")),console.log(s.bold(`
|
|
90
90
|
\u{1F4E6} Available Features:
|
|
@@ -92,16 +92,16 @@ No modules selected
|
|
|
92
92
|
\u{1F4B0} Pricing:
|
|
93
93
|
`)),console.log(s.white("\u2022 Per query: ~$0.0002")+s.gray(" (practically free)")),console.log(s.white("\u2022 100 queries: ~$0.02")+s.gray(" (2 cents)")),console.log(s.white("\u2022 1000 queries: ~$0.20")+s.gray(" (20 cents)")),console.log(s.bold(`
|
|
94
94
|
\u{1F680} Getting Started:
|
|
95
|
-
`)),r?(console.log(s.green("\u2713 You're all set!")),console.log(s.white(' Try: workspai ai recommend "user authentication"'))):(console.log(s.white("1. Get OpenAI API key: https://platform.openai.com/api-keys")),console.log(s.white("2. Configure: workspai config set-api-key")),console.log(s.white('3. Try: workspai ai recommend "user authentication"'))),console.log();}),e.command("generate-embeddings").description("Generate AI embeddings for all modules (one-time setup)").option("--force","Force regeneration even if embeddings exist").action(async()=>{try{let r=jr();r||(console.log(s.red(`
|
|
95
|
+
`)),r?(console.log(s.green("\u2713 You're all set!")),console.log(s.white(' Try: workspai ai recommend "user authentication"'))):(console.log(s.white("1. Get OpenAI API key: https://platform.openai.com/api-keys")),console.log(s.white("2. Configure: workspai config set-api-key")),console.log(s.white('3. Try: workspai ai recommend "user authentication"'))),console.log();}),e$1.command("generate-embeddings").description("Generate AI embeddings for all modules (one-time setup)").option("--force","Force regeneration even if embeddings exist").action(async()=>{try{let r=jr();r||(console.log(s.red(`
|
|
96
96
|
\u274C OpenAI API key not configured
|
|
97
97
|
`)),console.log(s.cyan(`To generate embeddings, you need an OpenAI API key:
|
|
98
98
|
`)),console.log(s.white("1. Get your key from: https://platform.openai.com/api-keys")),console.log(s.white("2. Configure it: workspai 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)),wo(r);let o=await Po(true);o&&(console.log(s.green("\u2705 Ready to use AI recommendations!")),console.log(s.cyan(`Try: workspai ai recommend "authentication"
|
|
101
|
-
`))),process.exit(o?0:1);}catch(r){let o=Vn(r);
|
|
101
|
+
`))),process.exit(o?0:1);}catch(r){let o=Vn(r);e.error("Failed to generate embeddings:",o.message),process.exit(1);}}),e$1.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let r=jr();r||(console.log(s.red(`
|
|
102
102
|
\u274C OpenAI API key not configured
|
|
103
103
|
`)),console.log(s.white(`Set your API key: workspai config set-api-key
|
|
104
|
-
`)),process.exit(1)),wo(r);let o=await ic();process.exit(o?0:1);}catch(r){let o=Vn(r);
|
|
104
|
+
`)),process.exit(1)),wo(r);let o=await ic();process.exit(o?0:1);}catch(r){let o=Vn(r);e.error("Failed to update embeddings:",o.message),process.exit(1);}});}var Gp="rapidkit.product-factory-plan.v1",Jp="rapidkit.private-product-manifest.v1";function pc(t){let e=process.argv;for(let r=0;r<e.length;r+=1){let o=e[r];if(o===t){let n=e[r+1];return n&&!n.startsWith("-")?n:void 0}if(o.startsWith(`${t}=`))return o.slice(t.length+1)}}function Sr(t,e=""){return typeof t=="string"&&t.trim()?t.trim():e}function Kn(t){return typeof t=="string"&&t.trim()?t.trim():null}function Vp(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function dc(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function mc(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 Kp(t,e,r){let o=Sr(t.slug);if(!o)throw new Error(`Backlog product at index ${e} is missing slug.`);mc(o);let n=dc(t.modules),a=dc(t.moduleGaps);return {rank:Vp(t.rank,e+1),slug:o,title:Sr(t.title,o),category:Sr(t.category,"Uncategorized"),tier:Sr(t.tier,"pro"),summary:Sr(t.summary),modules:n,moduleGaps:a,recommendedKit:r,workspaceProfile:"enterprise",readiness:{status:a.length>0?"blocked-by-module-gaps":"ready-for-private-manifest",blockingGaps:a}}}function Up(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Backlog must be a JSON object.");return t}async function Hp(t){let e=j.resolve(process.cwd(),t),r=Up(await O__default.readJson(e));if(!Array.isArray(r.products))throw new Error("Backlog must contain a products array.");return {absolutePath:e,payload:r}}function Bp(t,e){let r=[...t];if(e.tier){let o=e.tier.toLowerCase();r=r.filter(n=>n.tier.toLowerCase()===o);}if(e.category){let o=e.category.toLowerCase();r=r.filter(n=>n.category.toLowerCase()===o);}if(e.limit){let o=Number.parseInt(e.limit,10);if(!Number.isInteger(o)||o<1)throw new Error("--limit must be a positive integer.");r=r.slice(0,o);}return r}async function gc(t){let e=t.kit?.trim()||"fastapi.standard",{absolutePath:r,payload:o}=await Hp(t.backlogPath),n=o.products,a=n.map((f,u)=>Kp(f,u,e)),i=Bp(a,t),c=new Set(i.flatMap(f=>f.modules)),d=i.flatMap(f=>f.moduleGaps),l=i.filter(f=>f.readiness.status==="ready-for-private-manifest").length;return {schemaVersion:Gp,generatedAt:(t.now??new Date).toISOString(),source:{backlogPath:r,backlogSchemaVersion:Kn(o.schemaVersion),purpose:Kn(o.purpose),publicationRule:Kn(o.publicationRule)},defaults:{kit:e,workspaceProfile:"enterprise",projectSlug:"api"},stats:{totalProducts:n.length,plannedProducts:i.length,readyProducts:l,blockedProducts:i.length-l,uniqueModules:c.size,knownModuleGaps:d.length},products:i}}function Xt(t){return JSON.stringify(t,null,2)}function qp(t){return `sha256:${Pt.createHash("sha256").update(Xt(t)).digest("hex")}`}function zp(t){return t.replace(/\\/g,"/")}async function Yp(t){let e=await gc({backlogPath:t.backlogPath,kit:t.kit,now:t.now}),r=e.products.find(a=>a.slug===t.slug);if(!r)throw new Error(`Product "${t.slug}" was not found in backlog.`);let o=t.outputRoot||"../workspai-examples-pro",n={schemaVersion:Jp,generatedAt:e.generatedAt,product:{rank:r.rank,slug:r.slug,title:r.title,category:r.category,tier:r.tier,summary:r.summary},workspace:{name:r.slug,profile:"enterprise",outputHint:zp(j.join(o,r.slug))},projects:[{slug:"api",kit:r.recommendedKit,runtime:"python",framework:"fastapi",modules:r.modules,moduleGaps:r.moduleGaps}],factory:{sourceBacklogPath:e.source.backlogPath,manifestChecksum:"",requiredCommands:[`npx workspai create workspace ${r.slug} --yes --profile enterprise`,`npx workspai create project ${r.recommendedKit} api --yes --skip-install`,"npx workspai init","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"],releaseEvidencePath:`.workspai/product-factory/${r.slug}/release-evidence.json`}};return {...n,factory:{...n.factory,manifestChecksum:qp({...n,factory:{...n.factory,manifestChecksum:""}})}}}async function uc(t,e,r=false){let o=j.resolve(process.cwd(),t);if(!r&&await O__default.pathExists(o))throw new Error(`Refusing to overwrite existing file: ${o}. Use --force.`);await O__default.ensureDir(j.dirname(o)),await O__default.writeFile(o,`${Xt(e)}
|
|
105
105
|
`,"utf-8");}function Xp(t,e){let r=j.join(".workspai","product-factory","manifests",`${e}.manifest.json`);return t?t.endsWith(".json")?t:j.join(t,`${e}.manifest.json`):r}function Qp(t,e){console.log(s.bold(`
|
|
106
106
|
Workspai 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(`
|
|
@@ -112,16 +112,16 @@ Workspai 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: ${j.resolve(process.cwd(),e)}
|
|
114
114
|
`));}function fc(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(r,o)=>{try{let n=o.output||pc("--output"),a=await gc({backlogPath:r,kit:o.kit,tier:o.tier,category:o.category,limit:o.limit});a$4(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await uc(n,a,true),o.json?console.log(Xt(a)):Qp(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Xt({ok:false,error:{message:a}})):console.error(s.red(`Product plan failed: ${a}`)),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(r,o)=>{try{let n=o.output||pc("--output");mc(r);let a=await Yp({backlogPath:o.fromBacklog,slug:r,kit:o.kit,outputRoot:o.workspaceOutput});a$4(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=Xp(n,r);await uc(i,a,o.force===true),o.json?console.log(Xt(a)):Zp(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Xt({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var wc="rapidkit-workspace-snapshot-v1",Er="rapidkit-workspace-snapshot-v2",ed=wc,kc="rapidkit-project-archive-v1",pt="workspai-archive.json",bo="rapidkit-archive.json",td=[".workspai/workspace.json",".workspai-workspace","workspai.config.json","workspai.config.js","workspai.config.cjs","workspai.config.mjs",".rapidkit/workspace.json",".rapidkit-workspace","rapidkit.config.json","rapidkit.config.js","rapidkit.config.cjs","rapidkit.config.mjs","package.json"],rd=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),xr={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function Zt(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function Co(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 od(t){try{let e=await O__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function nd(t,e){if(!t)return e;let r=t.trim().toLowerCase();return ["true","yes","1","on"].includes(r)?true:["false","no","0","off"].includes(r)?false:e}async function sd(t){let e=s$1(t,"policies.yml").find(r=>existsSync(r))??p(t,"policies.yml");if(!await O__default.pathExists(e))return {...xr};try{let r=await O__default.readFile(e,"utf-8"),o=(n,a)=>{let i=r.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return nd(i?.[1],a)};return {requireReasonForDestructiveOps:o("require_reason_for_destructive_ops",xr.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:o("require_safety_snapshot_for_destructive_ops",xr.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:o("allow_permanent_delete",xr.allowPermanentDelete)}}catch{return {...xr}}}function ad(t){return p(t,"audit","events.jsonl")}async function Ze(t,e){let r={schema:"rapidkit-workspace-audit-event-v1",id:Pt.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},o=ad(t);return await O__default.ensureDir(j.dirname(o)),await O__default.appendFile(o,`${JSON.stringify(r)}
|
|
115
|
-
`,"utf-8"),r}async function So(t,e,r){let o=await sd(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function Un(t=process.cwd()){let e=j.resolve(t),r=j.resolve(Tn.tmpdir());for(;;){if(e!==r&&j$2(e))return e;let o=j.dirname(e);if(o===e)return null;e=o;}}function jt(t){let e=t?j.resolve(t):Un(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!j$2(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function vc(t){let e=await od(s$1(t,"workspace.json").find(o=>existsSync(o))??p(t,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():j.basename(t)}function er(t){return p(t,"snapshots")}function Rr(t){return p(t,"archive","projects")}function Qt(t){return j.join(t,"files")}function id(t){return j.join(Tn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${Pt.randomBytes(4).toString("hex")}`)}function cd(t,e){return j.join(er(t),`.tmp-${process.pid}-${e}-${Pt.randomBytes(4).toString("hex")}`)}function xo(t,e){let r=j.relative(t,e);if(!r)return true;let o=r.split(j.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>rd.has(n)||a$e(n))}async function ld(t){return (await a$f(t,{descendIntoMatchedProjects:false})).map(r=>({name:j.basename(r),relativePath:j.relative(t,r)}))}async function pd(t,e){let r=[],o=new Set;for(let n of td){let a=j.join(t,n);if(!await O__default.pathExists(a))continue;let i=v(n);if(o.has(i))continue;let c=j.join(e,i);await O__default.copy(a,c,{filter:p=>xo(t,p)}),r.push(i),o.add(i);}return r}async function Pc(t){let e=[];async function r(o){let n=[];try{n=await O__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=j.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=j.join(j.dirname(o),j.basename(v(j.basename(o))));await O__default.copy(o,n,{overwrite:false,errorOnExist:false}),await O__default.remove(o);}}async function jc(t,e){let r=e.schema===Er?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,r,"Workspace snapshot manifest"),await O__default.writeJson(j.join(t,"snapshot.json"),e,{spaces:2});}async function Hn(t){let e=j.join(t,"snapshot.json"),r=await O__default.readJson(e);if(!r||typeof r!="object"||![wc,Er].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===Er?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==Er||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function dd(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await O__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=j.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let p=await O__default.stat(c);e+=1,r+=p.size;}catch{}}}return {files:e,bytes:r}}async function Eo(t={}){let e=jt(t.workspacePath),r=t.name?t.name:`snapshot-${Zt()}`,o=Co(r),n=j.join(er(e),o),a=id(o);if(await O__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=Qt(a);try{await O__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",p=c==="full"?["."]:await pd(e,i);c==="full"&&(await O__default.copy(e,i,{filter:f=>xo(e,f)}),await Pc(i));let d={schema:ed,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await vc(e),workspacePath:e,copiedPaths:p,projects:await ld(e)};return await jc(a,d),await O__default.ensureDir(j.dirname(n)),await O__default.move(a,n,{overwrite:false}),await Ze(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:p,snapshotPath:n,projectCount:d.projects.length}}),{manifest:d,snapshotPath:n}}catch(c){throw await O__default.remove(a),await Ze(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function Ro(t){let e=j.resolve(t.workspacePath),r=j.resolve(t.projectPath),o=j.relative(e,r);if(!o||o.startsWith("..")||j.isAbsolute(o)||o.split(j.sep).some(f=>f===".workspai"||f===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=j.basename(r),a=Co(`${t.namePrefix}-${n}-${Zt()}-${Pt.randomBytes(3).toString("hex")}`),i=j.join(er(e),a),c=cd(e,a),p=j.join(Qt(c),o),d=false;try{await O__default.ensureDir(j.dirname(p)),t.moveSource?(await O__default.move(r,p,{overwrite:false}),d=true):await O__default.copy(r,p,{overwrite:false,errorOnExist:true,filter:m=>xo(r,m)});let f={schema:Er,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await vc(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await jc(c,f),await O__default.move(c,i,{overwrite:false}),await Ze(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:f,snapshotPath:i}}catch(f){if(d&&!await O__default.pathExists(r)){let m=await O__default.pathExists(p)?p:j.join(Qt(i),o);await O__default.pathExists(m)&&(await O__default.ensureDir(j.dirname(r)),await O__default.move(m,r,{overwrite:false}));}throw await O__default.remove(c),await O__default.remove(i),await Ze(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:f instanceof Error?f.message:String(f)}}),f}}async function bc(t){let e=jt(t.workspacePath),r=j.join(er(e),Co(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Hn(r),n=Qt(r),a=await dd(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function Cc(t={}){let e=jt(t.workspacePath),r=er(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=j.join(r,a.name);try{n.push({...await Hn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var ud=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function md(t){let e=j.dirname(t.workspacePath),r=j.basename(t.workspacePath),o=`${Zt()}-${Pt.randomBytes(4).toString("hex")}`,n=j.join(e,`.${r}.restore-staging-${o}`),a=j.join(e,`.${r}.pre-restore-${o}`),i=j.join(e,`.${r}.restore-failed-${o}`),c=[],p=false,d=false;try{await O__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:f=>xo(t.filesRoot,f)}),await Pc(n),await O__default.rename(t.workspacePath,a),p=true,await O__default.rename(n,t.workspacePath),d=true;for(let f of ud){let m=j.join(a,f);if(!await O__default.pathExists(m))continue;let w=j.join(t.workspacePath,f);if(await O__default.pathExists(w))throw new Error(`Full restore operational path collision: ${f}`);await O__default.ensureDir(j.dirname(w)),await O__default.rename(m,w),c.push(f);}return a}catch(f){for(let m of [...c].reverse()){let w=j.join(t.workspacePath,m),y=j.join(a,m);await O__default.pathExists(w)&&(await O__default.ensureDir(j.dirname(y)),await O__default.rename(w,y));}throw d&&await O__default.pathExists(t.workspacePath)&&await O__default.rename(t.workspacePath,i),p&&await O__default.pathExists(a)&&await O__default.rename(a,t.workspacePath),await O__default.remove(i),await O__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${f instanceof Error?f.message:String(f)}`)}}async function Sc(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=j.join(Qt(t.snapshotPath),r),n=j.join(e,r);await O__default.pathExists(o)&&!await O__default.pathExists(n)&&(await O__default.ensureDir(j.dirname(n)),await O__default.move(o,n,{overwrite:false})),await O__default.remove(t.snapshotPath);}async function xc(t){let e=jt(t.workspacePath),r=j.join(er(e),Co(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Hn(r),n=Qt(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(p=>{let d=v(p);return d.startsWith(".workspai/")?".workspai":d})));if(t.dryRun)return await Ze(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await So(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await md({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let p=o.recoveryScope?.relativePath;if(!p)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let d=j.join(n,p),f=j.join(e,p),m=await O__default.pathExists(f),w,y=j.join(j.dirname(f),`.${j.basename(f)}.pre-restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`),P=false;m&&t.safetySnapshot!==false?(w=await Ro({workspacePath:e,projectPath:f,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=w.snapshotPath):m&&(await O__default.rename(f,y),P=true);let S=j.join(j.dirname(f),`.${j.basename(f)}.restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`);try{await O__default.copy(d,S,{overwrite:false,errorOnExist:true}),await O__default.rename(S,f),P&&await O__default.remove(y);}catch(l){throw await O__default.remove(S),P&&await O__default.pathExists(y)&&(await O__default.remove(f),await O__default.rename(y,f)),w&&await Sc(w,e),l}}else t.safetySnapshot!==false&&(i=(await Eo({workspacePath:e,name:`pre-restore-${o.name}-${Zt()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let p=new Set;for(let d of o.copiedPaths){let f=v(d);p.has(f)||(await O__default.copy(j.join(n,d),j.join(e,f),{overwrite:true,errorOnExist:false}),p.add(f));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await Ze(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function Ec(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function Rc(t,e){let r=Ec(e),o=j.isAbsolute(r)?j.resolve(r):j.resolve(t,r);if(o.startsWith(`${j.resolve(t)}${j.sep}`)&&await O__default.pathExists(o))return o;let a=(await a$f(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=j.relative(t,i);return j.basename(i)===r||c===r});if(a.length===0)throw new Error(`Project not found in workspace: ${e}`);if(a.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return a[0]}async function Bn(t){let{syncWorkspaceProjects:e}=await import('./workspace-BNRSBWSL.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-ACSIHJIO.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-BSG5LK6N.js');await o({workspacePath:t,mode:"managed"});}function gd(t,e){let r=Pt.randomBytes(4).toString("hex");return j.join(Rr(t),`${e}-${Zt()}-${r}`)}async function Ac(t){let e=_c(t),r=await O__default.readJson(e);if(!r||typeof r!="object"||r.schema!==kc)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function _c(t){return [pt,bo].map(e=>j.join(t,e)).find(e=>O__default.existsSync(e))??j.join(t,pt)}async function qn(t={}){let e=jt(t.workspacePath),r=Rr(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=j.join(r,a.name),c=[pt,bo].map(p=>j.join(i,p)).find(p=>O__default.existsSync(p))??j.join(i,pt);try{n.push({...await Ac(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function fd(t,e){let r=Ec(e),o=j.isAbsolute(r)?j.resolve(r):j.resolve(Rr(t),r);if(o.startsWith(`${j.resolve(Rr(t))}${j.sep}`)&&(await O__default.pathExists(j.join(o,pt))||await O__default.pathExists(j.join(o,bo))))return o;let a=(await qn({workspacePath:t})).filter(i=>j.basename(i.archivePath)===r||i.projectName===r||j.relative(Rr(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function zn(t){let e=jt(t.workspacePath),r=await Rc(e,t.project),o=j.basename(r),n=gd(e,o),a=j.join(n,pt),i=`${n}.tmp-${process.pid}`,c=j.join(i,pt);for(let m of [pt,bo])if(await O__default.pathExists(j.join(r,m)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${m}`);if(t.dryRun)return await Ze(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await So(e,"project.archive",{reason:t.reason,safetySnapshot:true});let p=await Ro({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),d={schema:kc,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:p.snapshotPath};a$4(d,"contracts/project-archive.v1.json","Project archive manifest");let f=false;try{await O__default.ensureDir(j.dirname(n)),await O__default.move(r,i,{overwrite:false}),f=true,await O__default.writeJson(c,d,{spaces:2}),await O__default.rename(i,n);}catch(m){if(f&&!await O__default.pathExists(r)){let w=await O__default.pathExists(i)?i:n;await O__default.pathExists(w)&&(await O__default.remove(j.join(w,pt)),await O__default.move(w,r,{overwrite:false}));}throw await O__default.remove(i),m}return await c$3(e,[r]),await Bn(e),await Ze(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath,dryRun:false}}async function Ic(t){if(!t.permanent)return zn(t);let e=jt(t.workspacePath),r=await Rc(e,t.project),o=j.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await Ze(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await So(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Ro({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$3(e,[r]),await Bn(e),await Ze(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function Oc(t){let e=jt(t.workspacePath),r=await fd(e,t.archive),o=await Ac(r),n=t.targetName?.trim()||o.projectName,a=j.join(e,n);if(!a.startsWith(`${j.resolve(e)}${j.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await O__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await Ze(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:j.join(r,pt),dryRun:true};await So(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await O__default.pathExists(a),c=i?await Ro({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await Eo({workspacePath:e,name:`pre-restore-project-${n}-${Zt()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),p$1=_c(r),d=p(e,"audit","restores",`${j.basename(r)}.json`);try{await O__default.move(r,a,{overwrite:false}),await O__default.ensureDir(j.dirname(d)),await O__default.move(j.join(a,j.basename(p$1)),d,{overwrite:false});}catch(f){throw await O__default.pathExists(a)&&(await O__default.pathExists(d)&&await O__default.move(d,j.join(a,j.basename(p$1)),{overwrite:false}),await O__default.pathExists(r)||await O__default.move(a,r,{overwrite:false})),i&&await Sc(c,e),f}return await Bn(e),await Ze(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:d,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:d,safetySnapshotPath:c.snapshotPath,dryRun:false}}var yd="rapidkit.infra-stack.v1",Nc=h$3.infraPlan.schemaVersion,tr=".workspai/infra/docker-compose.yml",rr=i$2.infraPlan,Qn=".workspai/infra/.env.example";function wd(){let t=j.dirname(fileURLToPath(import.meta.url)),e=[j.join(t,"../../contracts/infra-stack.v1.json"),j.join(t,"../contracts/infra-stack.v1.json")];for(let r of e)if(_.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var Xn=null;function Ot(t){if(Xn)return Xn;let e=wd(),r=_.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==yd)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return kd(o),(Xn=o),o}function kd(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function Tc(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function or(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Mc(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function Pd(t){let e=j.join(t,"registry.json");if(!await O__default.pathExists(e))return [];try{let o=(await O__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function jd(t){let e=j.join(t,".env.example");if(!await O__default.pathExists(e))return [];try{let r=await O__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
|
|
116
|
-
`)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&o.push(i[1]);}return o}catch{return []}}async function bd(t){let e=s$1(t,"infra","overrides.json").find(r=>existsSync(r));if(!e)return [];try{let r=await O__default.readJson(e);return Array.isArray(r.services)?[...new Set(r.services.filter(o=>typeof o=="string"&&o.trim().length>0))]:[]}catch{return []}}async function Cd(t){let e=await d$
|
|
117
|
-
`)){let n=Sd(o);n&&(r[n.key]=n.value);}return r}catch{return {}}}async function Lc(t){let e={},r=await i$
|
|
115
|
+
`,"utf-8"),r}async function So(t,e,r){let o=await sd(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function Un(t=process.cwd()){let e=j.resolve(t),r=j.resolve(Tn.tmpdir());for(;;){if(e!==r&&j$2(e))return e;let o=j.dirname(e);if(o===e)return null;e=o;}}function jt(t){let e=t?j.resolve(t):Un(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!j$2(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function vc(t){let e=await od(s$1(t,"workspace.json").find(o=>existsSync(o))??p(t,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():j.basename(t)}function er(t){return p(t,"snapshots")}function Rr(t){return p(t,"archive","projects")}function Qt(t){return j.join(t,"files")}function id(t){return j.join(Tn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${Pt.randomBytes(4).toString("hex")}`)}function cd(t,e){return j.join(er(t),`.tmp-${process.pid}-${e}-${Pt.randomBytes(4).toString("hex")}`)}function xo(t,e){let r=j.relative(t,e);if(!r)return true;let o=r.split(j.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>rd.has(n)||a$f(n))}async function ld(t){return (await a$g(t,{descendIntoMatchedProjects:false})).map(r=>({name:j.basename(r),relativePath:j.relative(t,r)}))}async function pd(t,e){let r=[],o=new Set;for(let n of td){let a=j.join(t,n);if(!await O__default.pathExists(a))continue;let i=v(n);if(o.has(i))continue;let c=j.join(e,i);await O__default.copy(a,c,{filter:d=>xo(t,d)}),r.push(i),o.add(i);}return r}async function Pc(t){let e=[];async function r(o){let n=[];try{n=await O__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=j.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=j.join(j.dirname(o),j.basename(v(j.basename(o))));await O__default.copy(o,n,{overwrite:false,errorOnExist:false}),await O__default.remove(o);}}async function jc(t,e){let r=e.schema===Er?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,r,"Workspace snapshot manifest"),await O__default.writeJson(j.join(t,"snapshot.json"),e,{spaces:2});}async function Hn(t){let e=j.join(t,"snapshot.json"),r=await O__default.readJson(e);if(!r||typeof r!="object"||![wc,Er].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===Er?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==Er||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function dd(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await O__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=j.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let d=await O__default.stat(c);e+=1,r+=d.size;}catch{}}}return {files:e,bytes:r}}async function Eo(t={}){let e=jt(t.workspacePath),r=t.name?t.name:`snapshot-${Zt()}`,o=Co(r),n=j.join(er(e),o),a=id(o);if(await O__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=Qt(a);try{await O__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",d=c==="full"?["."]:await pd(e,i);c==="full"&&(await O__default.copy(e,i,{filter:f=>xo(e,f)}),await Pc(i));let l={schema:ed,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await vc(e),workspacePath:e,copiedPaths:d,projects:await ld(e)};return await jc(a,l),await O__default.ensureDir(j.dirname(n)),await O__default.move(a,n,{overwrite:false}),await Ze(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:d,snapshotPath:n,projectCount:l.projects.length}}),{manifest:l,snapshotPath:n}}catch(c){throw await O__default.remove(a),await Ze(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function Ro(t){let e=j.resolve(t.workspacePath),r=j.resolve(t.projectPath),o=j.relative(e,r);if(!o||o.startsWith("..")||j.isAbsolute(o)||o.split(j.sep).some(f=>f===".workspai"||f===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=j.basename(r),a=Co(`${t.namePrefix}-${n}-${Zt()}-${Pt.randomBytes(3).toString("hex")}`),i=j.join(er(e),a),c=cd(e,a),d=j.join(Qt(c),o),l=false;try{await O__default.ensureDir(j.dirname(d)),t.moveSource?(await O__default.move(r,d,{overwrite:false}),l=true):await O__default.copy(r,d,{overwrite:false,errorOnExist:true,filter:u=>xo(r,u)});let f={schema:Er,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await vc(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await jc(c,f),await O__default.move(c,i,{overwrite:false}),await Ze(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:f,snapshotPath:i}}catch(f){if(l&&!await O__default.pathExists(r)){let u=await O__default.pathExists(d)?d:j.join(Qt(i),o);await O__default.pathExists(u)&&(await O__default.ensureDir(j.dirname(r)),await O__default.move(u,r,{overwrite:false}));}throw await O__default.remove(c),await O__default.remove(i),await Ze(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:f instanceof Error?f.message:String(f)}}),f}}async function bc(t){let e=jt(t.workspacePath),r=j.join(er(e),Co(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Hn(r),n=Qt(r),a=await dd(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function Cc(t={}){let e=jt(t.workspacePath),r=er(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=j.join(r,a.name);try{n.push({...await Hn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var ud=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function md(t){let e=j.dirname(t.workspacePath),r=j.basename(t.workspacePath),o=`${Zt()}-${Pt.randomBytes(4).toString("hex")}`,n=j.join(e,`.${r}.restore-staging-${o}`),a=j.join(e,`.${r}.pre-restore-${o}`),i=j.join(e,`.${r}.restore-failed-${o}`),c=[],d=false,l=false;try{await O__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:f=>xo(t.filesRoot,f)}),await Pc(n),await O__default.rename(t.workspacePath,a),d=true,await O__default.rename(n,t.workspacePath),l=true;for(let f of ud){let u=j.join(a,f);if(!await O__default.pathExists(u))continue;let w=j.join(t.workspacePath,f);if(await O__default.pathExists(w))throw new Error(`Full restore operational path collision: ${f}`);await O__default.ensureDir(j.dirname(w)),await O__default.rename(u,w),c.push(f);}return a}catch(f){for(let u of [...c].reverse()){let w=j.join(t.workspacePath,u),y=j.join(a,u);await O__default.pathExists(w)&&(await O__default.ensureDir(j.dirname(y)),await O__default.rename(w,y));}throw l&&await O__default.pathExists(t.workspacePath)&&await O__default.rename(t.workspacePath,i),d&&await O__default.pathExists(a)&&await O__default.rename(a,t.workspacePath),await O__default.remove(i),await O__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${f instanceof Error?f.message:String(f)}`)}}async function Sc(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=j.join(Qt(t.snapshotPath),r),n=j.join(e,r);await O__default.pathExists(o)&&!await O__default.pathExists(n)&&(await O__default.ensureDir(j.dirname(n)),await O__default.move(o,n,{overwrite:false})),await O__default.remove(t.snapshotPath);}async function xc(t){let e=jt(t.workspacePath),r=j.join(er(e),Co(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Hn(r),n=Qt(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(d=>{let l=v(d);return l.startsWith(".workspai/")?".workspai":l})));if(t.dryRun)return await Ze(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await So(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await md({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let d=o.recoveryScope?.relativePath;if(!d)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let l=j.join(n,d),f=j.join(e,d),u=await O__default.pathExists(f),w,y=j.join(j.dirname(f),`.${j.basename(f)}.pre-restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`),P=false;u&&t.safetySnapshot!==false?(w=await Ro({workspacePath:e,projectPath:f,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=w.snapshotPath):u&&(await O__default.rename(f,y),P=true);let S=j.join(j.dirname(f),`.${j.basename(f)}.restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`);try{await O__default.copy(l,S,{overwrite:false,errorOnExist:true}),await O__default.rename(S,f),P&&await O__default.remove(y);}catch(p){throw await O__default.remove(S),P&&await O__default.pathExists(y)&&(await O__default.remove(f),await O__default.rename(y,f)),w&&await Sc(w,e),p}}else t.safetySnapshot!==false&&(i=(await Eo({workspacePath:e,name:`pre-restore-${o.name}-${Zt()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let d=new Set;for(let l of o.copiedPaths){let f=v(l);d.has(f)||(await O__default.copy(j.join(n,l),j.join(e,f),{overwrite:true,errorOnExist:false}),d.add(f));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await Ze(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function Ec(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function Rc(t,e){let r=Ec(e),o=j.isAbsolute(r)?j.resolve(r):j.resolve(t,r);if(o.startsWith(`${j.resolve(t)}${j.sep}`)&&await O__default.pathExists(o))return o;let a=(await a$g(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=j.relative(t,i);return j.basename(i)===r||c===r});if(a.length===0)throw new Error(`Project not found in workspace: ${e}`);if(a.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return a[0]}async function Bn(t){let{syncWorkspaceProjects:e}=await import('./workspace-UUU4VMZB.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-3BWIRSVQ.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-N7REBQ3A.js');await o({workspacePath:t,mode:"managed"});}function gd(t,e){let r=Pt.randomBytes(4).toString("hex");return j.join(Rr(t),`${e}-${Zt()}-${r}`)}async function Ac(t){let e=_c(t),r=await O__default.readJson(e);if(!r||typeof r!="object"||r.schema!==kc)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function _c(t){return [pt,bo].map(e=>j.join(t,e)).find(e=>O__default.existsSync(e))??j.join(t,pt)}async function qn(t={}){let e=jt(t.workspacePath),r=Rr(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=j.join(r,a.name),c=[pt,bo].map(d=>j.join(i,d)).find(d=>O__default.existsSync(d))??j.join(i,pt);try{n.push({...await Ac(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function fd(t,e){let r=Ec(e),o=j.isAbsolute(r)?j.resolve(r):j.resolve(Rr(t),r);if(o.startsWith(`${j.resolve(Rr(t))}${j.sep}`)&&(await O__default.pathExists(j.join(o,pt))||await O__default.pathExists(j.join(o,bo))))return o;let a=(await qn({workspacePath:t})).filter(i=>j.basename(i.archivePath)===r||i.projectName===r||j.relative(Rr(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function zn(t){let e=jt(t.workspacePath),r=await Rc(e,t.project),o=j.basename(r),n=gd(e,o),a=j.join(n,pt),i=`${n}.tmp-${process.pid}`,c=j.join(i,pt);for(let u of [pt,bo])if(await O__default.pathExists(j.join(r,u)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${u}`);if(t.dryRun)return await Ze(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await So(e,"project.archive",{reason:t.reason,safetySnapshot:true});let d=await Ro({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),l={schema:kc,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:d.snapshotPath};a$4(l,"contracts/project-archive.v1.json","Project archive manifest");let f=false;try{await O__default.ensureDir(j.dirname(n)),await O__default.move(r,i,{overwrite:false}),f=true,await O__default.writeJson(c,l,{spaces:2}),await O__default.rename(i,n);}catch(u){if(f&&!await O__default.pathExists(r)){let w=await O__default.pathExists(i)?i:n;await O__default.pathExists(w)&&(await O__default.remove(j.join(w,pt)),await O__default.move(w,r,{overwrite:false}));}throw await O__default.remove(i),u}return await c$4(e,[r]),await Bn(e),await Ze(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:d.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:d.snapshotPath,dryRun:false}}async function Ic(t){if(!t.permanent)return zn(t);let e=jt(t.workspacePath),r=await Rc(e,t.project),o=j.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await Ze(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await So(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Ro({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$4(e,[r]),await Bn(e),await Ze(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function Oc(t){let e=jt(t.workspacePath),r=await fd(e,t.archive),o=await Ac(r),n=t.targetName?.trim()||o.projectName,a=j.join(e,n);if(!a.startsWith(`${j.resolve(e)}${j.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await O__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await Ze(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:j.join(r,pt),dryRun:true};await So(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await O__default.pathExists(a),c=i?await Ro({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await Eo({workspacePath:e,name:`pre-restore-project-${n}-${Zt()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),d=_c(r),l=p(e,"audit","restores",`${j.basename(r)}.json`);try{await O__default.move(r,a,{overwrite:false}),await O__default.ensureDir(j.dirname(l)),await O__default.move(j.join(a,j.basename(d)),l,{overwrite:false});}catch(f){throw await O__default.pathExists(a)&&(await O__default.pathExists(l)&&await O__default.move(l,j.join(a,j.basename(d)),{overwrite:false}),await O__default.pathExists(r)||await O__default.move(a,r,{overwrite:false})),i&&await Sc(c,e),f}return await Bn(e),await Ze(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:l,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:l,safetySnapshotPath:c.snapshotPath,dryRun:false}}var yd="rapidkit.infra-stack.v1",Nc=h$3.infraPlan.schemaVersion,tr=".workspai/infra/docker-compose.yml",rr=i$1.infraPlan,Qn=".workspai/infra/.env.example";function wd(){let t=j.dirname(fileURLToPath(import.meta.url)),e=[j.join(t,"../../contracts/infra-stack.v1.json"),j.join(t,"../contracts/infra-stack.v1.json")];for(let r of e)if(_.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var Xn=null;function Ot(t){if(Xn)return Xn;let e=wd(),r=_.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==yd)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return kd(o),(Xn=o),o}function kd(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function Tc(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function or(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Mc(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function Pd(t){let e=j.join(t,"registry.json");if(!await O__default.pathExists(e))return [];try{let o=(await O__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function jd(t){let e=j.join(t,".env.example");if(!await O__default.pathExists(e))return [];try{let r=await O__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
|
|
116
|
+
`)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&o.push(i[1]);}return o}catch{return []}}async function bd(t){let e=s$1(t,"infra","overrides.json").find(r=>existsSync(r));if(!e)return [];try{let r=await O__default.readJson(e);return Array.isArray(r.services)?[...new Set(r.services.filter(o=>typeof o=="string"&&o.trim().length>0))]:[]}catch{return []}}async function Cd(t){let e=await d$7(t,i$1.workspaceContract);if(!e)return [];try{let r=await O__default.readJson(e),o=[];for(let n of r.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&o.push({project:a,env:i.trim().toUpperCase()});}return o}catch{return []}}function Ao(t,e,r,o){t.add(r),e.push(o);}async function Wc(t){let e=j.resolve(t.workspacePath),r=t.contract||Ot(),o=new Set,n=[],a=new Set,i=new Set,c=new Set,d=await i$7(e);for(let l of d){let f=j.dirname(j.dirname(l)),u=j.basename(f);for(let w of await Pd(f)){a.add(w);for(let y of Tc(r,w))Ao(o,n,y,{kind:"module",value:w,project:u});}for(let w of await jd(f)){i.add(w);for(let y of or(r,w))Ao(o,n,y,{kind:"env-var",value:w,project:u});}}for(let l of await Cd(e)){i.add(l.env);for(let f of or(r,l.env))Ao(o,n,f,{kind:"contract-env",value:l.env,project:l.project});}for(let l of await bd(e))c.add(l),Ao(o,n,l,{kind:"override",value:l});return {modules:[...a].sort(),envVars:[...i].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...o].sort()}}function Sd(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let r=e.indexOf("=");if(r<=0)return null;let o=e.slice(0,r).trim();if(!/^[A-Z0-9_]+$/.test(o))return null;let n=e.slice(r+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let a=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),i=(a?a[1]:n).trim();return i?{key:o,value:i}:null}async function xd(t){if(!await O__default.pathExists(t))return {};try{let e=await O__default.readFile(t,"utf-8"),r={};for(let o of e.split(`
|
|
117
|
+
`)){let n=Sd(o);n&&(r[n.key]=n.value);}return r}catch{return {}}}async function Lc(t){let e={},r=await i$7(t.workspacePath);for(let o of r){let n=j.dirname(j.dirname(o)),a=await xd(j.join(n,".env.example"));for(let[i,c]of Object.entries(a))or(t.contract,i).length>0&&(e[i]=c);}return e}function Fc(t,e){return t.filter(r=>or(e,r).length>0).sort()}function Gc(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let r=new URL(e),o=r.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(r.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(r.password||"postgres"),POSTGRES_DB:o||"postgres"}}catch{return}}function Jc(t){let e=t.POSTGRES_USER||"postgres",r=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${r}`]}function Ed(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
|
|
118
118
|
`)?JSON.stringify(t):t}function Vc(t,e){return Object.entries(t).map(([r,o])=>`${e}${r}: ${Ed(o)}`).join(`
|
|
119
119
|
`)}function Rd(t,e){let r=t.test.map(o=>JSON.stringify(o)).join(", ");return [`${e}healthcheck:`,`${e} test: [${r}]`,`${e} interval: ${t.interval}`,`${e} timeout: ${t.timeout}`,`${e} retries: ${t.retries}`].join(`
|
|
120
120
|
`)}function Kc(t){let e=["# Generated by Workspai infra plan \u2014 do not edit manually.",`# Workspace: ${t.workspaceName}`,`# Generated at: ${t.plan.generatedAt}`,"name: workspai-infra"],r=new Set;if(t.plan.services.length===0)return e.push("services: {}"),e.push(""),e.join(`
|
|
121
121
|
`);e.push("services:");for(let o of t.plan.services){let n=t.contract.services[o.id];if(n){if(e.push(` ${o.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: workspai-${o.id}`),n.command?.length){let a=n.command.map(i=>JSON.stringify(i)).join(", ");e.push(` command: [${a}]`);}if(n.env&&Object.keys(n.env).length>0){e.push(" environment:");let a={...n.env,...t.plan.serviceEnvOverrides?.[o.id]||{}};e.push(Vc(a," "));}else t.plan.serviceEnvOverrides?.[o.id]&&(e.push(" environment:"),e.push(Vc(t.plan.serviceEnvOverrides[o.id]," ")));if(n.ports.length>0){e.push(" ports:");for(let a of n.ports)e.push(` - "${a.host}:${a.container}"`);}if(n.volumes?.length){e.push(" volumes:");for(let a of n.volumes){e.push(` - ${a}`);let i=a.split(":")[0];i&&!i.startsWith("/")&&r.add(i);}}if(n.healthcheck){let a=t.plan.serviceEnvOverrides?.[o.id];if(o.id==="postgres"&&a){let i=Jc(a).map(c=>JSON.stringify(c)).join(", ");e.push(" healthcheck:"),e.push(` test: [${i}]`),e.push(` interval: ${n.healthcheck.interval}`),e.push(` timeout: ${n.healthcheck.timeout}`),e.push(` retries: ${n.healthcheck.retries}`);}else e.push(Rd(n.healthcheck," "));}e.push(" restart: unless-stopped");}}if(r.size>0){e.push("volumes:");for(let o of [...r].sort())e.push(` ${o}:`),e.push(" driver: local");}return e.push(""),e.join(`
|
|
122
|
-
`)}function _d(t,e,r){return t.kind==="override"?t.value===e:t.kind==="module"?r.moduleMappings[t.value]?.includes(e)??false:r.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function Id(t){let e=new Map,r=[];for(let o of t)for(let n of o.ports){let a=e.get(n.host);a&&a!==o.id?r.push(`Port collision on host ${n.host} between services '${a}' and '${o.id}'`):e.set(n.host,o.id);}return r}async function Od(t){let e=s$1(t,"workspace.json").find(r=>existsSync(r));if(e)try{let r=await O__default.readJson(e);return r.workspace_name||r.name}catch{return}}async function es(t){let e=j.resolve(t.workspacePath),r=Ot(),o=await Wc({workspacePath:e,contract:r}),n=o.serviceIds.map(w=>{let y=r.services[w];return y?{id:w,displayName:y.displayName,category:y.category,image:y.image,ports:y.ports,sources:o.sources.filter(P=>_d(P,w,r))}:null}).filter(w=>w!==null),a=Id(n);n.length===0&&a.push("No infrastructure services detected. Install modules with infra dependencies or add .workspai/infra/overrides.json");for(let w of o.overrides)r.services[w]||a.push(`Override references unknown service '${w}'`);let i=await d$
|
|
122
|
+
`)}function _d(t,e,r){return t.kind==="override"?t.value===e:t.kind==="module"?r.moduleMappings[t.value]?.includes(e)??false:r.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function Id(t){let e=new Map,r=[];for(let o of t)for(let n of o.ports){let a=e.get(n.host);a&&a!==o.id?r.push(`Port collision on host ${n.host} between services '${a}' and '${o.id}'`):e.set(n.host,o.id);}return r}async function Od(t){let e=s$1(t,"workspace.json").find(r=>existsSync(r));if(e)try{let r=await O__default.readJson(e);return r.workspace_name||r.name}catch{return}}async function es(t){let e=j.resolve(t.workspacePath),r=Ot(),o=await Wc({workspacePath:e,contract:r}),n=o.serviceIds.map(w=>{let y=r.services[w];return y?{id:w,displayName:y.displayName,category:y.category,image:y.image,ports:y.ports,sources:o.sources.filter(P=>_d(P,w,r))}:null}).filter(w=>w!==null),a=Id(n);n.length===0&&a.push("No infrastructure services detected. Install modules with infra dependencies or add .workspai/infra/overrides.json");for(let w of o.overrides)r.services[w]||a.push(`Override references unknown service '${w}'`);let i=await d$7(e,i$1.workspaceContract)?i$1.workspaceContract:void 0,c=Mc(r,o.serviceIds),d=await Lc({workspacePath:e,contract:r}),l={...c,...d};d.RAPIDKIT_DB_POSTGRES_URL&&(l.DATABASE_URL=d.RAPIDKIT_DB_POSTGRES_URL);let f={},u=Gc(l);return u&&o.serviceIds.includes("postgres")&&(f.postgres=u),{schemaVersion:Nc,generatedAt:(t.now||(()=>new Date))().toISOString(),workspacePath:e,workspaceName:await Od(e),contractPath:i,strategy:"sidecar",composePath:tr,envExamplePath:Qn,services:n,connectionEnv:l,serviceEnvOverrides:Object.keys(f).length>0?f:void 0,sources:{modules:o.modules,envVars:o.envVars,overrides:o.overrides},warnings:a}}async function ts(t){let e=j.resolve(t.workspacePath),r=j.join(e,tr),o=j.join(e,rr),n=j.join(e,Qn),a=Ot();a$4(t.plan,"contracts/infra-plan.v1.json","Workspai infrastructure plan");let i=Kc({plan:t.plan,contract:a,workspaceName:t.plan.workspaceName||j.basename(e)}),c=["# Generated by: npx workspai infra plan","# Copy values into project .env files as needed.",...Object.entries(t.plan.connectionEnv).map(([d,l])=>`${d}=${l}`),""].join(`
|
|
123
123
|
`);return t.dryRun?{composePath:r,planPath:o,envExamplePath:n}:(await O__default.ensureDir(j.dirname(r)),await O__default.ensureDir(j.dirname(o)),await O__default.writeFile(r,i,"utf-8"),await O__default.writeFile(o,`${JSON.stringify(t.plan,null,2)}
|
|
124
|
-
`,"utf-8"),await O__default.writeFile(n,c,"utf-8"),{composePath:r,planPath:o,envExamplePath:n})}function $d(t){return j.resolve(t).split(j.sep).join("/")}async function Hc(){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 Nd(){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 Hc();}function Bc(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 .workspai/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 qc(t){await Nd();let e=await Hc(),r=$d(t.composePath),o=await execa(e.command,[...e.prefixArgs,"-f",r,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}function Io(t){let e=t?j.resolve(t):Un(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");return a$
|
|
124
|
+
`,"utf-8"),await O__default.writeFile(n,c,"utf-8"),{composePath:r,planPath:o,envExamplePath:n})}function $d(t){return j.resolve(t).split(j.sep).join("/")}async function Hc(){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 Nd(){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 Hc();}function Bc(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 .workspai/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 qc(t){await Nd();let e=await Hc(),r=$d(t.composePath),o=await execa(e.command,[...e.prefixArgs,"-f",r,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}function Io(t){let e=t?j.resolve(t):Un(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");return a$9(e)}function Td(t){return j.join(t,tr)}async function rs(t){let e=j.join(t,rr);if(!await O__default.pathExists(e))throw new Error(`Infra plan not found at ${rr}. Run: npx workspai infra plan`);let r=await O__default.readJson(e);return a$4(r,"contracts/infra-plan.v1.json",`Infra plan ${e}`),r}async function os(t){let e=Td(t.workspacePath);if(!await O__default.pathExists(e))throw new Error(`Compose file not found at ${tr}. Run: npx workspai infra plan`);return qc({composePath:e,workspacePath:t.workspacePath,args:t.args})}function Md(t,e={}){if(console.log(s.bold(`
|
|
125
125
|
Workspai infra plan
|
|
126
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: ${rr}`)),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 r of t.services){let o=r.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${r.id}`),s.gray(`(${r.displayName})`),o?s.white(`ports ${o}`):"");}}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 r=Ot(),o=Fc(t.sources.envVars,r);console.log(s.bold("Detected from env vars (infra-mapped):")),o.length>0?console.log(s.gray(` ${o.join(", ")}`)):console.log(s.gray(" none"));let n=t.sources.envVars.length-o.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 a=t.sources.envVars.filter(i=>!o.includes(i));a.length>0&&console.log(s.gray(` Other scanned env vars: ${a.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[r,o]of Object.entries(t.connectionEnv))console.log(s.gray(` ${r}=${o}`));}if(t.warnings.length>0){console.log(""),console.log(s.yellow("Warnings:"));for(let r of t.warnings)console.log(s.yellow(` - ${r}`));}console.log("");}function zc(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 r=>{try{let o=Io(r.workspace),n=await es({workspacePath:o}),a=await ts({workspacePath:o,plan:n,dryRun:r.dryRun});if(r.json){console.log(JSON.stringify({...n,artifacts:r.dryRun?{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath,dryRun:true}:{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath}},null,2));return}Md(n,{verbose:r.verbose}),r.dryRun?console.log(s.yellow(`Dry run \u2014 no files written.
|
|
127
127
|
`)):(console.log(s.green("Artifacts written:")),console.log(s.gray(` ${a.composePath}`)),console.log(s.gray(` ${a.planPath}`)),console.log(s.gray(` ${a.envExamplePath}
|
|
@@ -144,36 +144,36 @@ Workspai infra status
|
|
|
144
144
|
`))),i.exitCode!==0&&(i.stderr&&process.stderr.write(i.stderr),process.exit(i.exitCode)),r.strict&&/Restarting|Exit|unhealthy/i.test(i.stdout)&&(console.log(""),console.log(s.red("One or more infra containers are not healthy.")),console.log(s.gray(`Inspect logs with: docker logs workspai-postgres (or redis/mailpit)
|
|
145
145
|
`)),process.exit(1));}catch(o){console.error(s.red(`
|
|
146
146
|
\u274C ${o instanceof Error?o.message:String(o)}
|
|
147
|
-
`)),process.exit(1);}});}function Dd(t){try{let e=j.join(t,"Makefile");return _.existsSync(e)?_.readFileSync(e,"utf8"):""}catch{return ""}}function dt(t,e){let r=Dd(t);return r?new RegExp(`^${e}\\s*:`,"m").test(r):false}var $o=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}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,r,o=3){let n=[],a=[{dir:e,depth:0}],i=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;a.length>0;){let c=a.shift();if(!c||c.depth>o)continue;let
|
|
147
|
+
`)),process.exit(1);}});}function Dd(t){try{let e=j.join(t,"Makefile");return _.existsSync(e)?_.readFileSync(e,"utf8"):""}catch{return ""}}function dt(t,e){let r=Dd(t);return r?new RegExp(`^${e}\\s*:`,"m").test(r):false}var $o=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}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,r,o=3){let n=[],a=[{dir:e,depth:0}],i=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;a.length>0;){let c=a.shift();if(!c||c.depth>o)continue;let d=[];try{d=_.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let l of d){let f=j.join(c.dir,l.name);if(l.isDirectory()){i.has(l.name)||a.push({dir:f,depth:c.depth+1});continue}l.name.toLowerCase().endsWith(r.toLowerCase())&&n.push(f);}}return n.sort()}findProjectFile(e){let r=this.findFilesBySuffix(e,".csproj");return r.find(o=>!o.toLowerCase().includes(".tests.csproj"))||r[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(o=>o.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let r=await this.ensureDotnetInstalled(e);return r||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=await this.run("dotnet",o?["restore",o]:["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 r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=o?["watch","--project",o,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",o?["test",o]:["test"],e)}async runBuild(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["build",o,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["run","--project",o]:["run"],e)}async runLint(e){if(!b$3()&&dt(e,"lint"))return this.run("make",["lint"],e);let r=j.join(e,"Directory.Build.props");if(_.existsSync(r)&&_.readFileSync(r,"utf-8").includes("EnforceCodeStyleInBuild")){let o=await this.ensureDotnetInstalled(e);if(o)return o;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(!b$3()&&dt(e,"format"))return this.run("make",["format"],e);let r=await this.ensureDotnetInstalled(e);return r||(_.existsSync(j.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 No=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}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 r=j.join(e,"main.go");if(_.existsSync(r))return "./main.go";let o=j.join(e,"cmd");try{let n=_.readdirSync(o,{withFileTypes:true}).filter(a=>a.isDirectory()).map(a=>a.name).sort();for(let a of n)if(_.existsSync(j.join(o,a,"main.go")))return `./cmd/${a}`}catch{}return "./."}findWorkspaceRoot(e){let r=e;for(;;){if(_.existsSync(j.join(r,".workspai-workspace"))||_.existsSync(j.join(r,".rapidkit-workspace")))return r;let o=j.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>_.existsSync(a));if(!n)return "isolated";try{let c=_.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,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?j.join(n||e,".workspai","cache","go"):j.join(e,".workspai","cache","go"),i=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=j.join(a,"mod"),process.env.GOCACHE=j.join(a,"build"),r().finally(()=>{typeof i>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=i,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&&_.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&_.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 r=await this.ensureGoInstalled(e);return r||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let r=await this.ensureGoInstalled(e);if(r)return r;let o=j.join(e,"Makefile");return !b$3()&&_.existsSync(o)?this.run("make",["run"],e):this.run("go",["run",this.findGoRunTarget(e)],e)})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let o=(b$3()?[j.join(e,"server.exe"),j.join(e,"server")]:[j.join(e,"server")]).find(a=>_.existsSync(a));if(o)return this.run(o,[],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 r=await this.ensureGoInstalled(e);return r||(!b$3()&&dt(e,"lint")?this.run("make",["lint"],e):_.existsSync(j.join(e,".golangci.yml"))||_.existsSync(j.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 r=await this.ensureGoInstalled(e);return r||(!b$3()&&dt(e,"fmt")?this.run("make",["fmt"],e):!b$3()&&dt(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 To=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return (_.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return _.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let r=process.env.JAVA_HOME?.trim();if(!r)return "java";let o=j.join(r,"bin",process.platform==="win32"?"java.exe":"java");return _.existsSync(o)?o:"java"}parseMajorJavaVersion(e){if(!e)return null;let o=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(o,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let r=j.join(e,"pom.xml");if(!_.existsSync(r))return 21;try{let n=_.readFileSync(r,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,r){try{let o=await execa(e,["-version"],{cwd:r,timeout:5e3,reject:false});if(o.exitCode!==0)return null;let n=`${o.stdout||""}
|
|
148
148
|
${o.stderr||""}`,a=n.match(/version\s+"([^"]+)"/i);if(a?.[1])return this.parseMajorJavaVersion(a[1]);let i=n.match(/(?:openjdk|java)\s+(\d+(?:[._]\d+)?)/i);return i?.[1]?this.parseMajorJavaVersion(i[1]):null}catch{return null}}parseMavenVersion(e){if(!e)return null;let r=e.match(/Apache Maven\s+(\d+)\.(\d+)\.(\d+)/i);return r?[Number.parseInt(r[1],10),Number.parseInt(r[2],10),Number.parseInt(r[3],10)]:null}isMavenVersionAtLeast(e,r){for(let o=0;o<3;o+=1){if(e[o]>r[o])return true;if(e[o]<r[o])return false}return true}async checkSystemMavenVersion(e){try{let r=await execa("mvn",["-version"],{cwd:e,timeout:5e3,reject:false});if(r.exitCode!==0)return {exitCode:r.exitCode||1,message:"Maven is required and must be available on PATH (3.9+)."};let o=this.parseMavenVersion(`${r.stdout||""}
|
|
149
|
-
${r.stderr||""}`);return o?this.isMavenVersionAtLeast(o,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${o.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 r=_.existsSync(j.join(e,"pom.xml")),o=_.existsSync(j.join(e,"mvnw"))||_.existsSync(j.join(e,"mvnw.cmd")),n=_.existsSync(j.join(e,"build.gradle"))||_.existsSync(j.join(e,"build.gradle.kts"))||_.existsSync(j.join(e,"settings.gradle"))||_.existsSync(j.join(e,"settings.gradle.kts")),a=_.existsSync(j.join(e,"gradlew"))||_.existsSync(j.join(e,"gradlew.bat"));return {hasMavenProject:r||o,hasMavenWrapper:o,hasGradleProject:n||a,hasGradleWrapper:a}}findWorkspaceRoot(e){let r=e;for(;;){if(_.existsSync(j.join(r,".workspai-workspace"))||_.existsSync(j.join(r,".rapidkit-workspace")))return r;let o=j.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>_.existsSync(a));if(!n)return "isolated";try{let c=_.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 r=j.join(e,"mvnw.cmd");if(process.platform==="win32"&&_.existsSync(r))return {command:r,baseArgs:[]};let o=j.join(e,"mvnw");return _.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let r=j.join(e,"gradlew.bat");if(process.platform==="win32"&&_.existsSync(r))return {command:r,baseArgs:[]};let o=j.join(e,"gradlew");return _.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let r=[],o=new Set,n=[e];for(;n.length>0;){let a=n.shift();if(!a||o.has(a))continue;o.add(a);let i=[];try{i=_.readdirSync(a,{withFileTypes:true});}catch{continue}for(let c of i){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let p=j.join(a,c.name),d=this.inspectJavaProject(p);(d.hasMavenProject||d.hasGradleProject)&&r.push(p),n.push(p);}}return r}withJavaCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?j.join(n||e,".workspai","cache","java","m2"):j.join(e,".workspai","cache","java","m2"),i=o==="shared-runtime-caches"?j.join(n||e,".workspai","cache","java","gradle"):j.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,p=process.env.GRADLE_USER_HOME,d=`-Dmaven.repo.local=${a}`;return process.env.MAVEN_OPTS=c?`${c} ${d}`:d,process.env.GRADLE_USER_HOME=i,r().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof p>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=p;})}async runBuildTool(e,r,o=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:a}=this.buildToolCommand(e),i=await this.runCommand(n,[...a,...r],e);if(i===0||!o)return {exitCode:i};let c=_.existsSync(j.join(e,"pom.xml")),p=_.existsSync(j.join(e,"build.gradle"))||_.existsSync(j.join(e,"build.gradle.kts"));return {exitCode:i,message:c||p?"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 r=[j.join(e,"target"),j.join(e,"build","libs")];for(let o of r){if(!_.existsSync(o))continue;let a=_.readdirSync(o).filter(i=>i.toLowerCase().endsWith(".jar")).find(i=>!i.toLowerCase().endsWith("-sources.jar")&&!i.toLowerCase().endsWith("-javadoc.jar")&&!i.toLowerCase().endsWith("-plain.jar"));if(a)return j.join(o,a)}return null}commandArgsFor(e,r){if(e==="gradle"){let o=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return r==="init"?[...o,"dependencies"]:r==="dev"?[...o,"bootRun"]:r==="test"?[...o,"test"]:[...o,"bootJar"]}return r==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:r==="dev"?["spring-boot:run"]:r==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),r=this.resolveJavaCommand(e),o=await this.runCommand(r,["-version"],e);if(o!==0)return {exitCode:o,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),p=await this.detectInstalledJavaMajor(r,e);if(p!==null&&p<c)return {exitCode:1,message:`Detected Java ${p}, but project requires Java ${c}+.`};let d=j.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&_.existsSync(d))try{let m=_.readFileSync(d,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),w=this.parseMajorJavaVersion(m?.[1]);if(w!==null&&w<c)return {exitCode:1,message:`Detected JAVA_HOME version ${w}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),p=c==="gradle"?["--version"]:["-version"],d=await this.runBuildTool(e,p);return d.exitCode!==0?d:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):d}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let p=c.reduce((m,w)=>Math.max(m,this.readRequiredJavaMajor(w)),0);if(p>0){let m=await this.detectInstalledJavaMajor(r,e);if(m!==null&&m<p){let w=c.filter(y=>this.readRequiredJavaMajor(y)>m).map(y=>j.relative(e,y)).join(", ");return {exitCode:1,message:`Detected Java ${m}, but workspace project(s) [${w}] require Java ${p}+.`}}}let d=false,f=false;for(let m of c){let w=this.inspectJavaProject(m);w.hasMavenProject&&!w.hasMavenWrapper&&(d=true),w.hasGradleProject&&!w.hasGradleWrapper&&(f=true);}if(d){let m=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(m!==0)return {exitCode:m,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 w=await this.checkSystemMavenVersion(e);if(w.exitCode!==0)return w}if(f){let m=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(m!==0)return {exitCode:m,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 a=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(a===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return i===0?{exitCode:0}:{exitCode:a||i||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 r=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return r&&_.mkdirSync(r,{recursive:true}),process.env.GRADLE_USER_HOME&&_.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 r=this.resolveJarPath(e);if(r)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",r],e)};let o=await this.runBuild(e);if(o.exitCode!==0)return o;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(dt(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let r=j.join(e,"pom.xml");if(_.existsSync(r)){let o=_.readFileSync(r,"utf-8");if(o.includes("spotless-maven-plugin"))return this.runBuildTool(e,["spotless:check"]);if(o.includes("checkstyle"))return this.runBuildTool(e,["checkstyle:check"])}return {exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){if(dt(e,"format"))return {exitCode:await this.runCommand("make",["format"],e)};let r=j.join(e,"pom.xml");return _.existsSync(r)&&_.readFileSync(r,"utf-8").includes("spotless-maven-plugin")?this.runBuildTool(e,["spotless:apply"]):["build.gradle","build.gradle.kts"].map(n=>j.join(e,n)).filter(n=>_.existsSync(n)).some(n=>_.readFileSync(n,"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 Maven/Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run npx workspai init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var Mo=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}findWorkspaceRoot(e){let r=e;for(;;){if(_.existsSync(j.join(r,".workspai-workspace"))||_.existsSync(j.join(r,".rapidkit-workspace")))return r;let o=j.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>_.existsSync(a));if(!n)return "isolated";try{let c=_.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,r,o){let n=this.resolveDependencyMode(e),a=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=n==="isolated"?j.join(e,".workspai","cache","node"):j.join(a||e,".workspai","cache","node"),c=process.env.npm_config_cache,p=process.env.npm_config_store_dir,d=process.env.RAPIDKIT_DEP_SHARING_MODE,f=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,a&&(process.env.RAPIDKIT_WORKSPACE_PATH=a),r==="pnpm"?(process.env.npm_config_store_dir=j.join(i,"pnpm-store"),process.env.npm_config_cache=j.join(i,"pnpm-cache")):r==="yarn"?process.env.npm_config_cache=j.join(i,"yarn-cache"):process.env.npm_config_cache=j.join(i,"npm-cache"),o().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof p>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=p,typeof d>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=d,typeof f>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=f;})}detectPackageManager(e){if(_.existsSync(j.join(e,"package-lock.json")))return "npm";if(_.existsSync(j.join(e,"pnpm-lock.yaml")))return "pnpm";if(_.existsSync(j.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 _.existsSync(j.join(e,"package-lock.json"))||_.existsSync(j.join(e,"pnpm-lock.yaml"))||_.existsSync(j.join(e,"yarn.lock"))}availablePackageManagers(e){let r=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[r]:[r,...["npm","pnpm","yarn"].filter(n=>n!==r&&this.commandAvailable(n))]}commandAvailable(e){let r=e$a(e);return spawnSync(r.command,[...r.prefixArgs,"--version"],{stdio:"ignore",shell:c$e(),env:g$8()}).status===0}scriptArgs(e,r){return e==="npm"?["run-script",r,"--foreground-scripts"]:["run",r]}async runScriptWithFallback(e,r){let o={exitCode:1};for(let n of this.availablePackageManagers(e))if(o=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,r),e)),o.exitCode===0)return o;return o}async runLifecycle(e,r){let o=i$3(e),n=j$4(e,o),a=t$1(e,r,{framework:n.key});return a?this.runScriptWithFallback(e,a.scriptName):{exitCode:1,message:`No npm script available for \`${r}\`. Add a "${r}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let r=this.detectPackageManager(e);return this.withDependencyEnv(e,r,async()=>{try{return process.env.npm_config_cache&&_.mkdirSync(process.env.npm_config_cache,{recursive:true}),r==="pnpm"&&process.env.npm_config_store_dir&&_.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 r=this.detectPackageManager(e),o=this.resolveDependencyMode(e),n=o==="shared-runtime-caches"||o==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,r,()=>this.run(r,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 Do=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,r){return {exitCode:await this.withPythonCacheEnv(r,()=>this.runCore(e,r))}}findWorkspaceRoot(e){let r=e;for(;;){if(_.existsSync(j.join(r,".workspai-workspace"))||_.existsSync(j.join(r,".rapidkit-workspace")))return r;let o=j.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>_.existsSync(a));if(!n)return "isolated";try{let c=_.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,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?j.join(n||e,".workspai","cache","python"):j.join(e,".workspai","cache","python"),i=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=j.join(a,"pip"),process.env.POETRY_CACHE_DIR=j.join(a,"poetry"),r().finally(()=>{typeof i>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=i,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),r=await this.run(["doctor","check"],e);return r.exitCode===0?r: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 workspai doctor workspace" for a full workspace scan.','Use "npx workspai init" after adding or changing modules.',"Use `npx workspai <command>` from the project root to avoid environment drift."]}};var Lo=class{constructor(e){this.runCommand=e;}runCommand;runtime="php";async run(e,r,o){let n=await this.runCommand(e,r,o);return n===0?{exitCode:n}:{exitCode:n,message:`PHP lifecycle command failed (${e} ${r.join(" ")}). Ensure ${e} is available on PATH, then review composer.json and the command diagnostics above.`}}hasComposer(e){return _.existsSync(j.join(e,"composer.json"))}hasArtisan(e){return _.existsSync(j.join(e,"artisan"))}hasComposerScript(e,r){try{let o=JSON.parse(_.readFileSync(j.join(e,"composer.json"),"utf8"));return !!o.scripts&&Object.prototype.hasOwnProperty.call(o.scripts,r)}catch{return false}}missingManifest(){return {exitCode:1,message:"composer.json was not found. Run the command from a PHP project root."}}unsupported(e){return {exitCode:1,message:`No deterministic PHP ${e} command was detected. Add a "${e}" Composer script or the expected Laravel tooling.`}}async checkPrereqs(){let e=await this.run("php",["--version"],process.cwd());return e.exitCode!==0?e:this.run("composer",["--version"],process.cwd())}async initProject(e){return this.hasComposer(e)?this.run("composer",["install","--no-interaction"],e):this.missingManifest()}async runDev(e){return this.hasComposerScript(e,"dev")?this.run("composer",["run-script","dev"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("dev")}async runTest(e){return this.hasArtisan(e)?this.run("php",["artisan","test"],e):this.hasComposerScript(e,"test")?this.run("composer",["run-script","test"],e):this.unsupported("test")}async runBuild(e){return this.hasComposerScript(e,"build")?this.run("composer",["run-script","build"],e):this.unsupported("build")}async runStart(e){return this.hasComposerScript(e,"start")?this.run("composer",["run-script","start"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("start")}async runLint(e){for(let r of ["lint","analyse","analyze"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return this.unsupported("lint")}async runFormat(e){for(let r of ["format","fmt"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return _.existsSync(j.join(e,"vendor","bin","pint"))||_.existsSync(j.join(e,"pint.json"))?this.run("php",["vendor/bin/pint"],e):this.unsupported("format")}async doctorHints(e){return ["Install a supported PHP release and Composer, then keep both on PATH.","Commit composer.lock for deterministic application installs.","Expose test, lint, format, and build commands as Composer scripts when the framework does not provide them."]}};var Fo=class{constructor(e){this.runCommand=e;}runCommand;runtime="rust";async run(e,r){let o=await this.runCommand("cargo",e,r);return o===0?{exitCode:o}:{exitCode:o,message:`Cargo command failed (cargo ${e.join(" ")}). Ensure the stable Rust toolchain and cargo are available on PATH, then review Cargo.toml and the command diagnostics above.`}}hasManifest(e){return _.existsSync(j.join(e,"Cargo.toml"))}missingManifest(){return {exitCode:1,message:"Cargo.toml was not found. Run the command from a Rust project root."}}async checkPrereqs(){return this.run(["--version"],process.cwd())}async initProject(e){return this.hasManifest(e)?this.run(["fetch"],e):this.missingManifest()}async runDev(e){return this.hasManifest(e)?this.run(["run"],e):this.missingManifest()}async runTest(e){return this.hasManifest(e)?this.run(["test","--all-targets"],e):this.missingManifest()}async runBuild(e){return this.hasManifest(e)?this.run(["build","--release"],e):this.missingManifest()}async runStart(e){return this.hasManifest(e)?this.run(["run","--release"],e):this.missingManifest()}async runLint(e){return this.hasManifest(e)?this.run(["clippy","--all-targets","--all-features","--","-D","warnings"],e):this.missingManifest()}async runFormat(e){return this.hasManifest(e)?this.run(["fmt","--all"],e):this.missingManifest()}async doctorHints(e){return ["Install the Rust toolchain with rustup and ensure cargo is on PATH.","Use Cargo.lock for deterministic application builds.","Install rustfmt and clippy components for format and lint lifecycle commands."]}};function Jd(){let t={...process.env},e=t.PATH||"";if(e){let r=e.split(j.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(j.delimiter);t.PATH=r;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||i$9(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ke(t,e){return t==="go"?new No((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="node"?new Mo((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="java"?new To((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="dotnet"?new $o((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="rust"?new Fo((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="php"?new Lo((r,o,n)=>e.runCommandInCwd(r,o,n)):new Do((r,o)=>e.runCoreRapidkit(r,{cwd:o,env:Jd()}))}var Zc=j.join(Tn.homedir(),".workspai","cache"),el=1440*60*1e3;function is(){let t=g$3("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?j.join(Zc,`vitest-${e}`):Zc}var Jo=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 j.join(is(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let r=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${r}.tmp`}async get(e,r="1.0"){let o=this.memoryCache.get(e);if(o&&o.version===r&&Date.now()-o.timestamp<el)return f.debug(`Cache hit (memory): ${e}`),o.data;try{let n=this.getCachePath(e),a=await promises.readFile(n,"utf-8"),i=JSON.parse(a);if(i.version===r&&Date.now()-i.timestamp<el)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,i),i.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,r,o="1.0"){let n={data:r,timestamp:Date.now(),version:o};this.memoryCache.set(e,n);try{await promises.mkdir(is(),{recursive:true});let a=this.getCachePath(e),i=this.getTempCachePath(a);await promises.writeFile(i,JSON.stringify(n),"utf-8"),await promises.rename(i,a),f.debug(`Cache set: ${e}`);}catch(a){f.debug(`Cache write failed: ${e}`,a);}}async invalidate(e){this.memoryCache.delete(e);try{let r=this.getCachePath(e);await promises.unlink(r),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=is(),r=await promises.readdir(e);await Promise.all(r.map(o=>promises.unlink(j.join(e,o)))),f.debug("Cache cleared");}catch{}}};var Ir=["list","sync","registry","foundation","intelligence","model","snapshot","diff","impact","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp","policy","contract","share","export","archive","hydrate","import","connect","run","init"],Vo=["intelligence","model","snapshot","diff","impact","contract","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp"];function tl(t){return Vo.includes(t)}var rl="workspai-project-entry-capability-v1";var cs="workspai-cli-runtime-command-inventory-v1",Ko=[...l$2,"autopilot","pipeline","import","adopt","goal","agent","snapshot","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands","create","project"],ls=["bootstrap","setup","cache","mirror"],Uo="create",Ud=[...ls,Uo],Hd={bootstrap:"Bootstrap project or workspace dependencies through runtime-aware setup rules.",setup:"Prepare a selected runtime toolchain through the supported adapter boundary.",cache:"Inspect or clear Workspai cache state through the managed cache boundary.",mirror:"Coordinate supported mirror lifecycle operations for the current project.",create:"Create a supported workspace or project through the canonical planner boundary."},Ho=[["ai","generate-embeddings"],["ai","info"],["ai","recommend"],["ai","update-embeddings"],["agent","bootstrap"],["config","ai"],["config","remove-api-key"],["config","set-api-key"],["config","show"],["infra","down"],["infra","plan"],["infra","status"],["infra","up"],["product","manifest"],["product","manifest","create"],["product","plan"],["project","commands"],["project","agent-entry"],["project","coverage"],["project","workspace"],["project","archives"],["project","archive"],["project","restore"],["project","delete"],["snapshot","create"],["snapshot","inspect"],["snapshot","list"],["snapshot","restore"]];function Bd(t,e,r,o){let n=new Set(t),a=new Set(e),i=t.filter(w=>!a.has(w)).sort(),c=e.filter(w=>!n.has(w)).sort(),p=new Set(r),d=new Set(o),f=r.filter(w=>!d.has(w)).sort(),m=o.filter(w=>!p.has(w)).sort();return {ok:i.length===0&&c.length===0&&f.length===0&&m.length===0,registeredButUndeclared:i,declaredButUnregistered:c,registeredScopedButUndeclared:f,declaredScopedButUnregistered:m}}function ol(t,e=[]){return t.commands.flatMap(r=>{let o=r.name(),n=[...e,o];return [{path:n,command:o,parent:e.length>0?e.join(" "):null,registrationKind:"commander",aliases:r.aliases?.()??[],description:r.description?.()??"",hidden:r._hidden===true,arguments:(r.registeredArguments??[]).map(i=>({name:i.name(),required:i.required,variadic:i.variadic})),options:(r.options??[]).map(i=>({flags:i.flags,attributeName:i.attributeName?.()??null}))},...ol(r,n)]})}function nl(t){let e=ol(t),r=e.filter(c=>c.path.length===1).map(c=>c.command),o=new Set(r),n=Ud.filter(c=>!o.has(c)).map(c=>({path:[c],command:c,parent:null,registrationKind:"manual-handler",aliases:[],description:Hd[c],hidden:false,arguments:[],options:[]})),a=[...e,...n].sort((c,p)=>c.path.join(" ").localeCompare(p.path.join(" "))),i=[...new Set(a.filter(c=>c.path.length===1).map(c=>c.command))].sort();return {schemaVersion:cs,commands:a,topLevelCommands:i,integrity:Bd(i,Ko,e.filter(c=>c.path.length>1).map(c=>c.path.join(" ")),Ho.map(c=>c.join(" ")))}}function sl(t){return `CLI command surface integrity violation (${[t.registeredButUndeclared.length>0?`registered but undeclared: ${t.registeredButUndeclared.join(", ")}`:null,t.declaredButUnregistered.length>0?`declared but unreachable: ${t.declaredButUnregistered.join(", ")}`:null,t.registeredScopedButUndeclared.length>0?`registered scoped but undeclared: ${t.registeredScopedButUndeclared.join(", ")}`:null,t.declaredScopedButUnregistered.length>0?`declared scoped but unreachable: ${t.declaredScopedButUnregistered.join(", ")}`:null].filter(r=>r!==null).join("; ")})`}var qd={"--workspace":"Use an explicit workspace root instead of the nearest workspace.","--json":"Emit machine-readable JSON.","--strict":"Return a non-zero exit when governed evidence blocks the result.","--for-agent":"Build output for an agent surface (for example codex, copilot, or cursor).","--include-paths":"Include absolute filesystem paths.","--include-evidence":"Read and include referenced evidence metadata.","--scan-depth":"Set the bounded observable-project discovery depth.","--cache":"Reuse the model cache when the structural inputs are unchanged.","--refresh-graph":"Bypass the compatible persisted graph and rebuild from live sources.","--incremental":"Reuse unchanged projects and rebuild affected graph relations.","--write":"Persist the command artifact under .workspai/reports.","--scope":"Limit the operation to a bounded scope such as project:<name>.","--dry-run":"Preview the operation without applying writes.","--preset":"Select the generated agent customization preset.","--refresh-context":"Rebuild agent context before synchronization.","--refresh":"Refresh the underlying registry or context before reading it.","--agent-sync":"Synchronize agent grounding after writing the context artifact.","--no-agent-sync":"Do not synchronize agent grounding after writing context.","--target":"Select one or more agent customization targets.","--experimental-hooks":"Generate advisory VS Code agent hook design files.","--hydrate-prompts":"Add workspace-specific verification steps to supported prompts.","--project-grounding":"Select the project entrypoint policy: managed, local, or off.","--ci":"Produce a CI-oriented command plan.","--from":"Read the specified baseline, report, or graph artifact.","--from-impact":"Read the specified impact report for verification.","--output":"Write the requested export or report to this path.","--limit":"Bound graph query results (1\u2013100).","--once":"Build the initial observed state and exit.","--graph-stream":"Emit graph snapshot/delta events as NDJSON.","--force":"Replace an existing generated target where supported.","--no-doctor":"Exclude Doctor evidence from a share bundle.","--no-blueprint":"Exclude the reproducibility blueprint from a share bundle.","--include-env":"Include private environment files in an export archive.","--archive-compression":"Select the archive compression format.","--max-download-size":"Bound a remote archive download.","--max-expanded-size":"Bound the expanded archive size.","--download-timeout-ms":"Bound remote archive download time.","--allow-private-network":"Allow private-network archive sources explicitly.","--affected":"Run only projects affected by the selected Git change.","--blast-radius":"Include transitive downstream dependents.","--since":"Select the Git baseline used for affected-project discovery.","--parallel":"Run selected projects concurrently.","--max-workers":"Bound concurrent project workers.","--continue-on-error":"Continue remaining projects after a project failure.","--reuse-passed":"Reuse successful project-stage results where safe.","--no-gates":"Skip Doctor and Readiness pre-run gates.","--allow-breaking":"Allow a verified goal to use breaking dependency changes.","--allow-force":"Allow a verified goal to use force-based repair commands.","--card":"Select the dashboard card whose governed remediation actions should be repaired.","--action-id":"Select one exact governed remediation action.","--project":"Limit the repair transaction to one registered project name.","--proposal":"Read a bounded model repair proposal from a JSON file inside the workspace.","--transaction":"Select one durable repair transaction by id.","--approved-by":"Record the local actor approving the immutable repair plan.","--decision":"Submit one of the exact options exposed by a decision-required transaction.","--max-risk":"Set the maximum approved repair risk: safe, guarded, or invasive.","--no-auto-rollback":"Require a decision instead of automatically restoring a failed transaction.","--no-build":"Do not require build validation for the selected verified goal.","--no-tests":"Do not require test validation for the selected verified goal.","--no-run":"Read current goal evidence without executing verification commands.","--reuse-intelligence":"Reuse a just-completed canonical intelligence run while executing goal-specific checks."},Or={list:{usage:"workspai workspace list [--json]",summary:"List registered Workspai workspaces.",flags:["--json"],examples:["workspai workspace list","workspai workspace list --json"]},intelligence:{usage:"workspai workspace intelligence run [--for-agent <agent>] [--strict] [--json]",summary:"Run the canonical Workspace Intelligence chain in contract order.",flags:["--workspace","--json","--strict","--for-agent"],subactions:["run"],artifact:e$1.intelligenceRun,examples:["workspai workspace intelligence run --strict","workspai workspace intelligence run --for-agent codex --json"]},model:{usage:"workspai workspace model [--cache|--incremental] [--write] [--strict] [--json]",summary:"Build the canonical workspace model from registered and observed sources.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--cache","--incremental","--write","--strict"],artifact:e$1.model,examples:["workspai workspace model --write --json","workspai workspace model --incremental --write --json"]},"agent-sync":{usage:"workspai workspace agent-sync [--for-agent <agent>] [--target <targets>] [--project-grounding <mode>] [--write]",summary:"Synchronize bounded workspace grounding for supported agent surfaces.",flags:["--workspace","--json","--scope","--for-agent","--write","--dry-run","--strict","--preset","--refresh-context","--refresh","--target","--experimental-hooks","--hydrate-prompts","--project-grounding"],artifact:e$1.agentCustomizationPack,examples:["workspai workspace agent-sync --target all --write --strict","workspai workspace agent-sync --for-agent copilot --dry-run --json"]},"remediation-plan":{usage:"workspai workspace remediation-plan [--ci] [--write] [--json]",summary:"Build a governed repair plan from current workspace evidence.",flags:["--workspace","--json","--include-paths","--ci","--write"],artifact:i$2.artifactRemediationPlan,examples:["workspai workspace remediation-plan --write --json","workspai workspace remediation-plan --ci --json"]},repair:{usage:"workspai workspace repair <capabilities|plan|propose|approve|decide|execute|resume|status|list|rollback|cancel> [--transaction <id>] [--json]",summary:"Run a durable, approval-bound repair transaction through checkpoint, validation, canonical verification, and rollback.",flags:["--workspace","--json","--card","--action-id","--project","--proposal","--transaction","--approved-by","--decision","--max-risk","--allow-breaking","--allow-force","--no-auto-rollback"],subactions:["capabilities","plan","propose","approve","decide","execute","resume","status","list","rollback","cancel"],artifact:e$1.repairTransaction,examples:["workspai workspace repair capabilities --json","workspai workspace repair plan --card doctor --project api --json","workspai workspace repair propose --proposal .workspai/repair/inbox/proposal.json --json","workspai workspace repair approve --transaction repair_123 --approved-by local-user --json","workspai workspace repair decide --transaction repair_123 --decision approve-invasive --json","workspai workspace repair execute --transaction repair_123 --json","workspai workspace repair rollback --transaction repair_123 --json"]},context:{usage:"workspai workspace context [--for-agent <agent>] [--scope <scope>] [--write] [--json]",summary:"Build a bounded, evidence-backed context pack for people and agents.",flags:["--workspace","--json","--for-agent","--scope","--include-evidence","--scan-depth","--write","--agent-sync","--no-agent-sync","--preset","--target","--strict","--project-grounding"],artifact:e$1.agentContext,examples:["workspai workspace context --for-agent codex --write --json","workspai workspace context --scope project:api --json"]},snapshot:{usage:"workspai workspace snapshot [--json]",summary:"Persist the current model as the comparison baseline.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth"],artifact:e$1.snapshot,examples:["workspai workspace snapshot --json"]},diff:{usage:"workspai workspace diff --from <snapshot-or-model|git[:ref]> [--strict] [--json]",summary:"Compare the current model with a trusted model baseline.",flags:["--workspace","--json","--from","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:e$1.diff,examples:["workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","workspai workspace diff --from git --json"]},impact:{usage:"workspai workspace impact --from <diff> [--scope <scope>] [--strict] [--json]",summary:"Calculate the evidence-backed blast radius of the current model change.",flags:["--workspace","--json","--from","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:e$1.impact,examples:["workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json","workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --strict --json"]},verify:{usage:"workspai workspace verify [--from-impact <impact-report>] [--scope <scope>] [--strict] [--json]",summary:"Verify the selected change against contracts, gates, and current evidence.",flags:["--workspace","--json","--from-impact","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:e$1.verify,examples:["workspai workspace verify --strict --json","workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json"]},goal:{usage:"workspai workspace goal <plan|status|verify> <kind|goal-id> [--scope <scope>] [--target <percent>] [--json]",summary:"Plan, resume, and evidence-verify a durable engineering goal for people and agents.",flags:["--workspace","--json","--scope","--target","--allow-breaking","--allow-force","--no-build","--no-tests","--no-run","--reuse-intelligence"],flagDescriptions:{"--target":"Set the required test coverage percentage (0\u2013100)."},subactions:["plan","status","verify"],artifact:e$1.verifiedGoalStatus,examples:["workspai workspace goal plan release-readiness --json","workspai workspace goal plan dependency-security --scope project:api --json","workspai workspace goal plan test-coverage --scope project:web --target 75 --json","workspai workspace goal verify <goal-id> --json"]},graph:{usage:"workspai workspace graph [mode] [query|from] [to] [--json]",summary:"Build, query, prove, compare, or export the workspace graph.",flags:["--workspace","--json","--output","--from","--limit","--refresh-graph","--include-paths","--include-evidence","--scan-depth","--scope"],subactions:["emit","explain","entities","search","evidence","path","overlay","benchmark","dot","mermaid","jsonld","graphml","gexf"],examples:['workspai workspace graph search "authentication endpoint" --limit 12 --json','workspai workspace graph evidence "GET /users" --json',"workspai workspace graph mermaid"]},watch:{usage:"workspai workspace watch [--once] [--graph-stream] [--json]",summary:"Observe model changes and optionally stream graph deltas.",flags:["--workspace","--json","--once","--graph-stream","--scan-depth"],examples:["workspai workspace watch --once --json","workspai workspace watch --graph-stream"]},sync:{usage:"workspai workspace sync [--project-grounding <mode>] [--json]",summary:"Synchronize canonical workspace registration and project metadata.",flags:["--workspace","--json","--project-grounding"],examples:["workspai workspace sync --json"]},registry:{usage:"workspai workspace registry [--refresh] [--json]",summary:"Inspect the canonical workspace registry summary.",flags:["--workspace","--json","--refresh"],examples:["workspai workspace registry --refresh --json"]},foundation:{usage:"workspai workspace foundation [--force] [--json]",summary:"Create or repair the standard workspace foundation files.",flags:["--workspace","--json","--force"],examples:["workspai workspace foundation --json"]},policy:{usage:"workspai workspace policy [show|status|get|set] [key] [value] [--json]",summary:"Inspect or update workspace governance policy.",flags:["--workspace","--json"],subactions:["show","status","get","set"],examples:["workspai workspace policy get --json"]},contract:{usage:"workspai workspace contract [init|inspect|verify|graph] [--strict] [--json]",summary:"Create, inspect, verify, or project the workspace contract.",flags:["--workspace","--json","--output","--force","--strict"],subactions:["init","inspect","verify","graph"],artifact:i$2.workspaceContract,examples:["workspai workspace contract verify --strict --json","workspai workspace contract graph --json"]},share:{usage:"workspai workspace share [--output <file>] [--json]",summary:"Create a bounded, shareable workspace evidence bundle.",flags:["--workspace","--json","--output","--include-paths","--no-doctor","--no-blueprint"],examples:["workspai workspace share --output workspace-share.json --json"]},export:{usage:"workspai workspace export [--output <archive>] [--archive-compression <format>]",summary:"Export a portable workspace archive.",flags:["--workspace","--json","--output","--include-env","--archive-compression"],examples:["workspai workspace export --output workspace.tar.gz"]},archive:{usage:"workspai workspace archive <inspect|verify|doctor> <source> [safety options] [--json]",summary:"Inspect, verify, or diagnose a portable workspace archive without materializing it.",flags:["--json","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],subactions:["inspect","verify","doctor"],examples:["workspai workspace archive inspect ./workspace.tar.gz --json","workspai workspace archive verify ./workspace.tar.gz --strict --json","workspai workspace archive doctor ./workspace.tar.gz --json"]},hydrate:{usage:"workspai workspace hydrate <source> [--output <directory>] [--dry-run] [--json]",summary:"Hydrate a portable workspace into a controlled destination.",flags:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace hydrate workspace.tar.gz --output ./restored --dry-run --json"]},import:{usage:"workspai workspace import <source> [--output <directory>] [--dry-run] [--json]",summary:"Verify, materialize, register, relink, and reconcile a portable workspace archive safely.",flags:["--json","--output","--dry-run","--strict","--project-grounding","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace import workspace.tar.gz --output ./imported --json"]},connect:{usage:"workspai workspace connect [directory] [--project-grounding <mode>] [--dry-run] [--json]",summary:"Register and reconcile an existing Workspai workspace in place without moving its source.",flags:["--json","--dry-run","--project-grounding"],examples:["workspai workspace connect /path/to/existing-workspace --json"]},run:{usage:"workspai workspace run <stage> [selection and concurrency options] [--json]",summary:"Run a lifecycle stage across selected workspace projects.",flags:["--workspace","--json","--scope","--affected","--blast-radius","--since","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],subactions:["init","test","build","start","<custom-from-context>"],artifact:i$2.workspaceRunLast,examples:["workspai workspace run test --affected --blast-radius --strict","workspai workspace run build --parallel --max-workers 4 --json"]},explain:{usage:"workspai workspace explain [target] [--scope <scope>] [--write] [--json]",summary:"Explain current blockers or a selected workspace target from evidence.",flags:["--workspace","--json","--scope","--write"],artifact:e$1.explain,examples:["workspai workspace explain --write --json"]},why:{usage:"workspai workspace why [target] [--scope <scope>] [--write] [--json]",summary:"Alias the evidence-backed workspace explanation flow.",flags:["--workspace","--json","--scope","--write"],artifact:d$4,examples:["workspai workspace why readiness --json"]},trace:{usage:"workspai workspace trace --from <diff-artifact> [--write] [--json]",summary:"Trace a model change through blast radius and decision gates.",flags:["--workspace","--json","--from","--write"],artifact:e$2,examples:["workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --write --json"]},feedback:{usage:"echo '<event-json>' | workspai workspace feedback record --json",summary:"Record a structured outcome event for the workspace intelligence history.",flags:["--workspace","--json"],subactions:["record"],examples:[`echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | workspai workspace feedback record --json`]},eval:{usage:"workspai workspace eval [init|record|status|report|compare] [arguments] [--json]",summary:"Measure agent/model calls, tool use, tokens, latency, and verified outcome.",flags:["--workspace","--json","--from","--output"],subactions:["init","record","status","report","compare"],artifact:e$1.evaluationLastRun,examples:["workspai workspace eval init repair-readiness workspace-intelligence --json","workspai workspace eval report --output ./evaluation.json --json"]},mcp:{usage:"workspai workspace mcp serve",summary:"Serve bounded, read-mostly workspace evidence over stdio MCP.",flags:["--workspace","--json"],subactions:["serve"],examples:["workspai workspace mcp serve"]},init:{usage:"workspai workspace init [selection and concurrency options] [--json]",summary:"Initialize all selected projects through the workspace fleet runner.",flags:["--workspace","--json","--scope","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],artifact:i$2.workspaceRunLast,examples:["workspai workspace init --parallel --strict"]}};function ps(t){if(t)return Or[t]}function al(t){return t[0]==="workspace"&&!!ps(t[1])&&t.slice(2).some(e=>e==="--help"||e==="-h")}function il(t,e){let r=ps(e)?.flagDescriptions?.[t]??qd[t];if(!r)throw new Error(`Workspace action flag has no description: ${t}`);return r}function cl(t){let e=ps(t);if(!e)throw new Error(`Unknown workspace action: ${t}`);let r=[`Workspai workspace ${t}`,"",e.summary,"","Usage:",` ${e.usage}`];if(e.subactions&&e.subactions.length>0&&r.push("","Modes:",` ${e.subactions.join(" | ")}`),e.flags.length>0){r.push("","Options:");for(let o of e.flags){let n=il(o,t);r.push(` ${o.padEnd(24)} ${n}`.trimEnd());}}return e.artifact&&r.push("","Evidence:",` ${e.artifact}`),r.push("","Examples:",...e.examples.map(o=>` ${o}`),""),r.join(`
|
|
150
|
-
`)}var ll="rapidkit-runtime-command-surface-v1";var ds=h$3.doctorRemediationPlan.schemaVersion;var pl="workspai-workspace-intelligence-architecture-v1";var dl={autopilotRelease:h$3.autopilotReleaseLastRun.schemaVersion,workspaceList:"rapidkit-workspace-list-v1",workspaceSync:"rapidkit-workspace-sync-v1",compatibilityMatrix:h$3.compatibilityMatrix.schemaVersion,mcpDesign:h$3.workspaiMcpDesign.schemaVersion,agentHooks:h$3.agentHooks.schemaVersion,projectArchive:"rapidkit-project-archive-v1",workspaceSnapshot:"rapidkit-workspace-snapshot-v1",workspaceSnapshotV2:"rapidkit-workspace-snapshot-v2",infraPlan:h$3.infraPlan.schemaVersion,privateProductManifest:"rapidkit.private-product-manifest.v1",productFactoryPlan:"rapidkit.product-factory-plan.v1",workspaceModelCache:h$3.workspaceModelCache.schemaVersion,workspaceWatchEvent:"workspace-watch-event.v1",doctorProjectScan:"doctor-project-scan-v2",doctorWorkspaceCache:h$3.doctorWorkspaceCache.schemaVersion};var ul="project-workspace-resolution.v1";function ml(t){a$4(t,"contracts/project-workspace-resolution.v1.json","Project workspace resolution");}var us="workspai.ingestion-plan.v1",Bo="workspai.ingestion-result.v1",qo="workspai.adopt-effects.v1";var gl="contracts/ingestion-result.v1.json";function Nt(t){return {schemaVersion:us,...t}}var zd="workspai-published-contract-catalog-v1",Yd="workspace-graph-stream.v1";function $r(){return {workspaceContract:1,runtimeCommandSurface:ll,cliRuntimeCommandInventory:cs,cliOperationResult:a$C,publishedContractCatalog:zd,workspaceArchiveCapabilities:a$B,workspaceArchiveManifest:b$k,workspaceArchiveOperationResult:c$2,ingestionPlan:us,ingestionResult:Bo,adoptEffects:qo,projectEntryCapability:rl,projectWorkspaceLink:h$3.projectWorkspaceLink.schemaVersion,projectWorkspaceResolution:ul,projectContextAgent:h$3.projectContextAgent.schemaVersion,projectAgentEntry:a$A,agentBootstrapReceipt:c$c,doctorProjectEvidence:b$j,doctorWorkspaceEvidence:a$z,doctorGraphDiagnosis:d$b,doctorDiagnosis:a$y,doctorCapabilities:a$x,doctorValidation:c$b,doctorReceipt:h$3.doctorReceipt.schemaVersion,doctorSummary:e$8,projectTestCoverage:h$3.projectTestCoverage.schemaVersion,verifiedGoal:"workspai.verified-goal.v1",verifiedGoalStatus:f$3.verifiedGoalStatus,goalPack:a$w,goalAgentHandoff:b$i,goalPlanResult:c$a,goalIndex:e$7,goalLifecycleResult:g$6,workspaceIntelligenceArchitecture:pl,workspaceIntelligenceChain:a$v,workspaceIntelligenceArtifacts:f$3,cliLogEvent:c$9,freshnessMetadata:e$6,factFreshness:g$5,blockerResolution:a$u,workspaceModel:j$5,workspaceImpact:f$6,workspaceVerify:c$8,workspaceContext:a$t,workspaceDependencyGraph:b$h,workspaceKnowledgeGraph:a$s,workspaceGraphStream:Yd,workspaceKnowledgeGraphChangeOverlay:a$r,workspaceKnowledgeSearch:a$q,workspaceGraphTokenEfficiency:a$p,modelUsageEvent:a$o,workspaceIntelligenceEvaluation:b$g,workspaceIntelligenceEvaluationComparison:c$7,workspaceIntelligenceHistory:a$n,agentCustomizationPackCapabilities:c$6,agentCustomizationPackReport:f$3.agentCustomizationPack,agentReportsIndex:f$3.agentIndex,workspaceOperationalSkill:a$m,workspaceSkillsIndex:b$f,workspaceExplain:a$l,agentActionOutcome:a$k,doctorRemediationPlan:ds,doctorDependencyRepairTransaction:"workspai.doctor-dependency-repair-transaction.v1",artifactRemediationPlan:a$j,studioCardRepairCapabilities:i$6,workspaceRepairProposal:d$a,workspaceRepairCapabilities:f$5,workspaceRepairTransaction:a$i,doctorFixResult:a$h,backendImportStackParitySnapshot:"backend-import-stack-parity-v1",bootstrapCompliance:h$3.bootstrapCompliance.schemaVersion,commandCapabilities:"rapidkit-command-capabilities-v1",createPlannerCapabilities:"rapidkit-create-planner-capabilities-v1",doctorRemediationPlanLegacy:ds,extensionCliCompatibility:"rapidkit-extension-cli-compatibility.v1",infraStack:"rapidkit.infra-stack.v1",mirrorOps:h$3.mirrorOps.schemaVersion,moduleLayout:"rapidkit.module-layout.v1",moduleSupport:"rapidkit-module-support-v1",pipelineLastRun:h$3.pipelineLastRun.schemaVersion,transparencyEvidence:h$3.transparencyEvidence.schemaVersion,version:"rapidkit-version-v1",studioBlockerHandoff:"rapidkit-studio-blocker-handoff-v1",workspaceRegistry:h$3.workspaceRegistry.schemaVersion,workspaceRunLast:h$3.workspaceRunLast.schemaVersion,workspaceShareBundle:h$3.workspaceShareBundle.schemaVersion,...dl}}function zo(){let t=$r(),e={workspaceContract:"contracts/workspace-contract.v1.json",runtimeCommandSurface:"contracts/runtime-command-surface.v1.json",cliRuntimeCommandInventory:"contracts/cli-runtime-command-inventory.v1.snapshot.json",cliOperationResult:"contracts/cli-operation-result.v1.json",publishedContractCatalog:"contracts/published-contract-catalog.v1.json",workspaceArchiveCapabilities:"contracts/workspace-archive-capabilities.v1.json",workspaceArchiveManifest:"contracts/workspace-archive-manifest.v1.json",workspaceArchiveOperationResult:"contracts/workspace-archive-operation-result.v1.json",ingestionPlan:"contracts/ingestion-plan.v1.json",ingestionResult:"contracts/ingestion-result.v1.json",adoptEffects:"contracts/adopt-effects.v1.json",projectEntryCapability:"contracts/project-entry-capability.v1.json",projectWorkspaceLink:"contracts/project-workspace-link.v1.json",projectWorkspaceResolution:"contracts/project-workspace-resolution.v1.json",projectContextAgent:"contracts/workspace-intelligence/project-context-agent.v1.json",projectAgentEntry:"contracts/workspace-intelligence/project-agent-entry.v1.json",agentBootstrapReceipt:"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json",doctorProjectEvidence:"contracts/doctor-project-evidence.v1.json",doctorWorkspaceEvidence:"contracts/doctor-workspace-evidence.v1.json",doctorGraphDiagnosis:"contracts/workspace-intelligence/doctor-graph-diagnosis.v1.json",doctorDiagnosis:"contracts/workspace-intelligence/doctor-diagnosis.v1.json",doctorCapabilities:"contracts/workspace-intelligence/doctor-capabilities.v1.json",doctorValidation:"contracts/workspace-intelligence/doctor-validation.v1.json",doctorReceipt:"contracts/workspace-intelligence/doctor-receipt.v1.json",doctorSummary:"contracts/workspace-intelligence/doctor-summary.v1.json",projectTestCoverage:"contracts/project-test-coverage.v1.json",verifiedGoal:"contracts/workspace-intelligence/verified-goal.v1.json",verifiedGoalStatus:"contracts/workspace-intelligence/verified-goal-status.v1.json",goalPack:"contracts/workspace-intelligence/goal-pack.v1.json",goalAgentHandoff:"contracts/workspace-intelligence/goal-agent-handoff.v1.json",goalPlanResult:"contracts/workspace-intelligence/goal-plan-result.v1.json",goalIndex:"contracts/workspace-intelligence/goal-index.v1.json",goalLifecycleResult:"contracts/workspace-intelligence/goal-lifecycle-result.v1.json",workspaceIntelligenceArchitecture:"contracts/workspace-intelligence-architecture.v1.json",workspaceIntelligenceChain:"contracts/workspace-intelligence-chain.v1.json",workspaceIntelligenceArtifacts:null,cliLogEvent:"contracts/cli-log-event.v1.json",freshnessMetadata:null,factFreshness:"contracts/workspace-intelligence/fact-freshness.v1.json",blockerResolution:"contracts/workspace-intelligence/blocker-resolution.v1.json",workspaceModel:"contracts/workspace-intelligence/workspace-model.v1.json",workspaceImpact:"contracts/workspace-intelligence/workspace-impact.v1.json",workspaceVerify:"contracts/workspace-intelligence/workspace-verify.v1.json",workspaceContext:"contracts/workspace-intelligence/workspace-context.v1.json",workspaceDependencyGraph:"contracts/workspace-intelligence/workspace-dependency-graph.v1.json",workspaceKnowledgeGraph:"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json",workspaceGraphStream:"contracts/workspace-intelligence/workspace-graph-stream.v1.json",workspaceKnowledgeGraphChangeOverlay:"contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json",workspaceKnowledgeSearch:"contracts/workspace-intelligence/workspace-knowledge-search.v1.json",workspaceGraphTokenEfficiency:"contracts/workspace-intelligence/workspace-graph-token-efficiency.v1.json",modelUsageEvent:"contracts/workspace-intelligence/model-usage-event.v1.json",workspaceIntelligenceEvaluation:"contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",workspaceIntelligenceEvaluationComparison:"contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",workspaceIntelligenceHistory:"contracts/workspace-intelligence/workspace-intelligence-history.v1.json",agentCustomizationPackCapabilities:"contracts/agent-customization-pack.v1.json",agentCustomizationPackReport:"contracts/workspace-intelligence/agent-customization-pack-report.v1.json",agentReportsIndex:"contracts/workspace-intelligence/agent-reports-index.v1.json",workspaceOperationalSkill:"contracts/workspace-intelligence/workspace-operational-skill.v1.json",workspaceSkillsIndex:"contracts/workspace-intelligence/workspace-skills-index.v1.json",workspaceExplain:"contracts/workspace-intelligence/workspace-explain.v1.json",agentActionOutcome:"contracts/workspace-intelligence/agent-action-outcome.v1.json",doctorRemediationPlan:"contracts/doctor-remediation-plan.v2.json",doctorDependencyRepairTransaction:"contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json",artifactRemediationPlan:"contracts/artifact-remediation-plan.v1.json",studioCardRepairCapabilities:"contracts/studio-card-repair-capabilities.v1.json",workspaceRepairProposal:"contracts/workspace-intelligence/workspace-repair-proposal.v1.json",workspaceRepairCapabilities:"contracts/workspace-repair-capabilities.v1.json",workspaceRepairTransaction:"contracts/workspace-intelligence/workspace-repair-transaction.v1.json",doctorFixResult:"contracts/workspace-intelligence/doctor-fix-result.v1.json",backendImportStackParitySnapshot:"contracts/backend-import-stack-parity.snapshot.json",bootstrapCompliance:"contracts/bootstrap-compliance.v1.json",commandCapabilities:"contracts/command-capabilities.v1.json",createPlannerCapabilities:"contracts/create-planner-capabilities.v1.json",doctorRemediationPlanLegacy:"contracts/doctor-remediation-plan.v1.json",extensionCliCompatibility:"contracts/extension-cli-compatibility.v1.json",infraStack:"contracts/infra-stack.v1.json",mirrorOps:"contracts/mirror-ops.v1.json",moduleLayout:"contracts/module-layout.v1.json",moduleSupport:"contracts/module-support.v1.json",pipelineLastRun:"contracts/pipeline-last-run.v1.json",transparencyEvidence:"contracts/transparency-evidence.v1.json",version:"contracts/version.v1.json",studioBlockerHandoff:"contracts/workspace-intelligence/studio-blocker-handoff.v1.json",workspaceRegistry:"contracts/workspace-registry.v1.json",workspaceRunLast:"contracts/workspace-run-last.v1.json",workspaceShareBundle:"contracts/workspace-share-bundle.v1.json",autopilotRelease:"contracts/autopilot-release.v1.json",workspaceList:"contracts/workspace-list.v1.json",workspaceSync:"contracts/workspace-sync.v1.json",compatibilityMatrix:"contracts/compatibility-matrix.v1.json",mcpDesign:"contracts/workspace-intelligence/mcp-design.v1.json",agentHooks:"contracts/workspace-intelligence/agent-hooks.v1.json",projectArchive:"contracts/project-archive.v1.json",workspaceSnapshot:"contracts/workspace-snapshot.v1.json",workspaceSnapshotV2:"contracts/workspace-snapshot.v2.json",infraPlan:"contracts/infra-plan.v1.json",privateProductManifest:"contracts/private-product-manifest.v1.json",productFactoryPlan:"contracts/product-factory-plan.v1.json",workspaceModelCache:"contracts/workspace-model-cache.v1.json",workspaceWatchEvent:"contracts/workspace-watch-event.v1.json",doctorProjectScan:"contracts/doctor-project-scan.v2.json",doctorWorkspaceCache:"contracts/doctor-workspace-cache.v2.json"};return Object.fromEntries(Object.entries(t).map(([r,o])=>{let n=e[r];return [r,{schemaVersion:o,contractPath:n,publication:n?r==="runtimeCommandSurface"||r==="cliRuntimeCommandInventory"||r.endsWith("Capabilities")||r.endsWith("Snapshot")||r==="extensionCliCompatibility"||r==="moduleLayout"||r==="moduleSupport"?"capability-contract":"json-schema":"embedded-type",...r==="workspaceIntelligenceArtifacts"?{artifacts:Object.fromEntries(Object.keys(e$1).map(a=>[a,{path:e$1[a],schemaVersion:f$3[a],contractPath:g$4[a]}]))}:{}}]}))}var ms="rapidkit-command-capabilities-v1",fl="rapidkit-version-v1";var Xd=["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"],Qd={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},Zd={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"},eu={tauri:"desktop",electron:"desktop","vscode-extension":"extension",laravel:"api"};function tu(t){return t[Math.floor(Math.random()*t.length)]}function gs(t){let e=tu(Xd),r=j$6(t);if(r){let i=Zd[r.id]??"app";return `${e}-${i}`}let o=p$4(t);if(o)return `${e}-${eu[o.id]??"app"}`;let n=a$3(t),a=n?Qd[n.id]??"service":"app";return `${e}-${a}`}async function su(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function au(t){if(!await O.pathExists(t))return [];let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(o)for(let n of await promises.readdir(o,{withFileTypes:true})){let a=j.join(o,n.name);n.isFile()?e.push(a):n.isDirectory()&&r.push(a);}}return e}async function yl(t,e){await O.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
151
|
-
`,"utf-8");}function st(t,e){return j.isAbsolute(e)?e:j.join(t,e)}function iu(t,e){if(!e.trim()||j.isAbsolute(e)||/^[a-zA-Z]:[\\/]/.test(e))throw new Error(`Mirror artifact target must be a non-empty relative path: ${e}`);let r=j.resolve(t),o=j.resolve(r,e),n=j.relative(r,o);if(!n||n.startsWith("..")||j.isAbsolute(n))throw new Error(`Mirror artifact target escapes the managed artifact directory: ${e}`);return o}async function wl(t,e){let r=j.relative(t,e),o=t;for(let a of r.split(j.sep).slice(0,-1)){o=j.join(o,a);let i=await promises.lstat(o).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)break;if(i.isSymbolicLink())throw new Error(`Mirror artifact target traverses a symbolic link: ${o}`);if(!i.isDirectory())throw new Error(`Mirror artifact target parent is not a directory: ${o}`)}let n=await promises.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(n?.isSymbolicLink()||n&&!n.isFile())throw new Error(`Mirror artifact target must be absent or a regular file: ${e}`)}async function cu(t,e){let r=j.resolve(t),o=j.relative(r,j.resolve(e));if(!o||o.startsWith("..")||j.isAbsolute(o))throw new Error("Managed mirror directory escapes the workspace.");let n=r;for(let a of o.split(j.sep)){n=j.join(n,a);let i=await promises.lstat(n);if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Managed mirror path must contain only real directories: ${n}`)}}function lu(t,e){if(t.target)return t.target;if(t.source)return j.basename(t.source);if(t.url)try{let r=new URL(t.url).pathname,o=j.basename(r);if(o&&o!=="/")return o}catch{}return `${e}.artifact`}async function pu(t){let e=s$1(t,"trusted-sources.lock").find(o=>existsSync(o)),r=new Set(["localhost","127.0.0.1"]);if(!e)return r;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));for(let a of n)r.add(a.toLowerCase());}catch{}return r}async function du(t,e,r){await O.ensureDir(j.dirname(e)),await new Promise((o,n)=>{let i=(t.startsWith("https://")?Cl:bl).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let
|
|
152
|
-
`,"utf-8"),n}function gu(t,e){if(!e?.enabled)return {headers:{}};let r=process.env[e.hmacKeyEnv];if(!r)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let o=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(o,r).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":o}}}async function fu(t,e,r){let o=(r.algorithm||"sha256").toLowerCase(),n=st(t,r.publicKeyPath);if(!await O.pathExists(n))return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(o);c.update(i),c.end();let p=Buffer.from(r.signature,"base64"),d=c.verify(a,p),f=createHash("sha256").update(a).digest("hex");return {verified:d,algorithm:o,publicKeyPath:n,publicKeyFingerprint:f,signature:r.signature,message:d?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Attestation verification error: ${a.message}`}}}async function hu(t,e,r,o){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};let a=r.signaturePath?st(t,r.signaturePath):null;if(!a||!await O.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=r.certificatePath?st(t,r.certificatePath):null;c&&i.push("--certificate",c);let p=r.bundlePath?st(t,r.bundlePath):null;p&&i.push("--bundle",p);let d=r.keyPath?st(t,r.keyPath):null;d&&i.push("--key",d),r.identity&&i.push("--certificate-identity",r.identity),r.issuer&&i.push("--certificate-oidc-issuer",r.issuer),r.rekorUrl&&i.push("--rekor-url",r.rekorUrl),o.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let f=await execa("cosign",i,{reject:false});return f.exitCode===0?{verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${f.stderr||f.stdout||"unknown error"}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}}catch(f){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${f.message}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}}}async function yu(t,e){let r=e.algorithm||"sha256",o=st(t,e.policyPath),n=st(t,e.signaturePath),a=st(t,e.publicKeyPath);if(!await O.pathExists(o))return {verified:false,message:`Governance policy bundle not found: ${o}`,policies:null};if(!await O.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await O.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(o,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),p=await promises.readFile(a,"utf-8"),d=createVerify(r);return d.update(i),d.end(),d.verify(p,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function fs(t,e){let r=[],o={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=s$1(t,"mirror-config.json").find(W=>existsSync(W))??p(t,"mirror-config.json"),a=p(t,"mirror.lock"),i=p(t,"mirror","artifacts"),c=p(t,"reports"),p$1=await pu(t);if(!await O.pathExists(n))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:r,details:o};let d={};try{d=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return r.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:r,details:o}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||d.mode==="offline-only"))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:r,details:o};await O.ensureDir(i);try{await cu(t,i);}catch(W){return r.push({id:"mirror.root.safety",status:"failed",message:W instanceof Error?W.message:String(W)}),{checks:r,details:o}}let m=Math.max(0,d.prefetch?.retries??2),w=Math.max(0,d.prefetch?.backoffMs??250),y=Math.max(1e3,d.prefetch?.timeoutMs??15e3),P=d.security?.requireAttestation===true,S=d.security?.requireSigstore===true,l=d.security?.requireTransparencyLog===true,v=d.security?.requireSignedGovernance===true,u=d.security?.evidenceExport,h=(process.env.RAPIDKIT_ENV||d.security?.governance?.environment||"dev").toLowerCase(),g=d.security?.governance?.policies||{};if(d.security?.governanceBundle){let W=await yu(t,d.security.governanceBundle);if(r.push({id:"governance.bundle.verify",status:W.verified?"passed":"failed",message:W.message}),W.verified&&W.policies)g=W.policies,o.governanceBundleVerified=true;else if(v)return {checks:r,details:o}}let k=g[h],C=l||k?.requireTransparencyLog===true,x=[],b=Array.isArray(d.artifacts)?d.artifacts:[],E=[];for(let W=0;W<b.length;W+=1){let T=b[W],A=T.id||`artifact-${W+1}`,X=T.source?st(t,T.source):null,U=lu(T,A),q;try{q=iu(i,U),await wl(i,q);}catch(le){r.push({id:`mirror.target.${A}`,status:"failed",message:le instanceof Error?le.message:String(le)});continue}let Q=false,L=q,F=false,K=async()=>{F&&await promises.rm(L,{force:true}).catch(()=>{});},te={sourceType:"path",source:X||T.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(X&&await O.pathExists(X))await O.ensureDir(j.dirname(q)),L=`${q}.${process.pid}.${randomUUID()}.tmp`,F=true,await promises.copyFile(X,L),o.syncedArtifacts+=1,Q=true,te={sourceType:"path",source:X,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},r.push({id:`mirror.sync.${A}`,status:"passed",message:`Mirrored artifact ${A} from source path.`});else if(T.url){let le="";try{le=new URL(T.url).hostname.toLowerCase();}catch{r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Invalid URL for ${A}: ${T.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||p$1.has(le))){r.push({id:`mirror.prefetch.trust.${A}`,status:"failed",message:`Untrusted mirror host for ${A}: ${le}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await O.pathExists(q)?(Q=true,te={sourceType:"url",source:T.url,host:le,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},r.push({id:`mirror.prefetch.${A}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${A}.`})):r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${A} without an existing mirrored copy.`}),!Q))continue;if(!Q){await O.ensureDir(j.dirname(q)),L=`${q}.${process.pid}.${randomUUID()}.tmp`,F=true;let _e=null,N=0;for(let G=1;G<=m+1;G+=1){N=G;try{await promises.rm(L,{force:true}).catch(()=>{}),await du(T.url,L,y),o.syncedArtifacts+=1,Q=true,te={sourceType:"url",source:T.url,host:le,fetchedAt:new Date().toISOString(),attempts:N,trusted:true},r.push({id:`mirror.prefetch.${A}`,status:"passed",message:N>1?`Prefetched artifact ${A} from ${le} after ${N} attempts.`:`Prefetched artifact ${A} from ${le}.`});break}catch(de){if(_e=de,G<=m){await kl(w*G);continue}}}if(!Q){await K(),r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Failed to prefetch ${A} after ${m+1} attempt(s): ${_e?.message||"unknown error"}`});continue}}if(!Q){r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Failed to prefetch ${A}.`});continue}}if(!Q){T.required||e.offlineMode?r.push({id:`mirror.sync.${A}`,status:"failed",message:`Mirror source missing for ${A}${X?`: ${X}`:""}`}):r.push({id:`mirror.sync.${A}`,status:"skipped",message:`Mirror source not found for optional artifact ${A}.`});continue}let H=await su(L);if(T.sha256&&T.sha256.toLowerCase()!==H.toLowerCase()){r.push({id:`mirror.verify.${A}`,status:"failed",message:`Checksum mismatch for ${A}.`}),await K();continue}o.verifiedArtifacts+=1,r.push({id:`mirror.verify.${A}`,status:"passed",message:`Checksum verified for ${A}.`});let pe=T.attestation?await fu(t,L,T.attestation):null;if(T.attestation){if(r.push({id:`mirror.attest.${A}`,status:pe?.verified?"passed":"failed",message:pe?.message||"Attestation verification failed."}),!pe?.verified){await K();continue}}else if(P){r.push({id:`mirror.attest.${A}`,status:"failed",message:`Attestation is required but missing for ${A}.`}),await K();continue}else r.push({id:`mirror.attest.${A}`,status:"skipped",message:`No attestation provided for ${A}.`});let ue=T.attestation?.sigstore,ae=ue?await hu(t,L,ue,{requireTransparencyLog:C}):null;if(ue){if(r.push({id:`mirror.sigstore.${A}`,status:ae?.verified?"passed":"failed",message:ae?.message||"Sigstore verification failed."}),x.push({artifactId:A,verified:!!ae?.verified,tlogVerified:!!ae?.tlogVerified,identity:ae?.identity||null,issuer:ae?.issuer||null,rekorUrl:ae?.rekorUrl||null,timestamp:new Date().toISOString(),environment:h}),!ae?.verified){await K();continue}}else if(S){r.push({id:`mirror.sigstore.${A}`,status:"failed",message:`Sigstore attestation is required but missing for ${A}.`}),await K();continue}else r.push({id:`mirror.sigstore.${A}`,status:"skipped",message:`No Sigstore attestation provided for ${A}.`});if(ue&&ae?.verified&&k){let le=k.allowedIdentities||[];if(le.length>0){let _e=!!ae.identity&&le.includes(ae.identity);if(r.push({id:`mirror.sigstore.policy.identity.${A}`,status:_e?"passed":"failed",message:_e?`Sigstore identity policy passed for ${A} in ${h}.`:`Sigstore identity policy failed for ${A} in ${h}.`}),!_e){await K();continue}}let ut=k.allowedIssuers||[];if(ut.length>0){let _e=!!ae.issuer&&ut.includes(ae.issuer);if(r.push({id:`mirror.sigstore.policy.issuer.${A}`,status:_e?"passed":"failed",message:_e?`Sigstore issuer policy passed for ${A} in ${h}.`:`Sigstore issuer policy failed for ${A} in ${h}.`}),!_e){await K();continue}}let Ft=k.allowedRekorUrls||[];if(Ft.length>0){let _e=!!ae.rekorUrl&&Ft.includes(ae.rekorUrl);if(r.push({id:`mirror.sigstore.policy.rekor.${A}`,status:_e?"passed":"failed",message:_e?`Sigstore Rekor policy passed for ${A} in ${h}.`:`Sigstore Rekor policy failed for ${A} in ${h}.`}),!_e){await K();continue}}}else k&&r.push({id:`mirror.sigstore.policy.${A}`,status:"skipped",message:`Sigstore governance policy configured for ${h} but no verified Sigstore attestation for ${A}.`});F&&(await wl(i,q),await promises.rename(L,q),F=false);let ze=await promises.stat(q);E.push({id:A,path:j.relative(t,q),sha256:H,size:ze.size,provenance:te,attestation:{detached:{provided:!!T.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:!!ue,verified:ae?.verified||false,tlogVerified:ae?.tlogVerified||false,identity:ae?.identity||null,issuer:ae?.issuer||null,rekorUrl:ae?.rekorUrl||null,bundlePath:ae?.bundlePath||null,certificatePath:ae?.certificatePath||null,signaturePath:ae?.signaturePath||null,verifiedAt:ae?.verified?new Date().toISOString():null}}});}let R=d.retention?.keepLast;if(typeof R=="number"&&R>0){let W=new Set(E.map(A=>j.resolve(t,A.path))),T=(await au(i)).filter(A=>!W.has(j.resolve(A)));if(T.length>R){let A=await Promise.all(T.map(async U=>({filePath:U,stat:await promises.stat(U)})));A.sort((U,q)=>q.stat.mtimeMs-U.stat.mtimeMs);let X=A.slice(R);for(let U of X)await promises.unlink(U.filePath),o.rotatedFiles+=1;}}r.push({id:"mirror.rotate",status:"passed",message:o.rotatedFiles>0?`Mirror retention rotation removed ${o.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let $={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:d.mode||null,environment:h,artifacts:E};if(await promises.writeFile(a,`${JSON.stringify($,null,2)}
|
|
153
|
-
`,"utf-8"),o.lockWritten=true,r.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${j.relative(t,a)}.`}),o.transparencyEvidenceRecords=x.length,x.length>0){let
|
|
154
|
-
`,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=q,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${q}.`});}catch(q){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${q.message}`});}else if(u.target==="http")if(!u.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let q=Math.max(0,u.retries??0),Q=Math.max(0,u.backoffMs??500),L=gu(W,u.signing);L.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:L.error});try{let F=u.authTokenEnv?process.env[u.authTokenEnv]:void 0,K=false,te=null;for(let H=1;H<=q+1;H+=1)try{if(L.error)throw new Error(L.error);await uu(u.endpoint,W,U,F,L.headers),o.evidenceExported=true,o.evidenceExportTarget=u.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:H>1?`Transparency evidence exported to HTTP endpoint ${u.endpoint} after ${H} attempts.`:`Transparency evidence exported to HTTP endpoint ${u.endpoint}.`}),K=true;break}catch(pe){te=pe,H<=q&&await kl(Q*H);}if(!K)throw te||new Error("unknown evidence export error")}catch(F){let K=`Evidence HTTP export failed: ${F.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:K});try{let te=await mu(t,u.deadLetterPath,W,K);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${te}.`});}catch(te){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${te.message}`});}}}if(u.failOnError&&r.some(Q=>Q.status==="failed"&&(Q.id==="sigstore.evidence.export.file"||Q.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function Yo(t){let e=f$7(t.detection.runtime),r=u$1({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.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}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core 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."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"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:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function wu(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function Xo(t){if(t.existingProjectJson?.module_support===true){let e=wu(t.existingProjectJson),r=e?a$3(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}function Sl(t){return t.replace(/\\/g,"/")}function ku(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function vu(t,e){let r=Sl(j.relative(t,e));return !r||r.startsWith("..")?true:r.split("/").filter(Boolean).some(o=>o==="..")}function Nr(t){let e=Sl(j.relative(t.workspacePath,t.projectPath)),r=vu(t.workspacePath,t.projectPath),o=ku(t.projectName,j.basename(t.projectPath)),n=r?`external/${o}`:e||o;return {relativePath:e||n,contractRelativePath:n,isExternal:r}}var xl=[a$E,b$l];function Pu(t,e){let r=j.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!j.isAbsolute(r)}async function tt(t){let e=await O__default.realpath(t);for(let r of xl){let o=j.join(t,r),n=await O__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await O__default.realpath(o);if(!Pu(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function El(t){let e=j.basename(t);return xl.includes(e)?(await O__default.lstat(t)).isSymbolicLink():false}var _l={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},Cu={python:"Python",node:"Node",go:"Go",java:"Java",dotnet:".NET",php:"PHP",ruby:"Ruby",rust:"Rust",elixir:"Elixir",clojure:"Clojure",scala:"Scala",kotlin:"Kotlin",deno:"Deno",bun:"Bun",c:"C",cpp:"C++",unknown:"Unknown"},Su={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},Rl=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function ys(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function ws(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function Tr(t){if(typeof t!="string")return "unknown";let e=t.trim().toLowerCase();return e==="python"||e==="node"||e==="go"||e==="java"||e==="dotnet"||e==="php"||e==="ruby"||e==="rust"||e==="elixir"||e==="clojure"||e==="scala"||e==="kotlin"||e==="deno"||e==="bun"||e==="c"||e==="cpp"?e:e==="c++"||e==="cplusplus"||e==="cc"||e==="clang++"||e==="g++"?"cpp":e==="clang"||e==="gcc"?"c":"unknown"}function en(t){let e=new Set;for(let r of t)e.add(Tr(r));return [...e].sort((r,o)=>Rl.indexOf(r)-Rl.indexOf(o))}function xu(t){let e=en(t).filter(r=>r!=="unknown");if(e.length!==0)return e.length===1?Su[e[0]]:"polyglot"}function Al(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function Eu(t,e){return t?"none":e==="strict"?"error":"warning"}function Mr(t){let e=t.ok?void 0:xu(t.runtimes)??"polyglot";return {ok:t.ok,checkId:t.checkId,status:t.ok?"passed":"failed",profile:t.profile,runtimes:t.runtimes,message:t.message,recommendedProfile:e,recommendedCommand:e?Al(e):void 0,ciRecommendedCommand:e?Al(e,{ci:true}):void 0,severity:Eu(t.ok,t.mode)}}function Tt(t){let e=ws(t.profile),r=en(t.runtimes),o=t.mode??"warn",n=_l[e];if(n){let a=r.length===0||r.every(i=>ys(i)===n);return Mr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:r,message:a?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${r.join(", ")}].`,mode:o})}if(e==="minimal"){let a=r.filter(p=>p!=="unknown"),c=new Set(a.map(p=>ys(p))).size<=1;return Mr({ok:c,checkId:"profile.minimal",profile:e,runtimes:r,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${a.join(", ")}].`,mode:o})}return Mr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:r,message:`${e} profile accepts the detected runtime mix.`,mode:o})}function St(t){let e=ws(t.profile),r=Tr(t.runtime),o=t.mode??"warn",n=_l[e];if(!n||r==="unknown")return Mr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[r],message:r==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:o});let a=ys(r)===n;return Mr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:a?[r]:en([n,r]),message:a?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${Cu[r]}, but workspace profile is "${e}".`,mode:o})}async function ir(t){let e=(await Promise.all(s$1(t,"policies.yml").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "warn";try{return (await O__default.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function cr(t){let e=(await Promise.all(s$1(t,"workspace.json").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "minimal";try{let r=await O__default.readJson(e);return ws(r.profile)}catch{return "minimal"}}async function Mt(t$1,e={}){let r=new Set,o=[],n=new Set,a=[t$1];for(;a.length>0;){let i=a.pop();if(!i||n.has(i))continue;n.add(i);let c=[];try{c=await _.promises.readdir(i,{withFileTypes:true});}catch{continue}for(let p of c){if(!p.isDirectory()||p.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(p.name))continue;let d=j.join(i,p.name);if(d!==t$1&&j$2(d))continue;if((await Promise.all([...t(d,"context.json"),...t(d,"project.json")].map(async m=>O__default.pathExists(m)))).some(Boolean)){o.push(d);continue}a.push(d);}}for(let i of o){let c=i$3(i);r.add(Tr(j$4(i,c).runtime));}for(let i of await a$F(t$1))r.add(Tr(i.runtime));for(let i of e.additionalRuntimes??[])r.add(Tr(i));return en(r)}function tn(t,e={}){let r=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return r?`Recommended: ${r}`:null}function Il(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Au(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return Il(a)||"imported-project"}function xt(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function _u(t){return xt(t)?"git-url":"local-folder"}async function Iu(t,e){let r=Il(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=j.join(t,n);if(!await O__default.pathExists(a))return a;o+=1;}}function Ou(t,e){let r=j.resolve(t),o=j.resolve(e),n=j.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!j.isAbsolute(n)}function $u(t,e){if(Ou(t,e))throw new Error("Import source must be outside the current workspace root.")}function Nu(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function Tu(t){let e=j.basename(t);return !(await El(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||Nu(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Mu(t$1){await tt(t$1);for(let e of t(t$1,"project.json"))if(await O__default.pathExists(e))try{return await O__default.readJson(e)}catch{return null}return null}async function Wu(t){await tt(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:j.basename(t.projectPath),o=Nr({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=u(t.projectPath,"project.json"),i=u(t.projectPath,"import.json"),c=u(t.projectPath,"import-readiness.json"),p=Xo({existingProjectJson:t.existingProjectJson}),d=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],f=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},m={...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:j.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:j.basename(t.projectPath),kind:t.projectKind,category:a$d(t.projectKind),project_type:a$d(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:p,modules:d,contracts:f,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},w={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:j.basename(t.projectPath)},project:{name:m.name,slug:m.slug,relative_path:n,kind:t.projectKind,category:a$d(t.projectKind),module_support:p},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$d(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:p,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},y=Yo({projectName:String(m.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:p,projectPath:t.projectPath,generatedAt:new Date(e)});return await O__default.ensureDir(j.dirname(a)),await O__default.writeJson(a,m,{spaces:2}),await O__default.writeJson(i,w,{spaces:2}),await O__default.writeJson(c,y,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:p}}async function Du(t,e){let r={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,relationship:"imported",importedAt:new Date().toISOString()};await b$d(t,[r]);}async function Lu(t){await O__default.pathExists(t)&&(await tt(t),await O__default.remove(t));}async function Fu(t,e){await Lu(e),await c$3(t,[e]);}async function Ol(t){let e=j.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??_u(r),n=t.name??(o==="git-url"?Au(r):j.basename(r)),a=await Iu(e,n),i=false;try{if(o==="local-folder"){let h=j.resolve(r),g=await O__default.stat(h).catch(()=>null);if(!g||!g.isDirectory())throw new Error("Import source is not a directory.");if(await tt(h),j$2(h))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");$u(e,h),i=true,await O__default.copy(h,a,{overwrite:false,errorOnExist:true,filter:Tu});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$c()});await tt(a);let c=await Mu(a),p=j$4(a,c),d=await b$b(a,c),[f,m]=await Promise.all([cr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ir(e)]),w=St({profile:f,runtime:p.runtime,subjectLabel:j.basename(a),mode:m}),y=Tt({profile:f,runtimes:await Mt(e,{additionalRuntimes:[p.runtime]}),mode:m}),P=w.ok?y:w;if(!P.ok&&m==="strict")throw new Error(P.message);let S=await Wu({workspacePath:e,projectPath:a,sourceType:o,detection:p,existingProjectJson:c,projectKind:d,profileCompatibility:P}),l=Nr({workspacePath:e,projectPath:a,projectName:j.basename(a)}),v={ingestionPlan:Nt({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:j.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:j.basename(a),path:a,relativePath:l.contractRelativePath,stack:p.importStack,runtime:p.runtime,framework:p.key,frameworkDisplayName:p.displayName,supportTier:p.supportTier,moduleSupport:S.moduleSupport,confidence:p.confidence,source:o,projectJsonPath:S.projectJsonPath,importJsonPath:S.importJsonPath,importReadinessPath:S.importReadinessPath,profileCompatibility:P};await Du(e,v);let{syncWorkspaceContract:u}=await import('./workspace-contract-ACSIHJIO.js');return await u({workspacePath:e,strict:true}),await f$4({workspacePath:e,projectPath:v.path,projectName:v.name,relationship:"imported",mode:t.projectGrounding??"managed"}),v}catch(c){if(i)try{await Fu(e,a);let{syncWorkspaceContract:p}=await import('./workspace-contract-ACSIHJIO.js');await p({workspacePath:e,strict:true});}catch(p){let d=c instanceof Error?c.message:String(c),f=p instanceof Error?p.message:String(p);throw new Error(`Import failed: ${d}. Rollback also failed: ${f}`)}throw c}}function Gu(t){return {schemaVersion:qo,sourceMode:"linked",sourceCodeModified:false,projectMetadataFiles:[".workspai/project.json",".workspai/adopt.json",".workspai/adopt-readiness.json",f$2,...t==="off"?[]:[h$4,g,b$c]],repositoryControlFiles:[{path:".gitignore",action:"reconcile",condition:"machine-local workspace binding and project-grounding portability rules"},...t==="managed"?[{path:"AGENTS.md",action:"reconcile",condition:"managed grounding is enabled and the path is a regular file; authored deletions and symbolic links are preserved"},...g$1.map(e=>({path:e,action:"reconcile",condition:"managed provider adapter is enabled; authored content, deletions, symbolic links, and unsafe parent paths are preserved"}))]:[]],workspaceOperations:["register-project","sync-contract","rebuild-model","rebuild-graph","sync-agent-grounding"]}}function Ju(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Vu(t,e){return j.resolve(t)===j.resolve(e)}async function Ku(t$1){await tt(t$1);for(let e of t(t$1,"project.json")){if(!await O__default.pathExists(e))continue;let r;try{r=JSON.parse((await O__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}function Uu(t){if(!t?.adoption||typeof t.adoption!="object")return false;let e=t.adoption;return e.managed_by==="workspai"&&e.mode==="linked"}async function $l(t,e){let r=j.relative(t,e);if(r.startsWith("..")||j.isAbsolute(r))return true;let o=r.split(j.sep).slice(0,-1),n=t;for(let a of o){n=j.join(n,a);let i=await O__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)return false;if(i.isSymbolicLink()||!i.isDirectory())return true}return false}async function Hu(t){let e=j.join(t,".amazonq"),r=await O__default.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!r)return [e,j.join(e,"rules")];if(r.isSymbolicLink()||!r.isDirectory())return [];let o=j.join(e,"rules");return await O__default.lstat(o).catch(a=>{if(a.code==="ENOENT")return null;throw a})?[]:[o]}async function ks(t,e){let r=j.resolve(t),o=j.resolve(e);await tt(o);let n=[u(o,"project.json"),u(o,"adopt.json"),u(o,"adopt-readiness.json"),j.join(o,f$2),j.join(o,g),j.join(o,h$4),j.join(o,b$c),j.join(o,"AGENTS.md"),...g$1.map(a=>j.join(o,a)),j.join(o,".gitignore"),p(r,"imported-projects.json")];return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>{if(a.startsWith(`${o}${j.sep}`)&&await $l(o,a))return {path:a,contents:null,preserve:"unsafe-parent"};let i=await O__default.lstat(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});return i?.isSymbolicLink()?{path:a,contents:null,preserve:"symbolic-link"}:{path:a,contents:i?.isFile()?await O__default.readFile(a):null}})),createdAdapterDirectories:await Hu(o)}}function Nl(t,e,r){let o=[u(r,"project.json"),u(r,"adopt.json"),u(r,"adopt-readiness.json"),j.join(r,f$2),j.join(r,g),j.join(r,h$4),j.join(r,b$c),j.join(r,"AGENTS.md"),...g$1.map(a=>j.join(r,a)),j.join(r,".gitignore"),p(e,"imported-projects.json")].map(a=>j.resolve(a)),n=new Set([".amazonq",".amazonq/rules"].map(a=>j.resolve(r,a)));if(t.workspacePath!==j.resolve(e)||t.projectPath!==j.resolve(r)||t.files.length!==o.length||t.files.some((a,i)=>j.resolve(a.path)!==o[i])||t.createdAdapterDirectories.some(a=>!n.has(j.resolve(a)))||new Set(t.createdAdapterDirectories.map(a=>j.resolve(a))).size!==t.createdAdapterDirectories.length)throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function Bu(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=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,category:a$d(t.projectKind),project_type:a$d(t.projectKind),runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,framework:t.detection.key,kit:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:!t.refreshManagedDetection&&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:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function qu(t,e,r){await tt(e),Nl(r,t,e);let o=[];for(let n of r.files)try{if(n.preserve==="symbolic-link")continue;n.contents===null?await O__default.remove(n.path):(await O__default.ensureDir(j.dirname(n.path)),await O__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}for(let n of [...r.createdAdapterDirectories].reverse())try{if(await $l(e,n))continue;await O__default.rmdir(n);}catch(a){let i=a.code;i!=="ENOENT"&&i!=="ENOTEMPTY"&&o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function vs(t){let e=j.resolve(t.workspacePath),r=j.resolve(t.source),o=await O__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await tt(r),Vu(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(j$2(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t.rollbackSnapshot??await ks(e,r);Nl(n,e,r);let a=await Ku(r),i=Uu(a),c=j$4(r,i?null:a),p=i$5(r),d=[c.runtime,...p.filter(R=>R!==c.runtime)].filter((R,$,W)=>R!=="unknown"&&W.indexOf(R)===$);d.length===0&&d.push("unknown");let f=await b$b(r,a),m=Ju(t.name||(typeof a?.name=="string"?a.name:"")||j.basename(r))||"adopted-project",w=Nr({workspacePath:e,projectPath:r,projectName:m}),y=(t.now??new Date).toISOString(),P=u(r,"project.json"),S=u(r,"adopt.json"),l=u(r,"adopt-readiness.json"),v=Xo({existingProjectJson:a}),[u$1,h]=await Promise.all([cr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ir(e)]),g=St({profile:u$1,runtime:c.runtime,subjectLabel:m,mode:h}),k=Tt({profile:u$1,runtimes:await Mt(e,{additionalRuntimes:d}),mode:h}),C=g.ok?k:g;if(!C.ok&&h==="strict")throw new Error(C.message);let x=Bu({projectName:m,contractRelativePath:w.contractRelativePath,isExternal:w.isExternal,discoveredRelativePath:w.relativePath,detection:c,runtimeCandidates:d,existingProjectJson:a,refreshManagedDetection:i,projectKind:f,moduleSupport:v,adoptedAt:y}),b={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:y,managed_by:"workspai",mode:"linked",workspace:{name:j.basename(e),contract:i$2.workspaceContract},project:{name:m,relative_path:w.contractRelativePath,...w.isExternal?{}:{discovered_relative_path:w.relativePath},is_external:w.isExternal,kind:f,category:a$d(f),module_support:v},detection:{framework:c.key,framework_display_name:c.displayName,runtime:c.runtime,runtime_candidates:d,kind:f,category:a$d(f),confidence:c.confidence,support_tier:c.supportTier,import_stack:c.importStack,source:c.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:v,workspace_contract:"linked-project",profile_compatibility:{ok:C.ok,profile:C.profile,runtimes:C.runtimes,message:C.message,recommended_profile:C.recommendedProfile,recommended_command:C.recommendedCommand}}},E=Yo({projectName:m,relativePath:w.contractRelativePath,projectKind:f,source:"adopted-local",detection:c,moduleSupport:v,projectPath:r,generatedAt:new Date(y)});if(t.dryRun!==true)try{await tt(r),await O__default.ensureDir(j.dirname(P)),await O__default.writeJson(P,x,{spaces:2}),await O__default.writeJson(S,b,{spaces:2}),await O__default.writeJson(l,E,{spaces:2});let R={name:m,path:r,relativePath:w.contractRelativePath,relationship:"adopted",stack:c.importStack,runtime:c.runtime,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:v,confidence:c.confidence,source:"adopted-local",importedAt:y};await b$d(e,[R]);let{syncWorkspaceContract:$}=await import('./workspace-contract-ACSIHJIO.js');await $({workspacePath:e,strict:true}),await f$4({workspacePath:e,projectPath:r,projectName:m,relationship:"adopted",mode:t.projectGrounding??"managed",now:new Date(y)});}catch(R){try{await qu(e,r,n);let{syncWorkspaceContract:$}=await import('./workspace-contract-ACSIHJIO.js');await $({workspacePath:e,strict:true});}catch($){throw new AggregateError([R,$],`Adopt failed and rollback was incomplete: ${R instanceof Error?R.message:String(R)}`)}throw R}return {ingestionPlan:Nt({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t.projectGrounding??"managed"}),name:m,path:r,relativePath:w.relativePath,contractRelativePath:w.contractRelativePath,isExternal:w.isExternal,relationship:"adopted",stack:c.importStack,runtime:c.runtime,runtimeCandidates:d,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:v,confidence:c.confidence,projectJsonPath:P,adoptJsonPath:S,adoptReadinessPath:l,profileCompatibility:C,effects:Gu(t.projectGrounding??"managed"),wroteFiles:t.dryRun!==true}}async function zu(t){let e=await O__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=j.join(t,r),n=await O__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function Yu(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await O__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=j.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$e(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$5&&(await O__default.remove(i),e.push(j.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function Ml(t,e){if(await b$e(t,j.basename(t)),!(await g$2(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$g(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function Ps(t){let e=j.resolve(t.workspacePath);await zu(e);let r=Nt({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!j$2(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return rn(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$4(e);try{let n=await Ml(e,t.projectGrounding??"managed");return rn(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$6(e,o).catch(()=>{}),n}}async function js(t){if(t.dryRun){let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=j.resolve(o.outputPath),a=Tl(t,n);return rn(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?j.resolve(t.outputPath):void 0;if(e&&await O__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=j.resolve(o.outputPath);let n=Tl(t,r);if(!j$2(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await Yu(r);o.manifest?.portableContract&&await O__default.outputJson(j.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await Ml(r,t.projectGrounding??"managed");return rn(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,p,d)=>d.indexOf(c)===p),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$4(r).catch(()=>{}),await O__default.remove(r).catch(()=>{})),o}}function Tl(t,e){return Nt({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function rn(t,e){let r={schemaVersion:Bo,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$4(r,gl,"Workspace ingestion result"),r}function Wl(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function Dl(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function Ll(t){let e=t.trim(),r=e.startsWith("~/")?j.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!xt(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:xt(r)?r:j.resolve(r)};if(xt(r))return {kind:"git-project",source:r};let n=j.resolve(r);return j$2(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var em=Ho,tm=Ko;function Cs(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 rm(t=process.argv){let e=j.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function lr(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function om(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Oe(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function nm(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Os(t){try{return nm(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function Us(t$1,e){let r=Oe(t$1,"--port")?.trim(),o=t$1[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Oe(t$1,"--output")||".",i=j.resolve(e,a,o),c=t(i,"project.json").find(d=>_.existsSync(d))??u(i,"project.json");if(!await O__default.pathExists(c))return;let p=await O__default.readJson(c);await O__default.writeJson(c,{...p,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Gl(t){let e=be(process.cwd()),r=t.trim().toLowerCase();if(!e||!r)return true;try{let[o,n]=await Promise.all([cr(e),ir(e)]),a=a$3(r),i=j$6(r),c=p$4(r),p=i?"node":c?.runtime??a?.runtime??"python",d=St({profile:o,runtime:p,subjectLabel:r,mode:n}),f=Tt({profile:o,runtimes:await Mt(e,{additionalRuntimes:[p]}),mode:n}),m=d.ok?f:d;if(m.ok)return true;let w=tn(m);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${m.message}`)),w&&console.log(s.gray(`\u{1F4A1} ${w}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${m.message}`)),w&&console.log(s.gray(`\u{1F4A1} ${w}`));}catch{}return true}function Hs(){return j$7()}function Jl(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(j.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(j.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$9()),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 sm(t){return m$3(j.join(t,".venv"))}async function am(t,e){return await Ce(t,["--version"],e)===0}async function Lt(t){let e=j.join(t,"go.mod");if(await O__default.pathExists(e))return "go";let r=j.join(t,"pom.xml"),o=j.join(t,"build.gradle"),n=j.join(t,"build.gradle.kts");if(await O__default.pathExists(r)||await O__default.pathExists(o)||await O__default.pathExists(n))return "java";if((await O__default.pathExists(t)?await _.promises.readdir(t,{withFileTypes:true}):[]).some(y=>y.isFile()&&y.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=j.join(t,"src");if(await O__default.pathExists(i)&&(await _.promises.readdir(i,{withFileTypes:true})).some(P=>P.isFile()&&P.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=j.join(t,"Cargo.toml");if(await O__default.pathExists(c))return "rust";let p=j.join(t,"composer.json");if(await O__default.pathExists(p))return "php";let d=j.join(t,"package.json");if(await O__default.pathExists(d))return "node";let f=j.join(t,"pyproject.toml"),m=j.join(t,"requirements.txt"),w=j.join(t,"poetry.lock");return await O__default.pathExists(f)||await O__default.pathExists(m)||await O__default.pathExists(w)?"python":null}async function im(t,e={}){let r=e.runCommand??Ce;for(let o of e.pythonCandidates??Hs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function np(t,e={}){let r=e.runCommand??Ce;for(let o of e.pythonCandidates??Hs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function cm(t,e={}){let r=e.runCommand??Ce,o=m$3(j.join(t,".venv"));if(!await O__default.pathExists(o)){let c=await np(t,e);if(c!==0)return c}if(!(await r("poetry",["--version"],t)===0))return 0;let a=await r("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await r("poetry",["env","use",o],t);return i!==0?i:0}async function lm(t,e={}){let r=e.runCommand??Ce,o=m$3(j.join(t,".venv"));if(!await O__default.pathExists(o)){let i=await np(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=j.join(t,"requirements.txt");if(await O__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=j.join(t,"pyproject.toml");return await O__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function Ss(t,e){return await cm(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 O__default.pathExists(j.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await lm(t))}async function xs(t){let e=await Dt("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await am(o,t))continue;if(await Ce(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function pm(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Oe([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Oe([...e],"--java-version"),a=Oe([...e],"--spring-boot-version"),i=Oe([...e],"--springdoc-version"),c=Oe([...e],"--group-id"),p=Oe([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.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(p&&!/^[A-Za-z0-9_.-]+$/.test(p.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Oe([...e],"--target-framework"),a=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(a&&!/^[A-Za-z0-9_.]+$/.test(a.trim()))return "Invalid --root-namespace. Use dot-separated .NET namespace identifiers only."}return null}async function Vl(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||Ds(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:o}=await import('./create-HUEDWYDM.js');await o(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:r}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},{name:"Create it without workspace management",value:"none"}],default:1}]);if(r==="current"){let{registerWorkspaceAtPath:o}=await import('./create-HUEDWYDM.js');await o(process.cwd(),{skipGit:e,yes:false,userConfig:await b()});}else r==="none"&&t.push("--no-workspace");}async function dm(t){await O__default.ensureDir(t);let e=j.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await _.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
|
|
155
|
-
`),async()=>{await o.close().catch(()=>{}),await O__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await O__default.readJson(e).catch(()=>null),a=Number(n?.pid),i=false;if(Number.isInteger(a)&&a>0)try{process.kill(a,0),i=true;}catch(c){i=c.code==="EPERM";}if(!i){await O__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function sn(t,e={}){let r$1=j.join(q(),"transactions"),o=await dm(r$1),n;try{await b$
|
|
156
|
-
`),1;try{h$1(o);}catch(
|
|
149
|
+
${r.stderr||""}`);return o?this.isMavenVersionAtLeast(o,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${o.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 r=_.existsSync(j.join(e,"pom.xml")),o=_.existsSync(j.join(e,"mvnw"))||_.existsSync(j.join(e,"mvnw.cmd")),n=_.existsSync(j.join(e,"build.gradle"))||_.existsSync(j.join(e,"build.gradle.kts"))||_.existsSync(j.join(e,"settings.gradle"))||_.existsSync(j.join(e,"settings.gradle.kts")),a=_.existsSync(j.join(e,"gradlew"))||_.existsSync(j.join(e,"gradlew.bat"));return {hasMavenProject:r||o,hasMavenWrapper:o,hasGradleProject:n||a,hasGradleWrapper:a}}findWorkspaceRoot(e){let r=e;for(;;){if(_.existsSync(j.join(r,".workspai-workspace"))||_.existsSync(j.join(r,".rapidkit-workspace")))return r;let o=j.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>_.existsSync(a));if(!n)return "isolated";try{let c=_.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 r=j.join(e,"mvnw.cmd");if(process.platform==="win32"&&_.existsSync(r))return {command:r,baseArgs:[]};let o=j.join(e,"mvnw");return _.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let r=j.join(e,"gradlew.bat");if(process.platform==="win32"&&_.existsSync(r))return {command:r,baseArgs:[]};let o=j.join(e,"gradlew");return _.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let r=[],o=new Set,n=[e];for(;n.length>0;){let a=n.shift();if(!a||o.has(a))continue;o.add(a);let i=[];try{i=_.readdirSync(a,{withFileTypes:true});}catch{continue}for(let c of i){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let d=j.join(a,c.name),l=this.inspectJavaProject(d);(l.hasMavenProject||l.hasGradleProject)&&r.push(d),n.push(d);}}return r}withJavaCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?j.join(n||e,".workspai","cache","java","m2"):j.join(e,".workspai","cache","java","m2"),i=o==="shared-runtime-caches"?j.join(n||e,".workspai","cache","java","gradle"):j.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,d=process.env.GRADLE_USER_HOME,l=`-Dmaven.repo.local=${a}`;return process.env.MAVEN_OPTS=c?`${c} ${l}`:l,process.env.GRADLE_USER_HOME=i,r().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof d>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=d;})}async runBuildTool(e,r,o=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:a}=this.buildToolCommand(e),i=await this.runCommand(n,[...a,...r],e);if(i===0||!o)return {exitCode:i};let c=_.existsSync(j.join(e,"pom.xml")),d=_.existsSync(j.join(e,"build.gradle"))||_.existsSync(j.join(e,"build.gradle.kts"));return {exitCode:i,message:c||d?"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 r=[j.join(e,"target"),j.join(e,"build","libs")];for(let o of r){if(!_.existsSync(o))continue;let a=_.readdirSync(o).filter(i=>i.toLowerCase().endsWith(".jar")).find(i=>!i.toLowerCase().endsWith("-sources.jar")&&!i.toLowerCase().endsWith("-javadoc.jar")&&!i.toLowerCase().endsWith("-plain.jar"));if(a)return j.join(o,a)}return null}commandArgsFor(e,r){if(e==="gradle"){let o=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return r==="init"?[...o,"dependencies"]:r==="dev"?[...o,"bootRun"]:r==="test"?[...o,"test"]:[...o,"bootJar"]}return r==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:r==="dev"?["spring-boot:run"]:r==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),r=this.resolveJavaCommand(e),o=await this.runCommand(r,["-version"],e);if(o!==0)return {exitCode:o,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),d=await this.detectInstalledJavaMajor(r,e);if(d!==null&&d<c)return {exitCode:1,message:`Detected Java ${d}, but project requires Java ${c}+.`};let l=j.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&_.existsSync(l))try{let u=_.readFileSync(l,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),w=this.parseMajorJavaVersion(u?.[1]);if(w!==null&&w<c)return {exitCode:1,message:`Detected JAVA_HOME version ${w}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),d=c==="gradle"?["--version"]:["-version"],l=await this.runBuildTool(e,d);return l.exitCode!==0?l:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):l}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let d=c.reduce((u,w)=>Math.max(u,this.readRequiredJavaMajor(w)),0);if(d>0){let u=await this.detectInstalledJavaMajor(r,e);if(u!==null&&u<d){let w=c.filter(y=>this.readRequiredJavaMajor(y)>u).map(y=>j.relative(e,y)).join(", ");return {exitCode:1,message:`Detected Java ${u}, but workspace project(s) [${w}] require Java ${d}+.`}}}let l=false,f=false;for(let u of c){let w=this.inspectJavaProject(u);w.hasMavenProject&&!w.hasMavenWrapper&&(l=true),w.hasGradleProject&&!w.hasGradleWrapper&&(f=true);}if(l){let u=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(u!==0)return {exitCode:u,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 w=await this.checkSystemMavenVersion(e);if(w.exitCode!==0)return w}if(f){let u=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(u!==0)return {exitCode:u,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 a=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(a===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return i===0?{exitCode:0}:{exitCode:a||i||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 r=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return r&&_.mkdirSync(r,{recursive:true}),process.env.GRADLE_USER_HOME&&_.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 r=this.resolveJarPath(e);if(r)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",r],e)};let o=await this.runBuild(e);if(o.exitCode!==0)return o;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(dt(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let r=j.join(e,"pom.xml");if(_.existsSync(r)){let o=_.readFileSync(r,"utf-8");if(o.includes("spotless-maven-plugin"))return this.runBuildTool(e,["spotless:check"]);if(o.includes("checkstyle"))return this.runBuildTool(e,["checkstyle:check"])}return {exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){if(dt(e,"format"))return {exitCode:await this.runCommand("make",["format"],e)};let r=j.join(e,"pom.xml");return _.existsSync(r)&&_.readFileSync(r,"utf-8").includes("spotless-maven-plugin")?this.runBuildTool(e,["spotless:apply"]):["build.gradle","build.gradle.kts"].map(n=>j.join(e,n)).filter(n=>_.existsSync(n)).some(n=>_.readFileSync(n,"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 Maven/Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run npx workspai init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var Mo=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}findWorkspaceRoot(e){let r=e;for(;;){if(_.existsSync(j.join(r,".workspai-workspace"))||_.existsSync(j.join(r,".rapidkit-workspace")))return r;let o=j.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>_.existsSync(a));if(!n)return "isolated";try{let c=_.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,r,o){let n=this.resolveDependencyMode(e),a=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=n==="isolated"?j.join(e,".workspai","cache","node"):j.join(a||e,".workspai","cache","node"),c=process.env.npm_config_cache,d=process.env.npm_config_store_dir,l=process.env.RAPIDKIT_DEP_SHARING_MODE,f=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,a&&(process.env.RAPIDKIT_WORKSPACE_PATH=a),r==="pnpm"?(process.env.npm_config_store_dir=j.join(i,"pnpm-store"),process.env.npm_config_cache=j.join(i,"pnpm-cache")):r==="yarn"?process.env.npm_config_cache=j.join(i,"yarn-cache"):process.env.npm_config_cache=j.join(i,"npm-cache"),o().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof d>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=d,typeof l>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=l,typeof f>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=f;})}detectPackageManager(e){if(_.existsSync(j.join(e,"package-lock.json")))return "npm";if(_.existsSync(j.join(e,"pnpm-lock.yaml")))return "pnpm";if(_.existsSync(j.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 _.existsSync(j.join(e,"package-lock.json"))||_.existsSync(j.join(e,"pnpm-lock.yaml"))||_.existsSync(j.join(e,"yarn.lock"))}availablePackageManagers(e){let r=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[r]:[r,...["npm","pnpm","yarn"].filter(n=>n!==r&&this.commandAvailable(n))]}commandAvailable(e){let r=e$b(e);return spawnSync(r.command,[...r.prefixArgs,"--version"],{stdio:"ignore",shell:c$e(),env:g$8()}).status===0}scriptArgs(e,r){return e==="npm"?["run-script",r,"--foreground-scripts"]:["run",r]}async runScriptWithFallback(e,r){let o={exitCode:1};for(let n of this.availablePackageManagers(e))if(o=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,r),e)),o.exitCode===0)return o;return o}async runLifecycle(e,r){let o=i$2(e),n=j$4(e,o),a=t$1(e,r,{framework:n.key});return a?this.runScriptWithFallback(e,a.scriptName):{exitCode:1,message:`No npm script available for \`${r}\`. Add a "${r}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let r=this.detectPackageManager(e);return this.withDependencyEnv(e,r,async()=>{try{return process.env.npm_config_cache&&_.mkdirSync(process.env.npm_config_cache,{recursive:true}),r==="pnpm"&&process.env.npm_config_store_dir&&_.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 r=this.detectPackageManager(e),o=this.resolveDependencyMode(e),n=o==="shared-runtime-caches"||o==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,r,()=>this.run(r,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 Do=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,r){return {exitCode:await this.withPythonCacheEnv(r,()=>this.runCore(e,r))}}findWorkspaceRoot(e){let r=e;for(;;){if(_.existsSync(j.join(r,".workspai-workspace"))||_.existsSync(j.join(r,".rapidkit-workspace")))return r;let o=j.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>_.existsSync(a));if(!n)return "isolated";try{let c=_.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,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?j.join(n||e,".workspai","cache","python"):j.join(e,".workspai","cache","python"),i=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=j.join(a,"pip"),process.env.POETRY_CACHE_DIR=j.join(a,"poetry"),r().finally(()=>{typeof i>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=i,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),r=await this.run(["doctor","check"],e);return r.exitCode===0?r: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 workspai doctor workspace" for a full workspace scan.','Use "npx workspai init" after adding or changing modules.',"Use `npx workspai <command>` from the project root to avoid environment drift."]}};var Lo=class{constructor(e){this.runCommand=e;}runCommand;runtime="php";async run(e,r,o){let n=await this.runCommand(e,r,o);return n===0?{exitCode:n}:{exitCode:n,message:`PHP lifecycle command failed (${e} ${r.join(" ")}). Ensure ${e} is available on PATH, then review composer.json and the command diagnostics above.`}}hasComposer(e){return _.existsSync(j.join(e,"composer.json"))}hasArtisan(e){return _.existsSync(j.join(e,"artisan"))}hasComposerScript(e,r){try{let o=JSON.parse(_.readFileSync(j.join(e,"composer.json"),"utf8"));return !!o.scripts&&Object.prototype.hasOwnProperty.call(o.scripts,r)}catch{return false}}missingManifest(){return {exitCode:1,message:"composer.json was not found. Run the command from a PHP project root."}}unsupported(e){return {exitCode:1,message:`No deterministic PHP ${e} command was detected. Add a "${e}" Composer script or the expected Laravel tooling.`}}async checkPrereqs(){let e=await this.run("php",["--version"],process.cwd());return e.exitCode!==0?e:this.run("composer",["--version"],process.cwd())}async initProject(e){return this.hasComposer(e)?this.run("composer",["install","--no-interaction"],e):this.missingManifest()}async runDev(e){return this.hasComposerScript(e,"dev")?this.run("composer",["run-script","dev"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("dev")}async runTest(e){return this.hasArtisan(e)?this.run("php",["artisan","test"],e):this.hasComposerScript(e,"test")?this.run("composer",["run-script","test"],e):this.unsupported("test")}async runBuild(e){return this.hasComposerScript(e,"build")?this.run("composer",["run-script","build"],e):this.unsupported("build")}async runStart(e){return this.hasComposerScript(e,"start")?this.run("composer",["run-script","start"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("start")}async runLint(e){for(let r of ["lint","analyse","analyze"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return this.unsupported("lint")}async runFormat(e){for(let r of ["format","fmt"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return _.existsSync(j.join(e,"vendor","bin","pint"))||_.existsSync(j.join(e,"pint.json"))?this.run("php",["vendor/bin/pint"],e):this.unsupported("format")}async doctorHints(e){return ["Install a supported PHP release and Composer, then keep both on PATH.","Commit composer.lock for deterministic application installs.","Expose test, lint, format, and build commands as Composer scripts when the framework does not provide them."]}};var Fo=class{constructor(e){this.runCommand=e;}runCommand;runtime="rust";async run(e,r){let o=await this.runCommand("cargo",e,r);return o===0?{exitCode:o}:{exitCode:o,message:`Cargo command failed (cargo ${e.join(" ")}). Ensure the stable Rust toolchain and cargo are available on PATH, then review Cargo.toml and the command diagnostics above.`}}hasManifest(e){return _.existsSync(j.join(e,"Cargo.toml"))}missingManifest(){return {exitCode:1,message:"Cargo.toml was not found. Run the command from a Rust project root."}}async checkPrereqs(){return this.run(["--version"],process.cwd())}async initProject(e){return this.hasManifest(e)?this.run(["fetch"],e):this.missingManifest()}async runDev(e){return this.hasManifest(e)?this.run(["run"],e):this.missingManifest()}async runTest(e){return this.hasManifest(e)?this.run(["test","--all-targets"],e):this.missingManifest()}async runBuild(e){return this.hasManifest(e)?this.run(["build","--release"],e):this.missingManifest()}async runStart(e){return this.hasManifest(e)?this.run(["run","--release"],e):this.missingManifest()}async runLint(e){return this.hasManifest(e)?this.run(["clippy","--all-targets","--all-features","--","-D","warnings"],e):this.missingManifest()}async runFormat(e){return this.hasManifest(e)?this.run(["fmt","--all"],e):this.missingManifest()}async doctorHints(e){return ["Install the Rust toolchain with rustup and ensure cargo is on PATH.","Use Cargo.lock for deterministic application builds.","Install rustfmt and clippy components for format and lint lifecycle commands."]}};function Jd(){let t={...process.env},e=t.PATH||"";if(e){let r=e.split(j.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(j.delimiter);t.PATH=r;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||i$8(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ke(t,e){return t==="go"?new No((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="node"?new Mo((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="java"?new To((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="dotnet"?new $o((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="rust"?new Fo((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="php"?new Lo((r,o,n)=>e.runCommandInCwd(r,o,n)):new Do((r,o)=>e.runCoreRapidkit(r,{cwd:o,env:Jd()}))}var Zc=j.join(Tn.homedir(),".workspai","cache"),el=1440*60*1e3;function is(){let t=f$4("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?j.join(Zc,`vitest-${e}`):Zc}var Jo=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 j.join(is(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let r=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${r}.tmp`}async get(e$1,r="1.0"){let o=this.memoryCache.get(e$1);if(o&&o.version===r&&Date.now()-o.timestamp<el)return e.debug(`Cache hit (memory): ${e$1}`),o.data;try{let n=this.getCachePath(e$1),a=await promises.readFile(n,"utf-8"),i=JSON.parse(a);if(i.version===r&&Date.now()-i.timestamp<el)return e.debug(`Cache hit (disk): ${e$1}`),this.memoryCache.set(e$1,i),i.data;await promises.unlink(n).catch(()=>{});}catch{e.debug(`Cache miss: ${e$1}`);}return null}async set(e$1,r,o="1.0"){let n={data:r,timestamp:Date.now(),version:o};this.memoryCache.set(e$1,n);try{await promises.mkdir(is(),{recursive:true});let a=this.getCachePath(e$1),i=this.getTempCachePath(a);await promises.writeFile(i,JSON.stringify(n),"utf-8"),await promises.rename(i,a),e.debug(`Cache set: ${e$1}`);}catch(a){e.debug(`Cache write failed: ${e$1}`,a);}}async invalidate(e$1){this.memoryCache.delete(e$1);try{let r=this.getCachePath(e$1);await promises.unlink(r),e.debug(`Cache invalidated: ${e$1}`);}catch{}}async clear(){this.memoryCache.clear();try{let e$1=is(),r=await promises.readdir(e$1);await Promise.all(r.map(o=>promises.unlink(j.join(e$1,o)))),e.debug("Cache cleared");}catch{}}};var Ir=["list","sync","registry","foundation","intelligence","model","snapshot","diff","impact","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp","policy","contract","share","export","archive","hydrate","import","connect","run","init"],Vo=["intelligence","model","snapshot","diff","impact","contract","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp"];function tl(t){return Vo.includes(t)}var rl="workspai-project-entry-capability-v1";var cs="workspai-cli-runtime-command-inventory-v1",Ko=[...l$2,"autopilot","pipeline","import","adopt","goal","agent","snapshot","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands","create","project"],ls=["bootstrap","setup","cache","mirror"],Uo="create",Ud=[...ls,Uo],Hd={bootstrap:"Bootstrap project or workspace dependencies through runtime-aware setup rules.",setup:"Prepare a selected runtime toolchain through the supported adapter boundary.",cache:"Inspect or clear Workspai cache state through the managed cache boundary.",mirror:"Coordinate supported mirror lifecycle operations for the current project.",create:"Create a supported workspace or project through the canonical planner boundary."},Ho=[["ai","generate-embeddings"],["ai","info"],["ai","recommend"],["ai","update-embeddings"],["agent","bootstrap"],["config","ai"],["config","remove-api-key"],["config","set-api-key"],["config","show"],["infra","down"],["infra","plan"],["infra","status"],["infra","up"],["product","manifest"],["product","manifest","create"],["product","plan"],["project","commands"],["project","agent-entry"],["project","coverage"],["project","workspace"],["project","archives"],["project","archive"],["project","restore"],["project","delete"],["snapshot","create"],["snapshot","inspect"],["snapshot","list"],["snapshot","restore"]];function Bd(t,e,r,o){let n=new Set(t),a=new Set(e),i=t.filter(w=>!a.has(w)).sort(),c=e.filter(w=>!n.has(w)).sort(),d=new Set(r),l=new Set(o),f=r.filter(w=>!l.has(w)).sort(),u=o.filter(w=>!d.has(w)).sort();return {ok:i.length===0&&c.length===0&&f.length===0&&u.length===0,registeredButUndeclared:i,declaredButUnregistered:c,registeredScopedButUndeclared:f,declaredScopedButUnregistered:u}}function ol(t,e=[]){return t.commands.flatMap(r=>{let o=r.name(),n=[...e,o];return [{path:n,command:o,parent:e.length>0?e.join(" "):null,registrationKind:"commander",aliases:r.aliases?.()??[],description:r.description?.()??"",hidden:r._hidden===true,arguments:(r.registeredArguments??[]).map(i=>({name:i.name(),required:i.required,variadic:i.variadic})),options:(r.options??[]).map(i=>({flags:i.flags,attributeName:i.attributeName?.()??null}))},...ol(r,n)]})}function nl(t){let e=ol(t),r=e.filter(c=>c.path.length===1).map(c=>c.command),o=new Set(r),n=Ud.filter(c=>!o.has(c)).map(c=>({path:[c],command:c,parent:null,registrationKind:"manual-handler",aliases:[],description:Hd[c],hidden:false,arguments:[],options:[]})),a=[...e,...n].sort((c,d)=>c.path.join(" ").localeCompare(d.path.join(" "))),i=[...new Set(a.filter(c=>c.path.length===1).map(c=>c.command))].sort();return {schemaVersion:cs,commands:a,topLevelCommands:i,integrity:Bd(i,Ko,e.filter(c=>c.path.length>1).map(c=>c.path.join(" ")),Ho.map(c=>c.join(" ")))}}function sl(t){return `CLI command surface integrity violation (${[t.registeredButUndeclared.length>0?`registered but undeclared: ${t.registeredButUndeclared.join(", ")}`:null,t.declaredButUnregistered.length>0?`declared but unreachable: ${t.declaredButUnregistered.join(", ")}`:null,t.registeredScopedButUndeclared.length>0?`registered scoped but undeclared: ${t.registeredScopedButUndeclared.join(", ")}`:null,t.declaredScopedButUnregistered.length>0?`declared scoped but unreachable: ${t.declaredScopedButUnregistered.join(", ")}`:null].filter(r=>r!==null).join("; ")})`}var qd={"--workspace":"Use an explicit workspace root instead of the nearest workspace.","--json":"Emit machine-readable JSON.","--strict":"Return a non-zero exit when governed evidence blocks the result.","--for-agent":"Build output for an agent surface (for example codex, copilot, or cursor).","--include-paths":"Include absolute filesystem paths.","--include-evidence":"Read and include referenced evidence metadata.","--scan-depth":"Set the bounded observable-project discovery depth.","--cache":"Reuse the model cache when the structural inputs are unchanged.","--refresh-graph":"Bypass the compatible persisted graph and rebuild from live sources.","--incremental":"Reuse unchanged projects and rebuild affected graph relations.","--write":"Persist the command artifact under .workspai/reports.","--scope":"Limit the operation to a bounded scope such as project:<name>.","--dry-run":"Preview the operation without applying writes.","--preset":"Select the generated agent customization preset.","--refresh-context":"Rebuild agent context before synchronization.","--refresh":"Refresh the underlying registry or context before reading it.","--agent-sync":"Synchronize agent grounding after writing the context artifact.","--no-agent-sync":"Do not synchronize agent grounding after writing context.","--target":"Select one or more agent customization targets.","--experimental-hooks":"Generate advisory VS Code agent hook design files.","--hydrate-prompts":"Add workspace-specific verification steps to supported prompts.","--project-grounding":"Select the project entrypoint policy: managed, local, or off.","--ci":"Produce a CI-oriented command plan.","--from":"Read the specified baseline, report, or graph artifact.","--from-impact":"Read the specified impact report for verification.","--output":"Write the requested export or report to this path.","--limit":"Bound graph query results (1\u2013100).","--once":"Build the initial observed state and exit.","--graph-stream":"Emit graph snapshot/delta events as NDJSON.","--force":"Replace an existing generated target where supported.","--no-doctor":"Exclude Doctor evidence from a share bundle.","--no-blueprint":"Exclude the reproducibility blueprint from a share bundle.","--include-env":"Include private environment files in an export archive.","--archive-compression":"Select the archive compression format.","--max-download-size":"Bound a remote archive download.","--max-expanded-size":"Bound the expanded archive size.","--download-timeout-ms":"Bound remote archive download time.","--allow-private-network":"Allow private-network archive sources explicitly.","--affected":"Run only projects affected by the selected Git change.","--blast-radius":"Include transitive downstream dependents.","--since":"Select the Git baseline used for affected-project discovery.","--parallel":"Run selected projects concurrently.","--max-workers":"Bound concurrent project workers.","--continue-on-error":"Continue remaining projects after a project failure.","--reuse-passed":"Reuse successful project-stage results where safe.","--no-gates":"Skip Doctor and Readiness pre-run gates.","--allow-breaking":"Allow a verified goal to use breaking dependency changes.","--allow-force":"Allow a verified goal to use force-based repair commands.","--card":"Select the dashboard card whose governed remediation actions should be repaired.","--action-id":"Select one exact governed remediation action.","--project":"Limit the repair transaction to one registered project name.","--proposal":"Read a bounded model repair proposal from a JSON file inside the workspace.","--transaction":"Select one durable repair transaction by id.","--approved-by":"Record the local actor approving the immutable repair plan.","--decision":"Submit one of the exact options exposed by a decision-required transaction.","--max-risk":"Set the maximum approved repair risk: safe, guarded, or invasive.","--no-auto-rollback":"Require a decision instead of automatically restoring a failed transaction.","--no-build":"Do not require build validation for the selected verified goal.","--no-tests":"Do not require test validation for the selected verified goal.","--no-run":"Read current goal evidence without executing verification commands.","--reuse-intelligence":"Reuse a just-completed canonical intelligence run while executing goal-specific checks."},Or={list:{usage:"workspai workspace list [--json]",summary:"List registered Workspai workspaces.",flags:["--json"],examples:["workspai workspace list","workspai workspace list --json"]},intelligence:{usage:"workspai workspace intelligence run [--for-agent <agent>] [--strict] [--json]",summary:"Run the canonical Workspace Intelligence chain in contract order.",flags:["--workspace","--json","--strict","--for-agent"],subactions:["run"],artifact:e$2.intelligenceRun,examples:["workspai workspace intelligence run --strict","workspai workspace intelligence run --for-agent codex --json"]},model:{usage:"workspai workspace model [--cache|--incremental] [--write] [--strict] [--json]",summary:"Build the canonical workspace model from registered and observed sources.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--cache","--incremental","--write","--strict"],artifact:e$2.model,examples:["workspai workspace model --write --json","workspai workspace model --incremental --write --json"]},"agent-sync":{usage:"workspai workspace agent-sync [--for-agent <agent>] [--target <targets>] [--project-grounding <mode>] [--write]",summary:"Synchronize bounded workspace grounding for supported agent surfaces.",flags:["--workspace","--json","--scope","--for-agent","--write","--dry-run","--strict","--preset","--refresh-context","--refresh","--target","--experimental-hooks","--hydrate-prompts","--project-grounding"],artifact:e$2.agentCustomizationPack,examples:["workspai workspace agent-sync --target all --write --strict","workspai workspace agent-sync --for-agent copilot --dry-run --json"]},"remediation-plan":{usage:"workspai workspace remediation-plan [--ci] [--write] [--json]",summary:"Build a governed repair plan from current workspace evidence.",flags:["--workspace","--json","--include-paths","--ci","--write"],artifact:i$1.artifactRemediationPlan,examples:["workspai workspace remediation-plan --write --json","workspai workspace remediation-plan --ci --json"]},repair:{usage:"workspai workspace repair <capabilities|plan|propose|approve|decide|execute|resume|status|list|rollback|cancel> [--transaction <id>] [--json]",summary:"Run a durable, approval-bound repair transaction through checkpoint, validation, canonical verification, and rollback.",flags:["--workspace","--json","--card","--action-id","--project","--proposal","--transaction","--approved-by","--decision","--max-risk","--allow-breaking","--allow-force","--no-auto-rollback"],subactions:["capabilities","plan","propose","approve","decide","execute","resume","status","list","rollback","cancel"],artifact:e$2.repairTransaction,examples:["workspai workspace repair capabilities --json","workspai workspace repair plan --card doctor --project api --json","workspai workspace repair propose --proposal .workspai/repair/inbox/proposal.json --json","workspai workspace repair approve --transaction repair_123 --approved-by local-user --json","workspai workspace repair decide --transaction repair_123 --decision approve-invasive --json","workspai workspace repair execute --transaction repair_123 --json","workspai workspace repair rollback --transaction repair_123 --json"]},context:{usage:"workspai workspace context [--for-agent <agent>] [--scope <scope>] [--write] [--json]",summary:"Build a bounded, evidence-backed context pack for people and agents.",flags:["--workspace","--json","--for-agent","--scope","--include-evidence","--scan-depth","--write","--agent-sync","--no-agent-sync","--preset","--target","--strict","--project-grounding"],artifact:e$2.agentContext,examples:["workspai workspace context --for-agent codex --write --json","workspai workspace context --scope project:api --json"]},snapshot:{usage:"workspai workspace snapshot [--json]",summary:"Persist the current model as the comparison baseline.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth"],artifact:e$2.snapshot,examples:["workspai workspace snapshot --json"]},diff:{usage:"workspai workspace diff --from <snapshot-or-model|git[:ref]> [--strict] [--json]",summary:"Compare the current model with a trusted model baseline.",flags:["--workspace","--json","--from","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:e$2.diff,examples:["workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","workspai workspace diff --from git --json"]},impact:{usage:"workspai workspace impact --from <diff> [--scope <scope>] [--strict] [--json]",summary:"Calculate the evidence-backed blast radius of the current model change.",flags:["--workspace","--json","--from","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:e$2.impact,examples:["workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json","workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --strict --json"]},verify:{usage:"workspai workspace verify [--from-impact <impact-report>] [--scope <scope>] [--strict] [--json]",summary:"Verify the selected change against contracts, gates, and current evidence.",flags:["--workspace","--json","--from-impact","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:e$2.verify,examples:["workspai workspace verify --strict --json","workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json"]},goal:{usage:"workspai workspace goal <plan|status|verify> <kind|goal-id> [--scope <scope>] [--target <percent>] [--json]",summary:"Plan, resume, and evidence-verify a durable engineering goal for people and agents.",flags:["--workspace","--json","--scope","--target","--allow-breaking","--allow-force","--no-build","--no-tests","--no-run","--reuse-intelligence"],flagDescriptions:{"--target":"Set the required test coverage percentage (0\u2013100)."},subactions:["plan","status","verify"],artifact:e$2.verifiedGoalStatus,examples:["workspai workspace goal plan release-readiness --json","workspai workspace goal plan dependency-security --scope project:api --json","workspai workspace goal plan test-coverage --scope project:web --target 75 --json","workspai workspace goal verify <goal-id> --json"]},graph:{usage:"workspai workspace graph [mode] [query|from] [to] [--json]",summary:"Build, query, prove, compare, or export the workspace graph.",flags:["--workspace","--json","--output","--from","--limit","--refresh-graph","--include-paths","--include-evidence","--scan-depth","--scope"],subactions:["emit","explain","entities","search","evidence","path","overlay","benchmark","dot","mermaid","jsonld","graphml","gexf"],examples:['workspai workspace graph search "authentication endpoint" --limit 12 --json','workspai workspace graph evidence "GET /users" --json',"workspai workspace graph mermaid"]},watch:{usage:"workspai workspace watch [--once] [--graph-stream] [--json]",summary:"Observe model changes and optionally stream graph deltas.",flags:["--workspace","--json","--once","--graph-stream","--scan-depth"],examples:["workspai workspace watch --once --json","workspai workspace watch --graph-stream"]},sync:{usage:"workspai workspace sync [--project-grounding <mode>] [--json]",summary:"Synchronize canonical workspace registration and project metadata.",flags:["--workspace","--json","--project-grounding"],examples:["workspai workspace sync --json"]},registry:{usage:"workspai workspace registry [--refresh] [--json]",summary:"Inspect the canonical workspace registry summary.",flags:["--workspace","--json","--refresh"],examples:["workspai workspace registry --refresh --json"]},foundation:{usage:"workspai workspace foundation [--force] [--json]",summary:"Create or repair the standard workspace foundation files.",flags:["--workspace","--json","--force"],examples:["workspai workspace foundation --json"]},policy:{usage:"workspai workspace policy [show|status|get|set] [key] [value] [--json]",summary:"Inspect or update workspace governance policy.",flags:["--workspace","--json"],subactions:["show","status","get","set"],examples:["workspai workspace policy get --json"]},contract:{usage:"workspai workspace contract [init|inspect|verify|graph] [--strict] [--json]",summary:"Create, inspect, verify, or project the workspace contract.",flags:["--workspace","--json","--output","--force","--strict"],subactions:["init","inspect","verify","graph"],artifact:i$1.workspaceContract,examples:["workspai workspace contract verify --strict --json","workspai workspace contract graph --json"]},share:{usage:"workspai workspace share [--output <file>] [--json]",summary:"Create a bounded, shareable workspace evidence bundle.",flags:["--workspace","--json","--output","--include-paths","--no-doctor","--no-blueprint"],examples:["workspai workspace share --output workspace-share.json --json"]},export:{usage:"workspai workspace export [--output <archive>] [--archive-compression <format>]",summary:"Export a portable workspace archive.",flags:["--workspace","--json","--output","--include-env","--archive-compression"],examples:["workspai workspace export --output workspace.tar.gz"]},archive:{usage:"workspai workspace archive <inspect|verify|doctor> <source> [safety options] [--json]",summary:"Inspect, verify, or diagnose a portable workspace archive without materializing it.",flags:["--json","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],subactions:["inspect","verify","doctor"],examples:["workspai workspace archive inspect ./workspace.tar.gz --json","workspai workspace archive verify ./workspace.tar.gz --strict --json","workspai workspace archive doctor ./workspace.tar.gz --json"]},hydrate:{usage:"workspai workspace hydrate <source> [--output <directory>] [--dry-run] [--json]",summary:"Hydrate a portable workspace into a controlled destination.",flags:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace hydrate workspace.tar.gz --output ./restored --dry-run --json"]},import:{usage:"workspai workspace import <source> [--output <directory>] [--dry-run] [--json]",summary:"Verify, materialize, register, relink, and reconcile a portable workspace archive safely.",flags:["--json","--output","--dry-run","--strict","--project-grounding","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace import workspace.tar.gz --output ./imported --json"]},connect:{usage:"workspai workspace connect [directory] [--project-grounding <mode>] [--dry-run] [--json]",summary:"Register and reconcile an existing Workspai workspace in place without moving its source.",flags:["--json","--dry-run","--project-grounding"],examples:["workspai workspace connect /path/to/existing-workspace --json"]},run:{usage:"workspai workspace run <stage> [selection and concurrency options] [--json]",summary:"Run a lifecycle stage across selected workspace projects.",flags:["--workspace","--json","--scope","--affected","--blast-radius","--since","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],subactions:["init","test","build","start","<custom-from-context>"],artifact:i$1.workspaceRunLast,examples:["workspai workspace run test --affected --blast-radius --strict","workspai workspace run build --parallel --max-workers 4 --json"]},explain:{usage:"workspai workspace explain [target] [--scope <scope>] [--write] [--json]",summary:"Explain current blockers or a selected workspace target from evidence.",flags:["--workspace","--json","--scope","--write"],artifact:e$2.explain,examples:["workspai workspace explain --write --json"]},why:{usage:"workspai workspace why [target] [--scope <scope>] [--write] [--json]",summary:"Alias the evidence-backed workspace explanation flow.",flags:["--workspace","--json","--scope","--write"],artifact:d$4,examples:["workspai workspace why readiness --json"]},trace:{usage:"workspai workspace trace --from <diff-artifact> [--write] [--json]",summary:"Trace a model change through blast radius and decision gates.",flags:["--workspace","--json","--from","--write"],artifact:e$3,examples:["workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --write --json"]},feedback:{usage:"echo '<event-json>' | workspai workspace feedback record --json",summary:"Record a structured outcome event for the workspace intelligence history.",flags:["--workspace","--json"],subactions:["record"],examples:[`echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | workspai workspace feedback record --json`]},eval:{usage:"workspai workspace eval [init|record|status|report|compare] [arguments] [--json]",summary:"Measure agent/model calls, tool use, tokens, latency, and verified outcome.",flags:["--workspace","--json","--from","--output"],subactions:["init","record","status","report","compare"],artifact:e$2.evaluationLastRun,examples:["workspai workspace eval init repair-readiness workspace-intelligence --json","workspai workspace eval report --output ./evaluation.json --json"]},mcp:{usage:"workspai workspace mcp serve",summary:"Serve bounded, read-mostly workspace evidence over stdio MCP.",flags:["--workspace","--json"],subactions:["serve"],examples:["workspai workspace mcp serve"]},init:{usage:"workspai workspace init [selection and concurrency options] [--json]",summary:"Initialize all selected projects through the workspace fleet runner.",flags:["--workspace","--json","--scope","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],artifact:i$1.workspaceRunLast,examples:["workspai workspace init --parallel --strict"]}};function ps(t){if(t)return Or[t]}function al(t){return t[0]==="workspace"&&!!ps(t[1])&&t.slice(2).some(e=>e==="--help"||e==="-h")}function il(t,e){let r=ps(e)?.flagDescriptions?.[t]??qd[t];if(!r)throw new Error(`Workspace action flag has no description: ${t}`);return r}function cl(t){let e=ps(t);if(!e)throw new Error(`Unknown workspace action: ${t}`);let r=[`Workspai workspace ${t}`,"",e.summary,"","Usage:",` ${e.usage}`];if(e.subactions&&e.subactions.length>0&&r.push("","Modes:",` ${e.subactions.join(" | ")}`),e.flags.length>0){r.push("","Options:");for(let o of e.flags){let n=il(o,t);r.push(` ${o.padEnd(24)} ${n}`.trimEnd());}}return e.artifact&&r.push("","Evidence:",` ${e.artifact}`),r.push("","Examples:",...e.examples.map(o=>` ${o}`),""),r.join(`
|
|
150
|
+
`)}var ll="rapidkit-runtime-command-surface-v1";var ds=h$3.doctorRemediationPlan.schemaVersion;var pl="workspai-workspace-intelligence-architecture-v1";var dl={autopilotRelease:h$3.autopilotReleaseLastRun.schemaVersion,workspaceList:"rapidkit-workspace-list-v1",workspaceSync:"rapidkit-workspace-sync-v1",compatibilityMatrix:h$3.compatibilityMatrix.schemaVersion,mcpDesign:h$3.workspaiMcpDesign.schemaVersion,agentHooks:h$3.agentHooks.schemaVersion,projectArchive:"rapidkit-project-archive-v1",workspaceSnapshot:"rapidkit-workspace-snapshot-v1",workspaceSnapshotV2:"rapidkit-workspace-snapshot-v2",infraPlan:h$3.infraPlan.schemaVersion,privateProductManifest:"rapidkit.private-product-manifest.v1",productFactoryPlan:"rapidkit.product-factory-plan.v1",workspaceModelCache:h$3.workspaceModelCache.schemaVersion,workspaceWatchEvent:"workspace-watch-event.v1",doctorProjectScan:"doctor-project-scan-v2",doctorWorkspaceCache:h$3.doctorWorkspaceCache.schemaVersion};var ul="project-workspace-resolution.v1";function ml(t){a$4(t,"contracts/project-workspace-resolution.v1.json","Project workspace resolution");}var us="workspai.ingestion-plan.v1",Bo="workspai.ingestion-result.v1",qo="workspai.adopt-effects.v1";var gl="contracts/ingestion-result.v1.json";function Nt(t){return {schemaVersion:us,...t}}var zd="workspai-published-contract-catalog-v1",Yd="workspace-graph-stream.v1";function $r(){return {workspaceContract:1,runtimeCommandSurface:ll,cliRuntimeCommandInventory:cs,cliOperationResult:a$E,publishedContractCatalog:zd,workspaceArchiveCapabilities:a$D,workspaceArchiveManifest:b$j,workspaceArchiveOperationResult:c$3,ingestionPlan:us,ingestionResult:Bo,adoptEffects:qo,projectEntryCapability:rl,projectWorkspaceLink:h$3.projectWorkspaceLink.schemaVersion,projectWorkspaceResolution:ul,projectContextAgent:h$3.projectContextAgent.schemaVersion,projectAgentEntry:a$C,agentBootstrapReceipt:c$c,doctorProjectEvidence:b$i,doctorWorkspaceEvidence:a$B,doctorGraphDiagnosis:d$a,doctorDiagnosis:a$A,doctorCapabilities:a$z,doctorValidation:c$b,doctorReceipt:h$3.doctorReceipt.schemaVersion,doctorSummary:e$9,projectTestCoverage:h$3.projectTestCoverage.schemaVersion,verifiedGoal:"workspai.verified-goal.v1",verifiedGoalStatus:f$2.verifiedGoalStatus,goalPack:a$y,goalAgentHandoff:b$h,goalPlanResult:c$a,goalIndex:e$8,goalLifecycleResult:g$6,workspaceIntelligenceArchitecture:pl,workspaceIntelligenceChain:a$x,workspaceIntelligenceArtifacts:f$2,cliLogEvent:a$w,freshnessMetadata:e$7,factFreshness:g$5,blockerResolution:a$v,workspaceModel:j$5,workspaceImpact:f$6,workspaceVerify:c$9,workspaceContext:a$u,workspaceDependencyGraph:b$g,workspaceKnowledgeGraph:a$t,workspaceGraphStream:Yd,workspaceKnowledgeGraphChangeOverlay:a$s,workspaceKnowledgeSearch:a$r,workspaceGraphTokenEfficiency:a$q,modelUsageEvent:a$p,workspaceIntelligenceEvaluation:b$f,workspaceIntelligenceEvaluationComparison:c$8,workspaceIntelligenceHistory:a$o,agentCustomizationPackCapabilities:c$7,agentCustomizationPackReport:f$2.agentCustomizationPack,agentReportsIndex:f$2.agentIndex,workspaceOperationalSkill:a$n,workspaceSkillsIndex:b$e,workspaceExplain:a$m,agentActionOutcome:a$l,doctorRemediationPlan:ds,doctorDependencyRepairTransaction:"workspai.doctor-dependency-repair-transaction.v1",artifactRemediationPlan:a$k,studioCardRepairCapabilities:i$5,workspaceRepairProposal:d$9,workspaceRepairCapabilities:f$5,workspaceRepairTransaction:a$j,doctorFixResult:a$i,backendImportStackParitySnapshot:"backend-import-stack-parity-v1",bootstrapCompliance:h$3.bootstrapCompliance.schemaVersion,commandCapabilities:"rapidkit-command-capabilities-v1",createPlannerCapabilities:"rapidkit-create-planner-capabilities-v1",doctorRemediationPlanLegacy:ds,extensionCliCompatibility:"rapidkit-extension-cli-compatibility.v1",infraStack:"rapidkit.infra-stack.v1",mirrorOps:h$3.mirrorOps.schemaVersion,moduleLayout:"rapidkit.module-layout.v1",moduleSupport:"rapidkit-module-support-v1",pipelineLastRun:h$3.pipelineLastRun.schemaVersion,transparencyEvidence:h$3.transparencyEvidence.schemaVersion,version:"rapidkit-version-v1",studioBlockerHandoff:"rapidkit-studio-blocker-handoff-v1",workspaceRegistry:h$3.workspaceRegistry.schemaVersion,workspaceRunLast:h$3.workspaceRunLast.schemaVersion,workspaceShareBundle:h$3.workspaceShareBundle.schemaVersion,...dl}}function zo(){let t=$r(),e={workspaceContract:"contracts/workspace-contract.v1.json",runtimeCommandSurface:"contracts/runtime-command-surface.v1.json",cliRuntimeCommandInventory:"contracts/cli-runtime-command-inventory.v1.snapshot.json",cliOperationResult:"contracts/cli-operation-result.v1.json",publishedContractCatalog:"contracts/published-contract-catalog.v1.json",workspaceArchiveCapabilities:"contracts/workspace-archive-capabilities.v1.json",workspaceArchiveManifest:"contracts/workspace-archive-manifest.v1.json",workspaceArchiveOperationResult:"contracts/workspace-archive-operation-result.v1.json",ingestionPlan:"contracts/ingestion-plan.v1.json",ingestionResult:"contracts/ingestion-result.v1.json",adoptEffects:"contracts/adopt-effects.v1.json",projectEntryCapability:"contracts/project-entry-capability.v1.json",projectWorkspaceLink:"contracts/project-workspace-link.v1.json",projectWorkspaceResolution:"contracts/project-workspace-resolution.v1.json",projectContextAgent:"contracts/workspace-intelligence/project-context-agent.v1.json",projectAgentEntry:"contracts/workspace-intelligence/project-agent-entry.v1.json",agentBootstrapReceipt:"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json",doctorProjectEvidence:"contracts/doctor-project-evidence.v1.json",doctorWorkspaceEvidence:"contracts/doctor-workspace-evidence.v1.json",doctorGraphDiagnosis:"contracts/workspace-intelligence/doctor-graph-diagnosis.v1.json",doctorDiagnosis:"contracts/workspace-intelligence/doctor-diagnosis.v1.json",doctorCapabilities:"contracts/workspace-intelligence/doctor-capabilities.v1.json",doctorValidation:"contracts/workspace-intelligence/doctor-validation.v1.json",doctorReceipt:"contracts/workspace-intelligence/doctor-receipt.v1.json",doctorSummary:"contracts/workspace-intelligence/doctor-summary.v1.json",projectTestCoverage:"contracts/project-test-coverage.v1.json",verifiedGoal:"contracts/workspace-intelligence/verified-goal.v1.json",verifiedGoalStatus:"contracts/workspace-intelligence/verified-goal-status.v1.json",goalPack:"contracts/workspace-intelligence/goal-pack.v1.json",goalAgentHandoff:"contracts/workspace-intelligence/goal-agent-handoff.v1.json",goalPlanResult:"contracts/workspace-intelligence/goal-plan-result.v1.json",goalIndex:"contracts/workspace-intelligence/goal-index.v1.json",goalLifecycleResult:"contracts/workspace-intelligence/goal-lifecycle-result.v1.json",workspaceIntelligenceArchitecture:"contracts/workspace-intelligence-architecture.v1.json",workspaceIntelligenceChain:"contracts/workspace-intelligence-chain.v1.json",workspaceIntelligenceArtifacts:null,cliLogEvent:"contracts/cli-log-event.v1.json",freshnessMetadata:null,factFreshness:"contracts/workspace-intelligence/fact-freshness.v1.json",blockerResolution:"contracts/workspace-intelligence/blocker-resolution.v1.json",workspaceModel:"contracts/workspace-intelligence/workspace-model.v1.json",workspaceImpact:"contracts/workspace-intelligence/workspace-impact.v1.json",workspaceVerify:"contracts/workspace-intelligence/workspace-verify.v1.json",workspaceContext:"contracts/workspace-intelligence/workspace-context.v1.json",workspaceDependencyGraph:"contracts/workspace-intelligence/workspace-dependency-graph.v1.json",workspaceKnowledgeGraph:"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json",workspaceGraphStream:"contracts/workspace-intelligence/workspace-graph-stream.v1.json",workspaceKnowledgeGraphChangeOverlay:"contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json",workspaceKnowledgeSearch:"contracts/workspace-intelligence/workspace-knowledge-search.v1.json",workspaceGraphTokenEfficiency:"contracts/workspace-intelligence/workspace-graph-token-efficiency.v1.json",modelUsageEvent:"contracts/workspace-intelligence/model-usage-event.v1.json",workspaceIntelligenceEvaluation:"contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",workspaceIntelligenceEvaluationComparison:"contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",workspaceIntelligenceHistory:"contracts/workspace-intelligence/workspace-intelligence-history.v1.json",agentCustomizationPackCapabilities:"contracts/agent-customization-pack.v1.json",agentCustomizationPackReport:"contracts/workspace-intelligence/agent-customization-pack-report.v1.json",agentReportsIndex:"contracts/workspace-intelligence/agent-reports-index.v1.json",workspaceOperationalSkill:"contracts/workspace-intelligence/workspace-operational-skill.v1.json",workspaceSkillsIndex:"contracts/workspace-intelligence/workspace-skills-index.v1.json",workspaceExplain:"contracts/workspace-intelligence/workspace-explain.v1.json",agentActionOutcome:"contracts/workspace-intelligence/agent-action-outcome.v1.json",doctorRemediationPlan:"contracts/doctor-remediation-plan.v2.json",doctorDependencyRepairTransaction:"contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json",artifactRemediationPlan:"contracts/artifact-remediation-plan.v1.json",studioCardRepairCapabilities:"contracts/studio-card-repair-capabilities.v1.json",workspaceRepairProposal:"contracts/workspace-intelligence/workspace-repair-proposal.v1.json",workspaceRepairCapabilities:"contracts/workspace-repair-capabilities.v1.json",workspaceRepairTransaction:"contracts/workspace-intelligence/workspace-repair-transaction.v1.json",doctorFixResult:"contracts/workspace-intelligence/doctor-fix-result.v1.json",backendImportStackParitySnapshot:"contracts/backend-import-stack-parity.snapshot.json",bootstrapCompliance:"contracts/bootstrap-compliance.v1.json",commandCapabilities:"contracts/command-capabilities.v1.json",createPlannerCapabilities:"contracts/create-planner-capabilities.v1.json",doctorRemediationPlanLegacy:"contracts/doctor-remediation-plan.v1.json",extensionCliCompatibility:"contracts/extension-cli-compatibility.v1.json",infraStack:"contracts/infra-stack.v1.json",mirrorOps:"contracts/mirror-ops.v1.json",moduleLayout:"contracts/module-layout.v1.json",moduleSupport:"contracts/module-support.v1.json",pipelineLastRun:"contracts/pipeline-last-run.v1.json",transparencyEvidence:"contracts/transparency-evidence.v1.json",version:"contracts/version.v1.json",studioBlockerHandoff:"contracts/workspace-intelligence/studio-blocker-handoff.v1.json",workspaceRegistry:"contracts/workspace-registry.v1.json",workspaceRunLast:"contracts/workspace-run-last.v1.json",workspaceShareBundle:"contracts/workspace-share-bundle.v1.json",autopilotRelease:"contracts/autopilot-release.v1.json",workspaceList:"contracts/workspace-list.v1.json",workspaceSync:"contracts/workspace-sync.v1.json",compatibilityMatrix:"contracts/compatibility-matrix.v1.json",mcpDesign:"contracts/workspace-intelligence/mcp-design.v1.json",agentHooks:"contracts/workspace-intelligence/agent-hooks.v1.json",projectArchive:"contracts/project-archive.v1.json",workspaceSnapshot:"contracts/workspace-snapshot.v1.json",workspaceSnapshotV2:"contracts/workspace-snapshot.v2.json",infraPlan:"contracts/infra-plan.v1.json",privateProductManifest:"contracts/private-product-manifest.v1.json",productFactoryPlan:"contracts/product-factory-plan.v1.json",workspaceModelCache:"contracts/workspace-model-cache.v1.json",workspaceWatchEvent:"contracts/workspace-watch-event.v1.json",doctorProjectScan:"contracts/doctor-project-scan.v2.json",doctorWorkspaceCache:"contracts/doctor-workspace-cache.v2.json"};return Object.fromEntries(Object.entries(t).map(([r,o])=>{let n=e[r];return [r,{schemaVersion:o,contractPath:n,publication:n?r==="runtimeCommandSurface"||r==="cliRuntimeCommandInventory"||r.endsWith("Capabilities")||r.endsWith("Snapshot")||r==="extensionCliCompatibility"||r==="moduleLayout"||r==="moduleSupport"?"capability-contract":"json-schema":"embedded-type",...r==="workspaceIntelligenceArtifacts"?{artifacts:Object.fromEntries(Object.keys(e$2).map(a=>[a,{path:e$2[a],schemaVersion:f$2[a],contractPath:g$4[a]}]))}:{}}]}))}var ms="rapidkit-command-capabilities-v1",fl="rapidkit-version-v1";var Xd=["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"],Qd={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},Zd={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"},eu={tauri:"desktop",electron:"desktop","vscode-extension":"extension",laravel:"api"};function tu(t){return t[Math.floor(Math.random()*t.length)]}function gs(t){let e=tu(Xd),r=j$6(t);if(r){let i=Zd[r.id]??"app";return `${e}-${i}`}let o=p$4(t);if(o)return `${e}-${eu[o.id]??"app"}`;let n=a$3(t),a=n?Qd[n.id]??"service":"app";return `${e}-${a}`}async function su(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function au(t){if(!await O.pathExists(t))return [];let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(o)for(let n of await promises.readdir(o,{withFileTypes:true})){let a=j.join(o,n.name);n.isFile()?e.push(a):n.isDirectory()&&r.push(a);}}return e}async function yl(t,e){await O.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
151
|
+
`,"utf-8");}function st(t,e){return j.isAbsolute(e)?e:j.join(t,e)}function iu(t,e){if(!e.trim()||j.isAbsolute(e)||/^[a-zA-Z]:[\\/]/.test(e))throw new Error(`Mirror artifact target must be a non-empty relative path: ${e}`);let r=j.resolve(t),o=j.resolve(r,e),n=j.relative(r,o);if(!n||n.startsWith("..")||j.isAbsolute(n))throw new Error(`Mirror artifact target escapes the managed artifact directory: ${e}`);return o}async function wl(t,e){let r=j.relative(t,e),o=t;for(let a of r.split(j.sep).slice(0,-1)){o=j.join(o,a);let i=await promises.lstat(o).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)break;if(i.isSymbolicLink())throw new Error(`Mirror artifact target traverses a symbolic link: ${o}`);if(!i.isDirectory())throw new Error(`Mirror artifact target parent is not a directory: ${o}`)}let n=await promises.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(n?.isSymbolicLink()||n&&!n.isFile())throw new Error(`Mirror artifact target must be absent or a regular file: ${e}`)}async function cu(t,e){let r=j.resolve(t),o=j.relative(r,j.resolve(e));if(!o||o.startsWith("..")||j.isAbsolute(o))throw new Error("Managed mirror directory escapes the workspace.");let n=r;for(let a of o.split(j.sep)){n=j.join(n,a);let i=await promises.lstat(n);if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Managed mirror path must contain only real directories: ${n}`)}}function lu(t,e){if(t.target)return t.target;if(t.source)return j.basename(t.source);if(t.url)try{let r=new URL(t.url).pathname,o=j.basename(r);if(o&&o!=="/")return o}catch{}return `${e}.artifact`}async function pu(t){let e=s$1(t,"trusted-sources.lock").find(o=>existsSync(o)),r=new Set(["localhost","127.0.0.1"]);if(!e)return r;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));for(let a of n)r.add(a.toLowerCase());}catch{}return r}async function du(t,e,r){await O.ensureDir(j.dirname(e)),await new Promise((o,n)=>{let i=(t.startsWith("https://")?Cl:bl).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let d=createWriteStream(e);c.pipe(d),d.on("finish",()=>{d.close(),o();}),d.on("error",l=>{n(l);});});i.setTimeout(r,()=>{i.destroy(new Error(`Request timeout after ${r}ms`));}),i.on("error",c=>{n(c);});});}async function uu(t,e,r,o,n){let a=new URL(t),i=JSON.stringify(e),c=a.protocol==="https:"?Cl:bl;await new Promise((d,l)=>{let f=c.request({method:"POST",hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:`${a.pathname}${a.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...o?{Authorization:`Bearer ${o}`}:{},...n||{}}},u=>{if(!u.statusCode||u.statusCode<200||u.statusCode>=300){l(new Error(`HTTP ${u.statusCode||"unknown"}`)),u.resume();return}u.resume(),d();});f.setTimeout(r,()=>{f.destroy(new Error(`Request timeout after ${r}ms`));}),f.on("error",u=>{l(u);}),f.write(i),f.end();});}function kl(t){return new Promise(e=>setTimeout(e,t))}async function mu(t,e,r,o){let n=st(t,e||".workspai/reports/evidence-export-dead-letter.ndjson");return await O.ensureDir(j.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:o,payload:r})}
|
|
152
|
+
`,"utf-8"),n}function gu(t,e){if(!e?.enabled)return {headers:{}};let r=process.env[e.hmacKeyEnv];if(!r)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let o=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(o,r).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":o}}}async function fu(t,e,r){let o=(r.algorithm||"sha256").toLowerCase(),n=st(t,r.publicKeyPath);if(!await O.pathExists(n))return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(o);c.update(i),c.end();let d=Buffer.from(r.signature,"base64"),l=c.verify(a,d),f=createHash("sha256").update(a).digest("hex");return {verified:l,algorithm:o,publicKeyPath:n,publicKeyFingerprint:f,signature:r.signature,message:l?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Attestation verification error: ${a.message}`}}}async function hu(t,e,r,o){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};let a=r.signaturePath?st(t,r.signaturePath):null;if(!a||!await O.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=r.certificatePath?st(t,r.certificatePath):null;c&&i.push("--certificate",c);let d=r.bundlePath?st(t,r.bundlePath):null;d&&i.push("--bundle",d);let l=r.keyPath?st(t,r.keyPath):null;l&&i.push("--key",l),r.identity&&i.push("--certificate-identity",r.identity),r.issuer&&i.push("--certificate-oidc-issuer",r.issuer),r.rekorUrl&&i.push("--rekor-url",r.rekorUrl),o.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let f=await execa("cosign",i,{reject:false});return f.exitCode===0?{verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:d,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${f.stderr||f.stdout||"unknown error"}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:d,certificatePath:c,signaturePath:a}}catch(f){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${f.message}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:d,certificatePath:c,signaturePath:a}}}async function yu(t,e){let r=e.algorithm||"sha256",o=st(t,e.policyPath),n=st(t,e.signaturePath),a=st(t,e.publicKeyPath);if(!await O.pathExists(o))return {verified:false,message:`Governance policy bundle not found: ${o}`,policies:null};if(!await O.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await O.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(o,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),d=await promises.readFile(a,"utf-8"),l=createVerify(r);return l.update(i),l.end(),l.verify(d,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function fs(t,e){let r=[],o={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=s$1(t,"mirror-config.json").find(M=>existsSync(M))??p(t,"mirror-config.json"),a=p(t,"mirror.lock"),i=p(t,"mirror","artifacts"),c=p(t,"reports"),d=await pu(t);if(!await O.pathExists(n))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:r,details:o};let l={};try{l=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return r.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:r,details:o}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||l.mode==="offline-only"))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:r,details:o};await O.ensureDir(i);try{await cu(t,i);}catch(M){return r.push({id:"mirror.root.safety",status:"failed",message:M instanceof Error?M.message:String(M)}),{checks:r,details:o}}let u=Math.max(0,l.prefetch?.retries??2),w=Math.max(0,l.prefetch?.backoffMs??250),y=Math.max(1e3,l.prefetch?.timeoutMs??15e3),P=l.security?.requireAttestation===true,S=l.security?.requireSigstore===true,p$1=l.security?.requireTransparencyLog===true,v=l.security?.requireSignedGovernance===true,m=l.security?.evidenceExport,h=(process.env.RAPIDKIT_ENV||l.security?.governance?.environment||"dev").toLowerCase(),g=l.security?.governance?.policies||{};if(l.security?.governanceBundle){let M=await yu(t,l.security.governanceBundle);if(r.push({id:"governance.bundle.verify",status:M.verified?"passed":"failed",message:M.message}),M.verified&&M.policies)g=M.policies,o.governanceBundleVerified=true;else if(v)return {checks:r,details:o}}let k=g[h],b=p$1||k?.requireTransparencyLog===true,x=[],C=Array.isArray(l.artifacts)?l.artifacts:[],R=[];for(let M=0;M<C.length;M+=1){let N=C[M],A=N.id||`artifact-${M+1}`,X=N.source?st(t,N.source):null,U=lu(N,A),q;try{q=iu(i,U),await wl(i,q);}catch(le){r.push({id:`mirror.target.${A}`,status:"failed",message:le instanceof Error?le.message:String(le)});continue}let Q=false,L=q,F=false,K=async()=>{F&&await promises.rm(L,{force:true}).catch(()=>{});},te={sourceType:"path",source:X||N.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(X&&await O.pathExists(X))await O.ensureDir(j.dirname(q)),L=`${q}.${process.pid}.${randomUUID()}.tmp`,F=true,await promises.copyFile(X,L),o.syncedArtifacts+=1,Q=true,te={sourceType:"path",source:X,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},r.push({id:`mirror.sync.${A}`,status:"passed",message:`Mirrored artifact ${A} from source path.`});else if(N.url){let le="";try{le=new URL(N.url).hostname.toLowerCase();}catch{r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Invalid URL for ${A}: ${N.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||d.has(le))){r.push({id:`mirror.prefetch.trust.${A}`,status:"failed",message:`Untrusted mirror host for ${A}: ${le}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await O.pathExists(q)?(Q=true,te={sourceType:"url",source:N.url,host:le,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},r.push({id:`mirror.prefetch.${A}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${A}.`})):r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${A} without an existing mirrored copy.`}),!Q))continue;if(!Q){await O.ensureDir(j.dirname(q)),L=`${q}.${process.pid}.${randomUUID()}.tmp`,F=true;let _e=null,T=0;for(let G=1;G<=u+1;G+=1){T=G;try{await promises.rm(L,{force:true}).catch(()=>{}),await du(N.url,L,y),o.syncedArtifacts+=1,Q=true,te={sourceType:"url",source:N.url,host:le,fetchedAt:new Date().toISOString(),attempts:T,trusted:true},r.push({id:`mirror.prefetch.${A}`,status:"passed",message:T>1?`Prefetched artifact ${A} from ${le} after ${T} attempts.`:`Prefetched artifact ${A} from ${le}.`});break}catch(de){if(_e=de,G<=u){await kl(w*G);continue}}}if(!Q){await K(),r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Failed to prefetch ${A} after ${u+1} attempt(s): ${_e?.message||"unknown error"}`});continue}}if(!Q){r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Failed to prefetch ${A}.`});continue}}if(!Q){N.required||e.offlineMode?r.push({id:`mirror.sync.${A}`,status:"failed",message:`Mirror source missing for ${A}${X?`: ${X}`:""}`}):r.push({id:`mirror.sync.${A}`,status:"skipped",message:`Mirror source not found for optional artifact ${A}.`});continue}let H=await su(L);if(N.sha256&&N.sha256.toLowerCase()!==H.toLowerCase()){r.push({id:`mirror.verify.${A}`,status:"failed",message:`Checksum mismatch for ${A}.`}),await K();continue}o.verifiedArtifacts+=1,r.push({id:`mirror.verify.${A}`,status:"passed",message:`Checksum verified for ${A}.`});let pe=N.attestation?await fu(t,L,N.attestation):null;if(N.attestation){if(r.push({id:`mirror.attest.${A}`,status:pe?.verified?"passed":"failed",message:pe?.message||"Attestation verification failed."}),!pe?.verified){await K();continue}}else if(P){r.push({id:`mirror.attest.${A}`,status:"failed",message:`Attestation is required but missing for ${A}.`}),await K();continue}else r.push({id:`mirror.attest.${A}`,status:"skipped",message:`No attestation provided for ${A}.`});let ue=N.attestation?.sigstore,ae=ue?await hu(t,L,ue,{requireTransparencyLog:b}):null;if(ue){if(r.push({id:`mirror.sigstore.${A}`,status:ae?.verified?"passed":"failed",message:ae?.message||"Sigstore verification failed."}),x.push({artifactId:A,verified:!!ae?.verified,tlogVerified:!!ae?.tlogVerified,identity:ae?.identity||null,issuer:ae?.issuer||null,rekorUrl:ae?.rekorUrl||null,timestamp:new Date().toISOString(),environment:h}),!ae?.verified){await K();continue}}else if(S){r.push({id:`mirror.sigstore.${A}`,status:"failed",message:`Sigstore attestation is required but missing for ${A}.`}),await K();continue}else r.push({id:`mirror.sigstore.${A}`,status:"skipped",message:`No Sigstore attestation provided for ${A}.`});if(ue&&ae?.verified&&k){let le=k.allowedIdentities||[];if(le.length>0){let _e=!!ae.identity&&le.includes(ae.identity);if(r.push({id:`mirror.sigstore.policy.identity.${A}`,status:_e?"passed":"failed",message:_e?`Sigstore identity policy passed for ${A} in ${h}.`:`Sigstore identity policy failed for ${A} in ${h}.`}),!_e){await K();continue}}let ut=k.allowedIssuers||[];if(ut.length>0){let _e=!!ae.issuer&&ut.includes(ae.issuer);if(r.push({id:`mirror.sigstore.policy.issuer.${A}`,status:_e?"passed":"failed",message:_e?`Sigstore issuer policy passed for ${A} in ${h}.`:`Sigstore issuer policy failed for ${A} in ${h}.`}),!_e){await K();continue}}let Ft=k.allowedRekorUrls||[];if(Ft.length>0){let _e=!!ae.rekorUrl&&Ft.includes(ae.rekorUrl);if(r.push({id:`mirror.sigstore.policy.rekor.${A}`,status:_e?"passed":"failed",message:_e?`Sigstore Rekor policy passed for ${A} in ${h}.`:`Sigstore Rekor policy failed for ${A} in ${h}.`}),!_e){await K();continue}}}else k&&r.push({id:`mirror.sigstore.policy.${A}`,status:"skipped",message:`Sigstore governance policy configured for ${h} but no verified Sigstore attestation for ${A}.`});F&&(await wl(i,q),await promises.rename(L,q),F=false);let ze=await promises.stat(q);R.push({id:A,path:j.relative(t,q),sha256:H,size:ze.size,provenance:te,attestation:{detached:{provided:!!N.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:!!ue,verified:ae?.verified||false,tlogVerified:ae?.tlogVerified||false,identity:ae?.identity||null,issuer:ae?.issuer||null,rekorUrl:ae?.rekorUrl||null,bundlePath:ae?.bundlePath||null,certificatePath:ae?.certificatePath||null,signaturePath:ae?.signaturePath||null,verifiedAt:ae?.verified?new Date().toISOString():null}}});}let E=l.retention?.keepLast;if(typeof E=="number"&&E>0){let M=new Set(R.map(A=>j.resolve(t,A.path))),N=(await au(i)).filter(A=>!M.has(j.resolve(A)));if(N.length>E){let A=await Promise.all(N.map(async U=>({filePath:U,stat:await promises.stat(U)})));A.sort((U,q)=>q.stat.mtimeMs-U.stat.mtimeMs);let X=A.slice(E);for(let U of X)await promises.unlink(U.filePath),o.rotatedFiles+=1;}}r.push({id:"mirror.rotate",status:"passed",message:o.rotatedFiles>0?`Mirror retention rotation removed ${o.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let $={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:l.mode||null,environment:h,artifacts:R};if(await promises.writeFile(a,`${JSON.stringify($,null,2)}
|
|
153
|
+
`,"utf-8"),o.lockWritten=true,r.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${j.relative(t,a)}.`}),o.transparencyEvidenceRecords=x.length,x.length>0){let M={schemaVersion:h$3.transparencyEvidence.schemaVersion,generatedAt:new Date().toISOString(),environment:h,records:x},N=new Date().toISOString().replace(/[:.]/g,"-"),A=j.join(c,`transparency-evidence-${N}.json`),X=j.join(c,"transparency-evidence.latest.json");if(b$l(`.workspai/reports/${j.basename(A)}`,M),b$l(i$1.transparencyEvidence,M),await O.ensureDir(c),await yl(A,M),await yl(X,M),o.transparencyEvidenceWritten=true,r.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${j.relative(t,X)}.`}),m?.enabled){let U=Math.max(1e3,m.timeoutMs??1e4);if(m.target==="file")if(!m.filePath)r.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let q=st(t,m.filePath);await O.ensureDir(j.dirname(q)),await promises.appendFile(q,`${JSON.stringify(M)}
|
|
154
|
+
`,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=q,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${q}.`});}catch(q){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${q.message}`});}else if(m.target==="http")if(!m.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let q=Math.max(0,m.retries??0),Q=Math.max(0,m.backoffMs??500),L=gu(M,m.signing);L.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:L.error});try{let F=m.authTokenEnv?process.env[m.authTokenEnv]:void 0,K=false,te=null;for(let H=1;H<=q+1;H+=1)try{if(L.error)throw new Error(L.error);await uu(m.endpoint,M,U,F,L.headers),o.evidenceExported=true,o.evidenceExportTarget=m.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:H>1?`Transparency evidence exported to HTTP endpoint ${m.endpoint} after ${H} attempts.`:`Transparency evidence exported to HTTP endpoint ${m.endpoint}.`}),K=true;break}catch(pe){te=pe,H<=q&&await kl(Q*H);}if(!K)throw te||new Error("unknown evidence export error")}catch(F){let K=`Evidence HTTP export failed: ${F.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:K});try{let te=await mu(t,m.deadLetterPath,M,K);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${te}.`});}catch(te){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${te.message}`});}}}if(m.failOnError&&r.some(Q=>Q.status==="failed"&&(Q.id==="sigstore.evidence.export.file"||Q.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function Yo(t){let e=f$7(t.detection.runtime),r=u$1({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.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}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core 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."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"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:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function wu(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function Xo(t){if(t.existingProjectJson?.module_support===true){let e=wu(t.existingProjectJson),r=e?a$3(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}function Sl(t){return t.replace(/\\/g,"/")}function ku(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function vu(t,e){let r=Sl(j.relative(t,e));return !r||r.startsWith("..")?true:r.split("/").filter(Boolean).some(o=>o==="..")}function Nr(t){let e=Sl(j.relative(t.workspacePath,t.projectPath)),r=vu(t.workspacePath,t.projectPath),o=ku(t.projectName,j.basename(t.projectPath)),n=r?`external/${o}`:e||o;return {relativePath:e||n,contractRelativePath:n,isExternal:r}}var xl=[a$G,b$k];function Pu(t,e){let r=j.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!j.isAbsolute(r)}async function tt(t){let e=await O__default.realpath(t);for(let r of xl){let o=j.join(t,r),n=await O__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await O__default.realpath(o);if(!Pu(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function El(t){let e=j.basename(t);return xl.includes(e)?(await O__default.lstat(t)).isSymbolicLink():false}var _l={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},Cu={python:"Python",node:"Node",go:"Go",java:"Java",dotnet:".NET",php:"PHP",ruby:"Ruby",rust:"Rust",elixir:"Elixir",clojure:"Clojure",scala:"Scala",kotlin:"Kotlin",deno:"Deno",bun:"Bun",c:"C",cpp:"C++",unknown:"Unknown"},Su={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},Rl=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function ys(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function ws(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function Tr(t){if(typeof t!="string")return "unknown";let e=t.trim().toLowerCase();return e==="python"||e==="node"||e==="go"||e==="java"||e==="dotnet"||e==="php"||e==="ruby"||e==="rust"||e==="elixir"||e==="clojure"||e==="scala"||e==="kotlin"||e==="deno"||e==="bun"||e==="c"||e==="cpp"?e:e==="c++"||e==="cplusplus"||e==="cc"||e==="clang++"||e==="g++"?"cpp":e==="clang"||e==="gcc"?"c":"unknown"}function en(t){let e=new Set;for(let r of t)e.add(Tr(r));return [...e].sort((r,o)=>Rl.indexOf(r)-Rl.indexOf(o))}function xu(t){let e=en(t).filter(r=>r!=="unknown");if(e.length!==0)return e.length===1?Su[e[0]]:"polyglot"}function Al(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function Eu(t,e){return t?"none":e==="strict"?"error":"warning"}function Mr(t){let e=t.ok?void 0:xu(t.runtimes)??"polyglot";return {ok:t.ok,checkId:t.checkId,status:t.ok?"passed":"failed",profile:t.profile,runtimes:t.runtimes,message:t.message,recommendedProfile:e,recommendedCommand:e?Al(e):void 0,ciRecommendedCommand:e?Al(e,{ci:true}):void 0,severity:Eu(t.ok,t.mode)}}function Tt(t){let e=ws(t.profile),r=en(t.runtimes),o=t.mode??"warn",n=_l[e];if(n){let a=r.length===0||r.every(i=>ys(i)===n);return Mr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:r,message:a?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${r.join(", ")}].`,mode:o})}if(e==="minimal"){let a=r.filter(d=>d!=="unknown"),c=new Set(a.map(d=>ys(d))).size<=1;return Mr({ok:c,checkId:"profile.minimal",profile:e,runtimes:r,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${a.join(", ")}].`,mode:o})}return Mr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:r,message:`${e} profile accepts the detected runtime mix.`,mode:o})}function St(t){let e=ws(t.profile),r=Tr(t.runtime),o=t.mode??"warn",n=_l[e];if(!n||r==="unknown")return Mr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[r],message:r==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:o});let a=ys(r)===n;return Mr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:a?[r]:en([n,r]),message:a?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${Cu[r]}, but workspace profile is "${e}".`,mode:o})}async function ir(t){let e=(await Promise.all(s$1(t,"policies.yml").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "warn";try{return (await O__default.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function cr(t){let e=(await Promise.all(s$1(t,"workspace.json").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "minimal";try{let r=await O__default.readJson(e);return ws(r.profile)}catch{return "minimal"}}async function Mt(t$1,e={}){let r=new Set,o=[],n=new Set,a=[t$1];for(;a.length>0;){let i=a.pop();if(!i||n.has(i))continue;n.add(i);let c=[];try{c=await _.promises.readdir(i,{withFileTypes:true});}catch{continue}for(let d of c){if(!d.isDirectory()||d.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(d.name))continue;let l=j.join(i,d.name);if(l!==t$1&&j$2(l))continue;if((await Promise.all([...t(l,"context.json"),...t(l,"project.json")].map(async u=>O__default.pathExists(u)))).some(Boolean)){o.push(l);continue}a.push(l);}}for(let i of o){let c=i$2(i);r.add(Tr(j$4(i,c).runtime));}for(let i of await a$H(t$1))r.add(Tr(i.runtime));for(let i of e.additionalRuntimes??[])r.add(Tr(i));return en(r)}function tn(t,e={}){let r=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return r?`Recommended: ${r}`:null}function Il(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Au(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return Il(a)||"imported-project"}function xt(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function _u(t){return xt(t)?"git-url":"local-folder"}async function Iu(t,e){let r=Il(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=j.join(t,n);if(!await O__default.pathExists(a))return a;o+=1;}}function Ou(t,e){let r=j.resolve(t),o=j.resolve(e),n=j.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!j.isAbsolute(n)}function $u(t,e){if(Ou(t,e))throw new Error("Import source must be outside the current workspace root.")}function Nu(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function Tu(t){let e=j.basename(t);return !(await El(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||Nu(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Mu(t$1){await tt(t$1);for(let e of t(t$1,"project.json"))if(await O__default.pathExists(e))try{return await O__default.readJson(e)}catch{return null}return null}async function Wu(t){await tt(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:j.basename(t.projectPath),o=Nr({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=u(t.projectPath,"project.json"),i=u(t.projectPath,"import.json"),c=u(t.projectPath,"import-readiness.json"),d=Xo({existingProjectJson:t.existingProjectJson}),l=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],f=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},u$1={...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:j.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:j.basename(t.projectPath),kind:t.projectKind,category:a$e(t.projectKind),project_type:a$e(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:d,modules:l,contracts:f,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},w={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:j.basename(t.projectPath)},project:{name:u$1.name,slug:u$1.slug,relative_path:n,kind:t.projectKind,category:a$e(t.projectKind),module_support:d},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$e(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:d,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},y=Yo({projectName:String(u$1.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:d,projectPath:t.projectPath,generatedAt:new Date(e)});return await O__default.ensureDir(j.dirname(a)),await O__default.writeJson(a,u$1,{spaces:2}),await O__default.writeJson(i,w,{spaces:2}),await O__default.writeJson(c,y,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:d}}async function Du(t,e){let r={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,relationship:"imported",importedAt:new Date().toISOString()};await b$c(t,[r]);}async function Lu(t){await O__default.pathExists(t)&&(await tt(t),await O__default.remove(t));}async function Fu(t,e){await Lu(e),await c$4(t,[e]);}async function Ol(t){let e=j.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??_u(r),n=t.name??(o==="git-url"?Au(r):j.basename(r)),a=await Iu(e,n),i=false;try{if(o==="local-folder"){let h=j.resolve(r),g=await O__default.stat(h).catch(()=>null);if(!g||!g.isDirectory())throw new Error("Import source is not a directory.");if(await tt(h),j$2(h))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");$u(e,h),i=true,await O__default.copy(h,a,{overwrite:false,errorOnExist:true,filter:Tu});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$d()});await tt(a);let c=await Mu(a),d=j$4(a,c),l=await b$a(a,c),[f,u]=await Promise.all([cr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ir(e)]),w=St({profile:f,runtime:d.runtime,subjectLabel:j.basename(a),mode:u}),y=Tt({profile:f,runtimes:await Mt(e,{additionalRuntimes:[d.runtime]}),mode:u}),P=w.ok?y:w;if(!P.ok&&u==="strict")throw new Error(P.message);let S=await Wu({workspacePath:e,projectPath:a,sourceType:o,detection:d,existingProjectJson:c,projectKind:l,profileCompatibility:P}),p=Nr({workspacePath:e,projectPath:a,projectName:j.basename(a)}),v={ingestionPlan:Nt({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:j.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:j.basename(a),path:a,relativePath:p.contractRelativePath,stack:d.importStack,runtime:d.runtime,framework:d.key,frameworkDisplayName:d.displayName,supportTier:d.supportTier,moduleSupport:S.moduleSupport,confidence:d.confidence,source:o,projectJsonPath:S.projectJsonPath,importJsonPath:S.importJsonPath,importReadinessPath:S.importReadinessPath,profileCompatibility:P};await Du(e,v);let{syncWorkspaceContract:m}=await import('./workspace-contract-3BWIRSVQ.js');return await m({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:v.path,projectName:v.name,relationship:"imported",mode:t.projectGrounding??"managed"}),v}catch(c){if(i)try{await Fu(e,a);let{syncWorkspaceContract:d}=await import('./workspace-contract-3BWIRSVQ.js');await d({workspacePath:e,strict:true});}catch(d){let l=c instanceof Error?c.message:String(c),f=d instanceof Error?d.message:String(d);throw new Error(`Import failed: ${l}. Rollback also failed: ${f}`)}throw c}}function Gu(t){return {schemaVersion:qo,sourceMode:"linked",sourceCodeModified:false,projectMetadataFiles:[".workspai/project.json",".workspai/adopt.json",".workspai/adopt-readiness.json",f$1,...t==="off"?[]:[h$4,g$1,b$b]],repositoryControlFiles:[{path:".gitignore",action:"reconcile",condition:"machine-local workspace binding and project-grounding portability rules"},...t==="managed"?[{path:"AGENTS.md",action:"reconcile",condition:"managed grounding is enabled and the path is a regular file; authored deletions and symbolic links are preserved"},...g$2.map(e=>({path:e,action:"reconcile",condition:"managed provider adapter is enabled; authored content, deletions, symbolic links, and unsafe parent paths are preserved"}))]:[]],workspaceOperations:["register-project","sync-contract","rebuild-model","rebuild-graph","sync-agent-grounding"]}}function Ju(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Vu(t,e){return j.resolve(t)===j.resolve(e)}async function Ku(t$1){await tt(t$1);for(let e of t(t$1,"project.json")){if(!await O__default.pathExists(e))continue;let r;try{r=JSON.parse((await O__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}function Uu(t){if(!t?.adoption||typeof t.adoption!="object")return false;let e=t.adoption;return e.managed_by==="workspai"&&e.mode==="linked"}async function $l(t,e){let r=j.relative(t,e);if(r.startsWith("..")||j.isAbsolute(r))return true;let o=r.split(j.sep).slice(0,-1),n=t;for(let a of o){n=j.join(n,a);let i=await O__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)return false;if(i.isSymbolicLink()||!i.isDirectory())return true}return false}async function Hu(t){let e=j.join(t,".amazonq"),r=await O__default.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!r)return [e,j.join(e,"rules")];if(r.isSymbolicLink()||!r.isDirectory())return [];let o=j.join(e,"rules");return await O__default.lstat(o).catch(a=>{if(a.code==="ENOENT")return null;throw a})?[]:[o]}async function ks(t,e){let r=j.resolve(t),o=j.resolve(e);await tt(o);let n=[u(o,"project.json"),u(o,"adopt.json"),u(o,"adopt-readiness.json"),j.join(o,f$1),j.join(o,g$1),j.join(o,h$4),j.join(o,b$b),j.join(o,"AGENTS.md"),...g$2.map(a=>j.join(o,a)),j.join(o,".gitignore"),p(r,"imported-projects.json")];return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>{if(a.startsWith(`${o}${j.sep}`)&&await $l(o,a))return {path:a,contents:null,preserve:"unsafe-parent"};let i=await O__default.lstat(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});return i?.isSymbolicLink()?{path:a,contents:null,preserve:"symbolic-link"}:{path:a,contents:i?.isFile()?await O__default.readFile(a):null}})),createdAdapterDirectories:await Hu(o)}}function Nl(t,e,r){let o=[u(r,"project.json"),u(r,"adopt.json"),u(r,"adopt-readiness.json"),j.join(r,f$1),j.join(r,g$1),j.join(r,h$4),j.join(r,b$b),j.join(r,"AGENTS.md"),...g$2.map(a=>j.join(r,a)),j.join(r,".gitignore"),p(e,"imported-projects.json")].map(a=>j.resolve(a)),n=new Set([".amazonq",".amazonq/rules"].map(a=>j.resolve(r,a)));if(t.workspacePath!==j.resolve(e)||t.projectPath!==j.resolve(r)||t.files.length!==o.length||t.files.some((a,i)=>j.resolve(a.path)!==o[i])||t.createdAdapterDirectories.some(a=>!n.has(j.resolve(a)))||new Set(t.createdAdapterDirectories.map(a=>j.resolve(a))).size!==t.createdAdapterDirectories.length)throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function Bu(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=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,category:a$e(t.projectKind),project_type:a$e(t.projectKind),runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,framework:t.detection.key,kit:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:!t.refreshManagedDetection&&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:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function qu(t,e,r){await tt(e),Nl(r,t,e);let o=[];for(let n of r.files)try{if(n.preserve==="symbolic-link")continue;n.contents===null?await O__default.remove(n.path):(await O__default.ensureDir(j.dirname(n.path)),await O__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}for(let n of [...r.createdAdapterDirectories].reverse())try{if(await $l(e,n))continue;await O__default.rmdir(n);}catch(a){let i=a.code;i!=="ENOENT"&&i!=="ENOTEMPTY"&&o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function vs(t){let e=j.resolve(t.workspacePath),r=j.resolve(t.source),o=await O__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await tt(r),Vu(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(j$2(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t.rollbackSnapshot??await ks(e,r);Nl(n,e,r);let a=await Ku(r),i=Uu(a),c=j$4(r,i?null:a),d=i$4(r),l=[c.runtime,...d.filter(E=>E!==c.runtime)].filter((E,$,M)=>E!=="unknown"&&M.indexOf(E)===$);l.length===0&&l.push("unknown");let f=await b$a(r,a),u$1=Ju(t.name||(typeof a?.name=="string"?a.name:"")||j.basename(r))||"adopted-project",w=Nr({workspacePath:e,projectPath:r,projectName:u$1}),y=(t.now??new Date).toISOString(),P=u(r,"project.json"),S=u(r,"adopt.json"),p=u(r,"adopt-readiness.json"),v=Xo({existingProjectJson:a}),[m,h]=await Promise.all([cr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ir(e)]),g=St({profile:m,runtime:c.runtime,subjectLabel:u$1,mode:h}),k=Tt({profile:m,runtimes:await Mt(e,{additionalRuntimes:l}),mode:h}),b=g.ok?k:g;if(!b.ok&&h==="strict")throw new Error(b.message);let x=Bu({projectName:u$1,contractRelativePath:w.contractRelativePath,isExternal:w.isExternal,discoveredRelativePath:w.relativePath,detection:c,runtimeCandidates:l,existingProjectJson:a,refreshManagedDetection:i,projectKind:f,moduleSupport:v,adoptedAt:y}),C={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:y,managed_by:"workspai",mode:"linked",workspace:{name:j.basename(e),contract:i$1.workspaceContract},project:{name:u$1,relative_path:w.contractRelativePath,...w.isExternal?{}:{discovered_relative_path:w.relativePath},is_external:w.isExternal,kind:f,category:a$e(f),module_support:v},detection:{framework:c.key,framework_display_name:c.displayName,runtime:c.runtime,runtime_candidates:l,kind:f,category:a$e(f),confidence:c.confidence,support_tier:c.supportTier,import_stack:c.importStack,source:c.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:v,workspace_contract:"linked-project",profile_compatibility:{ok:b.ok,profile:b.profile,runtimes:b.runtimes,message:b.message,recommended_profile:b.recommendedProfile,recommended_command:b.recommendedCommand}}},R=Yo({projectName:u$1,relativePath:w.contractRelativePath,projectKind:f,source:"adopted-local",detection:c,moduleSupport:v,projectPath:r,generatedAt:new Date(y)});if(t.dryRun!==true)try{await tt(r),await O__default.ensureDir(j.dirname(P)),await O__default.writeJson(P,x,{spaces:2}),await O__default.writeJson(S,C,{spaces:2}),await O__default.writeJson(p,R,{spaces:2});let E={name:u$1,path:r,relativePath:w.contractRelativePath,relationship:"adopted",stack:c.importStack,runtime:c.runtime,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:v,confidence:c.confidence,source:"adopted-local",importedAt:y};await b$c(e,[E]);let{syncWorkspaceContract:$}=await import('./workspace-contract-3BWIRSVQ.js');await $({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:r,projectName:u$1,relationship:"adopted",mode:t.projectGrounding??"managed",now:new Date(y)});}catch(E){try{await qu(e,r,n);let{syncWorkspaceContract:$}=await import('./workspace-contract-3BWIRSVQ.js');await $({workspacePath:e,strict:true});}catch($){throw new AggregateError([E,$],`Adopt failed and rollback was incomplete: ${E instanceof Error?E.message:String(E)}`)}throw E}return {ingestionPlan:Nt({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t.projectGrounding??"managed"}),name:u$1,path:r,relativePath:w.relativePath,contractRelativePath:w.contractRelativePath,isExternal:w.isExternal,relationship:"adopted",stack:c.importStack,runtime:c.runtime,runtimeCandidates:l,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:v,confidence:c.confidence,projectJsonPath:P,adoptJsonPath:S,adoptReadinessPath:p,profileCompatibility:b,effects:Gu(t.projectGrounding??"managed"),wroteFiles:t.dryRun!==true}}async function zu(t){let e=await O__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=j.join(t,r),n=await O__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function Yu(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await O__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=j.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$f(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$6&&(await O__default.remove(i),e.push(j.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function Ml(t,e){if(await b$d(t,j.basename(t)),!(await g$3(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$h(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function Ps(t){let e=j.resolve(t.workspacePath);await zu(e);let r=Nt({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!j$2(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return rn(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$5(e);try{let n=await Ml(e,t.projectGrounding??"managed");return rn(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$5(e,o).catch(()=>{}),n}}async function js(t){if(t.dryRun){let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=j.resolve(o.outputPath),a=Tl(t,n);return rn(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?j.resolve(t.outputPath):void 0;if(e&&await O__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=j.resolve(o.outputPath);let n=Tl(t,r);if(!j$2(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await Yu(r);o.manifest?.portableContract&&await O__default.outputJson(j.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await Ml(r,t.projectGrounding??"managed");return rn(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,d,l)=>l.indexOf(c)===d),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$5(r).catch(()=>{}),await O__default.remove(r).catch(()=>{})),o}}function Tl(t,e){return Nt({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function rn(t,e){let r={schemaVersion:Bo,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$4(r,gl,"Workspace ingestion result"),r}function Wl(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function Dl(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function Ll(t){let e=t.trim(),r=e.startsWith("~/")?j.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!xt(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:xt(r)?r:j.resolve(r)};if(xt(r))return {kind:"git-project",source:r};let n=j.resolve(r);return j$2(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var em=Ho,tm=Ko;function Cs(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 rm(t=process.argv){let e=j.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function lr(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function om(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Oe(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function nm(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Os(t){try{return nm(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function Us(t$1,e){let r=Oe(t$1,"--port")?.trim(),o=t$1[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Oe(t$1,"--output")||".",i=j.resolve(e,a,o),c=t(i,"project.json").find(l=>_.existsSync(l))??u(i,"project.json");if(!await O__default.pathExists(c))return;let d=await O__default.readJson(c);await O__default.writeJson(c,{...d,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Gl(t){let e=be(process.cwd()),r=t.trim().toLowerCase();if(!e||!r)return true;try{let[o,n]=await Promise.all([cr(e),ir(e)]),a=a$3(r),i=j$6(r),c=p$4(r),d=i?"node":c?.runtime??a?.runtime??"python",l=St({profile:o,runtime:d,subjectLabel:r,mode:n}),f=Tt({profile:o,runtimes:await Mt(e,{additionalRuntimes:[d]}),mode:n}),u=l.ok?f:l;if(u.ok)return true;let w=tn(u);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${u.message}`)),w&&console.log(s.gray(`\u{1F4A1} ${w}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${u.message}`)),w&&console.log(s.gray(`\u{1F4A1} ${w}`));}catch{}return true}function Hs(){return j$7()}function Jl(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(j.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(j.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$8()),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 sm(t){return m$3(j.join(t,".venv"))}async function am(t,e){return await Ce(t,["--version"],e)===0}async function Lt(t){let e=j.join(t,"go.mod");if(await O__default.pathExists(e))return "go";let r=j.join(t,"pom.xml"),o=j.join(t,"build.gradle"),n=j.join(t,"build.gradle.kts");if(await O__default.pathExists(r)||await O__default.pathExists(o)||await O__default.pathExists(n))return "java";if((await O__default.pathExists(t)?await _.promises.readdir(t,{withFileTypes:true}):[]).some(y=>y.isFile()&&y.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=j.join(t,"src");if(await O__default.pathExists(i)&&(await _.promises.readdir(i,{withFileTypes:true})).some(P=>P.isFile()&&P.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=j.join(t,"Cargo.toml");if(await O__default.pathExists(c))return "rust";let d=j.join(t,"composer.json");if(await O__default.pathExists(d))return "php";let l=j.join(t,"package.json");if(await O__default.pathExists(l))return "node";let f=j.join(t,"pyproject.toml"),u=j.join(t,"requirements.txt"),w=j.join(t,"poetry.lock");return await O__default.pathExists(f)||await O__default.pathExists(u)||await O__default.pathExists(w)?"python":null}async function im(t,e={}){let r=e.runCommand??Ce;for(let o of e.pythonCandidates??Hs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function np(t,e={}){let r=e.runCommand??Ce;for(let o of e.pythonCandidates??Hs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function cm(t,e={}){let r=e.runCommand??Ce,o=m$3(j.join(t,".venv"));if(!await O__default.pathExists(o)){let c=await np(t,e);if(c!==0)return c}if(!(await r("poetry",["--version"],t)===0))return 0;let a=await r("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await r("poetry",["env","use",o],t);return i!==0?i:0}async function lm(t,e={}){let r=e.runCommand??Ce,o=m$3(j.join(t,".venv"));if(!await O__default.pathExists(o)){let i=await np(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=j.join(t,"requirements.txt");if(await O__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=j.join(t,"pyproject.toml");return await O__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function Ss(t,e){return await cm(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 O__default.pathExists(j.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await lm(t))}async function xs(t){let e=await Dt("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await am(o,t))continue;if(await Ce(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function pm(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Oe([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Oe([...e],"--java-version"),a=Oe([...e],"--spring-boot-version"),i=Oe([...e],"--springdoc-version"),c=Oe([...e],"--group-id"),d=Oe([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.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(d&&!/^[A-Za-z0-9_.-]+$/.test(d.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Oe([...e],"--target-framework"),a=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(a&&!/^[A-Za-z0-9_.]+$/.test(a.trim()))return "Invalid --root-namespace. Use dot-separated .NET namespace identifiers only."}return null}async function Vl(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||Ds(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:o}=await import('./create-IRNHMUEN.js');await o(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:r}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},{name:"Create it without workspace management",value:"none"}],default:1}]);if(r==="current"){let{registerWorkspaceAtPath:o}=await import('./create-IRNHMUEN.js');await o(process.cwd(),{skipGit:e,yes:false,userConfig:await b()});}else r==="none"&&t.push("--no-workspace");}async function dm(t){await O__default.ensureDir(t);let e=j.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await _.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
|
|
155
|
+
`),async()=>{await o.close().catch(()=>{}),await O__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await O__default.readJson(e).catch(()=>null),a=Number(n?.pid),i=false;if(Number.isInteger(a)&&a>0)try{process.kill(a,0),i=true;}catch(c){i=c.code==="EPERM";}if(!i){await O__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function sn(t,e={}){let r$1=j.join(q(),"transactions"),o=await dm(r$1),n;try{await b$8(r$1),n=await a$a({journalDirectory:r$1});}catch(i){throw await o(),i}let a=new Set([j.join(q(),"workspaces.json"),j.join(r(),"workspaces.json"),a$b(t,d$8),b$9(t,d$8),a$b(t,a$c),b$9(t,a$c),...s$1(t,"imported-projects.json")]);e.projectPath&&(a.add(u(e.projectPath,"project.json")),a.add(u(e.projectPath,"context.json")),a.add(u(e.projectPath,"file-hashes.json")),a.add(u(e.projectPath,"adopt.json")),a.add(u(e.projectPath,"adopt-readiness.json")),a.add(j.join(e.projectPath,f$1)),a.add(j.join(e.projectPath,g$1)),a.add(j.join(e.projectPath,h$4)),a.add(j.join(e.projectPath,"AGENTS.md")),a.add(j.join(e.projectPath,".gitignore")));try{for(let c of a)(e.projectPath&&c===j.join(e.projectPath,"AGENTS.md")?await O__default.lstat(c).catch(f=>{if(f.code==="ENOENT")return null;throw f}):null)?.isSymbolicLink()||await n.captureFile(c);e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let i=false;return {registerCompensation:c=>n.registerCompensation(c),commit:async()=>{i||(await n.commit(),i=true,await o());},rollback:async()=>{if(!i){i=true;try{await n.rollback();}finally{await o();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await o(),i}}async function pr(t,e){try{await t.rollback();}catch(r){throw new AggregateError([e,r],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function Gr(t,e$1,r){if(t.includes("--no-workspace")||t.includes("--dry-run"))return;if(!await O__default.pathExists(e$1)){e.warn(`Created project path was not found for workspace linking: ${e$1}`);return}let o=be(e$1)||be(process.cwd()),n=false,a;if(o)a=await sn(o,{projectPath:e$1});else {o=o$1(),a=await sn(o,{projectPath:e$1,ownedWorkspace:o});try{o=(await Bs()).workspacePath;}catch(c){await pr(a,c);}n=true;}let i="managed";try{await o$2(e$1);let c=j.relative(o,e$1);(c.startsWith("..")||j.isAbsolute(c))&&(i=(await vs({source:e$1,workspacePath:o,name:r})).relationship);let{registerProjectInWorkspaceStrict:l,registerWorkspaceStrict:f}=await import('./workspace-UUU4VMZB.js'),{syncWorkspaceContract:u}=await import('./workspace-contract-3BWIRSVQ.js');await f(o,j.basename(o)),await l(o,r,e$1),await u({workspacePath:o,strict:true});let{syncProjectIntelligenceLens:w}=await import('./project-intelligence-lens-N7REBQ3A.js');await w({workspacePath:o,projectPath:e$1,projectName:r,relationship:i==="adopted"?"adopted":"managed",mode:"managed"}),await a.commit(),await Jr(o);}catch(c){await pr(a,c);}return n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${i$3}" (${i}).`)),console.log(s.gray(` Registry: ${j.join(q(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${o}`))),o}async function $s(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],r=a$3(e),o=t[3];if(!r||r.owner!=="npm")return 1;if(!o)return process.stderr.write(`Usage: ${r.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
|
|
156
|
+
`),1;try{h$1(o);}catch(u){let w=u instanceof Error?u.message:String(u);return process.stderr.write(`${w}
|
|
157
157
|
`),1}let n=pm(r.id,t);if(n)return process.stderr.write(`${n}
|
|
158
|
-
`),1;let a=Oe(t,"--output")||process.cwd(),i=j.resolve(a,o),c=t.includes("--skip-git")||t.includes("--no-git"),
|
|
159
|
-
`),1):
|
|
160
|
-
${r.label}`)),console.log(s.gray(` Runtime: ${r.runtime}`)),console.log(s.gray(` Target: ${i}`)),console.log(s.gray(" Dry run: no files or workspace state will be changed.")),0):(await
|
|
158
|
+
`),1;let a=Oe(t,"--output")||process.cwd(),i=j.resolve(a,o),c=t.includes("--skip-git")||t.includes("--no-git"),d=t.includes("--skip-install"),l=t.includes("--dry-run"),f=false;try{let{default:u}=await import('fs-extra');return await u.pathExists(i)?(process.stderr.write(`\u274C Directory "${i}" already exists
|
|
159
|
+
`),1):l?(console.log(s.bold(`
|
|
160
|
+
${r.label}`)),console.log(s.gray(` Runtime: ${r.runtime}`)),console.log(s.gray(` Target: ${i}`)),console.log(s.gray(" Dry run: no files or workspace state will be changed.")),0):(await u.ensureDir(j.dirname(i)),await u.ensureDir(i),f=true,await e$4(r,{projectName:o,projectPath:i,args:t,skipGit:c,skipInstall:d}),await Us(t,process.cwd()),await Gr(t,i,o),0)}catch(u){if(f){let{default:w}=await import('fs-extra');await w.remove(i).catch(()=>{});}return process.stderr.write(`Workspai ${r.id} generator failed: ${u?.message??u}
|
|
161
161
|
`),1}}async function Kl(t){let e=j$6(t[2]);if(!e)return 1;let r;try{let o=await n$1({args:t});return o.dryRun||(r=o.projectPath,await Gr(t,o.projectPath,o.projectName)),0}catch(o){return r&&await O__default.remove(r).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${o?.message??o}
|
|
162
162
|
`),t[3]||process.stderr.write(`Usage: ${m$2(e.id)}
|
|
163
163
|
`),1}}async function Ul(t){let e=p$4(t[2]);if(!e)return 1;let r;try{let o=await s$3(t);return o.dryRun||(r=o.projectPath,await Gr(t,o.projectPath,o.projectName)),0}catch(o){return r&&await O__default.remove(r).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${o?.message??o}
|
|
164
164
|
`),t[3]||process.stderr.write(`Usage: ${r$2(e.kitId)}
|
|
165
|
-
`),1}}async function on(t,e){if(t.includes("--json"))return process.stderr.write("Workspai CLI 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(`Workspai CLI could not run the Python core engine for \`create\`.
|
|
166
|
-
Reason: ${e}.
|
|
165
|
+
`),1}}async function on(t,e$1){if(t.includes("--json"))return process.stderr.write("Workspai CLI 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(`Workspai CLI could not run the Python core engine for \`create\`.
|
|
166
|
+
Reason: ${e$1}.
|
|
167
167
|
Install Python 3.10+ to use the interactive wizard and full kit catalog.
|
|
168
168
|
`),1;let n=t[2],a=t[3];if(!n||!a)return process.stderr.write(`Usage: npx workspai create project <kit> <name> [--output <dir>]
|
|
169
169
|
Tip: offline fallback supports only fastapi* and nestjs* kits.
|
|
170
170
|
`),1;let i=om(n);if(!i)return process.stderr.write(`Workspai CLI could not run the Python core engine to create this kit.
|
|
171
|
-
Reason: ${e}.
|
|
171
|
+
Reason: ${e$1}.
|
|
172
172
|
Requested kit: ${n}
|
|
173
173
|
Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
|
|
174
174
|
Install Python 3.10+ to access all kits.
|
|
175
|
-
`),1;let c=Oe(t,"--output")||process.cwd(),
|
|
176
|
-
`),1;let w="pip",y=be(process.cwd());if(y)try{let{readWorkspaceMarker:S}=await import('./workspace-marker-7NHMDIRL.js'),
|
|
175
|
+
`),1;let c=Oe(t,"--output")||process.cwd(),d=j.resolve(c,a),l=false,f=t.includes("--skip-git")||t.includes("--no-git"),u=t.includes("--skip-install");try{if(await O__default.ensureDir(j.dirname(d)),await O__default.pathExists(d))return process.stderr.write(`\u274C Directory "${d}" already exists
|
|
176
|
+
`),1;let w="pip",y=be(process.cwd());if(y)try{let{readWorkspaceMarker:S}=await import('./workspace-marker-7NHMDIRL.js'),p=await S(y);p?.metadata?.npm?.installMethod&&(w=p.metadata.npm.installMethod,e.debug(`Detected workspace engine: ${w}`));}catch(S){e.debug("Failed to read workspace marker",S);}else e.debug("No workspace found, using default engine: pip");await O__default.ensureDir(d),l=true;let{generateDemoKit:P}=await import('./demo-kit-QHIDCSBI.js');return await P(d,{project_name:a,template:i,kit_name:n,skipGit:f,skipInstall:u,engine:w}),await Us(t,process.cwd()),await Gr(t,d,a),0}catch(w){return l&&await O__default.remove(d).catch(()=>{}),process.stderr.write(`Workspai CLI offline fallback failed: ${w?.message??w}
|
|
177
177
|
`),1}}function um(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("Workspai native create is not available for this request yet.")}
|
|
178
178
|
`),process.stderr.write(s.gray(`Requested: ${e}
|
|
179
179
|
`)),process.stderr.write(s.gray(`Lane: ${t.lane} (${t.status})
|
|
@@ -260,18 +260,18 @@ Shortcuts:
|
|
|
260
260
|
|
|
261
261
|
Run:
|
|
262
262
|
npx workspai create workspace --help
|
|
263
|
-
npx workspai create project --help`);}function fm(t){let e=t[2]??"<kit>",r=t[3]??"<name>",o=Oe(t,"--output")||process.cwd();console.log("Workspai create project dry run (Dry-run mode)"),console.log(` kit: ${e}`),console.log(` name: ${r}`),console.log(` output: ${j.resolve(o)}`),console.log(" execution: RapidKit Core bridge"),console.log(" writes: none"),console.log(""),console.log("Run without --dry-run to scaffold the project.");}async function Ns(t){if(t[0]==="create"&&(t.includes("--help")||t.includes("-h")||t.includes("help")))return t[1]==="project"?Hl():t[1]==="workspace"?mm():gm(),0;let e$
|
|
263
|
+
npx workspai create project --help`);}function fm(t){let e=t[2]??"<kit>",r=t[3]??"<name>",o=Oe(t,"--output")||process.cwd();console.log("Workspai create project dry run (Dry-run mode)"),console.log(` kit: ${e}`),console.log(` name: ${r}`),console.log(` output: ${j.resolve(o)}`),console.log(" execution: RapidKit Core bridge"),console.log(" writes: none"),console.log(""),console.log("Run without --dry-run to scaffold the project.");}async function Ns(t){if(t[0]==="create"&&(t.includes("--help")||t.includes("-h")||t.includes("help")))return t[1]==="project"?Hl():t[1]==="workspace"?mm():gm(),0;let e$2=t[0]==="create"&&t[1]==="frontend",r=l$1(t);if(r&&(t=r),e$2&&!k$2(t[2]))return process.stderr.write(`Unknown frontend generator: ${t[2]?.replace(/^frontend\./,"")}
|
|
264
264
|
`),process.stderr.write(`Usage: ${m$2()}
|
|
265
|
-
`),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return on(t,"PYTHON_NOT_FOUND");let o=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace","--here"]);if(t[0]==="create"&&(!t[1]||t[1].startsWith("-"))){let n=t.includes("--yes")||t.includes("-y"),a$1=t.slice(1),i;if(!process.stdin.isTTY||n)i="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."));else {process.stdin.isTTY&&a("create");let
|
|
265
|
+
`),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return on(t,"PYTHON_NOT_FOUND");let o=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace","--here"]);if(t[0]==="create"&&(!t[1]||t[1].startsWith("-"))){let n=t.includes("--yes")||t.includes("-y"),a$1=t.slice(1),i;if(!process.stdin.isTTY||n)i="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."));else {process.stdin.isTTY&&a("create");let d=be(process.cwd()),l=d?j.basename(d):null;i=(await b$1([{type:"rawlist",name:"createTarget",message:l?`What would you like to add to ${l}?`:"What would you like to set up?",choices:Wl(l)}])).createTarget;}if(i==="existing"){let d=be(process.cwd()),{source:l}=await b$1([Dl()]),f=Ll(l);if(f.kind==="workspace-archive"){let w=await js({archivePathOrUrl:f.source,projectGrounding:"managed"});console.log(s.green(`\u2714 Workspace imported and registered: ${w.workspacePath}`));for(let y of w.warnings)console.log(s.yellow(` \u26A0 ${y}`));return 0}if(f.kind==="git-project")return await Ls(f.source,{workspace:d??void 0});if(f.kind==="local-workspace"){let w=await Ps({workspacePath:f.source,projectGrounding:"managed"});console.log(s.green(`\u2714 Workspace connected: ${w.workspacePath}`));for(let y of w.warnings)console.log(s.yellow(` \u26A0 ${y}`));return 0}let{existingProjectMode:u}=await b$1([{type:"rawlist",name:"existingProjectMode",message:"How should Workspai add this project?",choices:[{name:"Keep it where it is (recommended)",value:"link"},{name:"Copy it into the workspace",value:"copy"}]}]);return u==="link"?await mp(f.source,{workspace:d??void 0,projectGrounding:"managed"}):await Ls(f.source,{workspace:d??void 0,projectGrounding:"managed"})}let c=["create",i,...a$1];return await Ns(c)}if(t[0]==="create"&&t[1]==="workspace")try{let n=t.includes("--yes")||t.includes("-y"),a$2=t.includes("--skip-git")||t.includes("--no-git"),i$1=t.includes("--skip-python-engine")||t.includes("--no-python-engine"),c=t.includes("--dry-run"),d=t[2]&&!t[2].startsWith("-")?t[2]:void 0,l=Oe(t,"--install-method"),f=l==="poetry"||l==="venv"||l==="pipx"?l:void 0,u=Oe(t,"--profile"),w=u==="minimal"||u==="java-only"||u==="go-only"||u==="dotnet-only"||u==="python-only"||u==="node-only"||u==="polyglot"||u==="enterprise"?u:void 0,y=d;if(y||(n?y="my-workspace":(process.stdin.isTTY&&a("create workspace"),y=(await b$1([{type:"input",name:"workspaceName",message:"Workspace name:",default:"my-workspace"}])).workspaceName)),!y||!y.trim())return process.stderr.write(`Workspace name is required.
|
|
266
266
|
`),1;try{h$1(y);}catch(g){if(g instanceof a$1)return process.stderr.write(`${g.message}
|
|
267
|
-
`),1;throw g}let P=await j$1(t,{hasYes:n}),S=h$2(y.trim(),{argv:t,outputParent:P});c||await O__default.ensureDir(j.dirname(S));let
|
|
268
|
-
`),
|
|
269
|
-
`),1;let v=await b(),
|
|
270
|
-
`),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return Hl(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitChoice:y}=await b$1([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$
|
|
271
|
-
`),
|
|
272
|
-
`),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$
|
|
273
|
-
`),1)}return await d$
|
|
274
|
-
`),1)}}var Bl=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],hm=[...l$2,"autopilot","pipeline","import","adopt","snapshot","ai","config","product","infra","shell","commands"],ym=["init"],wm=q$2,ql=[...wm,...r$1];function km(t){return !!t&&tm.includes(t)}function Ts(t){let e=t[0],r=t[1];return e==="project"&&(r==="--help"||r==="-h"||r==="help")?true:em.some(([o,n])=>e!==o?false:r?r===n:true)}function Fr(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?Ts(t):km(t[0])||Ts(t)}function vm(t){return !!t&&hm.includes(t)}function zl(t){return vm(t[0])||Ts(t)}function Yl(t){return !!t&&ls.includes(t)}async function Xl(t,e){switch(t){case "bootstrap":return Wm(e);case "setup":return Dm(e);case "cache":return Fm(e);case "mirror":return Jm(e);default:{let r=t;throw new Error(`Unreachable npm-only manual command: ${String(r)}`)}}}function Pm(t=process.env){let e=t.npm_config_user_agent||"",r=t.npm_execpath||"",o=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(r)||o==="exec"||o==="x"}function sp(t={}){let e=w(process.cwd());if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai 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"}`));}function jm(){return {schemaVersion:fl,cli:"workspai",version:
|
|
267
|
+
`),1;throw g}let P=await j$1(t,{hasYes:n}),S=h$2(y.trim(),{argv:t,outputParent:P});c||await O__default.ensureDir(j.dirname(S));let p=m(y.trim());if(!c&&(i(p,S,{outputParent:P})&&p&&await O__default.pathExists(p)||await O__default.pathExists(S)))return process.stderr.write(`\u274C Workspace "${y}" already exists
|
|
268
|
+
`),p&&p!==S&&process.stderr.write(` Found at: ${p}
|
|
269
|
+
`),1;let v=await b(),m$1=v.author||process.env.USER||"Workspai User";if(!n){let g=await b$1([{type:"input",name:"author",message:"Author name:",default:m$1}]);g.author?.trim()&&(m$1=g.author.trim());}let{createProject:h}=await import('./create-IRNHMUEN.js');return await h(y,{skipGit:a$2,skipPythonEngine:i$1,yes:n,dryRun:c,userConfig:{...v,author:m$1},installMethod:f,profile:w,parentDirectory:j.dirname(S)}),0}catch(n){return process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
|
|
270
|
+
`),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return Hl(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitChoice:y}=await b$1([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$F()}]);if(d$1(y)||k$2(y)||q$1(y)){let p=gs(y),{projectName:v}=await b$1([{type:"input",name:"projectName",message:"Project name:",default:p,validate:k=>k.trim().length>0||"Project name is required"}]),m=t.slice(2).filter(k=>k.startsWith("-")),h=["create","project",y,v.trim(),...m];return await Gl(y)?(await Vl(h),k$2(y)?await Kl(h):q$1(y)?await Ul(h):await $s(h)):1}let P=gs(y),{projectName:S}=await b$1([{type:"input",name:"projectName",message:"Project name:",default:P,validate:p=>p.trim().length>0||"Project name is required"}]);t.splice(2,0,y,S.trim());}let a$1=t[2],i=c$d({kitId:a$1,framework:a$1,runtime:a$1});if(d$b(i))return um(i),1;if(!await Gl(t[2]||""))return 1;if(await Vl(t),d$1(t[2]))return await $s(t);if(k$2(t[2]))return await Kl(t);if(q$1(t[2]))return await Ul(t);if(t.includes("--skip-python-engine")||t.includes("--no-python-engine"))return process.stderr.write("`--skip-python-engine` is a workspace creation option. For projects, use `--skip-install` to scaffold first, then run `npx workspai init` when ready.\n"),1;if(t.includes("--dry-run"))return fm(t),0;let d=[...t.filter(y=>{let P=y.split("=")[0];return !o.has(y)&&!o.has(P)})],l=be(process.cwd()),w=t.includes("--skip-install")||!!l?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$c();let y=await e$1(d,{cwd:process.cwd(),env:w});if(y===0&&l&&!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 workspai init"))),y===0){await Us(t,process.cwd());let P=t[3],S=Oe(t,"--output")||process.cwd(),p=P?j.resolve(S,P):void 0,v=P&&p?await Gr(t,p,P).catch(async m=>{throw await O__default.remove(p).catch(()=>{}),m}):l;if(v)try{if(P&&p){let m=j.join(v,".python-version"),h=j.join(p,".python-version");if(_.existsSync(m)&&_.existsSync(p)){let g=_.readFileSync(m,"utf-8");_.writeFileSync(h,g.trim()+`
|
|
271
|
+
`),e.debug(`Synced Python version ${g.trim()} from workspace to ${P}`);}}}catch(m){e.debug("Could not sync Python version from workspace:",m);}}return y}catch(y){let P=Cs(y);return P?await on(t,P):(process.stderr.write(`Workspai failed to run the Python core engine: ${y?.message??y}
|
|
272
|
+
`),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$c();let n=await e$1(t,{cwd:process.cwd()});if(n===0){let a=be(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-UUU4VMZB.js');await i(a,true);}}return n}catch(n){let a=Cs(n);return a?await on(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
|
|
273
|
+
`),1)}return await d$c(),await e$1(t,{cwd:process.cwd()})}catch(n){let a=Cs(n);return a?await on(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
|
|
274
|
+
`),1)}}var Bl=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],hm=[...l$2,"autopilot","pipeline","import","adopt","snapshot","ai","config","product","infra","shell","commands"],ym=["init"],wm=q$2,ql=[...wm,...r$1];function km(t){return !!t&&tm.includes(t)}function Ts(t){let e=t[0],r=t[1];return e==="project"&&(r==="--help"||r==="-h"||r==="help")?true:em.some(([o,n])=>e!==o?false:r?r===n:true)}function Fr(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?Ts(t):km(t[0])||Ts(t)}function vm(t){return !!t&&hm.includes(t)}function zl(t){return vm(t[0])||Ts(t)}function Yl(t){return !!t&&ls.includes(t)}async function Xl(t,e){switch(t){case "bootstrap":return Wm(e);case "setup":return Dm(e);case "cache":return Fm(e);case "mirror":return Jm(e);default:{let r=t;throw new Error(`Unreachable npm-only manual command: ${String(r)}`)}}}function Pm(t=process.env){let e=t.npm_config_user_agent||"",r=t.npm_execpath||"",o=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(r)||o==="exec"||o==="x"}function sp(t={}){let e=w(process.cwd());if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai 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"}`));}function jm(){return {schemaVersion:fl,cli:"workspai",version:h(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:ms,contracts:$r(),contractCatalog:zo()}}function ap(){let t=nl(fe),e=[...t.topLevelCommands],r=[...a$5].filter(i=>!e.includes(i)),o=["init","dev","start","build","test","lint","format","help"],n=[...Ir],a=[...Vo];return {schemaVersion:ms,scope:"global",cli:"workspai",version:h(),cwd:process.cwd(),contracts:$r(),contractCatalog:zo(),commands:{npmOwned:e,coreBacked:r,projectScoped:o},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...r.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"}])]),runtimeInventory:t}}function bm(t={}){let e=ap();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(sl(e.runtimeInventory.integrity));console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai 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 `workspai project commands --json` inside a project."));}function Ms(t){return y(t)?(sp({json:t.includes("--json")||t.includes("--ci")}),true):false}function Ws(t){let e=w(process.cwd());if(!e.projectRoot)return false;let r=x(t,process.cwd());if(!r||r.status!=="unsupported")return false;console.error(s.red(z(r,e))),process.exit(1);}function qe(t){return _.existsSync(j.join(t,".workspai-workspace"))||_.existsSync(j.join(t,".workspai","workspace.json"))||_.existsSync(j.join(t,".rapidkit-workspace"))||_.existsSync(j.join(t,".rapidkit","workspace.json"))}function ip(t$1){let e=t$1;for(;;){let r=t(e,"context.json").find(n=>_.existsSync(n));if(r)return r;let o=j.dirname(e);if(o===e)break;e=o;}return null}function Ds(t){let e=t,r=j.resolve(tmpdir());for(;;){let o=[j.join(e,".workspai-workspace"),j.join(e,".rapidkit-workspace")].find(a=>_.existsSync(a));if(o&&j.resolve(e)!==r)return o;let n=j.dirname(e);if(n===e)break;e=n;}return null}function be(t){let e=b$5({startPath:t});return !e||j.resolve(e.workspacePath)===j.resolve(tmpdir())?null:e.workspacePath}function cp(t){try{let r=b$5({startPath:t,strict:true})?.workspacePath??null;return {workspacePath:r&&j.resolve(r)!==j.resolve(tmpdir())?r:null,error:null}}catch(e){if(e instanceof a$2&&e.code==="project.workspace.unlinked")return {workspacePath:null,error:null};if(e instanceof a$2)return {workspacePath:null,error:e};throw e}}async function Jr(t,e){try{let{syncWorkspaceConsumerArtifacts:r}=await import('./workspace-onboarding-XNBC6H2G.js');await r(t,{silent:e?.silent});}catch(r){e?.silent||(console.log(s.yellow(`\u26A0\uFE0F Workspace consumer sync skipped: ${r.message}`)),console.log(s.gray(" Retry: npx workspai workspace agent-sync --write --refresh-context --preset enterprise")));}}async function Cm(t,e=process.cwd(),r=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$3(r))return {detected:false};let n=p$1(e,r);for(let a of n){if(!await O__default.pathExists(a))continue;let i=a.toLowerCase();if(i.endsWith("rapidkit.cmd")||i.endsWith("rapidkit.exe"))return {detected:true,candidatePath:a,reason:"Found workspace-local rapidkit launcher on Windows."}}return {detected:false}}function Sm(t){let e=t;for(;;){let r=j.join(e,".rapidkit-workspace"),o=j.join(e,".rapidkit","workspace.json");if(!_.existsSync(r)&&_.existsSync(o))return e;let n=j.dirname(e);if(n===e)break;e=n;}return null}var lp={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function xm(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Dr(t,e){let r=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return r?r[1]==="true":lp[e]}function Ql(t){let e=t??"";return {mode:xm(e),dependency_sharing_mode:pp(e),rules:{enforce_workspace_marker:Dr(e,"enforce_workspace_marker"),enforce_toolchain_lock:Dr(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Dr(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Dr(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Dr(e,"require_mirror_lock_for_offline")}}}function Zl(t,e,r){let o=`${e}: ${r}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${o}
|
|
275
275
|
rules:`):`${t.endsWith(`
|
|
276
276
|
`)?t:`${t}
|
|
277
277
|
`}${o}
|
|
@@ -283,52 +283,52 @@ ${o}
|
|
|
283
283
|
`}function Rm(){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 workspai bootstrap --profile polyglot","# change mode/dependency manually: edit this file and rerun npx workspai 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(`
|
|
284
284
|
`)}async function ep(t){for(let e of s$1(t,"policies.yml"))if(await O__default.pathExists(e))return _.promises.readFile(e,"utf-8");return Rm()}async function Am(t,e){let r=p(t,"policies.yml");await O__default.ensureDir(j.dirname(r));let o=e.endsWith(`
|
|
285
285
|
`)?e:`${e}
|
|
286
|
-
`;await _.promises.writeFile(r,o,"utf-8");}function _m(t){let e=t.trim().toLowerCase();return e==="true"||e==="1"||e==="on"?true:e==="false"||e==="0"||e==="off"?false:null}function pp(t){if(!t)return "isolated";let r=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated"?r:"isolated"}function dp(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 r=e[1].toLowerCase();return r==="isolated"||r==="shared-runtime-caches"||r==="shared-node-deps"?{mode:r,status:"passed",message:`dependency_sharing_mode is valid: ${r}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${r}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function up(t,e){let r=be(t),o=r?s$1(r,"policies.yml").find(c=>_.existsSync(c)):null,n="isolated";if(o&&await O__default.pathExists(o))try{let c=await _.promises.readFile(o,"utf-8"),
|
|
287
|
-
`);try{return Zu.runInThisContext(i,{filename:j.join(r,"package.json#script")}),0}catch(
|
|
288
|
-
`),1}}let w=!(process.argv.includes("--json")||process.env.RAPIDKIT_WORKSPACE_RUN_CHILD==="1"||process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT==="1")&&t==="npm"&&(e[0]==="run"||e[0]==="run-script"||e[0]==="install"),y=()=>{let
|
|
289
|
-
`):""}catch{return ""}},P=Number.parseInt(process.env.RAPIDKIT_CHILD_COMMAND_TIMEOUT_MS||"",10),S=o.timeoutMs&&o.timeoutMs>0?o.timeoutMs:Number.isFinite(P)&&P>0?P:void 0;return await new Promise(
|
|
290
|
-
`);let x=b$3()&&/\.(?:cmd|bat)$/i.test(
|
|
291
|
-
`),
|
|
292
|
-
`),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(
|
|
293
|
-
`)),
|
|
294
|
-
`),
|
|
295
|
-
`,"utf-8");}function $m(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function Nm(t,e,r){let o=xt(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":j.basename(e),n=$m(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=j.join(t,i);if(!await O__default.pathExists(c))return c;a+=1;}}async function Ls(t,e,r){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?j.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:cp(process.cwd()),i=a.workspacePath,c=false,p=false,d=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!qe(n)){let w=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:w},null,2)):console.log(s.red(`\u274C ${w}`)),1}}else (!i||!qe(i))&&(i=o$1(),c=true,d=true);if(!i||!qe(i)&&!d){let w="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:w},null,2)):(console.log(s.red(`\u274C ${w}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let f="npx workspai project workspace status --json",m;try{let w=await Nm(i,t,e.name);if(m=await sn(i,{ownedDestination:w,ownedWorkspace:d?i:void 0}),d){let P=await Bs({silent:e.json});i=P.workspacePath,p=P.created;}let y=await Ol({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});y.path!==w&&m.registerCompensation(()=>O__default.remove(y.path));try{if(r?.syncWorkspaceProjects)await r.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:P,registerWorkspaceStrict:S}=await import('./workspace-BNRSBWSL.js');await S(i,j.basename(i)),await P(i,y.name,y.path);}await m.commit(),await Jr(i,{silent:e.json});}catch(P){try{await pr(m,P);}catch(S){if(S!==P)throw S}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${P instanceof Error?P.message:String(P)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?p:false,projectWorkspaceCommand:f,commandsResolveWorkspaceFromProject:true,plan:y.ingestionPlan,importedProject:y},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${y.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${y.path}`)),console.log(s.gray(` Stack: ${y.stack} (${y.confidence})`)),console.log(s.gray(` Source: ${e.git===true||xt(t)?"git-url":"local-folder"}`)),!y.profileCompatibility.ok){let P=tn(y.profileCompatibility);console.log(s.yellow(` Profile warning: ${y.profileCompatibility.message}`)),P&&console.log(s.gray(` ${P}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${f}`)),0}catch(w){if(m)try{await pr(m,w);}catch(P){P!==w&&(w=P);}let y=w instanceof Error?w.message:String(w);return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C Import failed: ${y}`)),1}}async function mp(t,e,r){let o=j.resolve(t||process.cwd()),n=e.workspace?j.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:cp(process.cwd()),i=a.workspacePath,c=false,p=false,d=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!qe(n)){let y=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C ${y}`)),1}}else (!i||!qe(i))&&(i=o$1(),c=true,d=e.dryRun!==true);let f=c&&i!==null&&(e.dryRun===true||d);if(!i||!qe(i)&&!f){let y="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:y},null,2)):(console.log(s.red(`\u274C ${y}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let m=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),w;try{if(e.dryRun!==true&&(w=await sn(i,{projectPath:o,ownedWorkspace:d?i:void 0}),d)){let h=await Bs({silent:e.json});i=h.workspacePath,p=h.created;}let y=await ks(i,o),P=await vs({workspacePath:i,source:o,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:y}),S="npx workspai project workspace status --json",l=e.dryRun===true?b$5({startPath:o}):null,v=e.dryRun!==true||l!==null&&j.resolve(l.workspacePath)===j.resolve(i)&&(!l.projectPath||j.resolve(l.projectPath)===o);if(e.dryRun!==true)try{if(r?.registerWorkspace||r?.registerProjectInWorkspace||r?.syncWorkspaceProjects)r.registerWorkspace&&await r.registerWorkspace(i,j.basename(i)),r.registerProjectInWorkspace&&await r.registerProjectInWorkspace(i,P.name,P.path),r.syncWorkspaceProjects&&await r.syncWorkspaceProjects(i);else {let{registerProjectInWorkspaceStrict:h,registerWorkspaceStrict:g}=await import('./workspace-BNRSBWSL.js');if(await g(i,j.basename(i)),await h(i,P.name,P.path),m)throw new Error("forced sync failure for command-level adopt rollback test")}await w?.commit(),await Jr(i,{silent:e.json});}catch(h){if(w)try{await pr(w,h);}catch(g){if(g!==h)throw g}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${h instanceof Error?h.message:String(h)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?p:false,wouldCreateDefaultWorkspace:c&&e.dryRun===true?!qe(i):false,projectWorkspaceCommand:S,commandsResolveWorkspaceFromProject:v,dryRun:e.dryRun===true,plan:P.ingestionPlan,adoptedProject:P},null,2)),0;c&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${i}`)),e.dryRun===true&&(console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.gray(" Planned effects: project metadata + workspace registration + model, graph, and agent-grounding sync.")),P.effects.repositoryControlFiles.length>0&&console.log(s.gray(` Repository controls may be reconciled: ${P.effects.repositoryControlFiles.map(h=>h.path).join(", ")}.`))),console.log(s.green(`\u2714 Adopted project: ${P.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${P.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)"));let u=P.stack==="unknown"?P.frameworkDisplayName||P.runtime:P.stack;if(console.log(s.gray(` Stack: ${u} (${P.confidence})`)),!P.profileCompatibility.ok){let h=tn(P.profileCompatibility);console.log(s.yellow(` Profile warning: ${P.profileCompatibility.message}`)),h&&console.log(s.gray(` ${h}`));}return console.log(s.gray(` Report: ${P.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Check: ${S}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(y){if(w)try{await pr(w,y);}catch(S){S!==y&&(y=S);}let P=y instanceof Error?y.message:String(y);return e.json?console.log(JSON.stringify({error:P},null,2)):console.log(s.red(`\u274C Adopt failed: ${P}`)),1}}async function Fs(t){let e=new Set(["python-only","polyglot","enterprise"]),r=Tm(),o="minimal",n$1=false;try{let p$1=s$1(t,"workspace.json").find(f=>_.existsSync(f))??p(t,"workspace.json"),d=JSON.parse(await _.promises.readFile(p$1,"utf-8"));o=d.profile??"minimal",n$1=d.bootstrap_note==="python-engine-skipped"||d.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(!n$1&&e.has(o))return true;let p=await Gs(t);if(p.length===0)return false;for(let d of p){let f=i$3(d),m=f?.module_support,w=p$3(d);if(n$1){if(w?.moduleSupport===true)return true;continue}if(!(j$3(f,d)||l(f,d)||m$1(f,d))&&m!==false)return n(f,d)||k$1(f,d),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:p}=await import('./workspace-marker-7NHMDIRL.js'),f=(await p(t))?.metadata?.npm?.installMethod;(f==="poetry"||f==="venv"||f==="pipx"||f==="pip")&&(i=f);}catch{}let c=async()=>{let p=sm(t);if(!await O__default.pathExists(p)){let w=await im(t);if(w!==0)return w}let d=g$3("DEV_PATH"),m=(d?await O__default.pathExists(d):false)&&d?["-m","pip","install",d,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await Ce(p,m,t,{timeoutMs:r})};if(i==="venv"){let p=await c();if(p!==0)return p}else if(i==="poetry"){let p=j.join(t,"pyproject.toml"),d=false;try{d=(await _.promises.readFile(p,"utf-8")).includes("rapidkit-core");}catch{d=false;}if(d){let f=await c();if(f!==0)return f}else {let f=await Ce("poetry",["install","--no-root"],t,{timeoutMs:r});if(f!==0)return f;let m=await Ce("poetry",["add","rapidkit-core"],t,{timeoutMs:r});if(m!==0)return m}}else return 0;try{let{writeWorkspaceLauncher:p}=await import('./create-HUEDWYDM.js');await p(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:p}=await import('./workspace-python-engine-state-J4QKW55K.js');await p(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function Tm(){let t=process.env.RAPIDKIT_WORKSPACE_DEPS_TIMEOUT_MS;if(t){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 12e4}async function Gs(t$1){let e=[],r=new Set,o=[t$1];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await _.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){if(!i.isDirectory()||i.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(i.name))continue;let c=j.join(n,i.name);if((await Promise.all([...t(c,"context.json"),...t(c,"project.json")].map(d=>O__default.pathExists(d)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function Mm(t){return n$2(t)}async function Bs(t={}){let e=o$1(),r=j.basename(e),o=qe(e);if(!o){let{createProject:n}=await import('./create-HUEDWYDM.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:j.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b()});}finally{t.silent&&(console.log=i,console.warn=c,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function Es(t){let r=await Ke("go",{runCommandInCwd:Ce,runCoreRapidkit:e}).initProject(t);return oe(r)}function oe(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Dt(t,e$1){let r=Ke("node",{runCommandInCwd:Ce,runCoreRapidkit:e});if(t==="init"){let n=await r.initProject(e$1);return oe(n)}if(t==="dev"){let n=await r.runDev(e$1);return oe(n)}if(t==="test"){let n=await r.runTest(e$1);return oe(n)}if(t==="build"){let n=await r.runBuild(e$1);return oe(n)}if(t==="lint"){let n=await r.runLint?.(e$1);return oe(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e$1);return oe(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e$1);return oe(o)}async function ft(t,e$1){let r=Ke("java",{runCommandInCwd:Ce,runCoreRapidkit:e});if(t==="init"){let n=await r.initProject(e$1);return oe(n)}if(t==="dev"){let n=await r.runDev(e$1);return oe(n)}if(t==="test"){let n=await r.runTest(e$1);return oe(n)}if(t==="build"){let n=await r.runBuild(e$1);return oe(n)}if(t==="lint"){let n=await r.runLint?.(e$1);return oe(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e$1);return oe(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e$1);return oe(o)}function Rs(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$8(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$9()})}async function Wm(t,e=Js){if(t.includes("--help")||t.includes("-h")||t.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(N){if(!N)return null;let G=N.trim().toLowerCase();return G==="minimal"||G==="java-only"||G==="go-only"||G==="dotnet-only"||G==="python-only"||G==="node-only"||G==="polyglot"||G==="enterprise"?G:null},i=function(N){let Je=N.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",We=(Pe,Ue)=>{let rt=N.match(new RegExp(`^\\s*${Pe}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return rt?rt[1].toLowerCase()==="true":Ue};return {mode:Je,dependency_sharing_mode:pp(N),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"],p$1,d=false,f=false,m=false,w=false;for(let N=1;N<t.length;N+=1){let G=t[N];if(G==="--ci"){d=true;continue}if(G==="--offline"){f=true;continue}if(G==="--json"){m=true;continue}if(G==="--compliance-only"){w=true;continue}if(G==="--profile"){let de=t[N+1];if(!de||de.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;p$1=de,N+=1;continue}if(G.startsWith("--profile=")){p$1=G.slice(10);continue}c.push(G);}let y=a(p$1);if(p$1&&!y)return console.log(s.red(`Invalid profile: ${p$1}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let P=process.cwd(),S=c.slice(1).filter(N=>!N.startsWith("-"));if(S.length>0){let N=j.resolve(P,S[0]),G=i$3(N),de=_.existsSync(N)?await Lt(N):"unknown";if(!qe(N)&&(j$3(G,N)||l(G,N)||m$1(G,N)||k$1(G,N)||n(G,N)||de!=="unknown"))return await e(c)}let l$1=j.join(P,".rapidkit-workspace"),v=j.join(P,".rapidkit","workspace.json"),u;!_.existsSync(l$1)&&_.existsSync(v)?u=P:(u=be(P),u||(u=Sm(P)));let h=[],g=null,k=null;if(u)try{let N=s$1(u,"workspace.json").find(Je=>_.existsSync(Je))??p(u,"workspace.json"),G=await _.promises.readFile(N,"utf-8"),de=JSON.parse(G);k=a(de.profile);}catch{k=null;}let C=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],x={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"},b=y;if(!!u&&!y&&!d&&!m&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let N=k||"minimal",{chosenProfile:G}=await b$1([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${N})`,choices:C.map(de=>({name:de===N?`${x[de]} \u2190 current`:x[de],value:de})),default:C.indexOf(N)}]);b=G;}let R=b||k||"minimal";if(u&&!w)try{let G=R==="python-only"||R==="polyglot"||R==="enterprise"?"poetry":"venv",de;try{let Ue=(await _.promises.readFile(j.join(u,".python-version"),"utf-8")).trim();Ue&&(de=Ue);}catch{}let{syncWorkspaceFoundationFiles:Je}=await import('./create-HUEDWYDM.js'),We=await Je(u,{workspaceName:j.basename(u),installMethod:G,pythonVersion:de,profile:R,writeMarker:true,writeGitignore:true,onlyIfMissing:true});h.push({id:"workspace.foundation.sync",status:We.length>0?"passed":"skipped",message:We.length>0?`Workspace foundation synchronized: ${We.join(", ")}`:"Workspace foundation files are already up to date."});}catch(N){h.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${N.message}`});}else u&&h.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(u&&!w&&b&&b!==k)try{let N=p(u,"workspace.json"),G=await _.promises.readFile(N,"utf-8"),de=JSON.parse(G);de.profile=b,await O__default.ensureDir(j.dirname(N)),await _.promises.writeFile(N,JSON.stringify(de,null,2)+`
|
|
296
|
-
`,"utf-8");let{syncWorkspaceContract:Je}=await import('./workspace-contract-
|
|
297
|
-
`):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${Q}`))),1}if(
|
|
298
|
-
`),1}let H=async
|
|
299
|
-
`);else {let
|
|
300
|
-
`):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),1;let a=async(y,P)=>{if(y==="node"){if(!_.existsSync(j.join(P,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let
|
|
301
|
-
`,"utf-8");}let h={requested:n,status:"not-requested",exitCode:null,targets:0,messages:[]};if(n&&S.exitCode===0){let g=[v];if(r==="java"&&
|
|
302
|
-
`),S.exitCode}finally{typeof y>"u"?delete process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT:process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT=y;}}let i=Ke(r,{runCommandInCwd:e
|
|
303
|
-
${
|
|
304
|
-
${X.stderr||""}`.match(/Apache Maven\s+(\S+)/i);g=q?q[1]:null;}else if(
|
|
305
|
-
${X.stderr||""}`.match(/Gradle\s+(\S+)/i);g=q?q[1]:null;}}catch{}v.java={...v.java||{},version:
|
|
306
|
-
`,"utf-8"),console.log(s.gray(" toolchain.lock updated (.workspai/toolchain.lock)"));}catch{}}else console.log(s.red(`\u274C ${r} prerequisites check failed.`));if(
|
|
307
|
-
Hints:`));for(let y of
|
|
308
|
-
`)){let o=r.trim(),n=o.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]/g,""));let a=o.match(/^prune_on_bootstrap:\s*(true|false)/);a&&(e.prune_on_bootstrap=a[1]==="true");let i=o.match(/^self_heal:\s*(true|false)/);i&&(e.self_heal=i[1]==="true");let c=o.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function Fm(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=t.includes("--dry-run"),n=Jo.getInstance(),a=be(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(a)try{let c=s$1(a,"cache-config.yml").find(
|
|
286
|
+
`;await _.promises.writeFile(r,o,"utf-8");}function _m(t){let e=t.trim().toLowerCase();return e==="true"||e==="1"||e==="on"?true:e==="false"||e==="0"||e==="off"?false:null}function pp(t){if(!t)return "isolated";let r=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated"?r:"isolated"}function dp(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 r=e[1].toLowerCase();return r==="isolated"||r==="shared-runtime-caches"||r==="shared-node-deps"?{mode:r,status:"passed",message:`dependency_sharing_mode is valid: ${r}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${r}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function up(t,e){let r=be(t),o=r?s$1(r,"policies.yml").find(c=>_.existsSync(c)):null,n="isolated";if(o&&await O__default.pathExists(o))try{let c=await _.promises.readFile(o,"utf-8"),d=dp(c);if(d.status==="failed")return console.log(s.red(`\u274C ${d.message}`)),{ok:false,code:1};n=d.mode;}catch{return console.log(s.red("\u274C Failed to read workspace policy file (.workspai/policies.yml).")),{ok:false,code:1}}let a=process.env.RAPIDKIT_DEP_SHARING_MODE,i=process.env.RAPIDKIT_WORKSPACE_PATH;process.env.RAPIDKIT_DEP_SHARING_MODE=n,r&&(process.env.RAPIDKIT_WORKSPACE_PATH=r);try{return {ok:true,value:await e()}}finally{typeof a>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=a,typeof i>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=i;}}async function Ce(t,e,r,o={}){let{buildPackageRunnerSubprocessEnv:n,resolvePackageRunnerInvocation:a}=await import('./platform-capabilities-PR6YL4KC.js'),i=Im(t,e,r),c=i?{command:process.execPath,prefixArgs:["-e",i]}:a(t),d=c.command,l=i?c.prefixArgs:[...c.prefixArgs,...e],f=n();if(i){lr()&&process.stderr.write(`[workspai-cli] runCommandInCwd.nodeEval=${JSON.stringify({cwd:r,scriptBytes:i.length})}
|
|
287
|
+
`);try{return Zu.runInThisContext(i,{filename:j.join(r,"package.json#script")}),0}catch(p){return process.stderr.write(`${p instanceof Error?p.stack||p.message:String(p)}
|
|
288
|
+
`),1}}let w=!(process.argv.includes("--json")||process.env.RAPIDKIT_WORKSPACE_RUN_CHILD==="1"||process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT==="1")&&t==="npm"&&(e[0]==="run"||e[0]==="run-script"||e[0]==="install"),y=()=>{let p=f.npm_config_cache;if(!p)return "";let v=j.join(p,"_logs");try{let h=_.readdirSync(v).filter(k=>k.endsWith(".log")).map(k=>{let b=j.join(v,k);return {filePath:b,mtimeMs:_.statSync(b).mtimeMs}}).sort((k,b)=>b.mtimeMs-k.mtimeMs)[0]?.filePath;return h?_.readFileSync(h,"utf-8").split(/\r?\n/).map(k=>k.trim()).filter(k=>/(?:^|\s)(?:npm\s+)?(?:error|verbose\s+(?:stack|cwd|os|node|npm|exit|code))\b/i.test(k)).slice(0,12).join(`
|
|
289
|
+
`):""}catch{return ""}},P=Number.parseInt(process.env.RAPIDKIT_CHILD_COMMAND_TIMEOUT_MS||"",10),S=o.timeoutMs&&o.timeoutMs>0?o.timeoutMs:Number.isFinite(P)&&P>0?P:void 0;return await new Promise(p=>{let v=[],m=[],h=false,g=null,k=null,b=()=>{try{k?.stdout?.destroy();}catch{}try{k?.stderr?.destroy();}catch{}try{k?.stdin?.destroy();}catch{}try{k?.removeAllListeners("close"),k?.removeAllListeners("error"),k?.unref();}catch{}};lr()&&process.stderr.write(`[workspai-cli] runCommandInCwd=${JSON.stringify({executable:d,args:l,cwd:r,directNodeEvalScript:i!==null,npmEnv:Object.fromEntries(Object.entries(f).filter(([C])=>["npm_config_if_present","npm_config_ignore_scripts","npm_config_loglevel","npm_config_silent","npm_config_json","npm_lifecycle_event","npm_lifecycle_script"].includes(C)))})}
|
|
290
|
+
`);let x=b$3()&&/\.(?:cmd|bat)$/i.test(d);k=spawn(d,l,{stdio:w?"inherit":["ignore","pipe","pipe"],cwd:r,shell:x,env:f,detached:!b$3()}),S&&S>0&&(g=setTimeout(()=>{if(!h){if(h=true,!b$3()&&k.pid)try{process.kill(-k.pid,"SIGTERM");}catch{k.kill("SIGTERM");}else k.kill("SIGTERM");b(),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`RapidKit command timed out after ${S}ms: ${d} ${l.join(" ")}
|
|
291
|
+
`),p(124);}},S)),w||(k.stdout?.on("data",C=>{v.push(C);}),k.stderr?.on("data",C=>{m.push(C);})),k.on("close",C=>{if(h)return;h=true,g&&clearTimeout(g);let R=Buffer.concat(v),E=Buffer.concat(m),$=C&&C!==0&&R.length===0&&E.length===0&&t==="npm"?y():"";lr()&&process.stderr.write(`[workspai-cli] runCommandInCwd.close=${JSON.stringify({code:C,stdoutBytes:R.length,stderrBytes:E.length,npmFailureExcerptBytes:$.length})}
|
|
292
|
+
`),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(R.length>0&&process.stdout.write(R),E.length>0?process.stderr.write(E):$&&process.stderr.write(`${$}
|
|
293
|
+
`)),p(C??1);}),k.on("error",C=>{h||(h=true,g&&clearTimeout(g),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`Workspai could not execute ${d}: ${C.message}. Install the required runtime or tool and ensure it is available on PATH.
|
|
294
|
+
`),p(1));});})}function Im(t,e,r){if(t!=="npm")return null;let o=e[0];if(o!=="run"&&o!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=j.join(r,"package.json");if(!_.existsSync(a))return null;try{let c=JSON.parse(_.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:Om(c)}catch{return null}}function Om(t){let e=t.trim(),r=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(r)return r[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let o=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return o?o[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function an(t,e){await O__default.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
295
|
+
`,"utf-8");}function $m(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function Nm(t,e,r){let o=xt(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":j.basename(e),n=$m(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=j.join(t,i);if(!await O__default.pathExists(c))return c;a+=1;}}async function Ls(t,e,r){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?j.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:cp(process.cwd()),i=a.workspacePath,c=false,d=false,l=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!qe(n)){let w=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:w},null,2)):console.log(s.red(`\u274C ${w}`)),1}}else (!i||!qe(i))&&(i=o$1(),c=true,l=true);if(!i||!qe(i)&&!l){let w="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:w},null,2)):(console.log(s.red(`\u274C ${w}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let f="npx workspai project workspace status --json",u;try{let w=await Nm(i,t,e.name);if(u=await sn(i,{ownedDestination:w,ownedWorkspace:l?i:void 0}),l){let P=await Bs({silent:e.json});i=P.workspacePath,d=P.created;}let y=await Ol({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});y.path!==w&&u.registerCompensation(()=>O__default.remove(y.path));try{if(r?.syncWorkspaceProjects)await r.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:P,registerWorkspaceStrict:S}=await import('./workspace-UUU4VMZB.js');await S(i,j.basename(i)),await P(i,y.name,y.path);}await u.commit(),await Jr(i,{silent:e.json});}catch(P){try{await pr(u,P);}catch(S){if(S!==P)throw S}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${P instanceof Error?P.message:String(P)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?d:false,projectWorkspaceCommand:f,commandsResolveWorkspaceFromProject:true,plan:y.ingestionPlan,importedProject:y},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${y.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${y.path}`)),console.log(s.gray(` Stack: ${y.stack} (${y.confidence})`)),console.log(s.gray(` Source: ${e.git===true||xt(t)?"git-url":"local-folder"}`)),!y.profileCompatibility.ok){let P=tn(y.profileCompatibility);console.log(s.yellow(` Profile warning: ${y.profileCompatibility.message}`)),P&&console.log(s.gray(` ${P}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${f}`)),0}catch(w){if(u)try{await pr(u,w);}catch(P){P!==w&&(w=P);}let y=w instanceof Error?w.message:String(w);return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C Import failed: ${y}`)),1}}async function mp(t,e,r){let o=j.resolve(t||process.cwd()),n=e.workspace?j.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:cp(process.cwd()),i=a.workspacePath,c=false,d=false,l=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!qe(n)){let y=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C ${y}`)),1}}else (!i||!qe(i))&&(i=o$1(),c=true,l=e.dryRun!==true);let f=c&&i!==null&&(e.dryRun===true||l);if(!i||!qe(i)&&!f){let y="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:y},null,2)):(console.log(s.red(`\u274C ${y}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let u=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),w;try{if(e.dryRun!==true&&(w=await sn(i,{projectPath:o,ownedWorkspace:l?i:void 0}),l)){let h=await Bs({silent:e.json});i=h.workspacePath,d=h.created;}let y=await ks(i,o),P=await vs({workspacePath:i,source:o,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:y}),S="npx workspai project workspace status --json",p=e.dryRun===true?b$5({startPath:o}):null,v=e.dryRun!==true||p!==null&&j.resolve(p.workspacePath)===j.resolve(i)&&(!p.projectPath||j.resolve(p.projectPath)===o);if(e.dryRun!==true)try{if(r?.registerWorkspace||r?.registerProjectInWorkspace||r?.syncWorkspaceProjects)r.registerWorkspace&&await r.registerWorkspace(i,j.basename(i)),r.registerProjectInWorkspace&&await r.registerProjectInWorkspace(i,P.name,P.path),r.syncWorkspaceProjects&&await r.syncWorkspaceProjects(i);else {let{registerProjectInWorkspaceStrict:h,registerWorkspaceStrict:g}=await import('./workspace-UUU4VMZB.js');if(await g(i,j.basename(i)),await h(i,P.name,P.path),u)throw new Error("forced sync failure for command-level adopt rollback test")}await w?.commit(),await Jr(i,{silent:e.json});}catch(h){if(w)try{await pr(w,h);}catch(g){if(g!==h)throw g}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${h instanceof Error?h.message:String(h)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?d:false,wouldCreateDefaultWorkspace:c&&e.dryRun===true?!qe(i):false,projectWorkspaceCommand:S,commandsResolveWorkspaceFromProject:v,dryRun:e.dryRun===true,plan:P.ingestionPlan,adoptedProject:P},null,2)),0;c&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${i}`)),e.dryRun===true&&(console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.gray(" Planned effects: project metadata + workspace registration + model, graph, and agent-grounding sync.")),P.effects.repositoryControlFiles.length>0&&console.log(s.gray(` Repository controls may be reconciled: ${P.effects.repositoryControlFiles.map(h=>h.path).join(", ")}.`))),console.log(s.green(`\u2714 Adopted project: ${P.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${P.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)"));let m=P.stack==="unknown"?P.frameworkDisplayName||P.runtime:P.stack;if(console.log(s.gray(` Stack: ${m} (${P.confidence})`)),!P.profileCompatibility.ok){let h=tn(P.profileCompatibility);console.log(s.yellow(` Profile warning: ${P.profileCompatibility.message}`)),h&&console.log(s.gray(` ${h}`));}return console.log(s.gray(` Report: ${P.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Check: ${S}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(y){if(w)try{await pr(w,y);}catch(S){S!==y&&(y=S);}let P=y instanceof Error?y.message:String(y);return e.json?console.log(JSON.stringify({error:P},null,2)):console.log(s.red(`\u274C Adopt failed: ${P}`)),1}}async function Fs(t){let e=new Set(["python-only","polyglot","enterprise"]),r=Tm(),o="minimal",n$1=false;try{let d=s$1(t,"workspace.json").find(f=>_.existsSync(f))??p(t,"workspace.json"),l=JSON.parse(await _.promises.readFile(d,"utf-8"));o=l.profile??"minimal",n$1=l.bootstrap_note==="python-engine-skipped"||l.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(!n$1&&e.has(o))return true;let d=await Gs(t);if(d.length===0)return false;for(let l$1 of d){let f=i$2(l$1),u=f?.module_support,w=p$3(l$1);if(n$1){if(w?.moduleSupport===true)return true;continue}if(!(j$3(f,l$1)||l(f,l$1)||m$1(f,l$1))&&u!==false)return n(f,l$1)||k$1(f,l$1),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:d}=await import('./workspace-marker-7NHMDIRL.js'),f=(await d(t))?.metadata?.npm?.installMethod;(f==="poetry"||f==="venv"||f==="pipx"||f==="pip")&&(i=f);}catch{}let c=async()=>{let d=sm(t);if(!await O__default.pathExists(d)){let w=await im(t);if(w!==0)return w}let l=f$4("DEV_PATH"),u=(l?await O__default.pathExists(l):false)&&l?["-m","pip","install",l,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await Ce(d,u,t,{timeoutMs:r})};if(i==="venv"){let d=await c();if(d!==0)return d}else if(i==="poetry"){let d=j.join(t,"pyproject.toml"),l=false;try{l=(await _.promises.readFile(d,"utf-8")).includes("rapidkit-core");}catch{l=false;}if(l){let f=await c();if(f!==0)return f}else {let f=await Ce("poetry",["install","--no-root"],t,{timeoutMs:r});if(f!==0)return f;let u=await Ce("poetry",["add","rapidkit-core"],t,{timeoutMs:r});if(u!==0)return u}}else return 0;try{let{writeWorkspaceLauncher:d}=await import('./create-IRNHMUEN.js');await d(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:d}=await import('./workspace-python-engine-state-J4QKW55K.js');await d(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function Tm(){let t=process.env.RAPIDKIT_WORKSPACE_DEPS_TIMEOUT_MS;if(t){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 12e4}async function Gs(t$1){let e=[],r=new Set,o=[t$1];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await _.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){if(!i.isDirectory()||i.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(i.name))continue;let c=j.join(n,i.name);if((await Promise.all([...t(c,"context.json"),...t(c,"project.json")].map(l=>O__default.pathExists(l)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function Mm(t){return n$2(t)}async function Bs(t={}){let e=o$1(),r=j.basename(e),o=qe(e);if(!o){let{createProject:n}=await import('./create-IRNHMUEN.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:j.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b()});}finally{t.silent&&(console.log=i,console.warn=c,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function Es(t){let r=await Ke("go",{runCommandInCwd:Ce,runCoreRapidkit:e$1}).initProject(t);return oe(r)}function oe(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Dt(t,e){let r=Ke("node",{runCommandInCwd:Ce,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return oe(n)}if(t==="dev"){let n=await r.runDev(e);return oe(n)}if(t==="test"){let n=await r.runTest(e);return oe(n)}if(t==="build"){let n=await r.runBuild(e);return oe(n)}if(t==="lint"){let n=await r.runLint?.(e);return oe(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return oe(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return oe(o)}async function ft(t,e){let r=Ke("java",{runCommandInCwd:Ce,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return oe(n)}if(t==="dev"){let n=await r.runDev(e);return oe(n)}if(t==="test"){let n=await r.runTest(e);return oe(n)}if(t==="build"){let n=await r.runBuild(e);return oe(n)}if(t==="lint"){let n=await r.runLint?.(e);return oe(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return oe(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return oe(o)}function Rs(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$8(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$a()})}async function Wm(t,e=Js){if(t.includes("--help")||t.includes("-h")||t.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(T){if(!T)return null;let G=T.trim().toLowerCase();return G==="minimal"||G==="java-only"||G==="go-only"||G==="dotnet-only"||G==="python-only"||G==="node-only"||G==="polyglot"||G==="enterprise"?G:null},i=function(T){let Je=T.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",De=(Pe,Ue)=>{let rt=T.match(new RegExp(`^\\s*${Pe}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return rt?rt[1].toLowerCase()==="true":Ue};return {mode:Je,dependency_sharing_mode:pp(T),rules:{enforce_workspace_marker:De("enforce_workspace_marker",true),enforce_toolchain_lock:De("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:De("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:De("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:De("require_mirror_lock_for_offline",true)}}};let c=["init"],d,l$1=false,f=false,u=false,w=false;for(let T=1;T<t.length;T+=1){let G=t[T];if(G==="--ci"){l$1=true;continue}if(G==="--offline"){f=true;continue}if(G==="--json"){u=true;continue}if(G==="--compliance-only"){w=true;continue}if(G==="--profile"){let de=t[T+1];if(!de||de.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;d=de,T+=1;continue}if(G.startsWith("--profile=")){d=G.slice(10);continue}c.push(G);}let y=a(d);if(d&&!y)return console.log(s.red(`Invalid profile: ${d}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let P=process.cwd(),S=c.slice(1).filter(T=>!T.startsWith("-"));if(S.length>0){let T=j.resolve(P,S[0]),G=i$2(T),de=_.existsSync(T)?await Lt(T):"unknown";if(!qe(T)&&(j$3(G,T)||l(G,T)||m$1(G,T)||k$1(G,T)||n(G,T)||de!=="unknown"))return await e(c)}let p$1=j.join(P,".rapidkit-workspace"),v=j.join(P,".rapidkit","workspace.json"),m;!_.existsSync(p$1)&&_.existsSync(v)?m=P:(m=be(P),m||(m=Sm(P)));let h=[],g=null,k=null;if(m)try{let T=s$1(m,"workspace.json").find(Je=>_.existsSync(Je))??p(m,"workspace.json"),G=await _.promises.readFile(T,"utf-8"),de=JSON.parse(G);k=a(de.profile);}catch{k=null;}let b=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],x={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"},C=y;if(!!m&&!y&&!l$1&&!u&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let T=k||"minimal",{chosenProfile:G}=await b$1([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${T})`,choices:b.map(de=>({name:de===T?`${x[de]} \u2190 current`:x[de],value:de})),default:b.indexOf(T)}]);C=G;}let E=C||k||"minimal";if(m&&!w)try{let G=E==="python-only"||E==="polyglot"||E==="enterprise"?"poetry":"venv",de;try{let Ue=(await _.promises.readFile(j.join(m,".python-version"),"utf-8")).trim();Ue&&(de=Ue);}catch{}let{syncWorkspaceFoundationFiles:Je}=await import('./create-IRNHMUEN.js'),De=await Je(m,{workspaceName:j.basename(m),installMethod:G,pythonVersion:de,profile:E,writeMarker:true,writeGitignore:true,onlyIfMissing:true});h.push({id:"workspace.foundation.sync",status:De.length>0?"passed":"skipped",message:De.length>0?`Workspace foundation synchronized: ${De.join(", ")}`:"Workspace foundation files are already up to date."});}catch(T){h.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${T.message}`});}else m&&h.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(m&&!w&&C&&C!==k)try{let T=p(m,"workspace.json"),G=await _.promises.readFile(T,"utf-8"),de=JSON.parse(G);de.profile=C,await O__default.ensureDir(j.dirname(T)),await _.promises.writeFile(T,JSON.stringify(de,null,2)+`
|
|
296
|
+
`,"utf-8");let{syncWorkspaceContract:Je}=await import('./workspace-contract-3BWIRSVQ.js');await Je({workspacePath:m}),h.push({id:"workspace.profile.sync",status:"passed",message:`Workspace profile synchronized to ${C} across canonical artifacts.`});}catch(T){h.push({id:"workspace.profile.sync",status:"failed",message:`Failed to synchronize workspace profile across canonical artifacts: ${T instanceof Error?T.message:String(T)}`});}let $={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}},M=null;if(m)try{let T=s$1(m,"policies.yml").find(de=>_.existsSync(de));if(!T)throw new Error("policy file missing");let G=await _.promises.readFile(T,"utf-8");M=G,$=i(G);}catch{h.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else h.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(m){let T=dp(M);$.dependency_sharing_mode=T.mode,h.push({id:"policy.schema.dependency_sharing_mode",status:T.status,message:T.message}),h.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:$.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":$.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 G=_.existsSync(j.join(m,".workspai-workspace"))||_.existsSync(j.join(m,".rapidkit-workspace"));h.push({id:"policy.enforce_workspace_marker",status:!$.rules.enforce_workspace_marker||G?"passed":"failed",message:!$.rules.enforce_workspace_marker||G?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let de=s$1(m,"toolchain.lock").some(Ee=>_.existsSync(Ee));h.push({id:"policy.enforce_toolchain_lock",status:!$.rules.enforce_toolchain_lock||de?"passed":"failed",message:!$.rules.enforce_toolchain_lock||de?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let Je=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||s$1(m,"trusted-sources.lock").some(Ee=>_.existsSync(Ee));h.push({id:"policy.disallow_untrusted_tool_sources",status:!$.rules.disallow_untrusted_tool_sources||Je?"passed":"failed",message:!$.rules.disallow_untrusted_tool_sources||Je?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let De=s$1(m,"compatibility-matrix.json").find(Ee=>_.existsSync(Ee))??p(m,"compatibility-matrix.json"),Pe=_.existsSync(De),Ue=$.rules.enforce_compatibility_matrix;if(h.push({id:"policy.enforce_compatibility_matrix",status:!Ue||Pe?"passed":"failed",message:!Ue||Pe?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),Pe)try{let Ee=await _.promises.readFile(De,"utf-8"),mt=JSON.parse(Ee),zs=!!mt&&typeof mt=="object";h.push({id:"compatibility.matrix.parse",status:zs?"passed":"failed",message:zs?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{h.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let rt=s$1(m,"mirror-config.json").find(Ee=>_.existsSync(Ee))??p(m,"mirror-config.json"),dr=s$1(m,"mirror.lock").find(Ee=>_.existsSync(Ee))??p(m,"mirror.lock"),ln=_.existsSync(rt),pn=_.existsSync(dr),qs={};if(ln)try{qs=JSON.parse(await _.promises.readFile(rt,"utf-8")),h.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{h.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(w)h.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let Ee=await fs(m,{ciMode:l$1,offlineMode:f});h.push(...Ee.checks.map(mt=>({id:mt.id,status:mt.status,message:mt.message}))),g=Ee.details,Ee.details.lockWritten&&(pn=true);}if(f){let Ee=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||qs.enabled===true;h.push({id:"offline.mirror.enabled",status:Ee?"passed":"failed",message:Ee?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let mt=$.rules.require_mirror_lock_for_offline;h.push({id:"offline.mirror.lock",status:!mt||pn?"passed":"failed",message:!mt||pn?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else h.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Vr=Tt({profile:E,runtimes:await Mt(m),mode:$.mode});Vr.profile!=="enterprise"?h.push({id:Vr.checkId,status:Vr.status,message:Vr.message}):(h.push({id:"profile.enterprise.ci",status:l$1?"passed":w?"skipped":"failed",message:l$1?"enterprise profile running with --ci.":w?"Enterprise runtime execution skipped by --compliance-only; --ci is not required.":"enterprise profile expects --ci for deterministic non-interactive mode."}),h.push({id:"profile.enterprise.compatibility-matrix",status:Pe?"passed":"failed",message:Pe?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),h.push({id:"profile.enterprise.mirror-config",status:ln?"passed":"failed",message:ln?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}l$1&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),f&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let A=h.some(T=>T.id.startsWith("policy.schema.")&&T.status==="failed")||$.mode==="strict"&&h.some(T=>T.status==="failed"),U=p(m||P,"reports"),q=new Date().toISOString().replace(/[:.]/g,"-"),Q=j.join(U,`bootstrap-compliance-${q}.json`),L=j.join(U,"bootstrap-compliance.latest.json"),F={schemaVersion:h$3.bootstrapCompliance.schemaVersion,command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:m,profile:E,options:{ci:l$1,offline:f,strict:$.mode==="strict",complianceOnly:w},policyMode:$.mode,policyRules:$.rules,mirrorLifecycle:g,checks:h},K=async T=>{b$l(`.workspai/reports/${j.basename(Q)}`,T),b$l(i$1.bootstrapCompliance,T),await O__default.ensureDir(U),await an(Q,T),await an(L,T);};if(A){let T=Rs({...F,result:"blocked",initExitCode:null},1,h);return await K(T),u?process.stdout.write(`${JSON.stringify(T,null,2)}
|
|
297
|
+
`):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${Q}`))),1}if(u&&E==="enterprise"&&!l$1&&!w){let T=Rs({...F,result:"blocked",initExitCode:null,complianceOnly:false,bootstrapRuntimeSkipped:{reason:"enterprise JSON bootstrap requires --ci for deterministic non-interactive execution.",nextAction:"npx workspai bootstrap --profile enterprise --ci --json"}},1,h);return await K(T),process.stdout.write(`${JSON.stringify(T,null,2)}
|
|
298
|
+
`),1}let H=async T=>{let G=process.stdout.write.bind(process.stdout),de=process.stderr.write.bind(process.stderr),Je=[],De=[];process.stdout.write=((Pe,Ue,rt)=>{let dr=typeof Ue=="function"?Ue:typeof rt=="function"?rt:void 0;return Je.push(typeof Pe=="string"?Pe:Pe instanceof Uint8Array?Buffer.from(Pe).toString("utf8"):String(Pe)),dr?.(),true}),process.stderr.write=((Pe,Ue,rt)=>{let dr=typeof Ue=="function"?Ue:typeof rt=="function"?rt:void 0;return De.push(typeof Pe=="string"?Pe:Pe instanceof Uint8Array?Buffer.from(Pe).toString("utf8"):String(Pe)),dr?.(),true});try{return {exitCode:await T(),stdout:Je.join(""),stderr:De.join("")}}finally{process.stdout.write=G,process.stderr.write=de;}},pe=T=>{let G=T.split(/\r?\n/).map(de=>de.trim()).filter(Boolean);return {bytes:Buffer.byteLength(T),excerpt:G.slice(0,12)}},ue=0,ae;if(!w)if(u){let T=await H(()=>e(c));ue=T.exitCode,ae={captured:true,stdout:pe(T.stdout),stderr:pe(T.stderr)};}else ue=await e(c);let le=h.filter(T=>T.status==="failed").length,ut=ue!==0?"failed":le>0?"ok_with_warnings":"ok",Ft=ue!==0?ue:le>0?1:0,_e=Rs({...F,result:ut,initExitCode:ue,complianceOnly:w,...ae?{initOutput:ae}:{}},Ft,h);if(await K(_e),m&&!w&&ue===0)try{let{syncWorkspaceProjects:T}=await import('./workspace-UUU4VMZB.js');await T(m,u),await Jr(m,{silent:u});}catch{}if(u)process.stdout.write(`${JSON.stringify(_e,null,2)}
|
|
299
|
+
`);else {let T=h.filter(G=>G.status==="failed").length;T>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${T} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${Q}`));}return Ft}finally{typeof r>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=r;}}async function Dm(t,e=Ce){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),0;let r=(t[1]||"").toLowerCase(),o=t.includes("--json"),n=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!r||!["python","node","go","java","dotnet","rust","php"].includes(r))return o?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]"},null,2)}
|
|
300
|
+
`):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),1;let a=async(y,P)=>{if(y==="node"){if(!_.existsSync(j.join(P,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let p=_.existsSync(j.join(P,"pnpm-lock.yaml")),v=_.existsSync(j.join(P,"yarn.lock"));return p?{exitCode:await e("pnpm",["install","--lockfile-only","--ignore-scripts"],P)}:v?{exitCode:await e("yarn",["install","--ignore-scripts"],P)}:{exitCode:await e("npm",["install","--package-lock-only","--ignore-scripts"],P)}}if(y==="go")return _.existsSync(j.join(P,"go.mod"))?{exitCode:await e("go",["mod","download"],P)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(y==="java"){let S=_.existsSync(j.join(P,"pom.xml")),p=_.existsSync(j.join(P,"build.gradle"))||_.existsSync(j.join(P,"build.gradle.kts")),v=j.join(P,process.platform==="win32"?"gradlew.bat":"gradlew"),m=_.existsSync(v);return !S&&!p?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:S?{exitCode:await e("mvn",["-B","-q","-DskipTests","dependency:go-offline"],P)}:{exitCode:await e(m?v:"gradle",["--no-daemon","dependencies"],P)}}return y==="dotnet"?(()=>{let p=[{dir:P,depth:0}],v=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;p.length>0;){let m=p.shift();if(!m||m.depth>3)continue;let h=[];try{h=_.readdirSync(m.dir,{withFileTypes:true});}catch{continue}for(let g of h)if(g.isFile()){let k=g.name.toLowerCase();if(k.endsWith(".sln")||k.endsWith(".csproj"))return true}else g.isDirectory()&&!v.has(g.name)&&p.push({dir:j.join(m.dir,g.name),depth:m.depth+1});}return false})()?{exitCode:await e("dotnet",["restore"],P)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:y==="rust"?_.existsSync(j.join(P,"Cargo.toml"))?{exitCode:await e("cargo",["fetch"],P)}:{exitCode:0,message:"Rust warm-up skipped: Cargo.toml not found in current directory."}:y==="php"?_.existsSync(j.join(P,"composer.json"))?{exitCode:await e("composer",["install","--no-interaction","--no-scripts"],P)}:{exitCode:0,message:"PHP warm-up skipped: composer.json not found in current directory."}:{exitCode:0,message:"Dependency warm-up is not available for this runtime."}};if(o){let y=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let S=await Ke(r,{runCommandInCwd:e,runCoreRapidkit:async(g,k)=>(await g$7(g,{...k,cwd:void 0})).exitCode}).checkPrereqs(),p$1=be(process.cwd()),v=p$1||process.cwd(),m=null;if(r==="node"&&S.exitCode===0&&(m=process.version),p$1&&m){let g=s$1(p$1,"toolchain.lock").find(x=>_.existsSync(x))??p(p$1,"toolchain.lock"),k=p(p$1,"toolchain.lock"),b={};try{b=JSON.parse(await _.promises.readFile(g,"utf-8"));}catch{}(!b.runtime||typeof b.runtime!="object")&&(b.runtime={}),b.runtime[r]={version:m,detectedAt:new Date().toISOString()},await O__default.ensureDir(j.dirname(k)),await _.promises.writeFile(k,JSON.stringify(b,null,2)+`
|
|
301
|
+
`,"utf-8");}let h={requested:n,status:"not-requested",exitCode:null,targets:0,messages:[]};if(n&&S.exitCode===0){let g=[v];if(r==="java"&&p$1){let R=(await Gs(p$1)).filter(E=>{let $=i$2(E);return l($,E)});R.length>0&&(g=R);}let k=[];for(let C of g)k.push(await a(r,C));let b=k.filter(C=>C.exitCode!==0),x=k.filter(C=>C.exitCode===0&&!/skipped/i.test(C.message||""));h.status=b.length>0?"failed":x.length>0?"passed":"skipped",h.exitCode=b[0]?.exitCode??0,h.targets=g.length,h.messages=k.map(C=>C.message).filter(C=>typeof C=="string");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:r,result:S.exitCode===0?"ok":"failed",exitCode:S.exitCode,workspacePath:p$1,version:m,warmDeps:n,warmDependencies:h},null,2)}
|
|
302
|
+
`),S.exitCode}finally{typeof y>"u"?delete process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT:process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT=y;}}let i=Ke(r,{runCommandInCwd:e,runCoreRapidkit:(y,P)=>e$1(y,{...P,cwd:void 0})}),c=await i.checkPrereqs(),d=await i.doctorHints(process.cwd()),l$1=be(process.cwd()),f=l$1||process.cwd(),u=null,w=async()=>r!=="java"||!l$1?[]:u||(u=(await Gs(l$1)).filter(P=>{let S=i$2(P);return l(S,P)}),u);if(c.exitCode===0){console.log(s.green(`\u2705 ${r} prerequisites look good.`));let y=["python","node","go","java","dotnet","rust","php"].filter(P=>P!==r).join("/");if(console.log(s.gray(` Scope: validated ${r} runtime only. ${y} checks are optional unless your workspace profile uses them.`)),r==="python"&&console.log(s.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),i.warmSetupCache&&((await i.warmSetupCache(f)).exitCode===0?console.log(s.gray(` ${r} cache warm-up completed.`)):console.log(s.yellow(` ${r} cache warm-up skipped (non-fatal).`))),n)if(r==="java"&&l$1){let P=await w();if(P.length>0){let S=0,p=0,v=0;for(let m of P){let h=await a("java",m),g=/skipped/i.test(h.message||""),k=j.relative(l$1,m)||j.basename(m);h.message&&console.log(s.gray(` [${k}] ${h.message}`)),h.exitCode===0&&!g?S+=1:h.exitCode===0&&g?v+=1:p+=1;}S>0&&console.log(s.gray(` java dependency warm-up completed for ${S} project(s) (--warm-deps).`)),p>0&&console.log(s.yellow(` java dependency warm-up failed for ${p} project(s) (non-fatal).`)),S===0&&p===0&&v>0&&console.log(s.gray(" java dependency warm-up skipped for discovered workspace projects."));}else {let S=await a("java",f),p=/skipped/i.test(S.message||"");S.message&&console.log(s.gray(` ${S.message}`)),S.exitCode===0&&!p?console.log(s.gray(` ${r} dependency warm-up completed (--warm-deps).`)):S.exitCode!==0&&console.log(s.yellow(` ${r} dependency warm-up failed (non-fatal).`));}}else {let P=await a(r,f),S=/skipped/i.test(P.message||"");P.message&&console.log(s.gray(` ${P.message}`)),P.exitCode===0&&!S?console.log(s.gray(` ${r} dependency warm-up completed (--warm-deps).`)):P.exitCode!==0&&console.log(s.yellow(` ${r} dependency warm-up failed (non-fatal).`));}if(l$1)try{let P=s$1(l$1,"toolchain.lock").find(m=>_.existsSync(m))??p(l$1,"toolchain.lock"),S=p(l$1,"toolchain.lock"),p$1={};try{p$1=JSON.parse(await _.promises.readFile(P,"utf-8"));}catch{}(!p$1.runtime||typeof p$1.runtime!="object")&&(p$1.runtime={});let v=p$1.runtime;if(r==="python"){let m=null;try{let{execa:h}=await import('execa');for(let g of Hs()){let b=await h(g,g==="py"?["-3","--version"]:["--version"],{cwd:l$1,stdio:"pipe",reject:false,timeout:3e3});if(b.exitCode===0){let C=(b.stdout||b.stderr||"").match(/Python\s+(\S+)/);if(m=C?C[1]:null,m)break}}}catch{}v.python={...v.python||{},version:m,last_setup:new Date().toISOString()};}else if(r==="node")v.node={...v.node||{},version:process.version,last_setup:new Date().toISOString()};else if(r==="go"){let m=null;try{let{execa:h}=await import('execa'),k=((await h("go",["version"],{cwd:l$1,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);m=k?k[1]:null;}catch{}v.go={...v.go||{},version:m,last_setup:new Date().toISOString()};}else if(r==="java"){let m=null,h=null,g=null,k=await w(),x=_.existsSync(j.join(f,"pom.xml"))||_.existsSync(j.join(f,"build.gradle"))||_.existsSync(j.join(f,"build.gradle.kts"))?f:k[0]||f;try{let{execa:C}=await import('execa'),R=await C("java",["-version"],{cwd:l$1,stdio:"pipe",reject:false,timeout:3e3}),$=`${R.stdout||""}
|
|
303
|
+
${R.stderr||""}`.match(/version\s+"([^"]+)"/i);m=$?$[1]:null;let M=_.existsSync(j.join(x,"pom.xml")),N=_.existsSync(j.join(x,"build.gradle"))||_.existsSync(j.join(x,"build.gradle.kts"));if(M){h="maven";let A=(()=>{let Q=j.join(x,"mvnw.cmd");if(process.platform==="win32"&&_.existsSync(Q))return Q;let L=j.join(x,"mvnw");return _.existsSync(L)?L:"mvn"})(),X=await C(A,["-version"],{cwd:x,stdio:"pipe",reject:false,timeout:3e3}),q=`${X.stdout||""}
|
|
304
|
+
${X.stderr||""}`.match(/Apache Maven\s+(\S+)/i);g=q?q[1]:null;}else if(N){h="gradle";let A=(()=>{let Q=j.join(x,"gradlew.bat");if(process.platform==="win32"&&_.existsSync(Q))return Q;let L=j.join(x,"gradlew");return _.existsSync(L)?L:"gradle"})(),X=await C(A,["--version"],{cwd:x,stdio:"pipe",reject:false,timeout:3e3}),q=`${X.stdout||""}
|
|
305
|
+
${X.stderr||""}`.match(/Gradle\s+(\S+)/i);g=q?q[1]:null;}}catch{}v.java={...v.java||{},version:m,build_tool:h,build_tool_version:g,last_setup:new Date().toISOString()};}else if(r==="dotnet"){let m=null;try{let{execa:h}=await import('execa'),k=((await h("dotnet",["--version"],{cwd:l$1,stdio:"pipe",reject:false,timeout:3e3})).stdout||"").trim();m=k.length>0?k:null;}catch{}v.dotnet={...v.dotnet||{},version:m,sdk:m,last_setup:new Date().toISOString()};}p$1.updated_at=new Date().toISOString(),await _.promises.writeFile(S,JSON.stringify(p$1,null,2)+`
|
|
306
|
+
`,"utf-8"),console.log(s.gray(" toolchain.lock updated (.workspai/toolchain.lock)"));}catch{}}else console.log(s.red(`\u274C ${r} prerequisites check failed.`));if(d.length>0){console.log(s.gray(`
|
|
307
|
+
Hints:`));for(let y of d)console.log(s.gray(`- ${y}`));}return c.exitCode}function Lm(t){let e={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let r of t.split(`
|
|
308
|
+
`)){let o=r.trim(),n=o.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]/g,""));let a=o.match(/^prune_on_bootstrap:\s*(true|false)/);a&&(e.prune_on_bootstrap=a[1]==="true");let i=o.match(/^self_heal:\s*(true|false)/);i&&(e.self_heal=i[1]==="true");let c=o.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function Fm(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=t.includes("--dry-run"),n=Jo.getInstance(),a=be(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(a)try{let c=s$1(a,"cache-config.yml").find(l=>_.existsSync(l));if(!c)throw new Error("cache config missing");let d=await _.promises.readFile(c,"utf-8");i=Lm(d);}catch{}if(e==="status"){let c={command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{enabled:true,strategy:i.strategy,selfHeal:i.self_heal,pruneOnBootstrap:i.prune_on_bootstrap,verifyIntegrity:i.verify_integrity,inMemory:true}};return r?(process.stdout.write(`${JSON.stringify(c,null,2)}
|
|
309
309
|
`),0):(console.log(s.cyan("Workspai cache is enabled")),console.log(s.cyan("Workspai cache status")),a?(console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Strategy: ${i.strategy}`)),console.log(s.gray(` Self-heal: ${i.self_heal}`)),console.log(s.gray(` Prune on bootstrap:${i.prune_on_bootstrap}`)),console.log(s.gray(` Verify integrity: ${i.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: workspai cache clear|prune|repair")),0)}return e==="clear"?(await n.clear(),r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{cleared:true,strategy:i.strategy}},null,2)}
|
|
310
310
|
`),0):(console.log(s.green("Cache clear completed")),console.log(s.green("\u2705 Cache cleared (all entries removed).")),0)):e==="prune"?(o||await n.clear(),r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,dryRun:o,cache:{pruned:!o,strategy:i.strategy,pruneOnBootstrap:i.prune_on_bootstrap},nextActions:i.prune_on_bootstrap?[]:["Set prune_on_bootstrap: true in .workspai/cache-config.yml to auto-prune on bootstrap."]},null,2)}
|
|
311
311
|
`),0):o?(console.log(s.green("Cache prune dry run completed")),console.log(s.gray(" No cache entries were removed.")),0):(console.log(s.green("\u2705 Cache pruned (stale entries removed).")),i.prune_on_bootstrap||console.log(s.gray(" Tip: set prune_on_bootstrap: true in .workspai/cache-config.yml to auto-prune on every bootstrap.")),0)):e==="repair"?i.self_heal?(await n.clear(),r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{repaired:true,selfHeal:i.self_heal,verifyIntegrity:i.verify_integrity}},null,2)}
|
|
312
312
|
`),0):(console.log(s.green("\u2705 Cache repaired (self-heal applied, stale entries evicted).")),i.verify_integrity&&console.log(s.gray(" Integrity verification is enabled in cache-config.yml.")),0)):r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"skipped",timestamp:new Date().toISOString(),workspacePath:a,reason:"self_heal is disabled in .workspai/cache-config.yml",cache:{selfHeal:i.self_heal,verifyIntegrity:i.verify_integrity}},null,2)}
|
|
313
|
-
`),0):(console.log(s.yellow("\u26A0\uFE0F self_heal is disabled in .workspai/cache-config.yml \u2014 skipping repair.")),0):(console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),1)}async function Gm(t,e,r,o,n=false){let a=(e||"show").toLowerCase(),i=p(t,"policies.yml");if(a==="show"||a==="status"||a==="get"){let
|
|
313
|
+
`),0):(console.log(s.yellow("\u26A0\uFE0F self_heal is disabled in .workspai/cache-config.yml \u2014 skipping repair.")),0):(console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),1)}async function Gm(t,e,r,o,n=false){let a=(e||"show").toLowerCase(),i=p(t,"policies.yml");if(a==="show"||a==="status"||a==="get"){let u=await ep(t),w=Ql(u);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,policy:w},null,2)}
|
|
314
314
|
`),0):(console.log(s.cyan(`Policy file: ${i}`)),console.log(s.gray(` mode: ${w.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${w.dependency_sharing_mode}`)),console.log(s.gray(" rules:")),console.log(s.gray(` enforce_workspace_marker: ${w.rules.enforce_workspace_marker}`)),console.log(s.gray(` enforce_toolchain_lock: ${w.rules.enforce_toolchain_lock}`)),console.log(s.gray(` disallow_untrusted_tool_sources: ${w.rules.disallow_untrusted_tool_sources}`)),console.log(s.gray(` enforce_compatibility_matrix: ${w.rules.enforce_compatibility_matrix}`)),console.log(s.gray(` require_mirror_lock_for_offline: ${w.rules.require_mirror_lock_for_offline}`)),console.log(s.gray("Examples:")),console.log(s.gray(" npx workspai workspace policy set mode strict")),console.log(s.gray(" npx workspai workspace policy set dependency_sharing_mode shared-runtime-caches")),console.log(s.gray(" npx workspai workspace policy set rules.enforce_toolchain_lock true")),0)}if(a!=="set")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_action",message:`Unknown workspace policy action: ${e||""}`},allowedActions:["show","status","get","set"]},null,2)}
|
|
315
315
|
`),1):(console.log(s.red(`Unknown workspace policy action: ${e||""}`)),console.log(s.gray("Available: show, set")),1);if(!r||typeof o>"u")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.missing_arguments",message:"Usage: workspai workspace policy set <key> <value>"},allowedKeys:["mode","dependency_sharing_mode","rules.enforce_workspace_marker","rules.enforce_toolchain_lock","rules.disallow_untrusted_tool_sources","rules.enforce_compatibility_matrix","rules.require_mirror_lock_for_offline"]},null,2)}
|
|
316
|
-
`),1):(console.log(s.yellow("Usage: workspai 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 c=r.trim(),
|
|
317
|
-
`),1):(console.log(s.red("\u274C Invalid mode. Use: warn | strict")),1);
|
|
318
|
-
`),1):(console.log(s.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1);
|
|
319
|
-
`),1):(console.log(s.red(`\u274C Unknown policy rule: ${
|
|
320
|
-
`),1):(console.log(s.red("\u274C Rule values must be boolean: true | false")),1);
|
|
321
|
-
`),1):(console.log(s.red(`\u274C Unknown policy key: ${c}`)),1);await Am(t,
|
|
322
|
-
`),0):(console.log(s.green(`\u2705 Updated ${c} in .workspai/policies.yml`)),console.log(s.gray(` mode: ${f.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${f.dependency_sharing_mode}`)),console.log(s.gray(" Tip: run `npx workspai workspace policy show` to inspect all values.")),0)}async function Jm(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=be(process.cwd());if(!o)return console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let n=s$1(o,"mirror-config.json").find(
|
|
323
|
-
`),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Config: ${
|
|
324
|
-
`),1;console.log(s.red("\u274C Mirror verify failed."));for(let
|
|
325
|
-
`),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${w.length} issue(s).`));for(let
|
|
326
|
-
`),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${
|
|
327
|
-
`).toLowerCase(),
|
|
328
|
-
`);for(let
|
|
329
|
-
`);process.exit(1);}}let x=await e(process.argv.slice(2),{cwd:e$
|
|
316
|
+
`),1):(console.log(s.yellow("Usage: workspai 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 c=r.trim(),l=await ep(t);if(c==="mode"){let u=o.trim().toLowerCase();if(u!=="warn"&&u!=="strict")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_mode",message:"Invalid mode. Use: warn | strict"}},null,2)}
|
|
317
|
+
`),1):(console.log(s.red("\u274C Invalid mode. Use: warn | strict")),1);l=Zl(l,"mode",`${u} # "warn" or "strict"`);}else if(c==="dependency_sharing_mode"){let u=o.trim().toLowerCase();if(u!=="isolated"&&u!=="shared-runtime-caches"&&u!=="shared-node-deps")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_dependency_sharing_mode",message:"Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps"}},null,2)}
|
|
318
|
+
`),1):(console.log(s.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1);l=Zl(l,"dependency_sharing_mode",`${u} # "isolated" or "shared-runtime-caches" or "shared-node-deps"`);}else if(c.startsWith("rules.")){let u=c.slice(6);if(!(u in lp))return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_rule",message:`Unknown policy rule: ${u}`}},null,2)}
|
|
319
|
+
`),1):(console.log(s.red(`\u274C Unknown policy rule: ${u}`)),1);let w=_m(o);if(w===null)return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_boolean",message:"Rule values must be boolean: true | false"}},null,2)}
|
|
320
|
+
`),1):(console.log(s.red("\u274C Rule values must be boolean: true | false")),1);l=Em(l,u,w);}else return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_key",message:`Unknown policy key: ${c}`}},null,2)}
|
|
321
|
+
`),1):(console.log(s.red(`\u274C Unknown policy key: ${c}`)),1);await Am(t,l);let f=Ql(l);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,updatedKey:c,policy:f},null,2)}
|
|
322
|
+
`),0):(console.log(s.green(`\u2705 Updated ${c} in .workspai/policies.yml`)),console.log(s.gray(` mode: ${f.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${f.dependency_sharing_mode}`)),console.log(s.gray(" Tip: run `npx workspai workspace policy show` to inspect all values.")),0)}async function Jm(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=be(process.cwd());if(!o)return console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let n=s$1(o,"mirror-config.json").find(u=>_.existsSync(u))??p(o,"mirror-config.json"),a=s$1(o,"mirror.lock").find(u=>_.existsSync(u))??p(o,"mirror.lock"),i=p(o,"mirror","artifacts"),c=p(o,"reports");async function d(u){if(!await O__default.pathExists(u))return 0;let w=0,y=[u];for(;y.length>0;){let P=y.shift();if(!P)continue;let S=await _.promises.readdir(P,{withFileTypes:true});for(let p of S)p.isFile()?w+=1:p.isDirectory()&&y.push(j.join(P,p.name));}return w}async function l(u){let w=new Date().toISOString().replace(/[:.]/g,"-"),y=j.join(c,`mirror-ops-${w}.json`),P=j.join(c,"mirror-ops.latest.json"),S={schemaVersion:h$3.mirrorOps.schemaVersion,...u};b$l(`.workspai/reports/${j.basename(y)}`,S),b$l(i$1.mirrorOps,S),await O__default.ensureDir(c),await an(y,S),await an(P,S);}async function f(){let u=await O__default.pathExists(n),w=await O__default.pathExists(a),y=await d(i);return {configExists:u,lockExists:w,artifactsCount:y}}if(e==="status"){let u=await O__default.pathExists(n),w=await O__default.pathExists(a),y=await d(i),P={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:{configExists:u,lockExists:w,artifactsCount:y}};return await l(P),r?(process.stdout.write(`${JSON.stringify(P,null,2)}
|
|
323
|
+
`),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Config: ${u?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${w?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${y}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let u=await fs(o,{ciMode:true,offlineMode:e==="verify",forceRun:true}),w=u.checks.filter(S=>S.status==="failed"),y=u.checks.some(S=>S.id.startsWith("mirror.verify.")&&S.status==="failed");if(e==="verify"&&y){let S={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await f(),details:u.details,checks:u.checks};if(await l(S),r)return process.stdout.write(`${JSON.stringify(S,null,2)}
|
|
324
|
+
`),1;console.log(s.red("\u274C Mirror verify failed."));for(let p of u.checks.filter(v=>v.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${p.id}: ${p.message}`));return 1}if(w.length>0){let S={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await f(),details:u.details,checks:u.checks};if(await l(S),r)return process.stdout.write(`${JSON.stringify(S,null,2)}
|
|
325
|
+
`),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${w.length} issue(s).`));for(let p of w)console.log(s.gray(`- ${p.id}: ${p.message}`));return 1}let P={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:await f(),details:u.details,checks:u.checks};return await l(P),r?(process.stdout.write(`${JSON.stringify(P,null,2)}
|
|
326
|
+
`),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${u.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${u.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${u.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Js(t){let e=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await up(r,async()=>{let n$1=be(r),a=Ke("python",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),i=Ke("dotnet",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),c=Ke("rust",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),d=Ke("php",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),l$1=t.slice(1).filter(p=>!p.startsWith("-"));if(l$1.length>0){let p=j.resolve(r,l$1[0]),v=i$2(p),m=await Lt(p);return j$3(v,p)||m==="go"?await Es(p):l(v,p)||m==="java"?await ft("init",p):m$1(v,p)||m==="dotnet"?oe(await i.initProject(p)):k$1(v,p)||m==="node"?await xs(p):n(v,p)||m==="python"?await Ss(p,a):m==="rust"?oe(await c.initProject(p)):m==="php"?oe(await d.initProject(p)):await e$1(t,{cwd:r})}let f=i$2(r),u=!!be(r)&&r===be(r);if(!u&&j$3(f,r))return await Es(r);let w=await Lt(r);if(!u&&(l(f,r)||w==="java"))return await ft("init",r);if(!u&&(m$1(f,r)||w==="dotnet"))return oe(await i.initProject(r));if(!u&&(k$1(f,r)||w==="node"))return await xs(r);if(!u&&(n(f,r)||w==="python"))return await Ss(r,a);if(!u&&w==="rust")return oe(await c.initProject(r));if(!u&&w==="php")return oe(await d.initProject(r));let y=n$1||be(r),P=ip(r),S=P?j.dirname(j.dirname(P)):null;if(S&&S!==y){let p=i$2(S),v=await Lt(S);return j$3(p,S)||v==="go"?await Es(S):l(p,S)||v==="java"?await ft("init",S):m$1(p,S)||v==="dotnet"?oe(await i.initProject(S)):k$1(p,S)||v==="node"?await xs(S):n(p,S)||v==="python"?await Ss(S,a):v==="rust"?oe(await c.initProject(S)):v==="php"?oe(await d.initProject(S)):await e$1(["init"],{cwd:S})}if(y&&r===y){console.log(s.yellow("\u26A0\uFE0F Running `npx workspai 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 p=await Fs(y);if(p!==0)return p;let{runWorkspaceStage:v}=await import('./workspace-run-I6E6VI6N.js');return (await v({workspacePath:y,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!y){let p=await b(),v=k$3(),{name:m}=Mm(v);await O__default.ensureDir(v);let{createProject:h}=await import('./create-IRNHMUEN.js');return await h(m,{yes:true,userConfig:p,parentDirectory:v}),0}return await e$1(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e;}}async function tp(t){let e=be(t);if(!e)return [];let r="warn";try{let d=s$1(e,"policies.yml").find(u=>_.existsSync(u));if(!d)return [];let l=await _.promises.readFile(d,"utf-8");(l.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??l.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n$1=s$1(e,"toolchain.lock").find(d=>_.existsSync(d));if(!n$1||!_.existsSync(n$1))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await _.promises.readFile(n$1,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=i$2(t);j$3(c,t)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):k$1(c,t)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):l(c,t)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):m$1(c,t)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):n(c,t)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let d=s$1(e,"workspace.json").find(y=>_.existsSync(y));if(!d)throw new Error("workspace manifest missing");let f=JSON.parse(await _.promises.readFile(d,"utf-8")).profile??"",u=j$4(t,c),w=St({profile:f,runtime:u.runtime,subjectLabel:j.basename(t),mode:"strict"});w.ok||o.push(`${w.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function Vm(){let t$1=async h=>{if(!b$3()||!h.toLowerCase().endsWith(".cmd"))return false;try{let k=(await O__default.readFile(h,"utf8")).replace(/\r\n/g,`
|
|
327
|
+
`).toLowerCase(),b=k.includes("\\.rapidkit\\rapidkit"),x=k.includes("\\.rapidkit\\rapidkit.cmd")||k.includes("\\.rapidkit\\rapidkit.exe")||k.includes("\\.venv\\scripts\\rapidkit.exe");return b&&!x}catch{return false}},e$2=process.cwd(),r=process.argv.slice(2),o=r[0],n$1=o==="init",a=new Set(q$2),i=!o||o==="--help"||o==="-h"||o==="help",c=qe(e$2),d=t(e$2,"project.json").some(h=>_.existsSync(h)),l$1=i$2(e$2),f=await Lt(e$2),u=j$3(l$1,e$2)||k$1(l$1,e$2)||n(l$1,e$2)||l(l$1,e$2)||m$1(l$1,e$2)||h$5(f??void 0),w=!!o&&a.has(o)&&u,y=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Fr(r)||r[0]==="create")return false;if(Ms(r))return true;if(r[0]==="init"&&c&&!d)return false;if(Ws(r))return true;try{let h=o==="shell"&&r[1]==="activate",g=o==="create",k=await Gi(e$2,{cwd:e$2,timeoutMs:1200});if(k.ok&&k.data?.isRapidkitProject&&k.data.engine==="python"){let b=g||Fr(r);if(!i&&!h&&!b&&!n$1&&!w&&On(r)){if(o&&ql.includes(o)){let C=await tp(e$2).catch(()=>[]);if(C.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
|
|
328
|
+
`);for(let R of C)process.stderr.write(s.red(` \u2022 ${R}`)+`
|
|
329
|
+
`);process.exit(1);}}let x=await e$1(process.argv.slice(2),{cwd:e$2});process.exit(x);}}}catch{}let P=ip(e$2),S=b$3(),p=y?[]:p$1(e$2),v=null;for(let h of p)if(await O__default.pathExists(h)){if(await t$1(h)){e.warn(`Skipping legacy/broken Windows launcher candidate: ${h}. Falling back to core bridge.`);continue}v=h;break}let m=o==="create";if(o==="init"&&c&&!d)return false;if(o&&ql.includes(o)){let h=await tp(e$2);if(h.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
|
|
330
330
|
`);for(let g of h)process.stderr.write(s.red(` \u2022 ${g}`)+`
|
|
331
|
-
`);process.exit(1);}}if(v&&o&&Bl.includes(o)&&!
|
|
331
|
+
`);process.exit(1);}}if(v&&o&&Bl.includes(o)&&!m&&!n$1&&!w){e.debug(`Delegating to local CLI: ${v} ${r.join(" ")}`);let h=o==="init"?Jl():process.env,g=spawn(v,r,{stdio:"inherit",cwd:e$2,shell:S,env:h});return g.on("close",k=>{process.exit(k??0);}),g.on("error",k=>{e.error(`Failed to run local rapidkit: ${k.message}`),process.exit(1);}),true}if(P&&await O__default.pathExists(P))try{let h=await O__default.readJson(P);if(Vi(h.engine)){let g=r[0],k=y?[]:p$1(e$2),b=null;for(let x of k)if(await O__default.pathExists(x)){if(await t$1(x)){e.warn(`Skipping legacy/broken Windows launcher candidate: ${x}. Falling back to core bridge.`);continue}b=x;break}if(b&&g&&Bl.includes(g)&&g!=="init"&&!w){e.debug(`Delegating to local CLI (early detection): ${b} ${r.join(" ")}`);let x=g==="init"?Jl():process.env,C=spawn(b,r,{stdio:"inherit",cwd:e$2,shell:S,env:x});return C.on("close",R=>process.exit(R??0)),C.on("error",R=>{e.error(`Failed to run local rapidkit: ${R.message}`),process.exit(1);}),true}if(g==="shell"&&r[1]==="activate"){let x=b$3()?`# RapidKit Core activation snippet (PowerShell)
|
|
332
332
|
$venv = ".venv"
|
|
333
333
|
if (Test-Path "$venv\\Scripts\\Activate.ps1") { . "$venv\\Scripts\\Activate.ps1" }
|
|
334
334
|
$env:RAPIDKIT_PROJECT_ROOT = (Get-Location).Path
|
|
@@ -350,7 +350,7 @@ export PATH="$(pwd)/.workspai:$(pwd)/.rapidkit:$(pwd):$PATH"
|
|
|
350
350
|
\u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
|
|
351
351
|
`)),console.log(x),console.log(s.gray(`
|
|
352
352
|
\u{1F4A1} After activation you can run: workspai dev
|
|
353
|
-
`)),process.exit(0);}if(!i&&!Fr(r)&&g!=="init"&&!w&&On(r)){let x=await e(r,{cwd:e$
|
|
353
|
+
`)),process.exit(0);}if(!i&&!Fr(r)&&g!=="init"&&!w&&On(r)){let x=await e$1(r,{cwd:e$2});process.exit(x);}}}catch{}return false}var Et=null,nn=false,Km=rm(),Vs="workspai",As="npx workspai",fe=new Command;fe.enablePositionalOptions();var Um=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function Hm(t){if(t.length===0)return false;let e=t[0],r=t[1];if(y(t)||ym.includes(e))return false;if(r$1.includes(e)){if(e==="lint"||e==="format"){let n$1=i$2(process.cwd()),a=await Lt(process.cwd());if(k$1(n$1,process.cwd())||a==="node"){let i=j$4(process.cwd(),n$1);if(t$1(process.cwd(),e,{framework:i.key})!==null)return false}if(n(n$1,process.cwd())||a==="python")return true;if(v$1(process.cwd()))return false}return true}if(Fr(t)||e==="shell"&&r==="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 o=await i$6();return In(e,o)?true:t.some(n=>_n.has(n))?false:o?o.has(e):!!(a$5.has(e)||t.length>1)}fe.name(Vs).description("Workspai workspace intelligence CLI").version(h());fe.addHelpText("beforeAll",`Workspai CLI
|
|
354
354
|
|
|
355
355
|
Workspace Intelligence for software systems.
|
|
356
356
|
`);fe.addHelpText("afterAll",`
|
|
@@ -358,24 +358,24 @@ Discover more:
|
|
|
358
358
|
${Vs} --help Product overview and first steps
|
|
359
359
|
${Vs} commands --json Complete machine-readable command inventory
|
|
360
360
|
https://workspai.dev Guides, contracts, and examples
|
|
361
|
-
`);fe.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-python-engine","Create a Python-aware workspace without installing rapidkit-core now").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 link it to any workspace").hideHelp()).option("--no-update-check","Skip checking for updates").option("--trust-config","Trust and execute workspai.config.js/mjs/cjs discovered in this tree").action(async(t,e$
|
|
362
|
-
\u274C ${
|
|
363
|
-
`),process.exit(1)),
|
|
364
|
-
\u274C Directory "${t}" already exists`),
|
|
361
|
+
`);fe.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-python-engine","Create a Python-aware workspace without installing rapidkit-core now").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 link it to any workspace").hideHelp()).option("--no-update-check","Skip checking for updates").option("--trust-config","Trust and execute workspai.config.js/mjs/cjs discovered in this tree").action(async(t,e$2)=>{try{e$2.debug&&(e.setDebug(true),e.debug("Debug mode enabled"));let r=await b();e.debug("User config loaded",{...r,openaiApiKey:r.openaiApiKey?"[REDACTED]":void 0});let o=await c(process.cwd(),{trustExecutableConfig:e$2.trustConfig===true||process.env.WORKSPAI_TRUST_CONFIG==="1"});e.debug("Workspai config loaded",o);let n=d(r,o,{author:e$2.author,pythonVersion:void 0,skipGit:e$2.skipGit});e.debug("Merged config",n),e$2.updateCheck!==false&&await g(),a("workspace"),t||(fp(),process.exit(0));try{h$1(t);}catch(d){throw d instanceof a$1&&(e.error(`
|
|
362
|
+
\u274C ${d.message}`),d.details&&e.warn(`\u{1F4A1} ${d.details}
|
|
363
|
+
`),process.exit(1)),d}let a$2=!!e$2.template,i$1;a$2||(e$2.here?i$1=process.cwd():e$2.output?i$1=j.resolve(e$2.output):i$1=await j$1([],{hasYes:e$2.yes}));let c$1=a$2?j.resolve(process.cwd(),t):h$2(t,{outputParent:i$1});if(Et=c$1,!e$2.dryRun){a$2||await O__default.ensureDir(j.dirname(c$1));let d=a$2?void 0:m(t);(!a$2&&i(d,c$1,{outputParent:i$1})&&d&&await O__default.pathExists(d)||await O__default.pathExists(c$1))&&(e.error(`
|
|
364
|
+
\u274C Directory "${t}" already exists`),d&&d!==c$1&&console.log(s.gray(` Found at: ${d}`)),console.log(s.cyan(`
|
|
365
365
|
\u{1F4A1} Choose a different name or delete the existing directory.
|
|
366
|
-
`)),process.exit(1));}if(e$
|
|
366
|
+
`)),process.exit(1));}if(e$2.dryRun){console.log(s.cyan(`
|
|
367
367
|
\u{1F50D} Dry-run mode - showing what would be created:
|
|
368
|
-
`)),console.log(s.white("\u{1F4C2} Path:"),c$1),console.log(s.white("\u{1F4E6} Type:"),a$2?`Project (${e$
|
|
369
|
-
`)),a$2){let
|
|
370
|
-
`),
|
|
371
|
-
`),
|
|
372
|
-
\u274C ${r.message}`),r.details&&
|
|
373
|
-
\u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Et=null;}});lc(fe);fc(fe);zc(fe);fe.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{bm({json:t.json});});fe.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:r}=await import('./analyze-52TEGLDR.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});Ui(fe);fe.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t$1=>{t$1!=="activate"&&(console.log(s.red(`Unknown shell command: ${t$1}`)),process.exit(1));let e=process.cwd();function r(p){let d=p;for(;;){let f=t(d,"context.json").find(w=>_.existsSync(w));if(f)return f;let m=j.dirname(d);if(m===d)break;d=m;}return null}let o$1=r(e);function n(p){let d=p;for(;;){let f=j.join(d,".venv"),m=[j.join(d,".workspai","activate"),j.join(d,".rapidkit","activate")].find(y=>_.existsSync(y))??j.join(d,".workspai","activate");if(_.existsSync(m)||_.existsSync(f))return {venv:f,activateFile:m};let w=j.dirname(d);if(w===d)break;d=w;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&_.existsSync(a.activateFile)?i=a.activateFile:a&&_.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$3();console.log(c?`call "${i}"`:`. "${i}"`);});fe.command(k.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").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({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});fe.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:r}=await import('./pipeline-62A2SDLC.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});fe.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 r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Os({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-NFLAKBA3.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});fe.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ls(t,e);r!==0&&process.exit(r);});fe.command("adopt [source]").description("Adopt an existing local project into a Workspai 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","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await mp(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});fe.command("goal [intent]").description("Compile a plain-language engineering intent into a governed, evidence-bound Goal Pack").option("--workspace <path>","Explicit canonical workspace path").option("--scope <scope>","Bound the goal to workspace or project:<name>").addOption(new Option("--for-agent <consumer>","Portable handoff consumer").choices(["generic","claude","codex"]).default("generic")).option("--max-attempts <count>","Maximum bounded proposal attempts","5").option("--refresh","Refresh the canonical Workspace Intelligence chain before planning").option("--dry-run","Validate and preview the Goal Pack without writing artifacts").option("--status [goal-id]","Inspect the active or named Goal Pack and validate its bindings").option("--list","List registered Goal Packs in the resolved workspace").option("--activate <goal-id>","Make a registered Goal Pack the active agent objective").option("--cancel <goal-id>","Cancel a registered Goal Pack without deleting evidence").option("--prepare <goal-id>","Create and link the deterministic CLI verification contract").option("--verify <goal-id>","Run CLI-owned verification for a prepared Goal Pack").option("--no-run","Read verification evidence without executing producer commands").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let{validateGoalCommandSelection:r}=await import('./goal-command-contract-CHE7U6YY.js'),o=r({intent:t,...e});if(o.operation!=="plan"){let d=b$5({startPath:process.cwd(),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!d)throw new Error("No canonical Workspai workspace could be resolved.");let{buildGoalLifecycleResult:f,inspectGoalLifecycle:m,prepareGoalVerification:w,transitionGoalLifecycle:y,verifyGoalLifecycle:P}=await import('./goal-lifecycle-NUKWVUAL.js'),S=e.prepare?await w({workspacePath:d.workspacePath,goalId:e.prepare}):null,l=e.verify?await P({workspacePath:d.workspacePath,goalId:e.verify,run:e.run!==false}):null,v=e.activate?await y({workspacePath:d.workspacePath,goalId:e.activate,action:"activate"}):e.cancel?await y({workspacePath:d.workspacePath,goalId:e.cancel,action:"cancel"}):null,u=await m({workspacePath:d.workspacePath,goalId:typeof e.status=="string"?e.status:v?.goal.id??S?.goal.id??l?.goal.id,validateBindings:!(e.list||e.cancel)}),h=f({operation:o.operation,activeGoalId:u.index.activeGoalId,goal:u.active,goals:u.index.goals,goalPack:u.goalPack,verifiedGoalId:l?.verifiedGoalId??S?.verifiedGoalId??null,verification:l?.verification??null});if(e.json)console.log(JSON.stringify(h,null,2));else if(e.list){console.log(s.bold(`Goals \xB7 ${u.index.goals.length}`));for(let g of u.index.goals)console.log(`${g.id===u.index.activeGoalId?s.green("\u25CF"):s.gray("\u25CB")} ${g.objective} \xB7 ${g.lifecycle} \xB7 ${g.state}`);}else u.active?(console.log(s.bold(u.active.objective)),console.log(s.gray(` Goal: ${u.active.id}`)),console.log(s.gray(` Lifecycle: ${u.active.lifecycle}`)),console.log(s.gray(` Planning state: ${u.active.state}`))):console.log(s.yellow("No active Goal Pack is registered."));return}let n=Number(e.maxAttempts??5),{planGoalPack:a}=await import('./goal-pack-TWOXHXN6.js'),i=await a({startPath:process.cwd(),intent:o.intent,workspacePath:e.workspace,scope:e.scope,consumer:e.forAgent,maxAttempts:n,refresh:e.refresh===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(i,null,2));return}let c=i.goalPack,p=c.state==="ready-to-plan"?s.green("\u2714 Governed Goal Pack ready to plan"):c.state==="blocked"?s.red("\u25A0 Goal Pack blocked by missing bounded evidence"):c.state==="needs-evidence"?s.yellow("\u25C6 Goal Pack needs measurement evidence"):s.yellow("\u25C6 Goal Pack needs clarification");console.log(p),console.log(s.bold(` ${c.intent.statement}`)),console.log(s.gray(` Goal: ${c.id}`)),console.log(s.gray(` Scope: ${c.scope.kind} \xB7 ${c.scope.projects.length} project(s) \xB7 ${c.baseline.runtimes.length} runtime(s)`)),console.log(s.gray(` Evidence: ${c.baseline.graph.entities} entities \xB7 ${c.baseline.graph.relationships} relationships \xB7 ${c.baseline.graph.proofCoveragePercent}% relation proof coverage`)),console.log(s.gray(" Mutation: proposal only \xB7 explicit approval \xB7 CLI-owned verify/rollback")),c.decision&&console.log(s.yellow(` Decision: ${c.decision.question}`)),i.dryRun?console.log(s.cyan(" Preview only; no artifacts were written.")):(console.log(s.gray(` Goal Pack: ${c.artifacts.goalPack}`)),console.log(s.gray(` Agent handoff: ${c.artifacts.agentHandoff}`))),console.log(s.gray(` Next: ${c.commands.planVerifiedGoal??c.commands.inspectGraph}`));}catch(r){let o=r instanceof Error?r.message:String(r),n=e.verify?"verify":e.prepare?"prepare":e.activate?"activate":e.cancel?"cancel":e.list?"list":e.status!==void 0?"status":null;e.json?console.log(JSON.stringify(c$1({operation:n?`goal.${n}`:"goal.plan",code:n?`goal.${n}.failed`:"goal.plan.failed",message:o,context:{scope:e.scope??null,refresh:e.refresh===true,goalId:e.prepare??e.verify??e.activate??e.cancel??(typeof e.status=="string"?e.status:null)}}),null,2)):console.log(s.red(`\u274C Goal ${n?`${n} operation`:"planning"} failed: ${o}`)),process.exit(1);}});var cn=fe.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");cn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await Eo({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot create",code:"snapshot.create.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});cn.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Cc({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 r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){t.json&&(console.log(JSON.stringify(c$1({operation:"snapshot list",code:"snapshot.list.failed",message:e.message,context:{workspacePath:t.workspace??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});cn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await bc({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot inspect",code:"snapshot.inspect.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});cn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await xc({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(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot restore",code:"snapshot.restore.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});function Bm(t){return (t instanceof Error?t.message:String(t)).replace(/file:\/\/\/[^\s"']+/g,"<local-path>").replace(/\\\\[^\\\s"']+[\\][^\s"']+/g,"<local-path>").replace(/[A-Za-z]:[\\/][^\s"']+/g,"<local-path>").replace(/\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\/[^\s"']+/g,"<local-path>")}async function gp(t){try{let{buildAgentBootstrapReceipt:e}=await import('./project-agent-entry-7SYHRY7J.js'),r=await e({startPath:t.project,forAgent:t.forAgent,validateLiveInputs:t.liveInputs!==false});if(t.json)console.log(JSON.stringify(r,null,2));else {let o=r.status==="ready"?s.green:r.status==="degraded"?s.yellow:s.red;console.log(o(`Agent entry: ${r.status}`)),console.log(s.gray(` Project: ${r.project.name}`)),console.log(s.gray(` Workspace: ${r.workspace.name}`)),console.log(s.gray(` Consumer: ${r.resolvedHost}`)),console.log(s.gray(` Receipt: ${r.receiptId.slice(0,16)}`));for(let n of r.checks.filter(a=>a.status!=="passed"))console.log((n.status==="failed"?s.red:s.yellow)(` ${n.id}: ${n.message}`));console.log(s.gray(` Next: ${r.nextActions[0]}`));}(r.status==="blocked"||t.strict&&r.status!=="ready")&&process.exit(2);}catch(e){let r=Bm(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"agent.entry.bootstrap.failed",message:r}),null,2)):console.log(s.red(`Agent entry failed: ${r}`)),process.exit(1);}}var qm=fe.command("agent").description("Bootstrap coding agents from canonical Workspai project evidence");qm.command("bootstrap").description("Issue a portable canonical-first grounding receipt for the current project").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier","generic").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless the complete entry receipt is ready").option("--json","Emit the versioned machine-readable receipt").action(async t=>gp({...t,operation:"agent bootstrap"}));var Rt=fe.command("project").description("Safe workspace project lifecycle operations");Rt.command("agent-entry [action]").description("Verify canonical-first project entry coverage for supported agent hosts").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier or all","all").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless all selected entry checks are ready").option("--json","Emit the versioned machine-readable receipt").action(async(t,e)=>{let r=t??"verify";if(r!=="verify"){let o=`Unknown project agent-entry action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project agent-entry",code:"project.agent-entry.action.invalid",message:o}),null,2)):(console.log(s.red(o)),console.log(s.gray(" workspai project agent-entry verify [--for-agent <agent|all>] [--strict] [--json]"))),process.exit(1);}await gp({...e,operation:"project agent-entry verify"});});Rt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{sp({json:t.json});});Rt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$5({startPath:j.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??j.join(o.projectPath,f$2),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json",pathPolicy:{classification:"machine-local",portable:false,persistence:"forbidden",disclosure:"forbidden",purpose:"runtime-workspace-resolution"}};if(ml(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});Rt.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-HP37HUV2.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let p of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${p.path}: ${p.percent===null?"unknown":`${p.percent}%`} (${p.uncovered} uncovered)`));}for(let p of o.diagnostics)console.log(s.gray(` ${p}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});Rt.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await qn({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 r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Rt.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await zn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});Rt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await Oc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});Rt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await Ic({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(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});fe.command(k.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json [mode]","Output JSON: full (default) or summary").option("--fresh","Bypass Doctor project scan cache and refresh live evidence").option("--verbose","Show every probe, lifecycle capability, and detailed project signal").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("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate an action or lifecycle plan without applying or executing changes").option("--apply","Apply remediation plan non-interactively").option("--runtime <runtime>","Filter Doctor capability truth by runtime family").option("--framework <framework>","Filter Doctor capability truth by framework").option("--validate","Run the versioned Doctor disease validation corpus").option("--write","Write Doctor capability/validation artifacts inside the workspace").action(async(t,e)=>{if(t&&t!=="workspace"&&t!=="project"&&t!=="capabilities"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project, capabilities")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project | npx workspai doctor capabilities")),process.exit(1)),typeof e.json=="string"&&!["full","summary"].includes(e.json)&&(console.log(s.red(`Invalid Doctor JSON mode: ${e.json}. Use full or summary.`)),process.exit(1)),t==="capabilities"){(e.fix||e.plan||e.apply||e.project)&&(console.log(s.red("Doctor capability inspection cannot be combined with repair or project-scope flags.")),process.exit(1));let{runDoctorCapabilities:i}=await import('./capabilities-command-VBLZXP2T.js'),c=await i({runtime:e.runtime,framework:e.framework,validate:e.validate===true,write:e.write===true,workspace:typeof e.workspace=="string"?e.workspace:void 0,json:!!e.json});c!==0&&process.exit(c);return}(e.runtime||e.framework||e.validate||e.write)&&(console.log(s.red('Doctor capability flags require the "doctor capabilities" scope.')),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 r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await Cm({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 workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-NAZEKMGU.js'),a=await n({...e,json:e.json==="summary"?"summary":!!e.json,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});fe.command(k.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
|
|
368
|
+
`)),console.log(s.white("\u{1F4C2} Path:"),c$1),console.log(s.white("\u{1F4E6} Type:"),a$2?`Project (${e$2.template})`:"Workspace"),console.log();return}if(!e$2.yes&&!a$2?await b$1([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"Workspai User"}]):e$2.yes&&console.log(s.gray(`Using default values (--yes flag)
|
|
369
|
+
`)),a$2){let d=String(e$2.template||"").trim(),l=b$2(d);if(d$1(l)){let m=await $s(["create","project",l,t,...e$2.skipGit?["--skip-git"]:[],...e$2.skipInstall?["--skip-install"]:[]]);m!==0&&process.exit(m);return}if(!!!Ds(process.cwd())){let{registerWorkspaceAtPath:m}=await import('./create-IRNHMUEN.js');if(e$2.createWorkspace)await m(process.cwd(),{skipGit:e$2.skipGit,yes:e$2.yes,userConfig:r});else if(!e$2.noWorkspace)if(e$2.yes)await m(process.cwd(),{skipGit:e$2.skipGit,yes:true,userConfig:r});else {let{createWs:h}=await b$1([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);h&&await m(process.cwd(),{skipGit:e$2.skipGit,yes:false,userConfig:r});}}let u=["create","project",l,t,"--output",process.cwd()];e$2.yes&&u.push("--yes");let w=be(process.cwd()),y=!!e$2.skipInstall,P=y||!!w;y&&u.push("--skip-essentials");let S=P?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,p=await f(u,{cwd:process.cwd(),env:S});p!==0&&process.exit(p),w&&!e$2.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init")));let v=Ds(process.cwd());if(v){let m=j.dirname(v),h=j.join(m,".python-version"),g=j.join(c$1,".python-version");try{if(await O__default.pathExists(h)){let k=_.readFileSync(h,"utf-8");_.writeFileSync(g,k.trim()+`
|
|
370
|
+
`),e.debug(`Synced Python version ${k.trim()} from workspace to project`);}}catch(k){e.debug("Could not sync Python version from workspace:",k);}}if(!e$2.skipInstall){let m=await e$1(["init",c$1],{cwd:process.cwd()});if(m!==0&&process.exit(m),v){let h=j.dirname(v),g=j.join(h,".python-version"),k=j.join(c$1,".python-version");try{if(await O__default.pathExists(g)){let b=_.readFileSync(g,"utf-8");_.writeFileSync(k,b.trim()+`
|
|
371
|
+
`),e.debug(`Re-synced Python version ${b.trim()} after init`);}}catch(b){e.debug("Could not re-sync Python version after init:",b);}}}}else {let{createProject:d}=await import('./create-IRNHMUEN.js');await d(t,{skipGit:e$2.skipGit,skipPythonEngine:e$2.skipPythonEngine,dryRun:e$2.dryRun,yes:e$2.yes,userConfig:n,installMethod:e$2.installMethod,profile:e$2.profile,parentDirectory:j.dirname(c$1)});}}catch(r){r instanceof a$1?(e.error(`
|
|
372
|
+
\u274C ${r.message}`),r.details&&e.warn(`\u{1F4A1} ${r.details}`),e.debug("Error code:",r.code)):(e.error(`
|
|
373
|
+
\u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Et=null;}});lc(fe);fc(fe);zc(fe);fe.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{bm({json:t.json});});fe.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:r}=await import('./analyze-FYNMI5KT.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});Ui(fe);fe.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t$1=>{t$1!=="activate"&&(console.log(s.red(`Unknown shell command: ${t$1}`)),process.exit(1));let e=process.cwd();function r(d){let l=d;for(;;){let f=t(l,"context.json").find(w=>_.existsSync(w));if(f)return f;let u=j.dirname(l);if(u===l)break;l=u;}return null}let o$1=r(e);function n(d){let l=d;for(;;){let f=j.join(l,".venv"),u=[j.join(l,".workspai","activate"),j.join(l,".rapidkit","activate")].find(y=>_.existsSync(y))??j.join(l,".workspai","activate");if(_.existsSync(u)||_.existsSync(f))return {venv:f,activateFile:u};let w=j.dirname(l);if(w===l)break;l=w;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&_.existsSync(a.activateFile)?i=a.activateFile:a&&_.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$3();console.log(c?`call "${i}"`:`. "${i}"`);});fe.command(k.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").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({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});fe.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:r}=await import('./pipeline-5O36G4ZV.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});fe.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 r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Os({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-O5PPB6HQ.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});fe.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ls(t,e);r!==0&&process.exit(r);});fe.command("adopt [source]").description("Adopt an existing local project into a Workspai 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","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await mp(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});fe.command("goal [intent]").description("Compile a plain-language engineering intent into a governed, evidence-bound Goal Pack").option("--workspace <path>","Explicit canonical workspace path").option("--scope <scope>","Bound the Goal to workspace, project:<name>, or projects:<name>,<name>").addOption(new Option("--runtime <runtime>","Bind a coverage Goal to a canonical runtime in its scope").choices(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"])).addOption(new Option("--for-agent <consumer>","Portable handoff consumer").choices(["generic","claude","codex"]).default("generic")).option("--max-attempts <count>","Maximum bounded proposal attempts","5").option("--refresh","Refresh the canonical Workspace Intelligence chain before planning").option("--dry-run","Validate and preview the Goal Pack without writing artifacts").option("--status [goal-id]","Inspect the active or named Goal Pack and validate its bindings").option("--list","List registered Goal Packs in the resolved workspace").option("--activate <goal-id>","Make a registered Goal Pack the active agent objective").option("--cancel <goal-id>","Cancel a registered Goal Pack without deleting evidence").option("--prepare <goal-id>","Create and link the deterministic CLI verification contract").option("--verify <goal-id>","Run CLI-owned verification for a prepared Goal Pack").option("--no-run","Read verification evidence without executing producer commands").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let{validateGoalCommandSelection:r}=await import('./goal-command-contract-43E22XQD.js'),o=r({intent:t,...e});if(o.operation!=="plan"){let u=b$5({startPath:process.cwd(),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!u)throw new Error("No canonical Workspai workspace could be resolved.");let{buildGoalLifecycleResult:w,inspectGoalLifecycle:y,prepareGoalVerification:P,transitionGoalLifecycle:S,verifyGoalLifecycle:p}=await import('./goal-lifecycle-VQDUWZVG.js'),v=e.prepare?await P({workspacePath:u.workspacePath,goalId:e.prepare}):null,m=e.verify?await p({workspacePath:u.workspacePath,goalId:e.verify,run:e.run!==false}):null,h=e.activate?await S({workspacePath:u.workspacePath,goalId:e.activate,action:"activate"}):e.cancel?await S({workspacePath:u.workspacePath,goalId:e.cancel,action:"cancel"}):null,g=await y({workspacePath:u.workspacePath,goalId:typeof e.status=="string"?e.status:h?.goal.id??v?.goal.id??m?.goal.id,validateBindings:!(e.list||e.cancel)}),k=w({operation:o.operation,activeGoalId:g.index.activeGoalId,goal:g.active,goals:g.index.goals,goalPack:g.goalPack,verifiedGoalId:m?.verifiedGoalId??v?.verifiedGoalId??null,verification:m?.verification??null});if(e.json)console.log(JSON.stringify(k,null,2));else if(e.list){console.log(s.bold(`Goals \xB7 ${g.index.goals.length}`));for(let b of g.index.goals)console.log(`${b.id===g.index.activeGoalId?s.green("\u25CF"):s.gray("\u25CB")} ${b.objective} \xB7 ${b.lifecycle} \xB7 ${b.state}`);}else g.active?(console.log(s.bold(g.active.objective)),console.log(s.gray(` Goal: ${g.active.id}`)),console.log(s.gray(` Lifecycle: ${g.active.lifecycle}`)),console.log(s.gray(` Planning state: ${g.active.state}`))):console.log(s.yellow("No active Goal Pack is registered."));return}let n=Number(e.maxAttempts??5),{planGoalPack:a}=await import('./goal-pack-U3ZP7A2A.js'),c=e.json!==true&&process.stdin.isTTY===true&&process.stdout.isTTY===true?await import('./goal-interactive-selection-6YJOK4WC.js'):null,d=await a({startPath:process.cwd(),intent:o.intent,workspacePath:e.workspace,scope:e.scope,runtime:e.runtime,consumer:e.forAgent,maxAttempts:n,refresh:e.refresh===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),...c?{selectScope:c.selectGoalScopeInteractively,selectCoverageRuntime:c.selectGoalCoverageRuntimeInteractively}:{}});if(e.json){console.log(JSON.stringify(d,null,2));return}let l=d.goalPack,f=l.state==="ready-to-plan"?s.green("\u2714 Governed Goal Pack ready to plan"):l.state==="blocked"?s.red("\u25A0 Goal Pack blocked by missing bounded evidence"):l.state==="needs-evidence"?s.yellow("\u25C6 Goal Pack needs measurement evidence"):s.yellow("\u25C6 Goal Pack needs clarification");console.log(f),console.log(s.bold(` ${l.intent.statement}`)),console.log(s.gray(` Goal: ${l.id}`)),console.log(s.gray(` Scope: ${l.scope.kind} \xB7 ${l.scope.projects.length} project(s) \xB7 ${l.baseline.runtimes.length} runtime(s)`)),console.log(s.gray(` Evidence: ${l.baseline.graph.entities} entities \xB7 ${l.baseline.graph.relationships} relationships \xB7 ${l.baseline.graph.proofCoveragePercent}% relation proof coverage`)),console.log(s.gray(" Mutation: proposal only \xB7 explicit approval \xB7 CLI-owned verify/rollback")),l.decision&&console.log(s.yellow(` Decision: ${l.decision.question}`)),d.dryRun?console.log(s.cyan(" Preview only; no artifacts were written.")):(console.log(s.gray(` Goal Pack: ${l.artifacts.goalPack}`)),console.log(s.gray(` Agent handoff: ${l.artifacts.agentHandoff}`))),console.log(s.gray(` Next: ${l.commands.planVerifiedGoal??l.commands.inspectGraph}`));}catch(r){let o=r instanceof Error?r.message:String(r),n=e.verify?"verify":e.prepare?"prepare":e.activate?"activate":e.cancel?"cancel":e.list?"list":e.status!==void 0?"status":null;e.json?console.log(JSON.stringify(c$1({operation:n?`goal.${n}`:"goal.plan",code:n?`goal.${n}.failed`:"goal.plan.failed",message:o,context:{scope:e.scope??null,runtime:e.runtime??null,refresh:e.refresh===true,goalId:e.prepare??e.verify??e.activate??e.cancel??(typeof e.status=="string"?e.status:null)}}),null,2)):console.log(s.red(`\u274C Goal ${n?`${n} operation`:"planning"} failed: ${o}`)),process.exit(1);}});var cn=fe.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");cn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await Eo({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot create",code:"snapshot.create.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});cn.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Cc({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 r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){t.json&&(console.log(JSON.stringify(c$1({operation:"snapshot list",code:"snapshot.list.failed",message:e.message,context:{workspacePath:t.workspace??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});cn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await bc({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot inspect",code:"snapshot.inspect.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});cn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await xc({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(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot restore",code:"snapshot.restore.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});function Bm(t){return (t instanceof Error?t.message:String(t)).replace(/file:\/\/\/[^\s"']+/g,"<local-path>").replace(/\\\\[^\\\s"']+[\\][^\s"']+/g,"<local-path>").replace(/[A-Za-z]:[\\/][^\s"']+/g,"<local-path>").replace(/\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\/[^\s"']+/g,"<local-path>")}async function gp(t){try{let{buildAgentBootstrapReceipt:e}=await import('./project-agent-entry-CN4K6JNZ.js'),r=await e({startPath:t.project,forAgent:t.forAgent,validateLiveInputs:t.liveInputs!==false});if(t.json)console.log(JSON.stringify(r,null,2));else {let o=r.status==="ready"?s.green:r.status==="degraded"?s.yellow:s.red;console.log(o(`Agent entry: ${r.status}`)),console.log(s.gray(` Project: ${r.project.name}`)),console.log(s.gray(` Workspace: ${r.workspace.name}`)),console.log(s.gray(` Consumer: ${r.resolvedHost}`)),console.log(s.gray(` Receipt: ${r.receiptId.slice(0,16)}`));for(let n of r.checks.filter(a=>a.status!=="passed"))console.log((n.status==="failed"?s.red:s.yellow)(` ${n.id}: ${n.message}`));console.log(s.gray(` Next: ${r.nextActions[0]}`));}(r.status==="blocked"||t.strict&&r.status!=="ready")&&process.exit(2);}catch(e){let r=Bm(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"agent.entry.bootstrap.failed",message:r}),null,2)):console.log(s.red(`Agent entry failed: ${r}`)),process.exit(1);}}var qm=fe.command("agent").description("Bootstrap coding agents from canonical Workspai project evidence");qm.command("bootstrap").description("Issue a portable canonical-first grounding receipt for the current project").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier","generic").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless the complete entry receipt is ready").option("--json","Emit the versioned machine-readable receipt").action(async t=>gp({...t,operation:"agent bootstrap"}));var Rt=fe.command("project").description("Safe workspace project lifecycle operations");Rt.command("agent-entry [action]").description("Verify canonical-first project entry coverage for supported agent hosts").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier or all","all").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless all selected entry checks are ready").option("--json","Emit the versioned machine-readable receipt").action(async(t,e)=>{let r=t??"verify";if(r!=="verify"){let o=`Unknown project agent-entry action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project agent-entry",code:"project.agent-entry.action.invalid",message:o}),null,2)):(console.log(s.red(o)),console.log(s.gray(" workspai project agent-entry verify [--for-agent <agent|all>] [--strict] [--json]"))),process.exit(1);}await gp({...e,operation:"project agent-entry verify"});});Rt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{sp({json:t.json});});Rt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$5({startPath:j.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??j.join(o.projectPath,f$1),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json",pathPolicy:{classification:"machine-local",portable:false,persistence:"forbidden",disclosure:"forbidden",purpose:"runtime-workspace-resolution"}};if(ml(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});Rt.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-E2Q4QL44.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let d of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${d.path}: ${d.percent===null?"unknown":`${d.percent}%`} (${d.uncovered} uncovered)`));}for(let d of o.diagnostics)console.log(s.gray(` ${d}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});Rt.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await qn({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 r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Rt.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await zn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});Rt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await Oc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});Rt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai 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 r=await Ic({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(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});fe.command(k.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json [mode]","Output JSON: full (default) or summary").option("--fresh","Bypass Doctor project scan cache and refresh live evidence").option("--verbose","Show every probe, lifecycle capability, and detailed project signal").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("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate an action or lifecycle plan without applying or executing changes").option("--apply","Apply remediation plan non-interactively").option("--runtime <runtime>","Filter Doctor capability truth by runtime family").option("--framework <framework>","Filter Doctor capability truth by framework").option("--validate","Run the versioned Doctor disease validation corpus").option("--write","Write Doctor capability/validation artifacts inside the workspace").action(async(t,e)=>{if(t&&t!=="workspace"&&t!=="project"&&t!=="capabilities"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project, capabilities")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project | npx workspai doctor capabilities")),process.exit(1)),typeof e.json=="string"&&!["full","summary"].includes(e.json)&&(console.log(s.red(`Invalid Doctor JSON mode: ${e.json}. Use full or summary.`)),process.exit(1)),t==="capabilities"){(e.fix||e.plan||e.apply||e.project)&&(console.log(s.red("Doctor capability inspection cannot be combined with repair or project-scope flags.")),process.exit(1));let{runDoctorCapabilities:i}=await import('./capabilities-command-VBLZXP2T.js'),c=await i({runtime:e.runtime,framework:e.framework,validate:e.validate===true,write:e.write===true,workspace:typeof e.workspace=="string"?e.workspace:void 0,json:!!e.json});c!==0&&process.exit(c);return}(e.runtime||e.framework||e.validate||e.write)&&(console.log(s.red('Doctor capability flags require the "doctor capabilities" scope.')),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 r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await Cm({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 workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-MAPZ2ZCD.js'),a=await n({...e,json:e.json==="summary"?"summary":!!e.json,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});fe.command(k.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
|
|
374
374
|
workspace run <stage> \u2014 fleet stage execution across discovered projects
|
|
375
375
|
stages: init | test | build | start | <custom-from-context>
|
|
376
376
|
workspace explain|why \u2014 blocker/project narrative (--write for artifact)
|
|
377
377
|
workspace trace \u2014 diff \u2192 blast radius \u2192 gates narrative (--from <diff>)
|
|
378
|
-
workspace mcp serve \u2014 read-mostly stdio MCP bridge over workspace evidence`).option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--output <file>","Output file path for workspace share/export artifacts").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 .workspai/reports").option("--include-evidence","Read status metadata from referenced evidence reports").option("--scan-depth <count>","Observable project discovery depth for large monorepos").option("--limit <count>","Bound graph search results (default 12, maximum 100)").option("--refresh-graph","Bypass the compatible persisted knowledge graph and rebuild from live workspace sources").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("--graph-stream","For workspace watch: emit workspace-graph-stream.v1 snapshot/delta NDJSON").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,gemini,qwen,kimi,grok,windsurf,amazon-q,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").addOption(new Option("--project-grounding <mode>","Project entrypoint policy for sync/agent-sync: managed, local, or off").choices(["managed","local","off"]).default("managed")).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(d$3.archiveCompression.signature,d$3.archiveCompression.description).option(d$3.maxDownloadSize.signature,d$3.maxDownloadSize.description).option(d$3.maxExpandedSize.signature,d$3.maxExpandedSize.description).option(d$3.downloadTimeoutMs.signature,d$3.downloadTimeoutMs.description).option(d$3.allowPrivateNetwork.signature,d$3.allowPrivateNetwork.description).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("--runtime <runtime>","Limit workspace run to one detected runtime family").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("--ci","Build CI-oriented command plans where supported").option("--strict","Return non-zero exit on warn/fail gate outcomes").option("--no-gates","Skip doctor/readiness pre-run gates").option("--allow-breaking","Allow breaking changes for a verified goal").option("--allow-force","Allow force-based repairs for a verified goal").option("--card <id>","Dashboard card id for a governed repair transaction").option("--action-id <id>","Exact governed remediation action id").option("--project <name>","Registered project name for a scoped repair transaction").option("--proposal <path>","Validated model repair proposal JSON for CLI-owned execution").option("--transaction <id>","Durable workspace repair transaction id").option("--approved-by <actor>","Local actor approving the immutable repair plan").addOption(new Option("--decision <choice>","Resolve a decision-required repair transaction").choices(["approve-guarded","approve-invasive","allow-breaking","allow-force","manual-repair","rollback","cancel"])).addOption(new Option("--max-risk <risk>","Maximum approved repair risk").choices(["safe","guarded","invasive"])).option("--no-auto-rollback","Require a decision instead of automatic rollback on failure").option("--no-build","Do not require build validation for a verified goal").option("--no-tests","Do not require test validation for a verified goal").option("--no-run","Read current goal evidence without executing verification commands").option("--reuse-intelligence","Reuse a just-completed canonical intelligence run for verified goal checks").addHelpText("after",`
|
|
378
|
+
workspace mcp serve \u2014 read-mostly stdio MCP bridge over workspace evidence`).option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--output <file>","Output file path for workspace share/export artifacts").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 .workspai/reports").option("--include-evidence","Read status metadata from referenced evidence reports").option("--scan-depth <count>","Observable project discovery depth for large monorepos").option("--limit <count>","Bound graph search results (default 12, maximum 100)").option("--refresh-graph","Bypass the compatible persisted knowledge graph and rebuild from live workspace sources").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("--graph-stream","For workspace watch: emit workspace-graph-stream.v1 snapshot/delta NDJSON").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,gemini,qwen,kimi,grok,windsurf,amazon-q,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").addOption(new Option("--project-grounding <mode>","Project entrypoint policy for sync/agent-sync: managed, local, or off").choices(["managed","local","off"]).default("managed")).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(d$3.archiveCompression.signature,d$3.archiveCompression.description).option(d$3.maxDownloadSize.signature,d$3.maxDownloadSize.description).option(d$3.maxExpandedSize.signature,d$3.maxExpandedSize.description).option(d$3.downloadTimeoutMs.signature,d$3.downloadTimeoutMs.description).option(d$3.allowPrivateNetwork.signature,d$3.allowPrivateNetwork.description).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("--runtime <runtime>","Limit workspace run or a test-coverage Goal to one detected runtime family").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("--ci","Build CI-oriented command plans where supported").option("--strict","Return non-zero exit on warn/fail gate outcomes").option("--no-gates","Skip doctor/readiness pre-run gates").option("--allow-breaking","Allow breaking changes for a verified goal").option("--allow-force","Allow force-based repairs for a verified goal").option("--card <id>","Dashboard card id for a governed repair transaction").option("--action-id <id>","Exact governed remediation action id").option("--project <name>","Registered project name for a scoped repair transaction").option("--proposal <path>","Validated model repair proposal JSON for CLI-owned execution").option("--transaction <id>","Durable workspace repair transaction id").option("--approved-by <actor>","Local actor approving the immutable repair plan").addOption(new Option("--decision <choice>","Resolve a decision-required repair transaction").choices(["approve-guarded","approve-invasive","allow-breaking","allow-force","manual-repair","rollback","cancel"])).addOption(new Option("--max-risk <risk>","Maximum approved repair risk").choices(["safe","guarded","invasive"])).option("--no-auto-rollback","Require a decision instead of automatic rollback on failure").option("--no-build","Do not require build validation for a verified goal").option("--no-tests","Do not require test validation for a verified goal").option("--no-run","Read current goal evidence without executing verification commands").option("--reuse-intelligence","Reuse a just-completed canonical intelligence run for verified goal checks").addHelpText("after",`
|
|
379
379
|
Workspace Actions:
|
|
380
380
|
Discovery & registry list | sync | registry | foundation
|
|
381
381
|
Intelligence loop model | snapshot | diff | impact | verify | context
|
|
@@ -386,23 +386,23 @@ Workspace Actions:
|
|
|
386
386
|
Fleet lifecycle run | init
|
|
387
387
|
|
|
388
388
|
Use "workspai commands --json" for the contract-backed runtime inventory.
|
|
389
|
-
See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=l=>{let v=n.workspace?j.resolve(n.workspace):null,u=null,h=null;try{u=b$5({startPath:process.cwd(),explicitWorkspacePath:v,strict:true})?.workspacePath??null;}catch(C){if(C instanceof a$2)h=C;else throw C}if(!u||!qe(u)){let C=h?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${l}`,code:h?.code??"workspace.root.required",message:C,context:{cwd:j.resolve(process.cwd()),...v?{requestedWorkspace:v}:{},...h?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${C}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let g=j.resolve(process.cwd()),k=j.resolve(u);return g!==k&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${u} for "${l}" (current directory: ${g}).`)),u},i=l=>process.argv.includes(l),c=l=>Oe(process.argv,l),p=()=>n.output||c("--output"),d=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0},f=(l,v)=>{if(!l)return;let u=l.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!u)throw new Error(`${v} must be a byte size such as 500gb or 2tb.`);let h={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},g=Number(u[1])*h[u[2]||"b"];if(!Number.isSafeInteger(Math.floor(g))||g<=0)throw new Error(`${v} is outside the supported numeric range.`);return Math.floor(g)},m=()=>{let l=n.downloadTimeoutMs,v=l===void 0?void 0:Number.parseInt(l,10);if(v!==void 0&&(!Number.isFinite(v)||v<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:f(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:f(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:v,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},w=new Set(Object.values(Or).flatMap(l=>[...l.flags])),y=new Set(process.argv.slice(2).filter(l=>l.startsWith("--")).map(l=>l.split("=",1)[0]).filter(l=>w.has(l))),P=Or[t]?.flags,S=P?[...y].filter(l=>!P.includes(l)):[];if(S.length>0){let l=`${S.join(", ")} ${S.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||y.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:l,exitCode:2,context:{action:t,unsupportedFlags:S,allowedFlags:P}}),null,2)):(console.log(s.red(`\u274C ${l}`)),console.log(s.gray(` Allowed flags: ${P.join(", ")||"none"}`))),process.exit(2);}if((tl(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$5({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:l}=await import('./workspace-BNRSBWSL.js');await l({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let l=a("intelligence"),{runWorkspaceIntelligenceChain:v}=await import('./workspace-intelligence-runner-QLLBUD6G.js'),u=await v({workspacePath:l,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(u,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${u.status}`));for(let h of u.stages)console.log(s.gray(` ${h.id}: ${h.status} \u2014 ${h.message}`));console.log(s.gray(` Evidence: ${u.artifactPath}`));}u.exitCode!==0&&process.exit(u.exitCode);}else if(t==="model"){let l=a("model"),{buildWorkspaceModelCached:v,buildWorkspaceModelIncremental:u,createWorkspaceModelBuildProvenance:h,writeWorkspaceModel:g}=await import('./workspace-model-EIQSKDX7.js'),k=n.incremental===true||i("--incremental"),C=n.cache===true||i("--cache")||k,x={workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:n.strict===true||i("--strict")},b,E;if(k){let W=await u(x);b=W.model,E=W.mode;}else {let W=await v({...x,cache:C});b=W.model,E=W.cache;}b={...b,build:h({mode:k?"incremental":C?"cache":"full",engineStatus:E})};let R;(n.write===true||i("--write"))&&(R=await g(b,l));let $=(n.strict===true||i("--strict"))&&b.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...b,...R?{outputPath:R}:{}},null,2)),$&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${b.workspace.name}`)),k?console.log(s.gray(` Build: ${E} (incremental)`)):C&&console.log(s.gray(` Cache: ${E}`)),console.log(s.gray(` Projects: ${b.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${b.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${b.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${b.identity.workspaceType}`)),console.log(s.gray(` Validation: ${b.validation?.status??"unknown"} (${b.validation?.errors??0} error, ${b.validation?.warnings??0} warning)`)),console.log(R?s.gray(` Written: ${R}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),$&&process.exit(1);}else if(t==="agent-sync"){let l=a("agent-sync"),{syncWorkspaceAgentGrounding:v,parseAgentGroundingTargets:u}=await import('./workspace-agent-sync-ANBHBZ2H.js'),h=n.strict===true||i("--strict"),g=n.write===true||i("--write"),k=i("--dry-run"),C=await v({workspacePath:l,scope:n.scope,agent:n.forAgent,write:g&&!k,dryRun:k,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:u(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(C,null,2));else {console.log(s.green(`\u2714 Agent grounding ${g&&!k?"synced":"planned"}`)),console.log(s.gray(` Index: ${C.indexPath}`)),C.contextPath&&console.log(s.gray(` Context: ${C.contextPath}`)),C.blockers.length>0&&console.log(s.yellow(` Blockers: ${C.blockers.slice(0,3).join(" \xB7 ")}`));let x=g&&!k?C.writtenFiles:C.skippedFiles;if(x.length>0&&console.log(s.gray(` Files: ${x.join(", ")}`)),C.strictViolations.length>0)for(let b of C.strictViolations)console.log(s.red(`\u274C ${b}`));}h&&C.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let l=e??"status",{approveWorkspaceRepair:v,cancelWorkspaceRepair:u,decideWorkspaceRepair:h,executeWorkspaceRepair:g,inspectWorkspaceRepairCapabilities:k,listWorkspaceRepairTransactions:C,planWorkspaceRepair:x,planWorkspaceRepairProposal:b,readWorkspaceRepairTransaction:E,rollbackWorkspaceRepair:R}=await import('./workspace-repair-engine-DHH2UUJN.js');if(l==="capabilities"){let U;if(n.workspace)U=a("repair capabilities");else try{let Q=b$5({startPath:process.cwd(),strict:false})?.workspacePath;Q&&qe(Q)&&(U=Q);}catch{}let q=await k(U?{workspacePath:U,project:n.project}:n.project?{project:n.project}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(q,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${q.adapters.length}`));for(let Q of q.adapters)console.log(s.gray(` ${Q.id.padEnd(14)} ${Q.support.padEnd(11)} ${Q.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let $=a("repair"),W=n.transaction??(["plan","propose","capabilities"].includes(l)?void 0:r),T=()=>{if(!W?.trim())throw new Error(`workspace repair ${l} requires --transaction <id> (or the id as the next positional argument).`);return W.trim()},A;if(l==="plan"){let U=n.card??r;if(!U?.trim())throw new Error("workspace repair plan requires --card <id>.");A=await x({workspacePath:$,cardId:U.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="propose"){let U=n.proposal??r;if(!U?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let q=j.resolve($,U.trim()),Q=j.relative($,q);if(Q.startsWith("..")||j.isAbsolute(Q))throw new Error("The repair proposal file must be inside the canonical workspace.");let L=await O__default.lstat(q).catch(()=>{});if(!L?.isFile()||L.isSymbolicLink()||L.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");A=await b({workspacePath:$,proposal:await O__default.readJson(q),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="approve")A=await v({workspacePath:$,transactionId:T(),approvedBy:n.approvedBy});else if(l==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");A=await h({workspacePath:$,transactionId:T(),decision:n.decision});}else if(l==="execute"||l==="resume")A=await g({workspacePath:$,transactionId:T()});else if(l==="status")A=await E({workspacePath:$,transactionId:T()});else if(l==="list")A=await C($);else if(l==="rollback")A=await R({workspacePath:$,transactionId:T()});else if(l==="cancel")A=await u({workspacePath:$,transactionId:T()});else throw new Error(`Unknown workspace repair action: ${l}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let X=j.join($,e$1.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$6(`workspace repair ${l}`,A,X),null,2));else if(Array.isArray(A)){console.log(s.green(`\u2714 Workspace repair transactions: ${A.length}`));for(let U of A.slice(0,20))console.log(s.gray(` ${U.transactionId} \xB7 ${U.target.cardId} \xB7 ${U.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${A.state}`)),console.log(s.gray(` Transaction: ${A.transactionId}`)),console.log(s.gray(` Target: ${A.target.cardId}`));for(let U of A.stages)console.log(s.gray(` ${U.status.padEnd(8)} ${U.kind}: ${U.summary}`));A.decision&&console.log(s.yellow(` Decision: ${A.decision.reason}`)),console.log(s.gray(` Evidence: ${e$1.repairTransaction}`));}Array.isArray(A)||(A.state==="decision-required"&&process.exit(2),(A.state==="rolled-back"||A.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let l=a("remediation-plan"),{buildArtifactRemediationPlan:v,writeArtifactRemediationPlan:u}=await import('./artifact-remediation-plan-HPNQTNJ2.js'),h=await v({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),g;if((n.write===true||i("--write"))&&(g=await u(h,l)),n.json===true||i("--json")){console.log(JSON.stringify(b$6("workspace remediation-plan",h,g),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${h.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${h.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${h.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${h.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${h.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${h.summary.risk.safe}, guarded=${h.summary.risk.guarded}, invasive=${h.summary.risk.invasive}`));for(let k of h.actions.slice(0,8))console.log(s.gray(` \u2022 ${k.cardId}: ${k.title} (${k.mode}, ${k.risk})`));h.actions.length>8&&console.log(s.gray(` \u2026 ${h.actions.length-8} more action(s)`)),console.log(g?s.gray(` Written: ${g}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let l=a("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 workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:v,writeWorkspaceAgentContext:u}=await import('./workspace-context-RAO62QVU.js'),h=n.strict===true||i("--strict"),g=await v({workspacePath:l,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:false}),k,C;if((n.write===true||i("--write"))&&(k=await u(g,l),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:E,parseAgentGroundingTargets:R}=await import('./workspace-agent-sync-ANBHBZ2H.js');if(C=await E({workspacePath:l,scope:n.scope,agent:g.agent,write:true,refreshContext:false,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",targets:R(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${C.writtenFiles.length} file(s) updated`)),h&&C.strictViolations.length>0){for(let $ of C.strictViolations)console.log(s.red(`\u274C ${$}`));process.exit(1);}}let x=h&&g.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...g,...k?{outputPath:k}:{},...C?{agentGroundingSync:C}:{}},null,2)),x&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${g.workspace.name}`)),console.log(s.gray(` Agent: ${g.agent}`)),console.log(s.gray(` Scope: ${g.scope.activeProject??g.scope.requested}`)),console.log(s.gray(` Projects included: ${g.projects.length}`)),console.log(s.gray(` Safe commands: ${g.safeCommands.length}`)),console.log(s.gray(` Validation: ${g.validation.status} (${g.validation.errors} error, ${g.validation.warnings} warning)`)),console.log(k?s.gray(` Written: ${k}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),x){for(let b of g.validation.issues)console.log(s.red(`\u274C ${b.severity}:${b.code}:${b.target}`));process.exit(1);}}else if(t==="snapshot"){let l=a("snapshot"),{buildWorkspaceModelSnapshot:v,writeWorkspaceModelSnapshot:u}=await import('./workspace-intelligence-3YERTBA3.js'),h=await v({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),g=await u(h,l);if(n.json){console.log(JSON.stringify(b$6("workspace snapshot",h,g),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${h.model.workspace.name}`)),console.log(s.gray(` Hash: ${h.modelHash}`)),console.log(s.gray(` Projects: ${h.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${h.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${g}`));}else if(t==="diff"){let l=a("diff"),v=n.from||e;v||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:u,writeWorkspaceModelDiff:h}=await import('./workspace-intelligence-3YERTBA3.js'),g;try{g=await u({workspacePath:l,fromPath:v,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:x.message,context:{workspacePath:l,fromPath:v},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),x}let k=await h(g,l);if(n.json){console.log(JSON.stringify(b$6("workspace diff",g,k),null,2));return}let C=g.summary.changed?s.yellow:s.green;console.log(C(`\u2714 Workspace model diff: ${g.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Added projects: ${g.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${g.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${g.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${g.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${g.summary.validationChanges}`)),g.git?.available&&console.log(s.gray(` Git: ${g.git.dirty?"dirty":"clean"} (${g.summary.gitChangedFiles} mapped change(s))`));for(let x of g.changes.slice(0,12))console.log(s.gray(` \u2022 ${x.type} ${x.target}: ${x.message}`));g.changes.length>12&&console.log(s.gray(` \u2026 ${g.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${k}`));}else if(t==="impact"){let l=a("impact"),v=n.from||e;v||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:u,writeWorkspaceImpact:h}=await import('./workspace-intelligence-3YERTBA3.js'),g;try{g=await u({workspacePath:l,fromPath:v,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:x.message,context:{workspacePath:l,fromPath:v},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),x}let k=await h(g,l);if(n.json){console.log(JSON.stringify(b$6("workspace impact",g,k),null,2));return}let C=g.summary.risk==="critical"||g.summary.risk==="high"?s.red:g.summary.risk==="medium"?s.yellow:s.green;console.log(C(`\u2714 Workspace impact: ${g.summary.risk}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Affected projects: ${g.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${g.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${g.summary.recommendedCommands}`));for(let x of g.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${x.title}: ${x.summary}`));g.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${g.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${k}`));}else if(t==="verify"){let l=a("verify"),{buildWorkspaceVerify:v,writeWorkspaceVerify:u,evaluateWorkspaceVerifyGate:h}=await import('./workspace-verify-W4P6LBIH.js'),g=await v({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),k=await u(g,l),C=h(g,{strict:n.strict===true||i("--strict")}),x=C.exitCode,{recordWorkspaceHistory:b,historyEntryFromVerify:E}=await import('./workspace-history-SYCDK7FO.js');if(await b(l,E(g,C.passed)),n.json){console.log(JSON.stringify(b$6("workspace verify",{...g,gate:C},k,x),null,2)),x!==0&&process.exit(x);return}let R=g.summary.verdict==="ready"?s.green:g.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(R(`\u2714 Workspace verify: ${g.summary.verdict}`)),console.log(s.gray(` Freshness: ${g.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${g.impact.risk}`)),console.log(s.gray(` Steps: ${g.steps.length}`)),console.log(s.gray(` Passed ${g.summary.stepsPassed}, warn ${g.summary.stepsWarn}, failed ${g.summary.stepsFailed}, missing ${g.summary.stepsMissing}`));for(let $ of g.steps.slice(0,10))console.log(s.gray(` \u2022 ${$.id}: ${$.status} \u2014 ${$.message}`));if(g.steps.length>10&&console.log(s.gray(` \u2026 ${g.steps.length-10} more step(s)`)),g.policyViolations.length>0){console.log(s.gray(` Policy (${g.policyMode}): ${g.policyViolations.length} violation(s)`));for(let $ of g.policyViolations.slice(0,5)){let W=$.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${W} [${$.source}] ${$.code}: ${$.message}`);}}console.log(s.gray(` Gate (${C.mode}): ${C.passed?"passed":"blocked"}`));for(let $ of C.reasons.slice(0,5))console.log(s.red(` \u2717 ${$}`));console.log(s.gray(` Written: ${k}`)),x!==0&&process.exit(x);}else if(t==="graph"){let l=a("graph"),{buildWorkspaceModel:v,workspaceModelProjectTopology:u}=await import('./workspace-model-EIQSKDX7.js'),{buildGraphEmit:h,renderGraphDot:g,renderGraphMermaid:k,explainGraphNode:C}=await import('./workspace-graph-2A5THUCI.js'),x=(e||"emit").toLowerCase(),b=new Set(["benchmark","entities","evidence","path","search"]),E=n.refreshGraph===true||i("--refresh-graph"),R=b.has(x)&&!E?await(await import('./workspace-knowledge-graph-snapshot-7DWHMEM2.js')).readWorkspaceKnowledgeGraphSnapshot(l):null,$=R?.status==="hit"?R.graph:null,W=R?.status==="hit"?R.model:await v({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),T=u(W);T||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:x,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let A=async()=>{if($)return $;let{buildWorkspaceKnowledgeGraph:L}=await import('./workspace-knowledge-graph-HZZP6ZRB.js'),{hashWorkspaceModel:F}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:K}=await import('./workspace-contract-ACSIHJIO.js'),te=null;try{te=(await K({workspacePath:l})).contract;}catch{}return L({workspacePath:l,workspace:{name:W.workspace.name,...W.workspace.profile?{profile:W.workspace.profile}:{}},projects:W.projects.map(H=>({id:H.name,path:H.path,...H.absolutePath?{absolutePath:H.absolutePath}:{},runtime:H.runtime,runtimeCandidates:H.runtimeCandidates,framework:H.framework,...H.kit?{kit:H.kit}:{}})),projectTopology:T,contract:te,now:new Date(W.generatedAt),source:{kind:"workspace-model",artifact:e$1.model,hashAlgorithm:"sha256",hash:F(W)}})};if(x==="dot"||x==="mermaid"){let L=x==="dot"?g(T):k(T),F=p();if(F){let K=j.resolve(l,F);await O__default.outputFile(K,`${L}
|
|
390
|
-
`,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${x}`,{format:x,nodeCount:
|
|
391
|
-
`,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${x}`,{format:x,entityCount:L.entities.length,relationCount:L.relations.length,proofCount:L.proofs.length},ue),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${x}`)),console.log(s.gray(` Written: ${ue}`)));return}console.log(H);return}if(x==="explain"){let L=(n.scope?.replace(/^project:/,"")||r||"").trim();L||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:
|
|
392
|
-
`,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace graph emit",{format:"json",nodeCount:
|
|
393
|
-
`,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace contract graph",{projectCount:E.graph.summary.projectCount,relationshipEdges:E.graph.summary.relationshipEdges,entityCount:E.graph.summary.entityCount,knowledgeRelations:E.graph.summary.knowledgeRelations,proofCount:E.graph.summary.proofCount},R),null,2)):(console.log(s.green("\u2714 Workspace contract graph exported as JSON")),console.log(s.gray(` Written: ${R}`)));return}if(n.json){console.log(JSON.stringify(E,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${E.contractPath}`)),console.log(s.gray(` Workspace: ${E.graph.workspace.name}`)),console.log(s.gray(` Projects: ${E.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${E.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${E.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${E.graph.summary.relationshipEdges} (${E.graph.summary.inferredEdges} inferred, ${E.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${E.graph.summary.connectedProjects}/${E.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(E.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(E.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${E.graph.summary.orphanProjects} \xB7 Hotspots: ${E.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${E.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${E.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${E.graph.summary.entityCount} entities \xB7 ${E.graph.summary.knowledgeRelations} relations \xB7 ${E.graph.summary.proofCount} proofs \xB7 ${E.graph.summary.providerCount} providers \xB7 ${E.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${E.graph.summary.portCount}`));for(let R of E.graph.nodes){let $=R.ports.map(T=>`${T.name}:${T.port}`).join(", ")||"none",W=R.operationalProfile?` risk=${R.operationalProfile.weight}/${R.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${R.id} (${R.runtime||"unknown"}${R.framework?`/${R.framework}`:""}) ports=${$} manifests=${R.files.manifests.length}${W}`));}for(let R of E.graph.edges){let $=R.type==="event"?`event:${R.label}`:R.label;console.log(s.gray(` ${R.from} -> ${R.to} [${$}]`));}if(E.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let R of E.graph.dependencyGraph.edges)console.log(s.gray(` ${R.from} -> ${R.to} [${R.kind}/${R.source}/${R.confidence}] evidence=${R.evidence.length}`));}for(let R of E.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${R.severity}: ${R.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${C}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${k}]`)),process.exit(1);}catch(E){n.json&&(console.log(JSON.stringify({command:`workspace contract ${C}`,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${C}.failed`,message:E.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${C} failed: ${E.message}`)),process.exit(1);}}else if(t==="share"){let l=a("share"),v=p()||e,{createWorkspaceShareBundle:u}=await import('./workspace-BNRSBWSL.js'),h=await u(l,{outputPath:v,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:l,bundlePath:h,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${h}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=a("export");try{let{exportWorkspaceArchive:v}=await import('./workspace-archive-ZBCKJHXS.js'),u=n.archiveCompression?.trim().toLowerCase()??"store";if(u!=="store"&&u!=="deflate")throw new Error("--archive-compression must be store or deflate.");let h=await v({workspacePath:l,outputPath:p()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:u});if(n.json){console.log(JSON.stringify(h,null,2));return}let g=(h.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.manifest.files.length}`)),console.log(s.gray(` Size: ${g} MB`)),h.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(v){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:v.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${v.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let l=r;l||(n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:v,inspectWorkspaceArchive:u,verifyWorkspaceArchive:h}=await import('./workspace-archive-ZBCKJHXS.js');try{if(e==="inspect"){let k=await u({archivePathOrUrl:l,safety:m()});if(n.json){console.log(JSON.stringify(k,null,2));return}let C=(k.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${k.archivePath}`)),console.log(s.gray(` Workspace: ${k.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${k.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${k.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${k.fileCount}`)),console.log(s.gray(` Payload: ${C} MB`));return}if(e==="doctor"){let k=await v({archivePathOrUrl:l,strict:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(k,null,2));else {let C=k.status==="passed"?s.green:k.status==="warning"?s.yellow:s.red;console.log(C(`\u2714 Workspace archive doctor ${k.status}: ${k.archivePath}`)),console.log(s.gray(` Workspace: ${k.workspaceName}`)),console.log(s.gray(` Files: ${k.fileCount}`));for(let x of k.checks){let b=x.status==="passed"?"\u2714":x.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${b} ${x.id}: ${x.message}`));}for(let x of k.recommendedActions)console.log(s.gray(` Next: ${x}`));}(k.status==="failed"||k.status==="warning"&&n.strict)&&process.exit(1);return}let g=await h({archivePathOrUrl:l,requireChecksums:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(g,null,2));else if(g.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${g.archivePath}`)),console.log(s.gray(` Files: ${g.verifiedFiles}/${g.fileCount}`));else {let k=g.status==="failed"?s.red:s.yellow;console.log(k(`\u274C Workspace archive verification ${g.status}: ${g.archivePath}`)),g.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${g.missingArchiveEntries.join(", ")}`)),g.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${g.extraArchiveEntries.join(", ")}`)),g.mismatches.length&&console.log(s.gray(` Mismatches: ${g.mismatches.map(C=>C.path).join(", ")}`)),g.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${g.missingChecksumFiles.join(", ")}`));}(g.status==="failed"||g.status==="warning"&&n.strict)&&process.exit(1);}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,error:{code:`workspace.archive.${e}.failed`,message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${g.message}`)),process.exit(1);}}else if(t==="connect"){let l=j.resolve(e||process.cwd());try{let v=await Ps({workspacePath:l,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(v.status==="preview"?`\u2714 Workspace connection preview: ${l}`:`\u2714 Workspace connected: ${l}`));for(let u of v.warnings)console.log(s.yellow(` \u26A0 ${u}`));}catch(v){let u=v instanceof Error?v.message:String(v);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:u}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${u}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let v=await js({archivePathOrUrl:l,outputPath:p(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:m()});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(v.status==="preview"?`\u2714 Workspace import preview: ${v.workspacePath}`:`\u2714 Workspace imported and registered: ${v.workspacePath}`));for(let u of v.warnings)console.log(s.yellow(` \u26A0 ${u}`));}else {let{hydrateWorkspaceArchive:v}=await import('./workspace-archive-ZBCKJHXS.js'),u=await v({archivePathOrUrl:l,outputPath:p(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:m()});if(n.json){console.log(JSON.stringify(u,null,2));return}console.log(s.green(u.dryRun?`\u2714 Workspace archive hydrate preview: ${u.outputPath}`:`\u2714 Workspace archive hydrated: ${u.outputPath}`)),console.log(s.gray(` Files: ${u.files.length}`)),u.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${u.manifest.workspaceName}`));}}catch(v){let u=v instanceof Error?v.message:String(v);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:u,context:{archivePathOrUrl:l,...p()?{outputPath:p()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,...p()?{outputPath:p()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:u}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${u}`)),process.exit(1);}}else if(t==="run"){let l=a(`run ${e||""}`.trim()),v=new Set(["init","test","build","start"]),u=e?.trim()??"";u||(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 .workspai/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)),v.has(u)||(!/^[a-z][a-z0-9_-]*$/i.test(u)||u==="dev"||u==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${u}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),u==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let h=Os({raw:n.maxWorkers,operation:`workspace run ${u}`,json:n.json===true||i("--json")});if(u==="init"&&n.json!==true){let C=await Fs(l);C!==0&&process.exit(C);}let{runWorkspaceStage:g}=await import('./workspace-run-BLHRXT2N.js'),k=await g({workspacePath:l,stage:u,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:h,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true,planOnly:n.plan===true,runtime:n.runtime});n.json&&console.log(JSON.stringify(k,null,2)),k.summary.exitCode!==0&&process.exit(k.summary.exitCode);}else if(t==="explain"||t==="why"){let l=a(t),{parseWorkspaceExplainTarget:v}=await import('./workspace-explain-contract-ZL4NMLZI.js'),{buildWorkspaceExplain:u,writeWorkspaceExplainReport:h}=await import('./workspace-explain-RH27OQB4.js'),g=(e??r??"").trim();!g&&n.scope&&(g=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),g||(g="release-blocked");let k=v(g);k||(console.log(s.red(`\u274C Invalid explain target: ${g}`)),process.exit(1));let C=await u({workspacePath:l,target:k}),x=n.write===true||i("--write"),b;if(x&&(b=await h(C,l,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$6(`workspace ${t}`,C,b),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${C.summary}`));for(let E of C.sections)console.log(s.bold(`
|
|
394
|
-
${
|
|
395
|
-
Written: ${
|
|
396
|
-
${
|
|
397
|
-
Written: ${
|
|
398
|
-
npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:
|
|
389
|
+
See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=p=>{let v=n.workspace?j.resolve(n.workspace):null,m=null,h=null;try{m=b$5({startPath:process.cwd(),explicitWorkspacePath:v,strict:true})?.workspacePath??null;}catch(b){if(b instanceof a$2)h=b;else throw b}if(!m||!qe(m)){let b=h?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${p}`,code:h?.code??"workspace.root.required",message:b,context:{cwd:j.resolve(process.cwd()),...v?{requestedWorkspace:v}:{},...h?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${b}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let g=j.resolve(process.cwd()),k=j.resolve(m);return g!==k&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${m} for "${p}" (current directory: ${g}).`)),m},i=p=>process.argv.includes(p),c=p=>Oe(process.argv,p),d=()=>n.output||c("--output"),l=()=>{if(!n.scanDepth)return;let p=Number.parseInt(n.scanDepth,10);return Number.isFinite(p)?p:void 0},f=(p,v)=>{if(!p)return;let m=p.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!m)throw new Error(`${v} must be a byte size such as 500gb or 2tb.`);let h={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},g=Number(m[1])*h[m[2]||"b"];if(!Number.isSafeInteger(Math.floor(g))||g<=0)throw new Error(`${v} is outside the supported numeric range.`);return Math.floor(g)},u=()=>{let p=n.downloadTimeoutMs,v=p===void 0?void 0:Number.parseInt(p,10);if(v!==void 0&&(!Number.isFinite(v)||v<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:f(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:f(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:v,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},w=new Set(Object.values(Or).flatMap(p=>[...p.flags])),y=new Set(process.argv.slice(2).filter(p=>p.startsWith("--")).map(p=>p.split("=",1)[0]).filter(p=>w.has(p))),P=Or[t]?.flags,S=P?[...y].filter(p=>!P.includes(p)):[];if(S.length>0){let p=`${S.join(", ")} ${S.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||y.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:p,exitCode:2,context:{action:t,unsupportedFlags:S,allowedFlags:P}}),null,2)):(console.log(s.red(`\u274C ${p}`)),console.log(s.gray(` Allowed flags: ${P.join(", ")||"none"}`))),process.exit(2);}if((tl(t)||t==="trace"||t==="feedback"||t==="mcp")&&c$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:p}=await import('./workspace-UUU4VMZB.js');await p({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let p=a("intelligence"),{runWorkspaceIntelligenceChain:v}=await import('./workspace-intelligence-runner-7KCGHRID.js'),m=await v({workspacePath:p,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(m,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${m.status}`));for(let h of m.stages)console.log(s.gray(` ${h.id}: ${h.status} \u2014 ${h.message}`));console.log(s.gray(` Evidence: ${m.artifactPath}`));}m.exitCode!==0&&process.exit(m.exitCode);}else if(t==="model"){let p=a("model"),{buildWorkspaceModelCached:v,buildWorkspaceModelIncremental:m,createWorkspaceModelBuildProvenance:h,writeWorkspaceModel:g}=await import('./workspace-model-ETCLINRB.js'),k=n.incremental===true||i("--incremental"),b=n.cache===true||i("--cache")||k,x={workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l(),strict:n.strict===true||i("--strict")},C,R;if(k){let M=await m(x);C=M.model,R=M.mode;}else {let M=await v({...x,cache:b});C=M.model,R=M.cache;}C={...C,build:h({mode:k?"incremental":b?"cache":"full",engineStatus:R})};let E;(n.write===true||i("--write"))&&(E=await g(C,p));let $=(n.strict===true||i("--strict"))&&C.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...C,...E?{outputPath:E}:{}},null,2)),$&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${C.workspace.name}`)),k?console.log(s.gray(` Build: ${R} (incremental)`)):b&&console.log(s.gray(` Cache: ${R}`)),console.log(s.gray(` Projects: ${C.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${C.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${C.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${C.identity.workspaceType}`)),console.log(s.gray(` Validation: ${C.validation?.status??"unknown"} (${C.validation?.errors??0} error, ${C.validation?.warnings??0} warning)`)),console.log(E?s.gray(` Written: ${E}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),$&&process.exit(1);}else if(t==="agent-sync"){let p=a("agent-sync"),{syncWorkspaceAgentGrounding:v,parseAgentGroundingTargets:m}=await import('./workspace-agent-sync-LQNIMGLN.js'),h=n.strict===true||i("--strict"),g=n.write===true||i("--write"),k=i("--dry-run"),b=await v({workspacePath:p,scope:n.scope,agent:n.forAgent,write:g&&!k,dryRun:k,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:m(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(b,null,2));else {console.log(s.green(`\u2714 Agent grounding ${g&&!k?"synced":"planned"}`)),console.log(s.gray(` Index: ${b.indexPath}`)),b.contextPath&&console.log(s.gray(` Context: ${b.contextPath}`)),b.blockers.length>0&&console.log(s.yellow(` Blockers: ${b.blockers.slice(0,3).join(" \xB7 ")}`));let x=g&&!k?b.writtenFiles:b.skippedFiles;if(x.length>0&&console.log(s.gray(` Files: ${x.join(", ")}`)),b.strictViolations.length>0)for(let C of b.strictViolations)console.log(s.red(`\u274C ${C}`));}h&&b.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let p=e??"status",{approveWorkspaceRepair:v,cancelWorkspaceRepair:m,decideWorkspaceRepair:h,executeWorkspaceRepair:g,inspectWorkspaceRepairCapabilities:k,listWorkspaceRepairTransactions:b,planWorkspaceRepair:x,planWorkspaceRepairProposal:C,readWorkspaceRepairTransaction:R,rollbackWorkspaceRepair:E}=await import('./workspace-repair-engine-7WGJWUBN.js');if(p==="capabilities"){let U;if(n.workspace)U=a("repair capabilities");else try{let Q=b$5({startPath:process.cwd(),strict:false})?.workspacePath;Q&&qe(Q)&&(U=Q);}catch{}let q=await k(U?{workspacePath:U,project:n.project}:n.project?{project:n.project}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(q,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${q.adapters.length}`));for(let Q of q.adapters)console.log(s.gray(` ${Q.id.padEnd(14)} ${Q.support.padEnd(11)} ${Q.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let $=a("repair"),M=n.transaction??(["plan","propose","capabilities"].includes(p)?void 0:r),N=()=>{if(!M?.trim())throw new Error(`workspace repair ${p} requires --transaction <id> (or the id as the next positional argument).`);return M.trim()},A;if(p==="plan"){let U=n.card??r;if(!U?.trim())throw new Error("workspace repair plan requires --card <id>.");A=await x({workspacePath:$,cardId:U.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(p==="propose"){let U=n.proposal??r;if(!U?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let q=j.resolve($,U.trim()),Q=j.relative($,q);if(Q.startsWith("..")||j.isAbsolute(Q))throw new Error("The repair proposal file must be inside the canonical workspace.");let L=await O__default.lstat(q).catch(()=>{});if(!L?.isFile()||L.isSymbolicLink()||L.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");A=await C({workspacePath:$,proposal:await O__default.readJson(q),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(p==="approve")A=await v({workspacePath:$,transactionId:N(),approvedBy:n.approvedBy});else if(p==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");A=await h({workspacePath:$,transactionId:N(),decision:n.decision});}else if(p==="execute"||p==="resume")A=await g({workspacePath:$,transactionId:N()});else if(p==="status")A=await R({workspacePath:$,transactionId:N()});else if(p==="list")A=await b($);else if(p==="rollback")A=await E({workspacePath:$,transactionId:N()});else if(p==="cancel")A=await m({workspacePath:$,transactionId:N()});else throw new Error(`Unknown workspace repair action: ${p}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let X=j.join($,e$2.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$6(`workspace repair ${p}`,A,X),null,2));else if(Array.isArray(A)){console.log(s.green(`\u2714 Workspace repair transactions: ${A.length}`));for(let U of A.slice(0,20))console.log(s.gray(` ${U.transactionId} \xB7 ${U.target.cardId} \xB7 ${U.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${A.state}`)),console.log(s.gray(` Transaction: ${A.transactionId}`)),console.log(s.gray(` Target: ${A.target.cardId}`));for(let U of A.stages)console.log(s.gray(` ${U.status.padEnd(8)} ${U.kind}: ${U.summary}`));A.decision&&console.log(s.yellow(` Decision: ${A.decision.reason}`)),console.log(s.gray(` Evidence: ${e$2.repairTransaction}`));}Array.isArray(A)||(A.state==="decision-required"&&process.exit(2),(A.state==="rolled-back"||A.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let p=a("remediation-plan"),{buildArtifactRemediationPlan:v,writeArtifactRemediationPlan:m}=await import('./artifact-remediation-plan-HPNQTNJ2.js'),h=await v({workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),g;if((n.write===true||i("--write"))&&(g=await m(h,p)),n.json===true||i("--json")){console.log(JSON.stringify(b$6("workspace remediation-plan",h,g),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${h.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${h.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${h.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${h.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${h.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${h.summary.risk.safe}, guarded=${h.summary.risk.guarded}, invasive=${h.summary.risk.invasive}`));for(let k of h.actions.slice(0,8))console.log(s.gray(` \u2022 ${k.cardId}: ${k.title} (${k.mode}, ${k.risk})`));h.actions.length>8&&console.log(s.gray(` \u2026 ${h.actions.length-8} more action(s)`)),console.log(g?s.gray(` Written: ${g}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let p=a("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 workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:v,writeWorkspaceAgentContext:m}=await import('./workspace-context-YAK5XX27.js'),h=n.strict===true||i("--strict"),g=await v({workspacePath:p,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l(),strict:false}),k,b;if((n.write===true||i("--write"))&&(k=await m(g,p),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:R,parseAgentGroundingTargets:E}=await import('./workspace-agent-sync-LQNIMGLN.js');if(b=await R({workspacePath:p,scope:n.scope,agent:g.agent,write:true,refreshContext:false,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",targets:E(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${b.writtenFiles.length} file(s) updated`)),h&&b.strictViolations.length>0){for(let $ of b.strictViolations)console.log(s.red(`\u274C ${$}`));process.exit(1);}}let x=h&&g.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...g,...k?{outputPath:k}:{},...b?{agentGroundingSync:b}:{}},null,2)),x&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${g.workspace.name}`)),console.log(s.gray(` Agent: ${g.agent}`)),console.log(s.gray(` Scope: ${g.scope.activeProject??g.scope.requested}`)),console.log(s.gray(` Projects included: ${g.projects.length}`)),console.log(s.gray(` Safe commands: ${g.safeCommands.length}`)),console.log(s.gray(` Validation: ${g.validation.status} (${g.validation.errors} error, ${g.validation.warnings} warning)`)),console.log(k?s.gray(` Written: ${k}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),x){for(let C of g.validation.issues)console.log(s.red(`\u274C ${C.severity}:${C.code}:${C.target}`));process.exit(1);}}else if(t==="snapshot"){let p=a("snapshot"),{buildWorkspaceModelSnapshot:v,writeWorkspaceModelSnapshot:m}=await import('./workspace-intelligence-625UN27X.js'),h=await v({workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()}),g=await m(h,p);if(n.json){console.log(JSON.stringify(b$6("workspace snapshot",h,g),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${h.model.workspace.name}`)),console.log(s.gray(` Hash: ${h.modelHash}`)),console.log(s.gray(` Projects: ${h.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${h.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${g}`));}else if(t==="diff"){let p=a("diff"),v=n.from||e;v||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:p},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:m,writeWorkspaceModelDiff:h}=await import('./workspace-intelligence-625UN27X.js'),g;try{g=await m({workspacePath:p,fromPath:v,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:x.message,context:{workspacePath:p,fromPath:v},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),x}let k=await h(g,p);if(n.json){console.log(JSON.stringify(b$6("workspace diff",g,k),null,2));return}let b=g.summary.changed?s.yellow:s.green;console.log(b(`\u2714 Workspace model diff: ${g.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Added projects: ${g.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${g.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${g.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${g.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${g.summary.validationChanges}`)),g.git?.available&&console.log(s.gray(` Git: ${g.git.dirty?"dirty":"clean"} (${g.summary.gitChangedFiles} mapped change(s))`));for(let x of g.changes.slice(0,12))console.log(s.gray(` \u2022 ${x.type} ${x.target}: ${x.message}`));g.changes.length>12&&console.log(s.gray(` \u2026 ${g.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${k}`));}else if(t==="impact"){let p=a("impact"),v=n.from||e;v||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:p},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:m,writeWorkspaceImpact:h}=await import('./workspace-intelligence-625UN27X.js'),g;try{g=await m({workspacePath:p,fromPath:v,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:x.message,context:{workspacePath:p,fromPath:v},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),x}let k=await h(g,p);if(n.json){console.log(JSON.stringify(b$6("workspace impact",g,k),null,2));return}let b=g.summary.risk==="critical"||g.summary.risk==="high"?s.red:g.summary.risk==="medium"?s.yellow:s.green;console.log(b(`\u2714 Workspace impact: ${g.summary.risk}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Affected projects: ${g.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${g.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${g.summary.recommendedCommands}`));for(let x of g.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${x.title}: ${x.summary}`));g.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${g.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${k}`));}else if(t==="verify"){let p=a("verify"),{buildWorkspaceVerify:v,writeWorkspaceVerify:m,evaluateWorkspaceVerifyGate:h}=await import('./workspace-verify-7ENGIY4S.js'),g=await v({workspacePath:p,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()}),k=await m(g,p),b=h(g,{strict:n.strict===true||i("--strict")}),x=b.exitCode,{recordWorkspaceHistory:C,historyEntryFromVerify:R}=await import('./workspace-history-SYCDK7FO.js');if(await C(p,R(g,b.passed)),n.json){console.log(JSON.stringify(b$6("workspace verify",{...g,gate:b},k,x),null,2)),x!==0&&process.exit(x);return}let E=g.summary.verdict==="ready"?s.green:g.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(E(`\u2714 Workspace verify: ${g.summary.verdict}`)),console.log(s.gray(` Freshness: ${g.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${g.impact.risk}`)),console.log(s.gray(` Steps: ${g.steps.length}`)),console.log(s.gray(` Passed ${g.summary.stepsPassed}, warn ${g.summary.stepsWarn}, failed ${g.summary.stepsFailed}, missing ${g.summary.stepsMissing}`));for(let $ of g.steps.slice(0,10))console.log(s.gray(` \u2022 ${$.id}: ${$.status} \u2014 ${$.message}`));if(g.steps.length>10&&console.log(s.gray(` \u2026 ${g.steps.length-10} more step(s)`)),g.policyViolations.length>0){console.log(s.gray(` Policy (${g.policyMode}): ${g.policyViolations.length} violation(s)`));for(let $ of g.policyViolations.slice(0,5)){let M=$.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${M} [${$.source}] ${$.code}: ${$.message}`);}}console.log(s.gray(` Gate (${b.mode}): ${b.passed?"passed":"blocked"}`));for(let $ of b.reasons.slice(0,5))console.log(s.red(` \u2717 ${$}`));console.log(s.gray(` Written: ${k}`)),x!==0&&process.exit(x);}else if(t==="graph"){let p=a("graph"),{buildWorkspaceModel:v,workspaceModelProjectTopology:m}=await import('./workspace-model-ETCLINRB.js'),{buildGraphEmit:h,renderGraphDot:g,renderGraphMermaid:k,explainGraphNode:b}=await import('./workspace-graph-2A5THUCI.js'),x=(e||"emit").toLowerCase(),C=new Set(["benchmark","entities","evidence","path","search"]),R=n.refreshGraph===true||i("--refresh-graph"),E=C.has(x)&&!R?await(await import('./workspace-knowledge-graph-snapshot-ZI4W735H.js')).readWorkspaceKnowledgeGraphSnapshot(p):null,$=E?.status==="hit"?E.graph:null,M=E?.status==="hit"?E.model:await v({workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()}),N=m(M);N||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:x,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let A=async()=>{if($)return $;let{buildWorkspaceKnowledgeGraph:L}=await import('./workspace-knowledge-graph-3ZBPSAS7.js'),{hashWorkspaceModel:F}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:K}=await import('./workspace-contract-3BWIRSVQ.js'),te=null;try{te=(await K({workspacePath:p})).contract;}catch{}return L({workspacePath:p,workspace:{name:M.workspace.name,...M.workspace.profile?{profile:M.workspace.profile}:{}},projects:M.projects.map(H=>({id:H.name,path:H.path,...H.absolutePath?{absolutePath:H.absolutePath}:{},runtime:H.runtime,runtimeCandidates:H.runtimeCandidates,framework:H.framework,...H.kit?{kit:H.kit}:{}})),projectTopology:N,contract:te,now:new Date(M.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:F(M)}})};if(x==="dot"||x==="mermaid"){let L=x==="dot"?g(N):k(N),F=d();if(F){let K=j.resolve(p,F);await O__default.outputFile(K,`${L}
|
|
390
|
+
`,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${x}`,{format:x,nodeCount:N.stats.nodeCount,edgeCount:N.stats.edgeCount},K),null,2)):(console.log(s.green(`\u2714 Workspace dependency graph exported as ${x}`)),console.log(s.gray(` Written: ${K}`)));return}console.log(L);return}if(x==="jsonld"||x==="graphml"||x==="gexf"){let L=await A(),{renderWorkspaceKnowledgeGraphGexf:F,renderWorkspaceKnowledgeGraphGraphMl:K,renderWorkspaceKnowledgeGraphJsonLd:te}=await import('./workspace-knowledge-graph-export-UYAYFTWX.js'),H=x==="jsonld"?te(L):x==="graphml"?K(L):F(L),pe=d();if(pe){let ue=j.resolve(p,pe);await O__default.outputFile(ue,`${H}
|
|
391
|
+
`,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${x}`,{format:x,entityCount:L.entities.length,relationCount:L.relations.length,proofCount:L.proofs.length},ue),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${x}`)),console.log(s.gray(` Written: ${ue}`)));return}console.log(H);return}if(x==="explain"){let L=(n.scope?.replace(/^project:/,"")||r||"").trim();L||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let F=b(N,L);if(n.json){console.log(JSON.stringify(F,null,2)),F.found||process.exit(1);return}F.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${L}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${F.project}`)),F.centrality&&console.log(s.gray(` Centrality: fanIn ${F.centrality.fanIn}, fanOut ${F.centrality.fanOut}, reach ${F.centrality.reach}, betweenness ${F.centrality.betweenness}${F.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${F.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${F.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${F.transitiveDependents.length}`));for(let K of F.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${K.id} (d${K.distance}, via ${K.via??"\u2014"})`));return}if(x==="entities"){let L=await A(),{queryKnowledgeEntities:F}=await import('./workspace-knowledge-graph-query-ON45H6Y7.js'),K=F(L,r);if(n.json){console.log(JSON.stringify({schemaVersion:L.schemaVersion,generatedAt:L.generatedAt,kind:r??null,count:K.length,entities:K},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${r?`: ${r}`:""}`)),console.log(s.gray(` Count: ${K.length}`));for(let te of K)console.log(s.gray(` \u2022 ${te.kind}: ${te.label} [${te.id}]`));return}if(x==="search"||x==="benchmark"){let L=(r||"").trim();L||(console.log(s.red(`\u274C workspace graph ${x} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${x} "authentication endpoint" --json`)),process.exit(1));let F=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(F)||F<1||F>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let K=await A();if(x==="benchmark"){let ue=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,{buildWorkspaceGraphTokenEfficiencyReport:ae}=await import('./workspace-graph-token-efficiency-D7CUT6NX.js'),ze=await ae({workspacePath:p,graph:K,query:L,limit:F,...ue?{projectId:ue}:{}});n.json?console.log(JSON.stringify(ze,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${L}`)),console.log(s.gray(` Estimated tokens: ${ze.corpus.estimatedTokens} corpus \u2192 ${ze.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${ze.savings.reductionRatio}\xD7 (${ze.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${ze.retrieval.matchCount}`)),console.log(s.yellow(` ${ze.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:te}=await import('./workspace-knowledge-graph-query-ON45H6Y7.js'),H=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,pe=te(K,{query:L,limit:F,...H?{projectId:H}:{},projection:"agent"});if(n.json)console.log(JSON.stringify(pe,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${L}`)),console.log(s.gray(` ${pe.entities.length}/${pe.totalMatches} match(es)${pe.truncated?" (bounded)":""}`));for(let ue of pe.entities)console.log(s.gray(` \u2022 ${ue.kind}: ${ue.label} [${ue.id}]`));}return}if(x==="evidence"){let L=(r||"").trim();L||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let F=await A(),{queryKnowledgeEvidence:K}=await import('./workspace-knowledge-graph-query-ON45H6Y7.js'),te=K(F,L);if(n.json)console.log(JSON.stringify(te,null,2));else if(te.found){console.log(s.green(`\u2714 Graph evidence: ${L}`));for(let H of te.proofs)console.log(s.gray(` \u2022 ${H.artifact}${H.pointer?`#${H.pointer}`:""} [${H.provider}/${H.trust}/${H.confidence}]`));}else {console.log(s.red(te.candidates.length>0?`\u274C Graph query is ambiguous: ${L}`:`\u274C Graph entity or relation not found: ${L}`));for(let H of te.candidates.slice(0,10))console.log(s.gray(` \u2022 ${H}`));}te.found||process.exit(1);return}if(x==="path"){let L=(r||"").trim(),F=(o||"").trim();(!L||!F)&&(console.log(s.red("\u274C workspace graph path requires <from> and <to>.")),console.log(s.gray(" npx workspai workspace graph path <from> <to> --json")),process.exit(1));let K=await A(),{queryKnowledgePath:te}=await import('./workspace-knowledge-graph-query-ON45H6Y7.js'),H=te(K,L,F);if(n.json)console.log(JSON.stringify(H,null,2));else if(H.found){console.log(s.green(`\u2714 Graph proof path: ${L} \u2192 ${F}`));for(let pe of H.hops)console.log(s.gray(` \u2022 ${pe.from} ${pe.direction==="forward"?"\u2192":"\u2190"} ${pe.to} [${pe.kind}]`));console.log(s.gray(` Proofs: ${H.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${L} and ${F}.`));H.found||process.exit(1);return}if(x==="overlay"){let L=(n.from||r||"").trim();L||(console.log(s.red("\u274C workspace graph overlay requires --from <graph.json>.")),console.log(s.gray(" npx workspai workspace graph overlay --from <graph.json> --json")),process.exit(1));let F=j.resolve(p,L),K;try{K=JSON.parse(await O__default.readFile(F,"utf8"));}catch(ut){console.log(s.red(`\u274C Could not read the base knowledge graph: ${ut instanceof Error?ut.message:String(ut)}`)),process.exit(1);}let te=K&&typeof K=="object"?K:{},H=te.graph,pe=H&&typeof H=="object"?H:{},ue=te.schemaVersion===f$2.knowledgeGraph?te:te.knowledgeGraph??pe.knowledgeGraph;(!ue||typeof ue!="object"||ue.schemaVersion!==f$2.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${f$2.knowledgeGraph} document.`)),process.exit(1));let ae=await A(),{buildWorkspaceKnowledgeGraphChangeOverlay:ze}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),le=ze(ue,ae);if(n.json){console.log(JSON.stringify(le,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${L}`)),console.log(s.gray(` Risk: ${le.summary.risk}`)),console.log(s.gray(` Entities: +${le.summary.entityAdds} -${le.summary.entityRemovals} ~${le.summary.entityChanges}`)),console.log(s.gray(` Relations: +${le.summary.relationAdds} -${le.summary.relationRemovals} ~${le.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${le.summary.proofAdds} -${le.summary.proofRemovals} ~${le.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${le.summary.impactedEntities} entities \xB7 ${le.summary.changedArtifacts} proof artifacts`));return}let X=h(N),U=await A(),q={...X,knowledgeGraph:U},Q=d();if(Q){let L=j.resolve(p,Q);await O__default.outputFile(L,`${JSON.stringify(q,null,2)}
|
|
392
|
+
`,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace graph emit",{format:"json",nodeCount:N.stats.nodeCount,edgeCount:N.stats.edgeCount,entityCount:U.entities.length,relationCount:U.relations.length,proofCount:U.proofs.length},L),null,2)):(console.log(s.green("\u2714 Workspace graph artifact exported as JSON")),console.log(s.gray(` Written: ${L}`)));return}if(n.json){console.log(JSON.stringify(q,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${X.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${X.graph.stats.edgeCount} (inferred ${X.graph.stats.inferredEdges}, contract ${X.graph.stats.contractEdges}, manual ${X.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${X.integrity.ok?"ok":"issues"} (cycles ${X.integrity.stats.cycleCount}, dangling ${X.integrity.stats.danglingCount}, orphans ${X.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${X.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${U.quality.entityCount} entities \xB7 ${U.quality.relationCount} relations \xB7 ${U.quality.proofCount} proofs \xB7 ${U.providers.length} providers`)),console.log(s.gray(" Query: workspace graph search <query> | entities [kind] | path <from> <to> | evidence <entity-or-relation> | overlay --from <graph.json>")),console.log(s.gray(" Render: workspace graph dot | mermaid | jsonld | graphml | gexf [--output <file>]"));}else if(t==="watch"){let p=a("watch"),{runWorkspaceWatch:v}=await import('./workspace-watch-2YFSB2WL.js'),m=n.once===true||i("--once"),h=n.graphStream===true||i("--graph-stream"),g=n.json===true||h,k=h?new(await import('./workspace-graph-stream-XTSDKRLM.js')).WorkspaceGraphStreamPublisher({workspacePath:p}):null,b=new AbortController,x=()=>b.abort();process.once("SIGINT",x),process.once("SIGTERM",x),g||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await v({workspacePath:p,once:m,signal:b.signal,buildOptions:{workspacePath:p,observableScanDepth:l()},onProgress:C=>{g||console.error(s.gray(` ${C}`));},onModel:k?async C=>{let R=(await import('./workspace-model-ETCLINRB.js')).workspaceModelProjectTopology(C);if(!R)return;let{buildWorkspaceKnowledgeGraph:E}=await import('./workspace-knowledge-graph-3ZBPSAS7.js'),{readWorkspaceContract:$}=await import('./workspace-contract-3BWIRSVQ.js'),M=null;try{M=(await $({workspacePath:p})).contract;}catch{}let N=await E({workspacePath:p,workspace:{name:C.workspace.name,...C.workspace.profile?{profile:C.workspace.profile}:{}},projects:C.projects.map(A=>({id:A.name,path:A.path,...A.absolutePath?{absolutePath:A.absolutePath}:{},runtime:A.runtime,runtimeCandidates:A.runtimeCandidates,framework:A.framework,...A.kit?{kit:A.kit}:{}})),projectTopology:R,contract:M,now:new Date(C.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(C)}});console.log(JSON.stringify(k.publish(C,N)));}:void 0,emit:C=>{if(h)return;if(g){console.log(JSON.stringify(C));return}if(C.kind==="ready"){console.log(s.gray(` Ready: ${C.graph.nodeCount} nodes, ${C.graph.edgeCount} edges (hash ${C.modelHash.slice(0,12)})`));return}if(C.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${C.error??"unknown error"}`));return}if(C.kind==="unchanged"){console.log(s.gray(` No structural change (${C.mode}, ${C.durationMs}ms)`));return}let R=[];C.changedProjects.length>0&&R.push(`changed: ${C.changedProjects.join(", ")}`),C.addedProjects.length>0&&R.push(`added: ${C.addedProjects.join(", ")}`),C.removedProjects.length>0&&R.push(`removed: ${C.removedProjects.join(", ")}`),C.graph.edgesAdded.length>0&&R.push(`+${C.graph.edgesAdded.length} edges`),C.graph.edgesRemoved.length>0&&R.push(`-${C.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${C.mode}, ${C.durationMs}ms): ${R.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",x),process.removeListener("SIGTERM",x),!g&&!m&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let p=a("sync"),{syncWorkspaceProjects:v}=await import('./workspace-UUU4VMZB.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${j.basename(p)}`));let m=await v(p,n.json===true);await Jr(p,{silent:n.json===true});let{syncWorkspaceProjectLenses:h}=await import('./project-intelligence-lens-N7REBQ3A.js'),g=await h({workspacePath:p,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:k}=await import('./workspace-registry-summary-VSOBKAJG.js'),b=await k(p);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:p,registry:m,contractSynced:true,projectLenses:{synced:g.projects.length,skipped:g.skipped},registrySummary:b},null,2));}else if(t==="registry"){let p=a("registry"),v=e||"status";v!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${v}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:m,resolveWorkspaceRegisteredProjects:h}=await import('./workspace-registry-summary-VSOBKAJG.js'),g=await m(p);if(n.json){console.log(JSON.stringify(g,null,2));return}let k=await h(p);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${g.authority}`)),console.log(s.gray(` Projects: ${g.projectCount}`)),console.log(s.gray(` Summary: ${g.registrySummaryPath}`)),k.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let p=a("foundation"),v=e||"ensure";v!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${v}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:m}=await import('./workspace-foundation-AISQHJA3.js'),h=await m(p,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(h,null,2));return}h.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${h.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let p=a("policy"),v=await Gm(p,e,r,o,n.json===true||i("--json"));v!==0&&process.exit(v);}else if(t==="contract"){let p=a("contract"),{buildWorkspaceContractGraph:v,readWorkspaceContract:m,verifyWorkspaceContract:h,writeWorkspaceContract:g,WORKSPACE_CONTRACT_PATH:k}=await import('./workspace-contract-3BWIRSVQ.js'),b=e||"inspect",x=d(),C=b==="graph"?void 0:x;try{if(b==="init"){let R=await g({workspacePath:p,outputPath:C,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(R,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${R.contractPath}`)),console.log(s.gray(` Projects: ${R.contract.projects.length}`));return}if(b==="inspect"){let R=await m({workspacePath:p,contractPath:C});if(n.json){console.log(JSON.stringify(R,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${R.contractPath}`)),console.log(s.gray(` Workspace: ${R.contract.workspace.name}`)),console.log(s.gray(` Projects: ${R.contract.projects.length}`)),console.log(s.gray(` Schema: v${R.contract.schemaVersion}`));return}if(b==="verify"){let R=await h({workspacePath:p,contractPath:C,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:E}=await import('./workspace-contract-3BWIRSVQ.js'),$=await E({workspacePath:p,result:R});if(n.json)console.log(JSON.stringify({...R,evidencePath:$},null,2));else {let M=R.status==="passed"?s.green:s.red;console.log(M(`\u2714 Workspace contract verification ${R.status}: ${R.contractPath}`)),console.log(s.gray(` Projects: ${R.projectCount}`));for(let N of R.checks){let A=N.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${A} ${N.id}: ${N.message}`));}for(let N of R.violations)console.log(s.gray(` Violation: ${N}`));}(R.status==="failed"||R.status!=="passed"&&n.strict)&&process.exit(1);return}if(b==="graph"){let R=await v({workspacePath:p,contractPath:C});if(x){let E=j.resolve(p,x);await O__default.outputFile(E,`${JSON.stringify(R,null,2)}
|
|
393
|
+
`,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace contract graph",{projectCount:R.graph.summary.projectCount,relationshipEdges:R.graph.summary.relationshipEdges,entityCount:R.graph.summary.entityCount,knowledgeRelations:R.graph.summary.knowledgeRelations,proofCount:R.graph.summary.proofCount},E),null,2)):(console.log(s.green("\u2714 Workspace contract graph exported as JSON")),console.log(s.gray(` Written: ${E}`)));return}if(n.json){console.log(JSON.stringify(R,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${R.contractPath}`)),console.log(s.gray(` Workspace: ${R.graph.workspace.name}`)),console.log(s.gray(` Projects: ${R.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${R.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${R.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${R.graph.summary.relationshipEdges} (${R.graph.summary.inferredEdges} inferred, ${R.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${R.graph.summary.connectedProjects}/${R.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(R.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(R.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${R.graph.summary.orphanProjects} \xB7 Hotspots: ${R.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${R.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${R.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${R.graph.summary.entityCount} entities \xB7 ${R.graph.summary.knowledgeRelations} relations \xB7 ${R.graph.summary.proofCount} proofs \xB7 ${R.graph.summary.providerCount} providers \xB7 ${R.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${R.graph.summary.portCount}`));for(let E of R.graph.nodes){let $=E.ports.map(N=>`${N.name}:${N.port}`).join(", ")||"none",M=E.operationalProfile?` risk=${E.operationalProfile.weight}/${E.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${E.id} (${E.runtime||"unknown"}${E.framework?`/${E.framework}`:""}) ports=${$} manifests=${E.files.manifests.length}${M}`));}for(let E of R.graph.edges){let $=E.type==="event"?`event:${E.label}`:E.label;console.log(s.gray(` ${E.from} -> ${E.to} [${$}]`));}if(R.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let E of R.graph.dependencyGraph.edges)console.log(s.gray(` ${E.from} -> ${E.to} [${E.kind}/${E.source}/${E.confidence}] evidence=${E.evidence.length}`));}for(let E of R.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${E.severity}: ${E.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${b}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${k}]`)),process.exit(1);}catch(R){n.json&&(console.log(JSON.stringify({command:`workspace contract ${b}`,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${b}.failed`,message:R.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${b} failed: ${R.message}`)),process.exit(1);}}else if(t==="share"){let p=a("share"),v=d()||e,{createWorkspaceShareBundle:m}=await import('./workspace-UUU4VMZB.js'),h=await m(p,{outputPath:v,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:p,bundlePath:h,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${h}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let p=a("export");try{let{exportWorkspaceArchive:v}=await import('./workspace-archive-ZBCKJHXS.js'),m=n.archiveCompression?.trim().toLowerCase()??"store";if(m!=="store"&&m!=="deflate")throw new Error("--archive-compression must be store or deflate.");let h=await v({workspacePath:p,outputPath:d()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:m});if(n.json){console.log(JSON.stringify(h,null,2));return}let g=(h.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.manifest.files.length}`)),console.log(s.gray(` Size: ${g} MB`)),h.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(v){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:v.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${v.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let p=r;p||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:v,inspectWorkspaceArchive:m,verifyWorkspaceArchive:h}=await import('./workspace-archive-ZBCKJHXS.js');try{if(e==="inspect"){let k=await m({archivePathOrUrl:p,safety:u()});if(n.json){console.log(JSON.stringify(k,null,2));return}let b=(k.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${k.archivePath}`)),console.log(s.gray(` Workspace: ${k.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${k.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${k.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${k.fileCount}`)),console.log(s.gray(` Payload: ${b} MB`));return}if(e==="doctor"){let k=await v({archivePathOrUrl:p,strict:n.strict===true||i("--strict"),safety:u()});if(n.json)console.log(JSON.stringify(k,null,2));else {let b=k.status==="passed"?s.green:k.status==="warning"?s.yellow:s.red;console.log(b(`\u2714 Workspace archive doctor ${k.status}: ${k.archivePath}`)),console.log(s.gray(` Workspace: ${k.workspaceName}`)),console.log(s.gray(` Files: ${k.fileCount}`));for(let x of k.checks){let C=x.status==="passed"?"\u2714":x.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${C} ${x.id}: ${x.message}`));}for(let x of k.recommendedActions)console.log(s.gray(` Next: ${x}`));}(k.status==="failed"||k.status==="warning"&&n.strict)&&process.exit(1);return}let g=await h({archivePathOrUrl:p,requireChecksums:n.strict===true||i("--strict"),safety:u()});if(n.json)console.log(JSON.stringify(g,null,2));else if(g.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${g.archivePath}`)),console.log(s.gray(` Files: ${g.verifiedFiles}/${g.fileCount}`));else {let k=g.status==="failed"?s.red:s.yellow;console.log(k(`\u274C Workspace archive verification ${g.status}: ${g.archivePath}`)),g.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${g.missingArchiveEntries.join(", ")}`)),g.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${g.extraArchiveEntries.join(", ")}`)),g.mismatches.length&&console.log(s.gray(` Mismatches: ${g.mismatches.map(b=>b.path).join(", ")}`)),g.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${g.missingChecksumFiles.join(", ")}`));}(g.status==="failed"||g.status==="warning"&&n.strict)&&process.exit(1);}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:p,error:{code:`workspace.archive.${e}.failed`,message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${g.message}`)),process.exit(1);}}else if(t==="connect"){let p=j.resolve(e||process.cwd());try{let v=await Ps({workspacePath:p,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(v.status==="preview"?`\u2714 Workspace connection preview: ${p}`:`\u2714 Workspace connected: ${p}`));for(let m of v.warnings)console.log(s.yellow(` \u26A0 ${m}`));}catch(v){let m=v instanceof Error?v.message:String(v);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:m}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${m}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let p=e;p||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let v=await js({archivePathOrUrl:p,outputPath:d(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:u()});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(v.status==="preview"?`\u2714 Workspace import preview: ${v.workspacePath}`:`\u2714 Workspace imported and registered: ${v.workspacePath}`));for(let m of v.warnings)console.log(s.yellow(` \u26A0 ${m}`));}else {let{hydrateWorkspaceArchive:v}=await import('./workspace-archive-ZBCKJHXS.js'),m=await v({archivePathOrUrl:p,outputPath:d(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:u()});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(v){let m=v instanceof Error?v.message:String(v);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:m,context:{archivePathOrUrl:p,...d()?{outputPath:d()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:p,...d()?{outputPath:d()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:m}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${m}`)),process.exit(1);}}else if(t==="run"){let p=a(`run ${e||""}`.trim()),v=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 .workspai/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)),v.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>")),m==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let h=Os({raw:n.maxWorkers,operation:`workspace run ${m}`,json:n.json===true||i("--json")});if(m==="init"&&n.json!==true){let b=await Fs(p);b!==0&&process.exit(b);}let{runWorkspaceStage:g}=await import('./workspace-run-I6E6VI6N.js'),k=await g({workspacePath:p,stage:m,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:h,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true,planOnly:n.plan===true,runtime:n.runtime});n.json&&console.log(JSON.stringify(k,null,2)),k.summary.exitCode!==0&&process.exit(k.summary.exitCode);}else if(t==="explain"||t==="why"){let p=a(t),{parseWorkspaceExplainTarget:v}=await import('./workspace-explain-contract-ZL4NMLZI.js'),{buildWorkspaceExplain:m,writeWorkspaceExplainReport:h}=await import('./workspace-explain-QH4FXQW5.js'),g=(e??r??"").trim();!g&&n.scope&&(g=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),g||(g="release-blocked");let k=v(g);k||(console.log(s.red(`\u274C Invalid explain target: ${g}`)),process.exit(1));let b=await m({workspacePath:p,target:k}),x=n.write===true||i("--write"),C;if(x&&(C=await h(b,p,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$6(`workspace ${t}`,b,C),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${b.summary}`));for(let R of b.sections)console.log(s.bold(`
|
|
394
|
+
${R.title}`)),console.log(R.body);C&&console.log(s.gray(`
|
|
395
|
+
Written: ${C}`));}else if(t==="trace"){let p=a("trace"),v=n.from||e;v||(console.log(s.red("\u274C workspace trace requires --from <diff-ref>")),console.log(s.gray(" npx workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{resolveWorkspaceTraceTarget:m}=await import('./workspace-explain-contract-ZL4NMLZI.js'),{buildWorkspaceExplain:h,writeWorkspaceExplainReport:g}=await import('./workspace-explain-QH4FXQW5.js'),k=m(v);(!k||k.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${v}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.workspai/reports/workspace-model-diff-last-run.json")),process.exit(1));let b=await h({workspacePath:p,target:k}),x=n.write===true||i("--write"),C;if(x&&(C=await g(b,p,"trace")),n.json){console.log(JSON.stringify(b$6("workspace trace",b,C),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${b.summary}`));for(let R of b.sections)console.log(s.bold(`
|
|
396
|
+
${R.title}`)),console.log(R.body);C&&console.log(s.gray(`
|
|
397
|
+
Written: ${C}`));}else if(t==="eval"){let p=a("eval"),v=(e||"status").toLowerCase(),{WORKSPACE_EVALUATION_LAST_RUN_PATH:m,WORKSPACE_EVALUATION_LIVE_PATH:h,appendWorkspaceEvaluationEvent:g,compareWorkspaceEvaluations:k,createWorkspaceEvaluation:b,finalizeWorkspaceEvaluation:x,readWorkspaceEvaluation:C,writeWorkspaceEvaluation:R}=await import('./workspace-intelligence-evaluation-CQDKOYZZ.js');if(v==="init"){let E=(r||"").trim(),$=(o||"workspace-intelligence").trim(),M=["full-corpus","grep","vector","graph","workspace-intelligence","custom"];(!E||!M.includes($))&&(console.log(s.red("\u274C workspace eval init requires <task> and an optional valid strategy.")),console.log(s.gray(` Strategies: ${M.join(" | ")}
|
|
398
|
+
npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:N}=await import('./workspace-marker-7NHMDIRL.js'),A=await N(p),X=b({workspacePath:p,workspaceName:A?.name,taskId:E,strategy:$}),U=await R(p,X);if(n.json){console.log(JSON.stringify(b$6("workspace eval init",X,U),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${E}`)),console.log(s.gray(` Run: ${X.runId}`)),console.log(s.gray(` Strategy: ${X.configuration.strategy}`)),console.log(s.gray(` Live: ${U}`));return}if(v==="record"){!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace eval record requires --json and a stdin event.")),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace eval record requires piped JSON on stdin.")),process.exit(1));let{parseFeedbackStdinPayload:E,readStdinAll:$}=await import('./workspace-feedback-RQ4TGJW6.js'),M=E(await $());M||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let N=await g({workspacePath:p,payload:M});console.log(JSON.stringify(N,null,2));}catch(N){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:N instanceof Error?N.message:String(N),context:{workspacePath:p}}),null,2)),process.exit(1);}return}if(v==="report"){let E=await x({workspacePath:p}),$=d(),M=E.outputPath;if($){let N=j.resolve(p,$);j.resolve(E.outputPath)!==N&&await O__default.copy(E.outputPath,N,{overwrite:true}),M=N;}if(n.json){console.log(JSON.stringify(b$6("workspace eval report",E.report,M),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${E.report.runId}`)),console.log(s.gray(` Tokens: ${E.report.summary.tokens.observedTotal} \xB7 model calls ${E.report.summary.modelCalls} \xB7 tool calls ${E.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${E.report.summary.outcome.status}${E.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${M}`));return}if(v==="compare"){let E=(n.from||r||"").trim();E||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let $=await C(p,m),M=await C(p,E),N=k($,M);if(n.json){console.log(JSON.stringify(N,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${N.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${N.delta.tokens}`)),console.log(s.gray(` Reduction: ${N.delta.reductionPercent===null?"unavailable":`${N.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${N.comparableOutcome?"yes":"no"}`));return}if(v==="status"){let E;try{E=await C(p,h);}catch{E=await C(p,m);}if(n.json){console.log(JSON.stringify(E,null,2));return}console.log(s.green(`\u2714 Evaluation ${E.status}: ${E.configuration.taskId}`)),console.log(s.gray(` Run: ${E.runId}`)),console.log(s.gray(` Events: ${E.events.length}`)),console.log(s.gray(` Tokens: ${E.summary.tokens.observedTotal} (${E.summary.tokenSources.providerReported} provider-reported calls, ${E.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${v}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let p=a("feedback"),v=(e||"record").toLowerCase();v!=="record"&&(console.log(s.red(`Unknown feedback action: ${v}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!i("--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 workspai 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 workspai workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:m,parseFeedbackStdinPayload:h,readStdinAll:g}=await import('./workspace-feedback-RQ4TGJW6.js'),k=await g(),b=h(k);b||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let x=await m({workspacePath:p,payload:b});n.json?console.log(JSON.stringify(x,null,2)):x.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${x.historyPath}`))):console.log(s.red(`\u274C ${x.error??"Failed to record feedback"}`)),x.ok||process.exit(1);}else if(t==="goal"){let p=a("goal"),v=(e||"status").toLowerCase(),m=r?.trim(),{planVerifiedGoal:h,readVerifiedGoal:g,verifyVerifiedGoal:k,VERIFIED_GOAL_SCHEMA_VERSION:b}=await import('./verified-goal-CIYKNDOU.js'),x=C=>{if(n.json){console.log(JSON.stringify(C,null,2));return}let R=C.goal;console.log(C.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(C.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),R&&console.log(s.bold(` ${R.summary}`)),console.log(s.gray(` Goal: ${C.status.goalId}`)),console.log(s.gray(` Progress: ${C.status.progress.message}`)),console.log(s.gray(` State: ${C.status.state}`)),C.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${C.status.blockingReasons[0]}`)),C.status.nextActions.length>0&&console.log(s.gray(` Next: ${C.status.nextActions[0]}`)),console.log(s.gray(` Status: ${C.status.artifactPath}`));};if(v==="plan"){if(!m||!["release-readiness","dependency-security","test-coverage"].includes(m)){let N="Goal kind must be release-readiness, dependency-security, or test-coverage.";n.json?console.log(JSON.stringify(c$1({operation:"workspace goal plan",code:"workspace.goal.kind.invalid",message:N}),null,2)):console.log(s.red(`\u274C ${N}`)),process.exit(1);}let R=Number(n.target??80);if(!Number.isFinite(R)||R<0||R>100)throw new Error("--target must be a number from 0 to 100.");let E=["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"],$=n.runtime;if(m==="test-coverage"&&$!==void 0&&!E.includes($))throw new Error(`--runtime must be one of: ${E.join(", ")}.`);let M=await h({workspacePath:p,kind:m,scope:n.scope,target:R,runtime:m==="test-coverage"?$:void 0,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});x(M);}else if(v==="status"){if(!m)throw new Error("workspace goal status requires a goal id.");let C=await g(p,m);x({...C,resumed:C.status.state!=="verified"});}else if(v==="verify"){if(!m)throw new Error("workspace goal verify requires a goal id.");let C=await g(p,m),R=await k({workspacePath:p,goalId:m,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});x({goal:C.goal,status:R}),R.state!=="verified"&&process.exit(2);}else {let C=`Unknown workspace goal action: ${v}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:C,context:{schemaVersion:b,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${C}`)),process.exit(1);}}else if(t==="mcp"){let p=a("mcp"),v=(e||"serve").toLowerCase();v!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:v,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${v}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${v}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:m}=await import('./workspace-mcp-serve-ALIZV72K.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await m({workspacePath:p});}else if(t==="init"){n.json||(console.log(s.yellow("\u2139 workspace init is an alias of: npx workspai workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
|
|
399
399
|
npx workspai init | npx workspai workspace init | npx workspai workspace run init
|
|
400
|
-
`)));let
|
|
400
|
+
`)));let p=a("init"),v=Os({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let g=await Fs(p);g!==0&&process.exit(g);}let{runWorkspaceStage:m}=await import('./workspace-run-I6E6VI6N.js'),h=await m({workspacePath:p,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:v,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(h,null,2)),h.summary.exitCode!==0&&process.exit(h.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:Ir}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${Ir.join(", ")}`)),process.exit(1);});function Lr(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function fp(){let t=n=>n.replace(/\bnpx (?:rapidkit|workspai)\b/g,As),e=(n,a)=>{let i=t(n);if(i.length>65){console.log(s.cyan(` ${i}`)),console.log(s.gray(` ${a}`));return}console.log(s.cyan(` ${i.padEnd(67)} `)+s.gray(a));},r=(n,a)=>{console.log(s.white(` ${n}`));for(let i=0;i<a.length;i+=8)console.log(s.gray(` ${a.slice(i,i+8).join(" \xB7 ")}`));};console.log(s.white(`Usage:
|
|
401
401
|
`)),console.log(s.cyan(` ${As} <command> [options]
|
|
402
402
|
`)),Km==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${As}.
|
|
403
403
|
`)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems
|
|
404
404
|
`)),console.log(s.white("Connect projects, contracts, evidence, and checks so developers, CI, IDEs, and AI agents share one current view of the system.")),console.log(s.dim(`One workspace. One truth. Humans and AI aligned.
|
|
405
|
-
`)),Lr("Workspace Lifecycle"),console.log(""),e("npx workspai create workspace my-workspace --profile minimal --yes","Start a new canonical workspace"),e("npx workspai create project","Choose an official frontend or backend kit interactively"),e("npx workspai create project nextjs web --yes","Scaffold an official kit and register the project"),e("npx workspai adopt .","Link the current project without moving its source"),e("npx workspai import <path|git-url>","Copy or clone software into a workspace"),e("npx workspai workspace intelligence run --for-agent generic --strict --json","Build or refresh the complete canonical evidence chain"),e("npx workspai agent bootstrap --for-agent <host> --strict --json","Prove agent entry before broad source discovery"),Lr("Golden Path \xB7 Understand \u2192 Impact \u2192 Act \u2192 Verify"),console.log(""),e('npx workspai goal "<outcome>" --
|
|
405
|
+
`)),Lr("Workspace Lifecycle"),console.log(""),e("npx workspai create workspace my-workspace --profile minimal --yes","Start a new canonical workspace"),e("npx workspai create project","Choose an official frontend or backend kit interactively"),e("npx workspai create project nextjs web --yes","Scaffold an official kit and register the project"),e("npx workspai adopt .","Link the current project without moving its source"),e("npx workspai import <path|git-url>","Copy or clone software into a workspace"),e("npx workspai workspace intelligence run --for-agent generic --strict --json","Build or refresh the complete canonical evidence chain"),e("npx workspai agent bootstrap --for-agent <host> --strict --json","Prove agent entry before broad source discovery"),Lr("Golden Path \xB7 Understand \u2192 Impact \u2192 Act \u2192 Verify"),console.log(""),e('npx workspai goal "<outcome>" --for-agent generic',"Auto-bind a project or choose a bounded multi-project scope"),e('npx workspai goal "<coverage outcome>" --scope projects:a,b --runtime node',"Bind automation explicitly to canonical projects and runtime"),e('npx workspai workspace graph search "<question>" --scope project:<name> --json',"Retrieve focused, proof-backed evidence"),e("npx workspai workspace diff --from git:HEAD~1 --json","Model what changed"),e("npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json","Bound the affected system before action"),e("npx workspai workspace repair --help","Plan, approve, execute, verify, or roll back"),e("npx workspai workspace verify --strict --json","Prove canonical workspace evidence"),Lr("Workspace Intelligence \xB7 What the loop builds"),console.log(s.gray(`
|
|
406
406
|
Code \xB7 APIs \xB7 infrastructure \xB7 docs \xB7 policies \xB7 runtime evidence`)),console.log(s.gray(" \u2193")),console.log(s.gray(" Canonical Workspace Model")),console.log(s.gray(" \u2193")),console.log(s.gray(" Evidence-backed Knowledge Graph")),console.log(s.gray(" \u2193")),console.log(s.gray(` diff \xB7 impact \xB7 Doctor \xB7 context \xB7 repair \xB7 verify \xB7 explain
|
|
407
407
|
`)),e("npx workspai workspace model --write --json","Build the canonical system model"),e("npx workspai workspace graph search <query> --json","Ask a bounded, proven question"),e("npx workspai doctor workspace --json","Diagnose projects and workspace health"),e("npx workspai project coverage --run --target 80 --json","Measure one project"),e("npx workspai workspace explain <target> --write --json","Explain a blocker or project"),e("npx workspai readiness --strict --json","Evaluate release readiness"),e("npx workspai pipeline --strict --json","Run the broader governance and release loop"),Lr("Complete Command Map"),console.log(s.gray(`
|
|
408
408
|
Commands are grouped by execution owner; use any command with --help.
|
|
@@ -412,13 +412,13 @@ Flags clarification:`)),console.log(s.gray(" --skip-install npm fa
|
|
|
412
412
|
`))):console.log(s.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
|
|
413
413
|
`));}var rp="__rapidkit_signal_handlers_registered__",op=globalThis;op[rp]||(op[rp]=true,process.on("SIGINT",async()=>{if(!nn){if(nn=true,console.log(s.yellow(`
|
|
414
414
|
|
|
415
|
-
\u26A0\uFE0F Interrupted by user`)),Et&&await O__default.pathExists(Et)){console.log(s.gray("Cleaning up partial installation..."));try{await O__default.remove(Et),console.log(s.green("\u2713 Cleanup complete"));}catch(t){
|
|
416
|
-
`),
|
|
417
|
-
`):await _s(`${
|
|
418
|
-
`)),Ms(t$1)&&await Ie(0),c&&e
|
|
419
|
-
`),process.exit(1);}):c&&Yl(e
|
|
420
|
-
`),process.exit(1);}):i
|
|
421
|
-
`),process.exit(1);}):
|
|
422
|
-
`),process.exit(1);}):Vm().then(async f=>{if(!f){let
|
|
423
|
-
`),zl(
|
|
424
|
-
`),w){let y=await e(
|
|
415
|
+
\u26A0\uFE0F Interrupted by user`)),Et&&await O__default.pathExists(Et)){console.log(s.gray("Cleaning up partial installation..."));try{await O__default.remove(Et),console.log(s.green("\u2713 Cleanup complete"));}catch(t){e.debug("Cleanup failed:",t);}}b$7(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!nn){if(nn=true,e.debug("Received SIGTERM"),Et&&await O__default.pathExists(Et))try{await O__default.remove(Et);}catch(t){e.debug("Cleanup failed:",t);}b$7(143,"Terminated"),process.exit(143);}}));var zm=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Ym=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),r=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return _.realpathSync(t)===_.realpathSync(fileURLToPath(import.meta.url))||r}catch{return j.resolve(t)===j.resolve(fileURLToPath(import.meta.url))||r}})(),Xm=!zm||Ym;function Qm(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}function Zm(){for(let t of [process.stdout,process.stderr]){if(t.isTTY)continue;let e=t;if(e.__rapidkitSyncWriteInstalled)continue;let r=t.fd;if(typeof r!="number")continue;let o=t.write.bind(t);e.write=((n,a,i)=>{let c=typeof a=="string"?a:"utf8",d=typeof a=="function"?a:typeof i=="function"?i:void 0;try{let l=typeof n=="string"?Buffer.from(n,c):n instanceof Uint8Array?Buffer.from(n):Buffer.from(String(n),c);return _.writeSync(r,l),d?.(),true}catch{return o(n,c,d)}}),e.__rapidkitSyncWriteInstalled=true;}}async function Ie(t){b$7(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(r=>{e.write("",()=>r());}))),process.exit(t);}async function _s(t,e=0){return _.writeSync(process.stdout.fd??1,t),Ie(e)}async function eg(){Qm(),Zm(),d$6(),a$6({argv:process.argv,cwd:process.cwd(),rapidkitVersion:h()}),c$6(process.argv);let t$1=process.argv.slice(2),e=t$1[0],r=process.cwd(),o=qe(r),n$1=t(r,"project.json").some(f=>_.existsSync(f)),a$1=Pm(),i=zl(t$1),c=a$1&&Fr(t$1),d=e==="init"&&o&&!n$1,l$1=t$1.length===0||t$1.length===1&&(e==="--help"||e==="-h"||e==="help");al(t$1)&&await _s(`${cl(t$1[1])}
|
|
416
|
+
`),l$1&&(a("npm cli"),fp(),await Ie(0)),t$1.some(f=>f==="--version"||f==="-V"||f==="-v")&&!t$1.some(f=>f==="--help"||f==="-h"||f==="help")&&(t$1.includes("--json")?await _s(`${JSON.stringify(jm(),null,2)}
|
|
417
|
+
`):await _s(`${h()}
|
|
418
|
+
`)),Ms(t$1)&&await Ie(0),c&&e===Uo?(async()=>{await Ie(await Ns(t$1));})().catch(f=>{process.stderr.write(`Workspai CLI failed to run create: ${f?.message??f}
|
|
419
|
+
`),process.exit(1);}):c&&Yl(e)?(async()=>{await Ie(await Xl(e,t$1));})().catch(f=>{process.stderr.write(`Workspai CLI failed to run ${e}: ${f?.message??f}
|
|
420
|
+
`),process.exit(1);}):i||c?fe.parseAsync().then(()=>Ie(0)).catch(f=>{let u=lr()&&f instanceof Error&&f.stack?f.stack:f?.message??f;process.stderr.write(`Workspai CLI failed: ${u}
|
|
421
|
+
`),process.exit(1);}):d?Js(t$1).then(f=>Ie(f)).catch(f=>{process.stderr.write(`Workspai CLI failed to run workspace init: ${f?.message??f}
|
|
422
|
+
`),process.exit(1);}):Vm().then(async f=>{if(!f){let u=process.argv.slice(2);if(lr()&&process.stderr.write(`[workspai-cli] argv=${JSON.stringify(u)}
|
|
423
|
+
`),zl(u)){await fe.parseAsync();return}if(Ms(u)&&await Ie(0),u[0]===Uo){let y=await Ns(u);await Ie(y);}if(u[0]==="init"){let y=await Js(u);await Ie(y);}if(Yl(u[0])){let y=await Xl(u[0],u);await Ie(y);}if(s$2(u[0])){if(Ws(u))return;let y=u[0],P=i$2(process.cwd()),S=await Lt(process.cwd()),p=be(process.cwd()),v=false;if(p){let k=s$1(p,"policies.yml").find(b=>_.existsSync(b));if(k&&await O__default.pathExists(k))try{let b=await _.promises.readFile(k,"utf-8");if(v=((b.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??b.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict",v){let R=s$1(p,"toolchain.lock").find(M=>_.existsSync(M)),E=[];if(!R||!await O__default.pathExists(R))E.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain).");else try{let N=JSON.parse(await _.promises.readFile(R,"utf-8")).runtime??{};j$3(P,process.cwd())&&!N.go?.version&&E.push("Go runtime version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."),k$1(P,process.cwd())&&!N.node?.version&&E.push("Node runtime version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."),l(P,process.cwd())&&!N.java?.version&&E.push("Java runtime version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."),m$1(P,process.cwd())&&!N.dotnet?.version&&E.push(".NET runtime version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."),n(P,process.cwd())&&!N.python?.version&&E.push("Python runtime version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");}catch{E.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode.");}let $=s$1(p,"workspace.json").find(M=>_.existsSync(M));if($&&await O__default.pathExists($))try{let N=JSON.parse(await _.promises.readFile($,"utf-8")).profile??"",A=j$4(process.cwd(),P),X=St({profile:N,runtime:A.runtime,subjectLabel:j.basename(process.cwd()),mode:"strict"});X.ok||E.push(`${X.message} Update the workspace profile or use a polyglot workspace.`);}catch{}if(E.length>0){console.log(s.red(`\u274C Strict policy violations block \`${y}\`:`));for(let M of E)console.log(s.red(` \u2022 ${M}`));console.log(s.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .workspai/policies.yml")),await Ie(1);}}}catch{}}let m=await a$7({startPath:process.cwd(),action:y,writeReport:true}),h=v||process.env.RAPIDKIT_LIFECYCLE_ENFORCE_READINESS==="1"||process.env.RAPIDKIT_ENFORCE_READINESS==="1";if(m.blocking&&h){console.log(s.red(`\u274C Release readiness blocks \`${y}\`:`));for(let k of m.blockingReasons)console.log(s.red(` \u2022 ${k}`));m.evidencePath&&console.log(s.gray(`\u2139\uFE0F Readiness evidence: ${m.evidencePath}`)),await Ie(1);}m.overallStatus!=="pass"&&!h&&(console.log(s.yellow(`\u26A0\uFE0F Release readiness is ${m.overallStatus}. Command continues in warn mode.`)),m.evidencePath&&console.log(s.gray(` Evidence: ${m.evidencePath} (set RAPIDKIT_LIFECYCLE_ENFORCE_READINESS=1 to block)`)));let g=await up(process.cwd(),async()=>{if(j$3(P,process.cwd())||S==="go"){let k=Ke("go",{runCommandInCwd:Ce,runCoreRapidkit:e$1});if(y==="lint")return oe(await k.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(y==="format")return oe(await k.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let b=y==="dev"?await k.runDev(process.cwd()):y==="test"?await k.runTest(process.cwd()):y==="build"?await k.runBuild(process.cwd()):await k.runStart(process.cwd());return b.message&&console.log(s.red(`\u274C ${b.message}`)),b.exitCode}if(l(P,process.cwd())||S==="java")return y==="dev"?await ft("dev",process.cwd()):y==="test"?await ft("test",process.cwd()):y==="build"?await ft("build",process.cwd()):y==="lint"?await ft("lint",process.cwd()):y==="format"?await ft("format",process.cwd()):await ft("start",process.cwd());if(m$1(P,process.cwd())||S==="dotnet"){let k=Ke("dotnet",{runCommandInCwd:Ce,runCoreRapidkit:e$1});if(y==="lint")return oe(await k.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(y==="format")return oe(await k.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let b=y==="dev"?await k.runDev(process.cwd()):y==="test"?await k.runTest(process.cwd()):y==="build"?await k.runBuild(process.cwd()):await k.runStart(process.cwd());return b.message&&console.log(s.red(`\u274C ${b.message}`)),b.exitCode}if(k$1(P,process.cwd())||S==="node")return y==="dev"?await Dt("dev",process.cwd()):y==="test"?await Dt("test",process.cwd()):y==="build"?await Dt("build",process.cwd()):y==="lint"?await Dt("lint",process.cwd()):y==="format"?await Dt("format",process.cwd()):await Dt("start",process.cwd());if(n(P,process.cwd())||S==="python"){if(y==="lint"||y==="format")return await e$1([y],{cwd:process.cwd()});let k=Ke("python",{runCommandInCwd:Ce,runCoreRapidkit:e$1});return oe(y==="dev"?await k.runDev(process.cwd()):y==="test"?await k.runTest(process.cwd()):y==="build"?await k.runBuild(process.cwd()):await k.runStart(process.cwd()))}if(S==="rust"||S==="php"){let k=Ke(S,{runCommandInCwd:Ce,runCoreRapidkit:e$1});if(y==="lint")return oe(await k.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(y==="format")return oe(await k.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let b=y==="dev"?await k.runDev(process.cwd()):y==="test"?await k.runTest(process.cwd()):y==="build"?await k.runBuild(process.cwd()):await k.runStart(process.cwd());return oe(b)}return -1});if(!g.ok){await Ie(g.code);return}if(g.ok&&g.value>=0){await Ie(g.value);return}if(g.ok&&g.value===-1){console.error(s.red(`\u274C Workspai cannot run \`${y}\` for this project runtime.`)),console.error(s.gray("Run `workspai project commands` to inspect supported commands.")),await Ie(1);return}}if(Ws(u))return;let w=await Hm(u);if(lr()&&process.stderr.write(`[workspai-cli] shouldForwardToCore=${w}
|
|
424
|
+
`),w){let y=await e$1(u,{cwd:process.cwd()});await Ie(y);}await fe.parseAsync();}});}Xm&&await eg();export{ms as COMMAND_CAPABILITIES_SCHEMA_VERSION,em as NPM_ONLY_SCOPED_COMMANDS,tm as NPM_ONLY_TOP_LEVEL_COMMANDS,fl as VERSION_CONTRACT_SCHEMA_VERSION,ym as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,eg as bootstrapCli,Cs as bridgeFailureCode,Jl as buildDelegationEnvForInit,tp as checkStrictPolicyPreflightForDelegation,am as commandAvailable,np as createProjectVenv,im as createWorkspaceVenv,Rm as defaultWorkspacePolicyYaml,Cm as detectWindowsDoctorWorkspaceShadow,cm as ensurePythonProjectUsesLocalVenv,ip as findContextFileUp,Sm as findLegacyWorkspaceUp,Ds as findWorkspaceMarkerUp,be as findWorkspaceUp,ap as getGlobalCommandCapabilities,zo as getPublishedContractCatalog,$r as getPublishedContractVersions,jm as getVersionContract,mp as handleAdoptCommand,Wm as handleBootstrapCommand,Fm as handleCacheCommand,Ns as handleCreateOrFallback,Es as handleGoInit,Ls as handleImportCommand,Js as handleInitCommand,ft as handleJavaCommand,Jm as handleMirrorCommand,Dt as handleNodeCommand,Dm as handleSetupCommand,qe as hasWorkspaceRootMarkers,Hs as hostPythonCandidates,Lt as inferRuntimeByFiles,lm as installPythonDependenciesWithPipFallback,Fs as installWorkspaceDependencies,Pm as isNpmExecInvocation,Fr as isNpmOnlyInvocation,Yl as isNpmOnlyManualHandlerCommand,vm as isNpmOnlyParseDirectCommand,zl as isNpmOnlyParseDirectInvocation,Ts as isNpmOnlyScopedCommand,km as isNpmOnlyTopLevelCommand,om as normalizeFallbackTemplate,Lm as parseCacheConfig,nm as parseMaxWorkersOption,Om as parseNodeEvalScript,_m as parsePolicyBooleanLiteral,fp as printHelp,fe as program,Oe as readFlagValue,Em as replaceOrInsertRulePolicyLine,Zl as replaceOrInsertTopLevelPolicyLine,rm as resolveInvokedCliName,Ce as runCommandInCwd,on as runCreateFallback,Hm as shouldForwardToCore,pm as validateNpmKitFlags};
|