workspai 0.43.1 → 0.45.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 +28 -11
- package/contracts/agent-customization-pack.v1.json +1 -1
- package/contracts/autopilot-release.v1.json +204 -0
- package/contracts/cli-operation-result.v1.json +119 -0
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +1368 -0
- package/contracts/command-capabilities.v1.json +303 -0
- package/contracts/compatibility-matrix.v1.json +37 -0
- package/contracts/create-planner-capabilities.v1.json +156 -65
- package/contracts/doctor-project-scan.v2.json +60 -0
- package/contracts/doctor-remediation-plan.v1.json +19 -4
- package/contracts/doctor-remediation-plan.v2.json +7 -0
- package/contracts/doctor-workspace-cache.v2.json +82 -0
- package/contracts/extension-cli-compatibility.v1.json +48 -3
- package/contracts/infra-plan.v1.json +189 -0
- package/contracts/private-product-manifest.v1.json +155 -0
- package/contracts/product-factory-plan.v1.json +200 -0
- package/contracts/project-archive.v1.json +40 -0
- package/contracts/project-entry-capability.v1.json +127 -0
- package/contracts/published-contract-catalog.v1.json +339 -0
- package/contracts/runtime-command-surface.v1.json +1680 -11
- package/contracts/version.v1.json +48 -0
- package/contracts/workspace-archive-capabilities.v1.json +90 -0
- package/contracts/workspace-archive-manifest.v1.json +107 -0
- package/contracts/workspace-archive-operation-result.v1.json +565 -0
- package/contracts/workspace-intelligence/agent-customization-pack-report.v1.json +98 -0
- package/contracts/workspace-intelligence/agent-hooks.v1.json +38 -0
- package/contracts/workspace-intelligence/agent-reports-index.v1.json +56 -0
- package/contracts/workspace-intelligence/mcp-design.v1.json +42 -0
- package/contracts/workspace-intelligence/workspace-context.v1.json +12 -0
- package/contracts/workspace-intelligence/workspace-explain.v1.json +1 -0
- package/contracts/workspace-intelligence-architecture.v1.json +723 -0
- package/contracts/workspace-intelligence-chain.v1.json +1194 -0
- package/contracts/workspace-list.v1.json +56 -0
- package/contracts/workspace-model-cache.v1.json +55 -0
- package/contracts/workspace-snapshot.v1.json +58 -0
- package/contracts/workspace-snapshot.v2.json +97 -0
- package/contracts/workspace-sync.v1.json +30 -0
- package/contracts/workspace-watch-event.v1.json +112 -0
- package/dist/analyze-YLV7NVLF.js +1 -0
- package/dist/{artifact-remediation-plan-244S5K6I.js → artifact-remediation-plan-WLZGROUU.js} +2 -2
- package/dist/autopilot-release-YBN3SWAA.js +1 -0
- package/dist/{chunk-LZQNVH7D.js → chunk-2K3GYCPS.js} +1 -1
- package/dist/chunk-2QOWRBQD.js +1 -0
- package/dist/chunk-42G2OK64.js +1 -0
- package/dist/chunk-5AKYMAIL.js +1 -0
- package/dist/chunk-5GNT4RJI.js +8 -0
- package/dist/{chunk-FDDDQMJ2.js → chunk-5PVEQ6CZ.js} +1 -1
- package/dist/chunk-6AA3WWQZ.js +2 -0
- package/dist/chunk-6ZENXBMG.js +33 -0
- package/dist/chunk-7RIWU5TZ.js +1 -0
- package/dist/chunk-BJLE5CH7.js +4 -0
- package/dist/{chunk-PPHTYJ7G.js → chunk-DXPU4DDV.js} +36 -37
- package/dist/{chunk-DOCPUNWS.js → chunk-G3H5R3RR.js} +1 -1
- package/dist/chunk-HYJK7W3B.js +1 -0
- package/dist/chunk-IMUU5Q2V.js +13 -0
- package/dist/chunk-J4AICQFB.js +1 -0
- package/dist/{chunk-EMTQ6OKI.js → chunk-JP25YL3J.js} +1 -1
- package/dist/{chunk-ONU457VN.js → chunk-K63BSU56.js} +52 -50
- package/dist/chunk-KPPGZCUW.js +78 -0
- package/dist/chunk-KU4S7RCM.js +1 -0
- package/dist/chunk-LCRROMRR.js +2 -0
- package/dist/chunk-LG6RFLPZ.js +1 -0
- package/dist/{chunk-JHC6SCJC.js → chunk-NHN4QXPP.js} +1 -1
- package/dist/{chunk-U6AXYUQY.js → chunk-OOOPYUL2.js} +1 -1
- package/dist/chunk-P7SCWJFG.js +8 -0
- package/dist/chunk-QWU2CZBG.js +2 -0
- package/dist/chunk-V2H2KRMZ.js +1 -0
- package/dist/chunk-WANW4QA4.js +4 -0
- package/dist/chunk-XIVFLY6G.js +1 -0
- package/dist/chunk-ZWO6K24C.js +2 -0
- package/dist/{create-42RTNLH2.js → create-KFR6FLRT.js} +1 -1
- package/dist/doctor-YJDM5XBH.js +1 -0
- package/dist/index.d.ts +284 -25
- package/dist/index.js +214 -204
- package/dist/pipeline-FEDYO3IA.js +5 -0
- package/dist/{platform-capabilities-XAVU4HSM.js → platform-capabilities-YICBF4FA.js} +1 -1
- package/dist/{pythonRapidkitExec-GCQ3M46E.js → pythonRapidkitExec-UJYIB6FL.js} +1 -1
- package/dist/{workspace-DZHWB7BV.js → workspace-PLXOO6ST.js} +1 -1
- package/dist/workspace-agent-sync-G5YVI3BJ.js +1 -0
- package/dist/workspace-archive-EEGLHZDW.js +10 -0
- package/dist/workspace-context-E3UFWL5X.js +1 -0
- package/dist/{workspace-contract-2TA27LGT.js → workspace-contract-LQJDZV36.js} +1 -1
- package/dist/workspace-explain-G74ZIF23.js +1 -0
- package/dist/workspace-explain-contract-KT757JGQ.js +1 -0
- package/dist/{workspace-feedback-R6H4UFZB.js → workspace-feedback-YY6WQPWQ.js} +1 -1
- package/dist/{workspace-foundation-FQWHPQGX.js → workspace-foundation-3C2DLCVI.js} +1 -1
- package/dist/{workspace-history-CGCK2DJI.js → workspace-history-VF3CHDYQ.js} +1 -1
- package/dist/workspace-intelligence-3GG7GEDQ.js +1 -0
- package/dist/workspace-mcp-serve-MJMUV4RY.js +3 -0
- package/dist/{workspace-model-F3B75TYT.js → workspace-model-NG45SRM5.js} +1 -1
- package/dist/workspace-registry-summary-JM2XY52C.js +1 -0
- package/dist/workspace-run-WEQYIERE.js +1 -0
- package/dist/{workspace-verify-OAATQV5T.js → workspace-verify-ZNT6JX7D.js} +1 -1
- package/dist/workspace-watch-W47T4RX2.js +1 -0
- package/docs/AI_FEATURES.md +67 -34
- package/docs/README.md +2 -1
- package/docs/commands-reference.md +39 -14
- package/docs/contracts/ARTIFACT_CATALOG.md +60 -36
- package/docs/contracts/COMMAND_OWNERSHIP_MATRIX.md +27 -6
- package/docs/contracts/README.md +3 -2
- package/docs/create-planner-capabilities.md +36 -18
- package/docs/workspace-operations.md +25 -0
- package/package.json +27 -14
- package/scripts/enterprise-package-smoke.mjs +40 -8
- package/scripts/prepack-enterprise.mjs +12 -0
- package/dist/analyze-5BU4QIPK.js +0 -1
- package/dist/autopilot-release-45YVOBQO.js +0 -1
- package/dist/chunk-3QVTWKUI.js +0 -4
- package/dist/chunk-753LOKFZ.js +0 -2
- package/dist/chunk-AMDKXXLP.js +0 -1
- package/dist/chunk-AQ4XZZC6.js +0 -1
- package/dist/chunk-CDE4Q77U.js +0 -2
- package/dist/chunk-DNAY5ALC.js +0 -1
- package/dist/chunk-FHSMY75W.js +0 -1
- package/dist/chunk-FM7GMFZA.js +0 -2
- package/dist/chunk-HV5ZFXAZ.js +0 -13
- package/dist/chunk-LRW2SAGL.js +0 -4
- package/dist/chunk-LTWYYP6E.js +0 -7
- package/dist/chunk-NAAQMSO3.js +0 -1
- package/dist/chunk-NFUXULIF.js +0 -1
- package/dist/chunk-OL64GWQC.js +0 -9
- package/dist/chunk-SI3AQKIP.js +0 -1
- package/dist/chunk-TH5Y3EMA.js +0 -33
- package/dist/chunk-UQKCCWUL.js +0 -78
- package/dist/chunk-XNGANEXM.js +0 -2
- package/dist/doctor-DK4BON3N.js +0 -1
- package/dist/pipeline-HQ57V6OZ.js +0 -5
- package/dist/workspace-agent-sync-5ADIQS7B.js +0 -1
- package/dist/workspace-archive-GCZNI44O.js +0 -3
- package/dist/workspace-context-GEXDHA7A.js +0 -1
- package/dist/workspace-explain-D5NNL3NG.js +0 -1
- package/dist/workspace-explain-contract-DNS2YEL7.js +0 -1
- package/dist/workspace-intelligence-BEM6WGCZ.js +0 -1
- package/dist/workspace-mcp-serve-OMBA5V3C.js +0 -3
- package/dist/workspace-registry-summary-6MFBRWDS.js +0 -1
- package/dist/workspace-run-3WJXIQKR.js +0 -1
- package/dist/workspace-watch-HU2OTQ52.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,90 +1,90 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$
|
|
2
|
+
import {f as f$3,c as c$3,b as b$c,a as a$m}from'./chunk-7RIWU5TZ.js';import {a as a$f}from'./chunk-ICGWHIMK.js';import {c as c$2,e as e$1,b as b$5,d as d$6,a as a$n}from'./chunk-BJLE5CH7.js';import {a as a$d}from'./chunk-3ZK2GU7C.js';import {b as b$6,d as d$4,a as a$2,c as c$4,f as f$a,e as e$6}from'./chunk-T3GJ7YVG.js';import {a as a$5}from'./chunk-22DT744Z.js';import {a as a$e}from'./chunk-2E6WGUN6.js';import {b as b$b,a as a$h,l as l$3}from'./chunk-6ZENXBMG.js';import {c as c$9,a as a$l}from'./chunk-LCRROMRR.js';import {c as c$a,a as a$j}from'./chunk-42G2OK64.js';import {f as f$8}from'./chunk-ZWO6K24C.js';import {a as a$i}from'./chunk-V2H2KRMZ.js';import {b as b$1,c as c$1,d,i,g,h as h$1,f as f$2,a as a$6}from'./chunk-G3H5R3RR.js';import {a,b as b$3}from'./chunk-NHN4QXPP.js';import {a as a$8}from'./chunk-A5FBGRJA.js';import {a as a$g}from'./chunk-J4AICQFB.js';import {f as f$5,g as g$2,h as h$3,i as i$5,j as j$1,c as c$b,a as a$k}from'./chunk-HYJK7W3B.js';import {m,d as d$5,e as e$2,f as f$4,g as g$1,h as h$2,i as i$2,q,j,s as s$1,k,c as c$6,l as l$1,r as r$1,t,n as n$2,p as p$1,a as a$p,o as o$3}from'./chunk-7UZVOYF5.js';export{l as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-7UZVOYF5.js';import {i as i$3}from'./chunk-4KUIFXHM.js';import {f as f$9}from'./chunk-QWU2CZBG.js';import {f as f$6}from'./chunk-6AA3WWQZ.js';import {a as a$4}from'./chunk-LG6RFLPZ.js';import {h,a as a$1,m as m$1,l as l$2,n as n$1,k as k$2,o as o$2,i as i$6}from'./chunk-5PVEQ6CZ.js';import {b as b$4,d as d$1,a as a$3,e as e$3}from'./chunk-P424XYHP.js';import {b as b$8,d as d$8}from'./chunk-GSWPGELT.js';import {a as a$a}from'./chunk-GZTYAEWX.js';import {d as d$2,e as e$4,a as a$c,c as c$8,b as b$a}from'./chunk-5AKYMAIL.js';import {c,b as b$2,a as a$b}from'./chunk-Y45WZR5N.js';import {f,d as d$3,b as b$7}from'./chunk-7YHK5NM3.js';import {a as a$9}from'./chunk-TQEMLBAG.js';import {c as c$c}from'./chunk-RO73VVHW.js';import {f as f$1,e,d as d$7,i as i$4,a as a$7,g as g$4}from'./chunk-JP25YL3J.js';import {b,n,o as o$1,c as c$7,h as h$4,p as p$2,l as l$4,i as i$7,e as e$7,g as g$5}from'./chunk-2K3GYCPS.js';import {c as c$d}from'./chunk-2FIX2MDC.js';import {c as c$5,b as b$9,a as a$o}from'./chunk-XZGVNGRB.js';import {i as i$1,p,o,r,l,q as q$1,k as k$1,f as f$7,g as g$3,e as e$5,j as j$2}from'./chunk-5XATWNME.js';import {Command,Option}from'commander';import s from'chalk';import C from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Jp from'vm';import*as R from'fs-extra';import R__default from'fs-extra';import S,{existsSync,promises,createWriteStream}from'fs';import Yr,{tmpdir}from'os';import {execa}from'execa';import ut,{createVerify,createHash,createHmac}from'crypto';import Ni from'http';import Mi from'https';function bc(){return i$7()}function jc(t,e){return t==="py"?["-3",...e]:e}function Cc(t){return typeof t=="object"&&t!==null}async function Sc(t,e,o,r=c$d()){try{let n=await execa(t,e,{cwd:o,timeout:r,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function xc(t,e){let o=["-m","rapidkit",...t],r=bc();for(let n of r){let a=await Sc(n,jc(n,o),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return Cc(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 sa(t,e){let o=await xc(["project","detect","--path",t,"--json"],e);return !o.ok||!o.data||o.data.schema_version!==1?{ok:false,command:o.command,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr}:o}var aa=new Set(["create"]),Gr=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),Ec=new Set(["pip","poetry","venv","pipx","python"]);function ia(t){return typeof t=="string"&&Ec.has(t)}function Br(t,e){return !t||aa.has(t)?false:a$7.has(t)?true:e?.has(t)??false}function Hr(t,e=null){let o=t[0];return !o||o.startsWith("-")||aa.has(o)||o==="init"?false:Br(o,e)?true:t.filter(n=>!n.startsWith("-")&&!Gr.has(n)).length<=1?false:t.length>1}var Ot=C.join(Yr.homedir(),".workspairc.json"),Rc=C.join(Yr.homedir(),".rapidkitrc.json"),_c=C.join(Yr.homedir(),".rapidkit","config.json");function qr(t){try{if(!S.existsSync(t))return {};let e=S.readFileSync(t,"utf-8"),o=JSON.parse(e);return !o||typeof o!="object"||Array.isArray(o)?{}:o}catch{return {}}}function ca(t){if(process.platform!=="win32")try{S.chmodSync(t,384);}catch{}}function Nt(){let t=qr(Ot),e=qr(Rc),o=qr(_c);return S.existsSync(Ot)&&ca(Ot),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??o.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??o.aiEnabled,telemetry:t.telemetry??e.telemetry??o.telemetry}}function Bo(t){let o={...Nt(),...t};S.writeFileSync(Ot,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),ca(Ot);}function io(){return process.env.OPENAI_API_KEY||Nt().openaiApiKey||null}function Qr(){return Nt().aiEnabled!==false}function Xr(){return Ot}function la(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 o=>{let r=o.key;r?r.startsWith("sk-")||(console.log(s.red(`
|
|
3
3
|
\u274C Invalid API key format (should start with sk-)
|
|
4
|
-
`)),process.exit(1)):r=(await b$
|
|
4
|
+
`)),process.exit(1)):r=(await b$3([{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,Bo({openaiApiKey:r}),console.log(s.green(`
|
|
5
5
|
\u2705 OpenAI API key saved successfully!
|
|
6
|
-
`)),console.log(s.gray(`Stored in: ${
|
|
6
|
+
`)),console.log(s.gray(`Stored in: ${Xr()}`)),console.log(s.cyan(`
|
|
7
7
|
\u{1F389} You can now use AI features:`)),console.log(s.white(' workspai ai recommend "I need user authentication"')),console.log(s.gray(`
|
|
8
8
|
\u{1F4A1} To generate module embeddings (one-time):`)),console.log(s.white(" cd packages/cli")),console.log(s.white(` npx tsx src/ai/generate-embeddings.ts
|
|
9
|
-
`));}),e.command("show").description("Show current configuration").action(()=>{let o=
|
|
9
|
+
`));}),e.command("show").description("Show current configuration").action(()=>{let o=Nt();if(console.log(s.bold(`
|
|
10
10
|
\u2699\uFE0F Workspai Configuration
|
|
11
11
|
`)),o.openaiApiKey){let r=o.openaiApiKey.substring(0,8)+"..."+o.openaiApiKey.slice(-4);console.log(s.cyan("OpenAI API Key:"),s.white(r));}else console.log(s.cyan("OpenAI API Key:"),s.red("Not set")),console.log(s.gray(" Set with: workspai config set-api-key"));console.log(s.cyan("AI Features:"),o.aiEnabled!==false?s.green("Enabled"):s.red("Disabled")),console.log(s.gray(`
|
|
12
|
-
\u{1F4C1} Config file: ${
|
|
13
|
-
`));}),e.command("remove-api-key").description("Remove stored OpenAI API key").action(async
|
|
12
|
+
\u{1F4C1} Config file: ${Xr()}
|
|
13
|
+
`));}),e.command("remove-api-key").description("Remove stored OpenAI API key").option("--yes","Remove without an interactive confirmation prompt").action(async o=>{if(!Nt().openaiApiKey){console.log(s.yellow(`
|
|
14
14
|
\u26A0\uFE0F No API key is currently stored
|
|
15
|
-
`));return}(await b$
|
|
15
|
+
`));return}let n=o.yes===true||process.argv.includes("--yes");!n&&(!process.stdin.isTTY||!process.stdout.isTTY)&&(console.error(s.red("Cannot confirm API key removal in a non-interactive session. Use --yes.")),process.exit(1)),(n?{confirm:true}:await b$3([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(Bo({openaiApiKey:void 0}),console.log(s.green(`
|
|
16
16
|
\u2705 API key removed successfully
|
|
17
17
|
`))):console.log(s.gray(`
|
|
18
18
|
Cancelled
|
|
19
19
|
`));}),e.command("ai <action>").description("Enable or disable AI features (enable|disable)").action(o=>{o!=="enable"&&o!=="disable"&&(console.log(s.red(`
|
|
20
20
|
\u274C Invalid action: ${o}`)),console.log(s.gray(`Use: workspai config ai enable|disable
|
|
21
|
-
`)),process.exit(1));let r=o==="enable";
|
|
21
|
+
`)),process.exit(1));let r=o==="enable";Bo({aiEnabled:r}),console.log(s.green(`
|
|
22
22
|
\u2705 AI features ${r?"enabled":"disabled"}
|
|
23
|
-
`));});}var Qt=null,Mo=false,Ir=null;async function Za(){return Ir||(Ir=(await import('openai')).default),Ir}function Fs(){Mo=true;}function Ls(t){let o=new Array(1536),r=0;for(let i=0;i<t.length;i++)r=(r<<5)-r+t.charCodeAt(i),r=r&r;for(let i=0;i<1536;i++)r=r*1664525+1013904223&4294967295,o[i]=r/4294967295*2-1;let n=Math.sqrt(o.reduce((i,a)=>i+a*a,0));return o.map(i=>i/n)}async function No(t){if(!t.trim()){Qt=null;return}let e=await Za();Qt=new e({apiKey:t});}function Js(){if(!Qt)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return Qt}async function $r(t){return Mo?Ls(t):(await Js().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function Ks(t){return Mo?t.map(Ls):(await Js().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(r=>r.embedding)}function Gs(){return Qt!==null}function Rt(){return Mo}function Or(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function ec(t){return !t||typeof t!="object"?{}:t}var Nr=[{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"]}],rt=null,Mr=0,tc=300*1e3;function oc(t){let e=ec(t),o=e.slug||e.name||e.id||e.module_id||"",r=Or(e.keywords??e.tags);return {id:o,name:e.display_name||e.name||"",category:rc(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:r.map(n=>n.toLowerCase()),framework:nc(e.framework),dependencies:Or(e.dependencies),useCases:Or(e.use_cases??e.useCases)}}function rc(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function nc(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 sc(){try{let t=await g$4(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.match(/\{[\s\S]*\}/),o=e?e[0]:t.stdout,r=JSON.parse(o),n=[];return Array.isArray(r)?n=r:r.modules&&Array.isArray(r.modules)?n=r.modules:r.data&&Array.isArray(r.data)&&(n=r.data),n.map(oc).filter(i=>i.id&&i.name)}catch(t){return console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",t.message),console.warn(" Using fallback module catalog (11 modules)"),Nr}}async function Wo(){let t=Date.now();return Rt()?(rt=Nr,Mr=t,rt):(rt&&t-Mr<tc||(rt=await sc(),Mr=t,rt.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),rt=Nr)),rt)}var ac=fileURLToPath(import.meta.url),Vs=b.dirname(ac),Et=null,Bs=new Map;function cc(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function lc(t){let e=Bs.get(t.id);if(e)return e;let o=await $r(cc(t));return Bs.set(t.id,o),o}function pc(){if(Et)return Et;let t=[b.join(Vs,"../../data/modules-embeddings.json"),b.join(Vs,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(S.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let o=S.readFileSync(e,"utf-8"),r=JSON.parse(o);if(Array.isArray(r)?Et={model:"mock-or-text-embedding-3-small",dimension:r[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:r}:Et=r,!Et)throw new Error("failed to load embeddings data");return Et}function Hs(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let o=0,r=0,n=0;for(let a=0;a<t.length;a++)o+=t[a]*e[a],r+=t[a]*t[a],n+=e[a]*e[a];let i=Math.sqrt(r)*Math.sqrt(n);return i===0?0:o/i}function qs(t,e){let o=e.toLowerCase(),r=t.keywords.filter(n=>o.includes(n)||n.includes(o));return r.length>0?`Matches: ${r.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function zs(t,e=5){let o=await Wo(),r=await $r(t);if(Rt()){let a=await Promise.all(o.map(async c=>{let u=await lc(c);return {module:c,score:Hs(r,u),reason:qs(c,t)}}));return a.sort((c,u)=>u.score-c.score),a.slice(0,e)}let i=pc().modules.map(a=>{let c=o.find(f=>f.id===a.id);if(!c)return null;let u=Hs(r,a.embedding);return {module:c,score:u,reason:qs(c,t)}}).filter(a=>a!==null);return i.sort((a,c)=>c.score-a.score),i.slice(0,e)}var uc=fileURLToPath(import.meta.url),Ys=b.dirname(uc);function Qs(t){return t instanceof Error?t.message:String(t)}function mc(){return [b.join(Ys,"../../data/modules-embeddings.json"),b.join(Ys,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")]}function Xs(){let t=mc();for(let e of t)if(S.existsSync(e))try{let o=JSON.parse(S.readFileSync(e,"utf-8")),r=Array.isArray(o)?o:o.modules||[];return {exists:true,path:e,moduleCount:r.length,generatedAt:o.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function To(t=true,e){try{if(!Gs()&&!Rt())return console.log(s.red(`
|
|
23
|
+
`));});}var co=null,Ho=false,Zr=null;async function Ac(){return Zr||(Zr=(await import('openai')).default),Zr}function pa(){Ho=true;}function da(t){let o=new Array(1536),r=0;for(let a=0;a<t.length;a++)r=(r<<5)-r+t.charCodeAt(a),r=r&r;for(let a=0;a<1536;a++)r=r*1664525+1013904223&4294967295,o[a]=r/4294967295*2-1;let n=Math.sqrt(o.reduce((a,i)=>a+i*i,0));return o.map(a=>a/n)}async function qo(t){if(!t.trim()){co=null;return}let e=await Ac();co=new e({apiKey:t});}function ua(){if(!co)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return co}async function en(t){return Ho?da(t):(await ua().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function ma(t){return Ho?t.map(da):(await ua().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(r=>r.embedding)}function fa(){return co!==null}function Mt(){return Ho}function tn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Ic(t){return !t||typeof t!="object"?{}:t}var rn=[{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"]}],pt=null,on=0,$c=300*1e3;function Oc(t){let e=Ic(t),o=e.slug||e.name||e.id||e.module_id||"",r=tn(e.keywords??e.tags);return {id:o,name:e.display_name||e.name||"",category:Nc(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:r.map(n=>n.toLowerCase()),framework:Mc(e.framework),dependencies:tn(e.dependencies),useCases:tn(e.use_cases??e.useCases)}}function Nc(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function Mc(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 Tc(){try{let t=await g$4(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.match(/\{[\s\S]*\}/),o=e?e[0]:t.stdout,r=JSON.parse(o),n=[];return Array.isArray(r)?n=r:r.modules&&Array.isArray(r.modules)?n=r.modules:r.data&&Array.isArray(r.data)&&(n=r.data),n.map(Oc).filter(a=>a.id&&a.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)"),rn}}async function zo(){let t=Date.now();return Mt()?(pt=rn,on=t,pt):(pt&&t-on<$c||(pt=await Tc(),on=t,pt.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),pt=rn)),pt)}var Dc=fileURLToPath(import.meta.url),ha=C.dirname(Dc),Tt=null,ya=new Map;function Lc(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function Fc(t){let e=ya.get(t.id);if(e)return e;let o=await en(Lc(t));return ya.set(t.id,o),o}function Jc(){if(Tt)return Tt;let t=[C.join(ha,"../../data/modules-embeddings.json"),C.join(ha,"../data/modules-embeddings.json"),C.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(S.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let o=S.readFileSync(e,"utf-8"),r=JSON.parse(o);if(Array.isArray(r)?Tt={model:"mock-or-text-embedding-3-small",dimension:r[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:r}:Tt=r,!Tt)throw new Error("failed to load embeddings data");return Tt}function wa(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let o=0,r=0,n=0;for(let i=0;i<t.length;i++)o+=t[i]*e[i],r+=t[i]*t[i],n+=e[i]*e[i];let a=Math.sqrt(r)*Math.sqrt(n);return a===0?0:o/a}function ka(t,e){let o=e.toLowerCase(),r=t.keywords.filter(n=>o.includes(n)||n.includes(o));return r.length>0?`Matches: ${r.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function va(t,e=5){let o=await zo(),r=await en(t);if(Mt()){let i=await Promise.all(o.map(async c=>{let l=await Fc(c);return {module:c,score:wa(r,l),reason:ka(c,t)}}));return i.sort((c,l)=>l.score-c.score),i.slice(0,e)}let a=Jc().modules.map(i=>{let c=o.find(p=>p.id===i.id);if(!c)return null;let l=wa(r,i.embedding);return {module:c,score:l,reason:ka(c,t)}}).filter(i=>i!==null);return a.sort((i,c)=>c.score-i.score),a.slice(0,e)}var Kc=fileURLToPath(import.meta.url),Pa=C.dirname(Kc);function ba(t){return t instanceof Error?t.message:String(t)}function Uc(){return [C.join(Pa,"../../data/modules-embeddings.json"),C.join(Pa,"../data/modules-embeddings.json"),C.join(process.cwd(),"data/modules-embeddings.json")]}function ja(){let t=Uc();for(let e of t)if(S.existsSync(e))try{let o=JSON.parse(S.readFileSync(e,"utf-8")),r=Array.isArray(o)?o:o.modules||[];return {exists:true,path:e,moduleCount:r.length,generatedAt:o.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function Qo(t=true,e){try{if(!fa()&&!Mt())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...
|
|
27
|
-
`)),console.log(s.gray("\u{1F4E1} Fetching modules from Workspai..."));let o=await
|
|
27
|
+
`)),console.log(s.gray("\u{1F4E1} Fetching modules from Workspai..."));let o=await zo();console.log(s.green(`\u2713 Found ${o.length} modules
|
|
28
28
|
`));let r=o.length*50/1e6*.02;if(console.log(s.cyan(`\u{1F4B0} Estimated cost: ~$${r.toFixed(3)}`)),console.log(s.gray(` (Based on ${o.length} modules at $0.02/1M tokens)
|
|
29
|
-
`)),t){let{confirm:
|
|
29
|
+
`)),t){let{confirm:i}=await b$3([{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=o.map(
|
|
32
|
-
\u2705 Embeddings generated successfully!`)),console.log(s.gray(`\u{1F4C1} Saved to: ${
|
|
33
|
-
`)),true}catch(
|
|
31
|
+
`)),false}let n=o.map(i=>`${i.name}. ${i.description}. ${i.longDescription}. Keywords: ${i.keywords.join(", ")}. Use cases: ${i.useCases.join(", ")}.`),a=b$7(`Generating embeddings for ${o.length} modules...`,{component:"ai",phase:"embeddings.generate"});try{let i=await ma(n);a.succeed(`Generated embeddings for ${o.length} modules`);let c={model:"text-embedding-3-small",dimension:i[0].length,generated_at:new Date().toISOString(),modules:o.map((f,d)=>({id:f.id,name:f.name,embedding:i[d]}))},l=e||C.join(process.cwd(),"data","modules-embeddings.json"),p=C.dirname(l);return S.existsSync(p)||S.mkdirSync(p,{recursive:true}),S.writeFileSync(l,JSON.stringify(c,null,2)),console.log(s.green(`
|
|
32
|
+
\u2705 Embeddings generated successfully!`)),console.log(s.gray(`\u{1F4C1} Saved to: ${l}`)),console.log(s.gray(`\u{1F4CA} Size: ${o.length} modules, ${i[0].length} dimensions
|
|
33
|
+
`)),true}catch(i){a.fail("Failed to generate embeddings");let c=ba(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(`
|
|
36
36
|
\u274C Invalid API key`)),console.log(s.yellow("Please set a valid API key:")),console.log(s.white(` workspai config set-api-key
|
|
37
37
|
`))):console.log(s.red(`
|
|
38
38
|
\u274C Error: ${c}
|
|
39
39
|
`)),false}}catch(o){return console.log(s.red(`
|
|
40
|
-
\u274C Failed to generate embeddings: ${
|
|
41
|
-
`)),false}}async function
|
|
40
|
+
\u274C Failed to generate embeddings: ${ba(o)}
|
|
41
|
+
`)),false}}async function Ca(t=true){if(ja().exists)return true;if(console.log(s.yellow(`
|
|
42
42
|
\u26A0\uFE0F Module embeddings not found`)),console.log(s.gray(`AI recommendations require embeddings to be generated.
|
|
43
43
|
`)),!t)return console.log(s.red("\u274C Cannot generate embeddings in non-interactive mode")),console.log(s.white(`Run: workspai ai generate-embeddings
|
|
44
|
-
`)),false;let{action:o}=await b$
|
|
44
|
+
`)),false;let{action:o}=await b$3([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"\u{1F680} Generate embeddings now (OpenAI key for production, or mock mode for testing)",value:"generate"},{name:"\u{1F4DD} Show me how to generate them manually",value:"manual"},{name:"\u274C Cancel",value:"cancel"}]}]);return o==="generate"?await Qo(true):(o==="manual"&&(console.log(s.cyan(`
|
|
45
45
|
\u{1F4DD} To generate embeddings manually:
|
|
46
46
|
`)),console.log(s.white("1. Get OpenAI API key from: https://platform.openai.com/api-keys")),console.log(s.white("2. Set the API key:")),console.log(s.gray(" workspai config set-api-key")),console.log(s.gray(` OR: export OPENAI_API_KEY="sk-..."
|
|
47
47
|
`)),console.log(s.white("3. Generate embeddings:")),console.log(s.gray(` workspai ai generate-embeddings
|
|
48
48
|
`)),console.log(s.cyan(`\u{1F4B0} Cost: ~$0.50 one-time
|
|
49
|
-
`))),false)}async function
|
|
49
|
+
`))),false)}async function Sa(){let t=ja();return t.exists?(console.log(s.blue(`
|
|
50
50
|
\u{1F504} Updating embeddings...`)),console.log(s.gray(`Current: ${t.moduleCount} modules`)),console.log(s.gray(`Generated: ${t.generatedAt||"unknown"}
|
|
51
|
-
`)),t.path?await
|
|
51
|
+
`)),t.path?await Qo(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
|
|
53
|
+
`)),false)}function nn(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 xa(t,e=0){console.log(JSON.stringify(t,null,2)),e!==0&&process.exit(e);}function Ea(t){let e=t.command("ai").description("AI-powered features");e.command("recommend").description("Get AI-powered module recommendations").argument("[query]",'What do you want to build? (e.g., "user authentication with email")').option("-n, --number <count>","Number of recommendations","5").option("--json","Output as JSON").action(async(o,r)=>{try{Qr()||(r.json&&xa({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
|
-
`)),process.exit(1));let n=
|
|
55
|
+
`)),process.exit(1));let n=io();n?await qo(n):(r.json||(console.log(s.yellow(`
|
|
56
56
|
\u26A0\uFE0F OpenAI API key not configured - using MOCK MODE for testing
|
|
57
57
|
`)),console.log(s.gray("\u{1F4DD} Note: Mock embeddings provide approximate results for testing.")),console.log(s.gray(` For production, configure your OpenAI API key:
|
|
58
58
|
`)),console.log(s.white(" 1. Get your key from: https://platform.openai.com/api-keys")),console.log(s.white(" 2. Configure it: workspai config set-api-key")),console.log(s.gray(` OR set: export OPENAI_API_KEY="sk-proj-..."
|
|
59
|
-
`))),
|
|
59
|
+
`))),pa());let a=o;a||(a=(await b$3([{type:"input",name:"query",message:"\u{1F916} What do you want to build?",validate:y=>y.length===0?"Please enter a description":y.length<3?"Please be more specific (at least 3 characters)":true}])).query),r.json||console.log(s.blue(`
|
|
60
60
|
\u{1F916} Analyzing your request...
|
|
61
|
-
`)),!n||await
|
|
61
|
+
`)),!n||await Ca(!r.json)||(r.json&&xa({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(r.number,10),
|
|
63
|
+
`)),process.exit(1));let c=parseInt(r.number,10),l=await va(a,c);if(l.length===0||l[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/rapidkitlabs/workspai/issues
|
|
69
|
-
`)),
|
|
70
|
-
`));else return;if(r.json){console.log(JSON.stringify({query:
|
|
71
|
-
`)),
|
|
72
|
-
`));let{shouldInstall:
|
|
73
|
-
\u{1F4E6} Installing ${
|
|
74
|
-
`)),console.log(s.gray(`Command: npx workspai add module ${
|
|
75
|
-
\u274C RapidKit Core modules are not available for this project.`)),console.log(s.gray(` ${
|
|
76
|
-
`));return}let
|
|
69
|
+
`)),l.length>0)console.log(s.yellow(`\u26A0\uFE0F Low confidence matches found:
|
|
70
|
+
`));else return;if(r.json){console.log(JSON.stringify({query:a,recommendations:l},null,2));return}console.log(s.green.bold(`\u{1F4E6} Recommended Modules:
|
|
71
|
+
`)),l.forEach((d,y)=>{let h=(d.score*100).toFixed(1),k=d.score>.8?" \u2B50":"";console.log(s.bold(`${y+1}. ${d.module.name}${k}`)),console.log(s.gray(` ${d.module.description}`)),console.log(s.cyan(` Match: ${h}%`)+s.gray(` - ${d.reason}`)),console.log(s.yellow(` Category: ${d.module.category}`)),d.module.dependencies.length>0&&console.log(s.magenta(` Requires: ${d.module.dependencies.join(", ")}`)),console.log();});let p=l.slice(0,3).map(d=>d.module.id);console.log(s.cyan("\u{1F4A1} Quick install (top 3):")),console.log(s.white(` npx workspai add module ${p.join(" ")}
|
|
72
|
+
`));let{shouldInstall:f}=await b$3([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(f){let{selectedModules:d}=await b$3([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:l.map(h=>({name:`${h.module.name} - ${h.module.description}`,value:h.module.id,checked:h.score>.7}))}]),y=d;if(y.length>0){console.log(s.blue(`
|
|
73
|
+
\u{1F4E6} Installing ${y.length} modules...
|
|
74
|
+
`)),console.log(s.gray(`Command: npx workspai add module ${y.join(" ")}`));let k=q(process.cwd()).commandMap.add;if(!k||k.status!=="supported"){console.log(s.red(`
|
|
75
|
+
\u274C RapidKit Core modules are not available for this project.`)),console.log(s.gray(` ${k?.reason??"Module commands require RapidKit Core module-enabled project metadata."}
|
|
76
|
+
`));return}let j=await f$1(["add","module",...y],{cwd:process.cwd()});console.log(j===0?s.green(`
|
|
77
77
|
\u2705 Selected modules installed successfully
|
|
78
78
|
`):s.red(`
|
|
79
|
-
\u274C Module installation failed (exit code: ${
|
|
79
|
+
\u274C Module installation failed (exit code: ${j})
|
|
80
80
|
`));}else console.log(s.gray(`
|
|
81
81
|
No modules selected
|
|
82
|
-
`));}}catch(n){let
|
|
83
|
-
\u274C Error:`,
|
|
82
|
+
`));}}catch(n){let a=nn(n);f.error(`
|
|
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 o=
|
|
87
|
+
`))),process.exit(1);}}),e.command("info").description("Show AI features information").action(()=>{let o=io(),r=Qr();console.log(s.bold(`
|
|
88
88
|
\u{1F916} Workspai AI Features
|
|
89
89
|
`)),console.log(s.cyan("Status:"),r?s.green("Enabled"):s.red("Disabled")),console.log(s.cyan("API Key:"),o?s.green("Configured \u2713"):s.red("Not configured \u2717")),console.log(s.bold(`
|
|
90
90
|
\u{1F4E6} Available Features:
|
|
@@ -92,90 +92,90 @@ 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
|
-
`)),o?(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 o=
|
|
95
|
+
`)),o?(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 o=io();o||(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
|
-
`)),process.exit(1)),
|
|
101
|
-
`))),process.exit(r?0:1);}catch(o){let r=
|
|
100
|
+
`)),process.exit(1)),qo(o);let r=await Qo(true);r&&(console.log(s.green("\u2705 Ready to use AI recommendations!")),console.log(s.cyan(`Try: workspai ai recommend "authentication"
|
|
101
|
+
`))),process.exit(r?0:1);}catch(o){let r=nn(o);f.error("Failed to generate embeddings:",r.message),process.exit(1);}}),e.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let o=io();o||(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)),
|
|
105
|
-
`,"utf-8");}function
|
|
104
|
+
`)),process.exit(1)),qo(o);let r=await Sa();process.exit(r?0:1);}catch(o){let r=nn(o);f.error("Failed to update embeddings:",r.message),process.exit(1);}});}var Bc="rapidkit.product-factory-plan.v1",Hc="rapidkit.private-product-manifest.v1";function Ra(t){let e=process.argv;for(let o=0;o<e.length;o+=1){let r=e[o];if(r===t){let n=e[o+1];return n&&!n.startsWith("-")?n:void 0}if(r.startsWith(`${t}=`))return r.slice(t.length+1)}}function po(t,e=""){return typeof t=="string"&&t.trim()?t.trim():e}function sn(t){return typeof t=="string"&&t.trim()?t.trim():null}function qc(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function _a(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function Ia(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 zc(t,e,o){let r=po(t.slug);if(!r)throw new Error(`Backlog product at index ${e} is missing slug.`);Ia(r);let n=_a(t.modules),a=_a(t.moduleGaps);return {rank:qc(t.rank,e+1),slug:r,title:po(t.title,r),category:po(t.category,"Uncategorized"),tier:po(t.tier,"pro"),summary:po(t.summary),modules:n,moduleGaps:a,recommendedKit:o,workspaceProfile:"enterprise",readiness:{status:a.length>0?"blocked-by-module-gaps":"ready-for-private-manifest",blockingGaps:a}}}function Yc(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Backlog must be a JSON object.");return t}async function Qc(t){let e=C.resolve(process.cwd(),t),o=Yc(await R__default.readJson(e));if(!Array.isArray(o.products))throw new Error("Backlog must contain a products array.");return {absolutePath:e,payload:o}}function Xc(t,e){let o=[...t];if(e.tier){let r=e.tier.toLowerCase();o=o.filter(n=>n.tier.toLowerCase()===r);}if(e.category){let r=e.category.toLowerCase();o=o.filter(n=>n.category.toLowerCase()===r);}if(e.limit){let r=Number.parseInt(e.limit,10);if(!Number.isInteger(r)||r<1)throw new Error("--limit must be a positive integer.");o=o.slice(0,r);}return o}async function $a(t){let e=t.kit?.trim()||"fastapi.standard",{absolutePath:o,payload:r}=await Qc(t.backlogPath),n=r.products,a=n.map((f,d)=>zc(f,d,e)),i=Xc(a,t),c=new Set(i.flatMap(f=>f.modules)),l=i.flatMap(f=>f.moduleGaps),p=i.filter(f=>f.readiness.status==="ready-for-private-manifest").length;return {schemaVersion:Bc,generatedAt:(t.now??new Date).toISOString(),source:{backlogPath:o,backlogSchemaVersion:sn(r.schemaVersion),purpose:sn(r.purpose),publicationRule:sn(r.publicationRule)},defaults:{kit:e,workspaceProfile:"enterprise",projectSlug:"api"},stats:{totalProducts:n.length,plannedProducts:i.length,readyProducts:p,blockedProducts:i.length-p,uniqueModules:c.size,knownModuleGaps:l.length},products:i}}function Dt(t){return JSON.stringify(t,null,2)}function Zc(t){return `sha256:${ut.createHash("sha256").update(Dt(t)).digest("hex")}`}function el(t){return t.replace(/\\/g,"/")}async function tl(t){let e=await $a({backlogPath:t.backlogPath,kit:t.kit,now:t.now}),o=e.products.find(a=>a.slug===t.slug);if(!o)throw new Error(`Product "${t.slug}" was not found in backlog.`);let r=t.outputRoot||"../workspai-examples-pro",n={schemaVersion:Hc,generatedAt:e.generatedAt,product:{rank:o.rank,slug:o.slug,title:o.title,category:o.category,tier:o.tier,summary:o.summary},workspace:{name:o.slug,profile:"enterprise",outputHint:el(C.join(r,o.slug))},projects:[{slug:"api",kit:o.recommendedKit,runtime:"python",framework:"fastapi",modules:o.modules,moduleGaps:o.moduleGaps}],factory:{sourceBacklogPath:e.source.backlogPath,manifestChecksum:"",requiredCommands:[`npx workspai create workspace ${o.slug} --yes --profile enterprise`,`npx workspai create project ${o.recommendedKit} api --yes --skip-install`,"npx workspai init","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"],releaseEvidencePath:`.workspai/product-factory/${o.slug}/release-evidence.json`}};return {...n,factory:{...n.factory,manifestChecksum:Zc({...n,factory:{...n.factory,manifestChecksum:""}})}}}async function Aa(t,e,o=false){let r=C.resolve(process.cwd(),t);if(!o&&await R__default.pathExists(r))throw new Error(`Refusing to overwrite existing file: ${r}. Use --force.`);await R__default.ensureDir(C.dirname(r)),await R__default.writeFile(r,`${Dt(e)}
|
|
105
|
+
`,"utf-8");}function ol(t,e){let o=C.join(".workspai","product-factory","manifests",`${e}.manifest.json`);return t?t.endsWith(".json")?t:C.join(t,`${e}.manifest.json`):o}function rl(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(`
|
|
108
|
-
Wrote plan: ${
|
|
108
|
+
Wrote plan: ${C.resolve(process.cwd(),e)}`)),console.log(s.gray(`
|
|
109
109
|
Next: npx workspai product manifest create <slug> --from-backlog <file>
|
|
110
|
-
`));}function
|
|
110
|
+
`));}function nl(t,e){console.log(s.bold(`
|
|
111
111
|
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
|
-
Wrote manifest: ${
|
|
114
|
-
`));}function
|
|
115
|
-
`,"utf-8"),o}async function Lo(t,e,o){let r=await $c(t);if(r.requireReasonForDestructiveOps&&!o.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(r.requireSafetySnapshotForDestructiveOps&&o.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(o.permanent&&!r.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return r}function Jr(t=process.cwd()){let e=b.resolve(t),o=b.resolve(Er.tmpdir());for(;;){if(e!==o&&f$5(e))return e;let r=b.dirname(e);if(r===e)return null;e=r;}}function it(t){let e=t?b.resolve(t):Jr(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!f$5(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function Mc(t){let e=await Ac(o(t,"workspace.json").find(r=>existsSync(r))??l(t,"workspace.json")),o$1=e?.workspace_name??e?.name;return typeof o$1=="string"&&o$1.trim()?o$1.trim():b.basename(t)}function Jo(t){return l(t,"snapshots")}function to(t){return l(t,"archive","projects")}function Kr(t){return b.join(t,"files")}function Nc(t){return b.join(Er.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${Tr.randomBytes(4).toString("hex")}`)}function Gr(t,e){let o=b.relative(t,e);if(!o)return true;let r=o.split(b.sep);return (r[0]===".workspai"||r[0]===".rapidkit")&&["snapshots","archive","audit"].includes(r[1]||"")?false:!r.some(n=>_c.has(n))}async function Wc(t){return (await a$a(t,{descendIntoMatchedProjects:false})).map(o=>({name:b.basename(o),relativePath:b.relative(t,o)}))}async function Dc(t,e){let o=[],r$1=new Set;for(let n of Ec){let i=b.join(t,n);if(!await ___default.pathExists(i))continue;let a=r(n);if(r$1.has(a))continue;let c=b.join(e,a);await ___default.copy(i,c,{filter:u=>Gr(t,u)}),o.push(a),r$1.add(a);}return o}async function ui(t){let e=[];async function o(r){let n=[];try{n=await ___default.readdir(r,{withFileTypes:true});}catch{return}for(let i of n){let a=b.join(r,i.name);i.isDirectory()?i.name===".rapidkit"?e.push(a):await o(a):i.isFile()&&i.name===".rapidkit-workspace"&&e.push(a);}}await o(t),e.sort((r,n)=>n.length-r.length);for(let r$1 of e){let n=b.join(b.dirname(r$1),b.basename(r(b.basename(r$1))));await ___default.copy(r$1,n,{overwrite:false,errorOnExist:false}),await ___default.remove(r$1);}}async function Tc(t,e){await ___default.writeJson(b.join(t,"snapshot.json"),e,{spaces:2});}async function Ur(t){let e=b.join(t,"snapshot.json"),o=await ___default.readJson(e);if(!o||typeof o!="object"||o.schema!==pi)throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);return o}async function Fc(t){let e=0,o=0,r=[t];for(;r.length>0;){let n=r.shift();if(!n)continue;let i=[];try{i=await ___default.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){let c=b.join(n,a.name);if(a.isDirectory()){r.push(c);continue}if(a.isFile())try{let u=await ___default.stat(c);e+=1,o+=u.size;}catch{}}}return {files:e,bytes:o}}async function $t(t={}){let e=it(t.workspacePath),o=t.name?t.name:`snapshot-${It()}`,r=Lr(o),n=b.join(Jo(e),r),i=Nc(r);if(await ___default.pathExists(n))throw new Error(`Snapshot already exists: ${r}`);let a=Kr(i);try{await ___default.ensureDir(a);let c=t.includeProjects?"full":"metadata",u=c==="full"?["."]:await Dc(e,a);c==="full"&&(await ___default.copy(e,a,{filter:p=>Gr(e,p)}),await ui(a));let f={schema:pi,name:r,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await Mc(e),workspacePath:e,copiedPaths:u,projects:await Wc(e)};return await Tc(i,f),await ___default.ensureDir(b.dirname(n)),await ___default.move(i,n,{overwrite:false}),await qe(e,{action:"snapshot.create",target:r,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:u,snapshotPath:n,projectCount:f.projects.length}}),{manifest:f,snapshotPath:n}}catch(c){throw await ___default.remove(i),await qe(e,{action:"snapshot.create",target:r,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function mi(t){let e=it(t.workspacePath),o=b.join(Jo(e),Lr(t.name));if(!await ___default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await Ur(o),n=Kr(o),i=await Fc(n);return {manifest:r,snapshotPath:o,filesRoot:n,estimatedFileCount:i.files,estimatedBytes:i.bytes}}async function fi(t={}){let e=it(t.workspacePath),o=Jo(e);if(!await ___default.pathExists(o))return [];let r=await ___default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=b.join(o,i.name);try{n.push({...await Ur(a),snapshotPath:a});}catch{}}return n.sort((i,a)=>a.createdAt.localeCompare(i.createdAt))}async function gi(t){let e=it(t.workspacePath),o=b.join(Jo(e),Lr(t.name));if(!await ___default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r$1=await Ur(o),n=Kr(o),i=r$1.mode==="full"?["."]:Array.from(new Set(r$1.copiedPaths.map(u=>{let f=r(u);return f.startsWith(".workspai/")?".workspai":f})));if(t.dryRun)return await qe(e,{action:"snapshot.restore",target:r$1.name,status:"planned",reason:t.reason,details:{restoredPaths:i}}),{workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await Lo(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let a;if(t.safetySnapshot!==false&&(a=(await $t({workspacePath:e,name:`pre-restore-${r$1.name}-${It()}`,reason:`Automatic safety snapshot before restoring ${r$1.name}`,includeProjects:false})).snapshotPath),r$1.mode==="full")await ___default.copy(n,e,{overwrite:true,errorOnExist:false,filter:u=>Gr(n,u)}),await ui(e);else {let u=new Set;for(let f of r$1.copiedPaths){let p=r(f);u.has(p)||(await ___default.copy(b.join(n,f),b.join(e,p),{overwrite:true,errorOnExist:false}),u.add(p));}}let c={workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:false,safetySnapshotPath:a};return await qe(e,{action:"snapshot.restore",target:r$1.name,status:"succeeded",reason:t.reason,details:{restoredPaths:i,safetySnapshotPath:a}}),c}function hi(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function yi(t,e){let o=hi(e),r=b.isAbsolute(o)?b.resolve(o):b.resolve(t,o);if(r.startsWith(`${b.resolve(t)}${b.sep}`)&&await ___default.pathExists(r))return r;let i=(await a$a(t,{descendIntoMatchedProjects:false})).filter(a=>{let c=b.relative(t,a);return b.basename(a)===o||c===o});if(i.length===0)throw new Error(`Project not found in workspace: ${e}`);if(i.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return i[0]}async function Vr(t){try{let{syncWorkspaceProjects:e}=await import('./workspace-DZHWB7BV.js');await e(t,true);}catch{}}function Lc(t,e){let o=Tr.randomBytes(4).toString("hex");return b.join(to(t),`${e}-${It()}-${o}`)}async function wi(t){let e=[st,Fr].map(r=>b.join(t,r)).find(r=>___default.existsSync(r))??b.join(t,st),o=await ___default.readJson(e);if(!o||typeof o!="object"||o.schema!==di)throw new Error(`Invalid Workspai archive manifest: ${e}`);return o}async function Br(t={}){let e=it(t.workspacePath),o=to(e);if(!await ___default.pathExists(o))return [];let r=await ___default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=b.join(o,i.name),c=[st,Fr].map(u=>b.join(a,u)).find(u=>___default.existsSync(u))??b.join(a,st);try{n.push({...await wi(a),archivePath:a,manifestPath:c});}catch{}}return n.sort((i,a)=>a.archivedAt.localeCompare(i.archivedAt))}async function Jc(t,e){let o=hi(e),r=b.isAbsolute(o)?b.resolve(o):b.resolve(to(t),o);if(r.startsWith(`${b.resolve(to(t))}${b.sep}`)&&(await ___default.pathExists(b.join(r,st))||await ___default.pathExists(b.join(r,Fr))))return r;let i=(await Br({workspacePath:t})).filter(a=>b.basename(a.archivePath)===o||a.projectName===o||b.relative(to(t),a.archivePath)===o);if(i.length===0)throw new Error(`Archived project not found: ${e}`);if(i.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return i[0].archivePath}async function Hr(t){let e=it(t.workspacePath),o=await yi(e,t.project),r=b.basename(o),n=Lc(e,r),i=b.join(n,st);if(t.dryRun)return await qe(e,{action:"project.archive",target:r,status:"planned",reason:t.reason,details:{projectPath:o,archivePath:n}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,dryRun:true};await Lo(e,"project.archive",{reason:t.reason,safetySnapshot:true});let a=await $t({workspacePath:e,name:`pre-archive-${r}-${It()}`,reason:t.reason||`Automatic safety snapshot before archiving ${r}`,includeProjects:false});await ___default.ensureDir(b.dirname(n)),await ___default.move(o,n,{overwrite:false});let c={schema:di,projectName:r,originalPath:o,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:a.snapshotPath};return await ___default.writeJson(i,c,{spaces:2}),await c$3(e,[o]),await Vr(e),await qe(e,{action:"project.archive",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath,dryRun:false}}async function ki(t){if(!t.permanent)return Hr(t);let e=it(t.workspacePath),o=await yi(e,t.project),r=b.basename(o);if(t.confirm!==r)throw new Error(`Permanent delete requires --confirm ${r}`);if(t.dryRun)return await qe(e,{action:"project.delete",target:r,status:"planned",reason:t.reason,details:{projectPath:o,permanent:true}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",dryRun:true};await Lo(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await $t({workspacePath:e,name:`pre-delete-${r}-${It()}`,reason:t.reason||`Automatic safety snapshot before deleting ${r}`,includeProjects:false});return await ___default.remove(o),await c$3(e,[o]),await Vr(e),await qe(e,{action:"project.delete",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function vi(t){let e=it(t.workspacePath),o=await Jc(e,t.archive),r=await wi(o),n=t.targetName?.trim()||r.projectName,i=b.join(e,n);if(!i.startsWith(`${b.resolve(e)}${b.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await ___default.pathExists(i)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${i}`);if(t.dryRun)return await qe(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:o,projectPath:i}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:b.join(o,st),dryRun:true};await Lo(e,"project.restore",{reason:t.reason,safetySnapshot:true});let a=await $t({workspacePath:e,name:`pre-restore-project-${n}-${It()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false});return await ___default.move(o,i,{overwrite:t.force===true}),await Vr(e),await qe(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:o,projectPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:b.join(i,st),safetySnapshotPath:a.snapshotPath,dryRun:false}}var Gc="rapidkit.infra-stack.v1",bi="rapidkit.infra-plan.v1",Ot=".workspai/infra/docker-compose.yml",Mt=".workspai/reports/infra-plan.json",Yr=".workspai/infra/.env.example";function Uc(){let t=b.dirname(fileURLToPath(import.meta.url)),e=[b.join(t,"../../contracts/infra-stack.v1.json"),b.join(t,"../contracts/infra-stack.v1.json")];for(let o of e)if(S.existsSync(o))return o;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var zr=null;function ft(t){if(zr)return zr;let e=Uc(),o=S.readFileSync(e,"utf-8"),r=JSON.parse(o);if(r.schemaVersion!==Gc)throw new Error(`Unsupported infra stack schema: ${r.schemaVersion}`);return Vc(r),(zr=r),r}function Vc(t){let e=new Set(Object.keys(t.services));for(let[o,r]of Object.entries(t.moduleMappings)){if(!Array.isArray(r))throw new Error(`Invalid moduleMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`moduleMappings/${o} references unknown service '${n}'`)}for(let[o,r]of Object.entries(t.envVarMappings)){if(!Array.isArray(r))throw new Error(`Invalid envVarMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`envVarMappings/${o} references unknown service '${n}'`)}}function Si(t,e){let o=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[o]||[]}function Nt(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function xi(t,e){let o={};for(let r of e){let n=t.services[r];n&&Object.assign(o,n.connectionEnv);}return o}async function Hc(t){let e=b.join(t,"registry.json");if(!await ___default.pathExists(e))return [];try{let r=(await ___default.readJson(e)).installed_modules||[];return [...new Set(r.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function qc(t){let e=b.join(t,".env.example");if(!await ___default.pathExists(e))return [];try{let o=await ___default.readFile(e,"utf-8"),r=[];for(let n of o.split(`
|
|
116
|
-
`)){let
|
|
117
|
-
`)){let n=
|
|
118
|
-
`)?JSON.stringify(t):t}function
|
|
119
|
-
`)}function
|
|
120
|
-
`)}function
|
|
121
|
-
`);e.push("services:");for(let r of t.plan.services){let n=t.contract.services[r.id];if(n){if(e.push(` ${r.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: workspai-${r.id}`),n.command?.length){let
|
|
122
|
-
`)}function
|
|
123
|
-
`);return t.dryRun?{composePath:o,planPath:r,envExamplePath:n}:(await
|
|
124
|
-
`,"utf-8"),await
|
|
113
|
+
Wrote manifest: ${C.resolve(process.cwd(),e)}
|
|
114
|
+
`));}function Oa(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(o,r)=>{try{let n=r.output||Ra("--output"),a=await $a({backlogPath:o,kit:r.kit,tier:r.tier,category:r.category,limit:r.limit});a$4(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await Aa(n,a,true),r.json?console.log(Dt(a)):rl(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);r.json?console.log(Dt({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(o,r)=>{try{let n=r.output||Ra("--output");Ia(o);let a=await tl({backlogPath:r.fromBacklog,slug:o,kit:r.kit,outputRoot:r.workspaceOutput});a$4(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=ol(n,o);await Aa(i,a,r.force===true),r.json?console.log(Dt(a)):nl(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);r.json?console.log(Dt({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var Ta="rapidkit-workspace-snapshot-v1",mo="rapidkit-workspace-snapshot-v2",sl=Ta,Wa="rapidkit-project-archive-v1",Ze="workspai-archive.json",Zo="rapidkit-archive.json",al=[".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"],il=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),uo={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function Ft(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function er(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 cl(t){try{let e=await R__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function ll(t,e){if(!t)return e;let o=t.trim().toLowerCase();return ["true","yes","1","on"].includes(o)?true:["false","no","0","off"].includes(o)?false:e}async function pl(t){let e=o(t,"policies.yml").find(o=>existsSync(o))??l(t,"policies.yml");if(!await R__default.pathExists(e))return {...uo};try{let o=await R__default.readFile(e,"utf-8"),r=(n,a)=>{let i=o.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return ll(i?.[1],a)};return {requireReasonForDestructiveOps:r("require_reason_for_destructive_ops",uo.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:r("require_safety_snapshot_for_destructive_ops",uo.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:r("allow_permanent_delete",uo.allowPermanentDelete)}}catch{return {...uo}}}function dl(t){return l(t,"audit","events.jsonl")}async function We(t,e){let o={schema:"rapidkit-workspace-audit-event-v1",id:ut.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},r=dl(t);return await R__default.ensureDir(C.dirname(r)),await R__default.appendFile(r,`${JSON.stringify(o)}
|
|
115
|
+
`,"utf-8"),o}async function tr(t,e,o){let r=await pl(t);if(r.requireReasonForDestructiveOps&&!o.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(r.requireSafetySnapshotForDestructiveOps&&o.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(o.permanent&&!r.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return r}function an(t=process.cwd()){let e=C.resolve(t),o=C.resolve(Yr.tmpdir());for(;;){if(e!==o&&f$7(e))return e;let r=C.dirname(e);if(r===e)return null;e=r;}}function mt(t){let e=t?C.resolve(t):an(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!f$7(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function Da(t){let e=await cl(o(t,"workspace.json").find(r=>existsSync(r))??l(t,"workspace.json")),o$1=e?.workspace_name??e?.name;return typeof o$1=="string"&&o$1.trim()?o$1.trim():C.basename(t)}function Jt(t){return l(t,"snapshots")}function fo(t){return l(t,"archive","projects")}function Lt(t){return C.join(t,"files")}function ul(t){return C.join(Yr.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${ut.randomBytes(4).toString("hex")}`)}function ml(t,e){return C.join(Jt(t),`.tmp-${process.pid}-${e}-${ut.randomBytes(4).toString("hex")}`)}function or(t,e){let o=C.relative(t,e);if(!o)return true;let r=o.split(C.sep);return (r[0]===".workspai"||r[0]===".rapidkit")&&["snapshots","archive","audit"].includes(r[1]||"")?false:!r.some(n=>il.has(n))}async function fl(t){return (await a$a(t,{descendIntoMatchedProjects:false})).map(o=>({name:C.basename(o),relativePath:C.relative(t,o)}))}async function gl(t,e){let o=[],r$1=new Set;for(let n of al){let a=C.join(t,n);if(!await R__default.pathExists(a))continue;let i=r(n);if(r$1.has(i))continue;let c=C.join(e,i);await R__default.copy(a,c,{filter:l=>or(t,l)}),o.push(i),r$1.add(i);}return o}async function La(t){let e=[];async function o(r){let n=[];try{n=await R__default.readdir(r,{withFileTypes:true});}catch{return}for(let a of n){let i=C.join(r,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await o(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await o(t),e.sort((r,n)=>n.length-r.length);for(let r$1 of e){let n=C.join(C.dirname(r$1),C.basename(r(C.basename(r$1))));await R__default.copy(r$1,n,{overwrite:false,errorOnExist:false}),await R__default.remove(r$1);}}async function Fa(t,e){let o=e.schema===mo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,o,"Workspace snapshot manifest"),await R__default.writeJson(C.join(t,"snapshot.json"),e,{spaces:2});}async function cn(t){let e=C.join(t,"snapshot.json"),o=await R__default.readJson(e);if(!o||typeof o!="object"||![Ta,mo].includes(o.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let r=o,n=r.schema===mo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(r,n,"Workspace snapshot manifest"),r.mode==="project"&&(r.schema!==mo||r.recoveryScope?.kind!=="project"||!r.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return r}async function hl(t){let e=0,o=0,r=[t];for(;r.length>0;){let n=r.shift();if(!n)continue;let a=[];try{a=await R__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=C.join(n,i.name);if(i.isDirectory()){r.push(c);continue}if(i.isFile())try{let l=await R__default.stat(c);e+=1,o+=l.size;}catch{}}}return {files:e,bytes:o}}async function rr(t={}){let e=mt(t.workspacePath),o=t.name?t.name:`snapshot-${Ft()}`,r=er(o),n=C.join(Jt(e),r),a=ul(r);if(await R__default.pathExists(n))throw new Error(`Snapshot already exists: ${r}`);let i=Lt(a);try{await R__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",l=c==="full"?["."]:await gl(e,i);c==="full"&&(await R__default.copy(e,i,{filter:f=>or(e,f)}),await La(i));let p={schema:sl,name:r,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await Da(e),workspacePath:e,copiedPaths:l,projects:await fl(e)};return await Fa(a,p),await R__default.ensureDir(C.dirname(n)),await R__default.move(a,n,{overwrite:false}),await We(e,{action:"snapshot.create",target:r,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:l,snapshotPath:n,projectCount:p.projects.length}}),{manifest:p,snapshotPath:n}}catch(c){throw await R__default.remove(a),await We(e,{action:"snapshot.create",target:r,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function nr(t){let e=C.resolve(t.workspacePath),o=C.resolve(t.projectPath),r=C.relative(e,o);if(!r||r.startsWith("..")||C.isAbsolute(r)||r.split(C.sep).some(f=>f===".workspai"||f===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${o}`);let n=C.basename(o),a=er(`${t.namePrefix}-${n}-${Ft()}-${ut.randomBytes(3).toString("hex")}`),i=C.join(Jt(e),a),c=ml(e,a),l=C.join(Lt(c),r),p=false;try{await R__default.ensureDir(C.dirname(l)),t.moveSource?(await R__default.move(o,l,{overwrite:false}),p=true):await R__default.copy(o,l,{overwrite:false,errorOnExist:true,filter:d=>or(o,d)});let f={schema:mo,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await Da(e),workspacePath:e,copiedPaths:[r],projects:[{name:n,relativePath:r}],recoveryScope:{kind:"project",projectName:n,relativePath:r}};return await Fa(c,f),await R__default.move(c,i,{overwrite:false}),await We(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[r],snapshotPath:i,projectCount:1}}),{manifest:f,snapshotPath:i}}catch(f){if(p&&!await R__default.pathExists(o)){let d=await R__default.pathExists(l)?l:C.join(Lt(i),r);await R__default.pathExists(d)&&(await R__default.ensureDir(C.dirname(o)),await R__default.move(d,o,{overwrite:false}));}throw await R__default.remove(c),await R__default.remove(i),await We(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 Ja(t){let e=mt(t.workspacePath),o=C.join(Jt(e),er(t.name));if(!await R__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await cn(o),n=Lt(o),a=await hl(n);return {manifest:r,snapshotPath:o,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function Va(t={}){let e=mt(t.workspacePath),o=Jt(e);if(!await R__default.pathExists(o))return [];let r=await R__default.readdir(o,{withFileTypes:true}),n=[];for(let a of r){if(!a.isDirectory())continue;let i=C.join(o,a.name);try{n.push({...await cn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var yl=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function wl(t){let e=C.dirname(t.workspacePath),o=C.basename(t.workspacePath),r=`${Ft()}-${ut.randomBytes(4).toString("hex")}`,n=C.join(e,`.${o}.restore-staging-${r}`),a=C.join(e,`.${o}.pre-restore-${r}`),i=C.join(e,`.${o}.restore-failed-${r}`),c=[],l=false,p=false;try{await R__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:f=>or(t.filesRoot,f)}),await La(n),await R__default.rename(t.workspacePath,a),l=true,await R__default.rename(n,t.workspacePath),p=true;for(let f of yl){let d=C.join(a,f);if(!await R__default.pathExists(d))continue;let y=C.join(t.workspacePath,f);if(await R__default.pathExists(y))throw new Error(`Full restore operational path collision: ${f}`);await R__default.ensureDir(C.dirname(y)),await R__default.rename(d,y),c.push(f);}return a}catch(f){for(let d of [...c].reverse()){let y=C.join(t.workspacePath,d),h=C.join(a,d);await R__default.pathExists(y)&&(await R__default.ensureDir(C.dirname(h)),await R__default.rename(y,h));}throw p&&await R__default.pathExists(t.workspacePath)&&await R__default.rename(t.workspacePath,i),l&&await R__default.pathExists(a)&&await R__default.rename(a,t.workspacePath),await R__default.remove(i),await R__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${f instanceof Error?f.message:String(f)}`)}}async function Ka(t,e){let o=t.manifest.recoveryScope?.relativePath;if(!o)return;let r=C.join(Lt(t.snapshotPath),o),n=C.join(e,o);await R__default.pathExists(r)&&!await R__default.pathExists(n)&&(await R__default.ensureDir(C.dirname(n)),await R__default.move(r,n,{overwrite:false})),await R__default.remove(t.snapshotPath);}async function Ua(t){let e=mt(t.workspacePath),o=C.join(Jt(e),er(t.name));if(!await R__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r$1=await cn(o),n=Lt(o),a=r$1.mode==="full"?["."]:Array.from(new Set(r$1.copiedPaths.map(l=>{let p=r(l);return p.startsWith(".workspai/")?".workspai":p})));if(t.dryRun)return await We(e,{action:"snapshot.restore",target:r$1.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:o,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await tr(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(r$1.mode==="full")i=await wl({workspacePath:e,filesRoot:n,snapshotName:r$1.name});else if(r$1.mode==="project"){let l=r$1.recoveryScope?.relativePath;if(!l)throw new Error(`Project recovery snapshot is missing recoveryScope: ${r$1.name}`);let p=C.join(n,l),f=C.join(e,l),d=await R__default.pathExists(f),y,h=C.join(C.dirname(f),`.${C.basename(f)}.pre-restore-${process.pid}-${ut.randomBytes(4).toString("hex")}`),k=false;d&&t.safetySnapshot!==false?(y=await nr({workspacePath:e,projectPath:f,namePrefix:`pre-restore-${r$1.name}`,reason:`Automatic project recovery snapshot before restoring ${r$1.name}`,moveSource:true}),i=y.snapshotPath):d&&(await R__default.rename(f,h),k=true);let j=C.join(C.dirname(f),`.${C.basename(f)}.restore-${process.pid}-${ut.randomBytes(4).toString("hex")}`);try{await R__default.copy(p,j,{overwrite:false,errorOnExist:true}),await R__default.rename(j,f),k&&await R__default.remove(h);}catch(_){throw await R__default.remove(j),k&&await R__default.pathExists(h)&&(await R__default.remove(f),await R__default.rename(h,f)),y&&await Ka(y,e),_}}else t.safetySnapshot!==false&&(i=(await rr({workspacePath:e,name:`pre-restore-${r$1.name}-${Ft()}`,reason:`Automatic safety snapshot before restoring ${r$1.name}`,includeProjects:false})).snapshotPath);if(r$1.mode==="metadata"){let l=new Set;for(let p of r$1.copiedPaths){let f=r(p);l.has(f)||(await R__default.copy(C.join(n,p),C.join(e,f),{overwrite:true,errorOnExist:false}),l.add(f));}}let c={workspacePath:e,snapshotPath:o,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await We(e,{action:"snapshot.restore",target:r$1.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function Ga(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function Ba(t,e){let o=Ga(e),r=C.isAbsolute(o)?C.resolve(o):C.resolve(t,o);if(r.startsWith(`${C.resolve(t)}${C.sep}`)&&await R__default.pathExists(r))return r;let a=(await a$a(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=C.relative(t,i);return C.basename(i)===o||c===o});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 ln(t){try{let{syncWorkspaceProjects:e}=await import('./workspace-PLXOO6ST.js');await e(t,true);}catch{}}function kl(t,e){let o=ut.randomBytes(4).toString("hex");return C.join(fo(t),`${e}-${Ft()}-${o}`)}async function Ha(t){let e=qa(t),o=await R__default.readJson(e);if(!o||typeof o!="object"||o.schema!==Wa)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(o,"contracts/project-archive.v1.json","Project archive manifest"),o}function qa(t){return [Ze,Zo].map(e=>C.join(t,e)).find(e=>R__default.existsSync(e))??C.join(t,Ze)}async function pn(t={}){let e=mt(t.workspacePath),o=fo(e);if(!await R__default.pathExists(o))return [];let r=await R__default.readdir(o,{withFileTypes:true}),n=[];for(let a of r){if(!a.isDirectory())continue;let i=C.join(o,a.name),c=[Ze,Zo].map(l=>C.join(i,l)).find(l=>R__default.existsSync(l))??C.join(i,Ze);try{n.push({...await Ha(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function vl(t,e){let o=Ga(e),r=C.isAbsolute(o)?C.resolve(o):C.resolve(fo(t),o);if(r.startsWith(`${C.resolve(fo(t))}${C.sep}`)&&(await R__default.pathExists(C.join(r,Ze))||await R__default.pathExists(C.join(r,Zo))))return r;let a=(await pn({workspacePath:t})).filter(i=>C.basename(i.archivePath)===o||i.projectName===o||C.relative(fo(t),i.archivePath)===o);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 dn(t){let e=mt(t.workspacePath),o=await Ba(e,t.project),r=C.basename(o),n=kl(e,r),a=C.join(n,Ze),i=`${n}.tmp-${process.pid}`,c=C.join(i,Ze);for(let d of [Ze,Zo])if(await R__default.pathExists(C.join(o,d)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${d}`);if(t.dryRun)return await We(e,{action:"project.archive",target:r,status:"planned",reason:t.reason,details:{projectPath:o,archivePath:n}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await tr(e,"project.archive",{reason:t.reason,safetySnapshot:true});let l=await nr({workspacePath:e,projectPath:o,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${r}`,moveSource:false}),p={schema:Wa,projectName:r,originalPath:o,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:l.snapshotPath};a$4(p,"contracts/project-archive.v1.json","Project archive manifest");let f=false;try{await R__default.ensureDir(C.dirname(n)),await R__default.move(o,i,{overwrite:false}),f=true,await R__default.writeJson(c,p,{spaces:2}),await R__default.rename(i,n);}catch(d){if(f&&!await R__default.pathExists(o)){let y=await R__default.pathExists(i)?i:n;await R__default.pathExists(y)&&(await R__default.remove(C.join(y,Ze)),await R__default.move(y,o,{overwrite:false}));}throw await R__default.remove(i),d}return await c$5(e,[o]),await ln(e),await We(e,{action:"project.archive",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath,dryRun:false}}async function za(t){if(!t.permanent)return dn(t);let e=mt(t.workspacePath),o=await Ba(e,t.project),r=C.basename(o);if(t.confirm!==r)throw new Error(`Permanent delete requires --confirm ${r}`);if(t.dryRun)return await We(e,{action:"project.delete",target:r,status:"planned",reason:t.reason,details:{projectPath:o,permanent:true}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",dryRun:true};await tr(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await nr({workspacePath:e,projectPath:o,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${r}`,moveSource:true});return await c$5(e,[o]),await ln(e),await We(e,{action:"project.delete",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function Ya(t){let e=mt(t.workspacePath),o=await vl(e,t.archive),r=await Ha(o),n=t.targetName?.trim()||r.projectName,a=C.join(e,n);if(!a.startsWith(`${C.resolve(e)}${C.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await R__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await We(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:o,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:o,manifestPath:C.join(o,Ze),dryRun:true};await tr(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await R__default.pathExists(a),c=i?await nr({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await rr({workspacePath:e,name:`pre-restore-project-${n}-${Ft()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),l$1=qa(o),p=l(e,"audit","restores",`${C.basename(o)}.json`);try{await R__default.move(o,a,{overwrite:false}),await R__default.ensureDir(C.dirname(p)),await R__default.move(C.join(a,C.basename(l$1)),p,{overwrite:false});}catch(f){throw await R__default.pathExists(a)&&(await R__default.pathExists(p)&&await R__default.move(p,C.join(a,C.basename(l$1)),{overwrite:false}),await R__default.pathExists(o)||await R__default.move(a,o,{overwrite:false})),i&&await Ka(c,e),f}return await ln(e),await We(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:o,projectPath:a,restoreReceiptPath:p,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:o,manifestPath:p,safetySnapshotPath:c.snapshotPath,dryRun:false}}var bl="rapidkit.infra-stack.v1",Xa="rapidkit.infra-plan.v1",Vt=".workspai/infra/docker-compose.yml",Kt=".workspai/reports/infra-plan.json",fn=".workspai/infra/.env.example";function jl(){let t=C.dirname(fileURLToPath(import.meta.url)),e=[C.join(t,"../../contracts/infra-stack.v1.json"),C.join(t,"../contracts/infra-stack.v1.json")];for(let o of e)if(S.existsSync(o))return o;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var mn=null;function jt(t){if(mn)return mn;let e=jl(),o=S.readFileSync(e,"utf-8"),r=JSON.parse(o);if(r.schemaVersion!==bl)throw new Error(`Unsupported infra stack schema: ${r.schemaVersion}`);return Cl(r),(mn=r),r}function Cl(t){let e=new Set(Object.keys(t.services));for(let[o,r]of Object.entries(t.moduleMappings)){if(!Array.isArray(r))throw new Error(`Invalid moduleMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`moduleMappings/${o} references unknown service '${n}'`)}for(let[o,r]of Object.entries(t.envVarMappings)){if(!Array.isArray(r))throw new Error(`Invalid envVarMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`envVarMappings/${o} references unknown service '${n}'`)}}function Za(t,e){let o=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[o]||[]}function Ut(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function ei(t,e){let o={};for(let r of e){let n=t.services[r];n&&Object.assign(o,n.connectionEnv);}return o}async function xl(t){let e=C.join(t,"registry.json");if(!await R__default.pathExists(e))return [];try{let r=(await R__default.readJson(e)).installed_modules||[];return [...new Set(r.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function El(t){let e=C.join(t,".env.example");if(!await R__default.pathExists(e))return [];try{let o=await R__default.readFile(e,"utf-8"),r=[];for(let n of o.split(`
|
|
116
|
+
`)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&r.push(i[1]);}return r}catch{return []}}async function Rl(t){let e=o(t,"infra","overrides.json").find(o=>existsSync(o));if(!e)return [];try{let o=await R__default.readJson(e);return Array.isArray(o.services)?[...new Set(o.services.filter(r=>typeof r=="string"&&r.trim().length>0))]:[]}catch{return []}}async function _l(t){let e=await f$6(t,".workspai/workspace.contract.json");if(!e)return [];try{let o=await R__default.readJson(e),r=[];for(let n of o.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&r.push({project:a,env:i.trim().toUpperCase()});}return r}catch{return []}}function sr(t,e,o,r){t.add(o),e.push(r);}async function ti(t){let e=C.resolve(t.workspacePath),o=t.contract||jt(),r=new Set,n=[],a=new Set,i=new Set,c=new Set,l=await f$9(e);for(let p of l){let f=C.dirname(C.dirname(p)),d=C.basename(f);for(let y of await xl(f)){a.add(y);for(let h of Za(o,y))sr(r,n,h,{kind:"module",value:y,project:d});}for(let y of await El(f)){i.add(y);for(let h of Ut(o,y))sr(r,n,h,{kind:"env-var",value:y,project:d});}}for(let p of await _l(e)){i.add(p.env);for(let f of Ut(o,p.env))sr(r,n,f,{kind:"contract-env",value:p.env,project:p.project});}for(let p of await Rl(e))c.add(p),sr(r,n,p,{kind:"override",value:p});return {modules:[...a].sort(),envVars:[...i].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...r].sort()}}function Al(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let o=e.indexOf("=");if(o<=0)return null;let r=e.slice(0,o).trim();if(!/^[A-Z0-9_]+$/.test(r))return null;let n=e.slice(o+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let a=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),i=(a?a[1]:n).trim();return i?{key:r,value:i}:null}async function Il(t){if(!await R__default.pathExists(t))return {};try{let e=await R__default.readFile(t,"utf-8"),o={};for(let r of e.split(`
|
|
117
|
+
`)){let n=Al(r);n&&(o[n.key]=n.value);}return o}catch{return {}}}async function ri(t){let e={},o=await f$9(t.workspacePath);for(let r of o){let n=C.dirname(C.dirname(r)),a=await Il(C.join(n,".env.example"));for(let[i,c]of Object.entries(a))Ut(t.contract,i).length>0&&(e[i]=c);}return e}function ni(t,e){return t.filter(o=>Ut(e,o).length>0).sort()}function si(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let o=new URL(e),r=o.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(o.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(o.password||"postgres"),POSTGRES_DB:r||"postgres"}}catch{return}}function ai(t){let e=t.POSTGRES_USER||"postgres",o=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${o}`]}function $l(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
|
|
118
|
+
`)?JSON.stringify(t):t}function ii(t,e){return Object.entries(t).map(([o,r])=>`${e}${o}: ${$l(r)}`).join(`
|
|
119
|
+
`)}function Ol(t,e){let o=t.test.map(r=>JSON.stringify(r)).join(", ");return [`${e}healthcheck:`,`${e} test: [${o}]`,`${e} interval: ${t.interval}`,`${e} timeout: ${t.timeout}`,`${e} retries: ${t.retries}`].join(`
|
|
120
|
+
`)}function ci(t){let e=["# Generated by Workspai infra plan \u2014 do not edit manually.",`# Workspace: ${t.workspaceName}`,`# Generated at: ${t.plan.generatedAt}`,"name: workspai-infra"],o=new Set;if(t.plan.services.length===0)return e.push("services: {}"),e.push(""),e.join(`
|
|
121
|
+
`);e.push("services:");for(let r of t.plan.services){let n=t.contract.services[r.id];if(n){if(e.push(` ${r.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: workspai-${r.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?.[r.id]||{}};e.push(ii(a," "));}else t.plan.serviceEnvOverrides?.[r.id]&&(e.push(" environment:"),e.push(ii(t.plan.serviceEnvOverrides[r.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("/")&&o.add(i);}}if(n.healthcheck){let a=t.plan.serviceEnvOverrides?.[r.id];if(r.id==="postgres"&&a){let i=ai(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(Ol(n.healthcheck," "));}e.push(" restart: unless-stopped");}}if(o.size>0){e.push("volumes:");for(let r of [...o].sort())e.push(` ${r}:`),e.push(" driver: local");}return e.push(""),e.join(`
|
|
122
|
+
`)}function Ml(t,e,o){return t.kind==="override"?t.value===e:t.kind==="module"?o.moduleMappings[t.value]?.includes(e)??false:o.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function Tl(t){let e=new Map,o=[];for(let r of t)for(let n of r.ports){let a=e.get(n.host);a&&a!==r.id?o.push(`Port collision on host ${n.host} between services '${a}' and '${r.id}'`):e.set(n.host,r.id);}return o}async function Wl(t){let e=o(t,"workspace.json").find(o=>existsSync(o));if(e)try{let o=await R__default.readJson(e);return o.workspace_name||o.name}catch{return}}async function hn(t){let e=C.resolve(t.workspacePath),o=jt(),r=await ti({workspacePath:e,contract:o}),n=r.serviceIds.map(y=>{let h=o.services[y];return h?{id:y,displayName:h.displayName,category:h.category,image:h.image,ports:h.ports,sources:r.sources.filter(k=>Ml(k,y,o))}:null}).filter(y=>y!==null),a=Tl(n);n.length===0&&a.push("No infrastructure services detected. Install modules with infra dependencies or add .workspai/infra/overrides.json");for(let y of r.overrides)o.services[y]||a.push(`Override references unknown service '${y}'`);let i=await f$6(e,".workspai/workspace.contract.json")?".workspai/workspace.contract.json":void 0,c=ei(o,r.serviceIds),l=await ri({workspacePath:e,contract:o}),p={...c,...l};l.RAPIDKIT_DB_POSTGRES_URL&&(p.DATABASE_URL=l.RAPIDKIT_DB_POSTGRES_URL);let f={},d=si(p);return d&&r.serviceIds.includes("postgres")&&(f.postgres=d),{schemaVersion:Xa,generatedAt:(t.now||(()=>new Date))().toISOString(),workspacePath:e,workspaceName:await Wl(e),contractPath:i,strategy:"sidecar",composePath:Vt,envExamplePath:fn,services:n,connectionEnv:p,serviceEnvOverrides:Object.keys(f).length>0?f:void 0,sources:{modules:r.modules,envVars:r.envVars,overrides:r.overrides},warnings:a}}async function yn(t){let e=C.resolve(t.workspacePath),o=C.join(e,Vt),r=C.join(e,Kt),n=C.join(e,fn),a=jt();a$4(t.plan,"contracts/infra-plan.v1.json","Workspai infrastructure plan");let i=ci({plan:t.plan,contract:a,workspaceName:t.plan.workspaceName||C.basename(e)}),c=["# Generated by: npx workspai infra plan","# Copy values into project .env files as needed.",...Object.entries(t.plan.connectionEnv).map(([l,p])=>`${l}=${p}`),""].join(`
|
|
123
|
+
`);return t.dryRun?{composePath:o,planPath:r,envExamplePath:n}:(await R__default.ensureDir(C.dirname(o)),await R__default.ensureDir(C.dirname(r)),await R__default.writeFile(o,i,"utf-8"),await R__default.writeFile(r,`${JSON.stringify(t.plan,null,2)}
|
|
124
|
+
`,"utf-8"),await R__default.writeFile(n,c,"utf-8"),{composePath:o,planPath:r,envExamplePath:n})}function Dl(t){return C.resolve(t).split(C.sep).join("/")}async function pi(){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 Ll(){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 pi();}function di(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 ui(t){await Ll();let e=await pi(),o=Dl(t.composePath),r=await execa(e.command,[...e.prefixArgs,"-f",o,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:r.exitCode??1,stdout:r.stdout,stderr:r.stderr}}function ir(t){let e=t?C.resolve(t):an(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");return a$8(e)}function Fl(t){return C.join(t,Vt)}async function wn(t){let e=C.join(t,Kt);if(!await R__default.pathExists(e))throw new Error(`Infra plan not found at ${Kt}. Run: npx workspai infra plan`);let o=await R__default.readJson(e);return a$4(o,"contracts/infra-plan.v1.json",`Infra plan ${e}`),o}async function kn(t){let e=Fl(t.workspacePath);if(!await R__default.pathExists(e))throw new Error(`Compose file not found at ${Vt}. Run: npx workspai infra plan`);return ui({composePath:e,workspacePath:t.workspacePath,args:t.args})}function Jl(t,e={}){if(console.log(s.bold(`
|
|
125
125
|
Workspai infra plan
|
|
126
|
-
`)),console.log(s.gray(`Workspace: ${t.workspacePath}`)),t.workspaceName&&console.log(s.gray(`Name: ${t.workspaceName}`)),console.log(s.gray(`Strategy: ${t.strategy} (sidecar compose)`)),console.log(s.gray(`Compose: ${t.composePath}`)),console.log(s.gray(`Plan report: ${
|
|
127
|
-
`)):(console.log(s.green("Artifacts written:")),console.log(s.gray(` ${
|
|
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: ${Kt}`)),console.log(s.gray(`Env example: ${t.envExamplePath}`)),console.log(""),t.services.length===0)console.log(s.yellow("No infrastructure services detected."));else {console.log(s.bold("Services:"));for(let o of t.services){let r=o.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${o.id}`),s.gray(`(${o.displayName})`),r?s.white(`ports ${r}`):"");}}if(t.sources.modules.length>0&&(console.log(""),console.log(s.bold("Detected from modules:")),console.log(s.gray(` ${t.sources.modules.join(", ")}`))),t.sources.envVars.length>0){let o=jt(),r=ni(t.sources.envVars,o);console.log(s.bold("Detected from env vars (infra-mapped):")),r.length>0?console.log(s.gray(` ${r.join(", ")}`)):console.log(s.gray(" none"));let n=t.sources.envVars.length-r.length;if(n>0&&!e.verbose)console.log(s.gray(` (${n} other project env vars scanned \u2014 use --verbose to list all)`));else if(e.verbose){let a=t.sources.envVars.filter(i=>!r.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[o,r]of Object.entries(t.connectionEnv))console.log(s.gray(` ${o}=${r}`));}if(t.warnings.length>0){console.log(""),console.log(s.yellow("Warnings:"));for(let o of t.warnings)console.log(s.yellow(` - ${o}`));}console.log("");}function mi(t){let e=t.command("infra").description("Plan and manage workspace infrastructure (Docker sidecar stack)");e.command("plan").description("Discover infra needs and generate compose plan artifacts").option("--workspace <path>","Workspace root path").option("--json","Print plan as JSON").option("--dry-run","Compute plan without writing artifacts").option("--verbose","Show all scanned project env vars").action(async o=>{try{let r=ir(o.workspace),n=await hn({workspacePath:r}),a=await yn({workspacePath:r,plan:n,dryRun:o.dryRun});if(o.json){console.log(JSON.stringify({...n,artifacts:o.dryRun?{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath,dryRun:true}:{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath}},null,2));return}Jl(n,{verbose:o.verbose}),o.dryRun?console.log(s.yellow(`Dry run \u2014 no files written.
|
|
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}
|
|
128
128
|
`)));}catch(r){console.error(s.red(`
|
|
129
129
|
\u274C ${r instanceof Error?r.message:String(r)}
|
|
130
|
-
`)),process.exit(1);}}),e.command("up").description("Start planned infrastructure services via Docker Compose").option("--workspace <path>","Workspace root path").option("--detach","Run containers in background",true).option("--build","Build images before starting").option("--no-plan","Skip refreshing plan artifacts before starting").action(async o=>{try{let r=
|
|
130
|
+
`)),process.exit(1);}}),e.command("up").description("Start planned infrastructure services via Docker Compose").option("--workspace <path>","Workspace root path").option("--detach","Run containers in background",true).option("--build","Build images before starting").option("--no-plan","Skip refreshing plan artifacts before starting").action(async o=>{try{let r=ir(o.workspace);if(o.plan!==false){let c=await hn({workspacePath:r});await yn({workspacePath:r,plan:c});}if((await wn(r)).services.length===0)throw new Error("Infra plan has no services. Run: npx workspai infra plan (from a workspace with .env.example, core modules, or .workspai/infra/overrides.json)");let a=["up"];o.detach!==false&&a.push("-d"),o.build&&a.push("--build");let i=await kn({workspacePath:r,args:a});if(i.stdout&&process.stdout.write(i.stdout),i.stderr&&process.stderr.write(i.stderr),i.exitCode!==0){let c=di(i.stderr);c&&console.error(s.yellow(`
|
|
131
131
|
\u26A0\uFE0F ${c}
|
|
132
|
-
`)),process.exit(
|
|
132
|
+
`)),process.exit(i.exitCode);}o.detach!==false&&(console.log(s.green(`
|
|
133
133
|
\u2705 Infrastructure stack started.
|
|
134
134
|
`)),console.log(s.gray(`Check status: npx workspai infra status
|
|
135
135
|
`)));}catch(r){console.error(s.red(`
|
|
136
136
|
\u274C ${r instanceof Error?r.message:String(r)}
|
|
137
|
-
`)),process.exit(1);}}),e.command("down").description("Stop planned infrastructure services").option("--workspace <path>","Workspace root path").option("--volumes","Remove named volumes").action(async o=>{try{let r=
|
|
137
|
+
`)),process.exit(1);}}),e.command("down").description("Stop planned infrastructure services").option("--workspace <path>","Workspace root path").option("--volumes","Remove named volumes").action(async o=>{try{let r=ir(o.workspace);await wn(r);let n=["down"];o.volumes&&n.push("-v");let a=await kn({workspacePath:r,args:n});a.stdout&&process.stdout.write(a.stdout),a.stderr&&process.stderr.write(a.stderr),a.exitCode!==0&&process.exit(a.exitCode),console.log(s.green(`
|
|
138
138
|
\u2705 Infrastructure stack stopped.
|
|
139
139
|
`));}catch(r){console.error(s.red(`
|
|
140
140
|
\u274C ${r instanceof Error?r.message:String(r)}
|
|
141
|
-
`)),process.exit(1);}}),e.command("status").description("Show Docker Compose status for planned infrastructure").option("--workspace <path>","Workspace root path").option("--json","Print docker compose ps JSON output").option("--strict","Exit non-zero when any container is not healthy/running").action(async o=>{try{let r=
|
|
141
|
+
`)),process.exit(1);}}),e.command("status").description("Show Docker Compose status for planned infrastructure").option("--workspace <path>","Workspace root path").option("--json","Print docker compose ps JSON output").option("--strict","Exit non-zero when any container is not healthy/running").action(async o=>{try{let r=ir(o.workspace),n=await wn(r),a=o.json?["ps","--format","json"]:["ps"],i=await kn({workspacePath:r,args:a});if(o.json){i.stdout&&process.stdout.write(i.stdout),i.exitCode!==0&&process.exit(i.exitCode);return}console.log(s.bold(`
|
|
142
142
|
Workspai infra status
|
|
143
|
-
`)),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Planned services: ${n.services.map(c=>c.id).join(", ")||"none"}`)),console.log(""),
|
|
144
|
-
`))),
|
|
143
|
+
`)),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Planned services: ${n.services.map(c=>c.id).join(", ")||"none"}`)),console.log(""),i.stdout.trim()?process.stdout.write(i.stdout):(console.log(s.yellow("No running containers found for the infra stack.")),console.log(s.gray(`Start with: npx workspai infra up
|
|
144
|
+
`))),i.exitCode!==0&&(i.stderr&&process.stderr.write(i.stderr),process.exit(i.exitCode)),o.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(r){console.error(s.red(`
|
|
146
146
|
\u274C ${r instanceof Error?r.message:String(r)}
|
|
147
|
-
`)),process.exit(1);}});}function
|
|
148
|
-
${r.stderr||""}`,
|
|
149
|
-
${o.stderr||""}`);return r?this.isMavenVersionAtLeast(r,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${r.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let o=S.existsSync(b.join(e,"pom.xml")),r=S.existsSync(b.join(e,"mvnw"))||S.existsSync(b.join(e,"mvnw.cmd")),n=S.existsSync(b.join(e,"build.gradle"))||S.existsSync(b.join(e,"build.gradle.kts"))||S.existsSync(b.join(e,"settings.gradle"))||S.existsSync(b.join(e,"settings.gradle.kts")),i=S.existsSync(b.join(e,"gradlew"))||S.existsSync(b.join(e,"gradlew.bat"));return {hasMavenProject:o||r,hasMavenWrapper:r,hasGradleProject:n||i,hasGradleWrapper:i}}findWorkspaceRoot(e){let o=e;for(;;){if(S.existsSync(b.join(o,".workspai-workspace"))||S.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o$1=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o$1==="shared-runtime-caches"||o$1==="shared-node-deps"||o$1==="isolated")return o$1;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o(r,"policies.yml").find(i=>S.existsSync(i));if(!n)return "isolated";try{let c=S.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let o=b.join(e,"mvnw.cmd");if(process.platform==="win32"&&S.existsSync(o))return {command:o,baseArgs:[]};let r=b.join(e,"mvnw");return S.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let o=b.join(e,"gradlew.bat");if(process.platform==="win32"&&S.existsSync(o))return {command:o,baseArgs:[]};let r=b.join(e,"gradlew");return S.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let o=[],r=new Set,n=[e];for(;n.length>0;){let i=n.shift();if(!i||r.has(i))continue;r.add(i);let a=[];try{a=S.readdirSync(i,{withFileTypes:true});}catch{continue}for(let c of a){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let u=b.join(i,c.name),f=this.inspectJavaProject(u);(f.hasMavenProject||f.hasGradleProject)&&o.push(u),n.push(u);}}return o}withJavaCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","m2"):b.join(e,".workspai","cache","java","m2"),a=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","gradle"):b.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,u=process.env.GRADLE_USER_HOME,f=`-Dmaven.repo.local=${i}`;return process.env.MAVEN_OPTS=c?`${c} ${f}`:f,process.env.GRADLE_USER_HOME=a,o().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof u>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=u;})}async runBuildTool(e,o,r=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:i}=this.buildToolCommand(e),a=await this.runCommand(n,[...i,...o],e);if(a===0||!r)return {exitCode:a};let c=S.existsSync(b.join(e,"pom.xml")),u=S.existsSync(b.join(e,"build.gradle"))||S.existsSync(b.join(e,"build.gradle.kts"));return {exitCode:a,message:c||u?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let o=[b.join(e,"target"),b.join(e,"build","libs")];for(let r of o){if(!S.existsSync(r))continue;let i=S.readdirSync(r).filter(a=>a.toLowerCase().endsWith(".jar")).find(a=>!a.toLowerCase().endsWith("-sources.jar")&&!a.toLowerCase().endsWith("-javadoc.jar")&&!a.toLowerCase().endsWith("-plain.jar"));if(i)return b.join(r,i)}return null}commandArgsFor(e,o){if(e==="gradle"){let r=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return o==="init"?[...r,"dependencies"]:o==="dev"?[...r,"bootRun"]:o==="test"?[...r,"test"]:[...r,"bootJar"]}return o==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:o==="dev"?["spring-boot:run"]:o==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),o=this.resolveJavaCommand(e),r=await this.runCommand(o,["-version"],e);if(r!==0)return {exitCode:r,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),u=await this.detectInstalledJavaMajor(o,e);if(u!==null&&u<c)return {exitCode:1,message:`Detected Java ${u}, but project requires Java ${c}+.`};let f=b.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&S.existsSync(f))try{let d=S.readFileSync(f,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),g=this.parseMajorJavaVersion(d?.[1]);if(g!==null&&g<c)return {exitCode:1,message:`Detected JAVA_HOME version ${g}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),u=c==="gradle"?["--version"]:["-version"],f=await this.runBuildTool(e,u);return f.exitCode!==0?f:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):f}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let u=c.reduce((d,g)=>Math.max(d,this.readRequiredJavaMajor(g)),0);if(u>0){let d=await this.detectInstalledJavaMajor(o,e);if(d!==null&&d<u){let g=c.filter(m=>this.readRequiredJavaMajor(m)>d).map(m=>b.relative(e,m)).join(", ");return {exitCode:1,message:`Detected Java ${d}, but workspace project(s) [${g}] require Java ${u}+.`}}}let f=false,p=false;for(let d of c){let g=this.inspectJavaProject(d);g.hasMavenProject&&!g.hasMavenWrapper&&(f=true),g.hasGradleProject&&!g.hasGradleWrapper&&(p=true);}if(f){let d=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(d!==0)return {exitCode:d,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 g=await this.checkSystemMavenVersion(e);if(g.exitCode!==0)return g}if(p){let d=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(d!==0)return {exitCode:d,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(i===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return a===0?{exitCode:0}:{exitCode:i||a||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let o=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return o&&S.mkdirSync(o,{recursive:true}),process.env.GRADLE_USER_HOME&&S.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let o=this.resolveJarPath(e);if(o)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",o],e)};let r=await this.runBuild(e);if(r.exitCode!==0)return r;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(ze(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let o=b.join(e,"pom.xml");return S.existsSync(o)&&S.readFileSync(o,"utf-8").includes("checkstyle")?this.runBuildTool(e,["checkstyle:check"]):{exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){return ze(e,"format")?{exitCode:await this.runCommand("make",["format"],e)}:["build.gradle","build.gradle.kts"].map(r=>b.join(e,r)).filter(r=>S.existsSync(r)).some(r=>S.readFileSync(r,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure spotless in Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run 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 zo=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}findWorkspaceRoot(e){let o=e;for(;;){if(S.existsSync(b.join(o,".workspai-workspace"))||S.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o$1=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o$1==="shared-runtime-caches"||o$1==="shared-node-deps"||o$1==="isolated")return o$1;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o(r,"policies.yml").find(i=>S.existsSync(i));if(!n)return "isolated";try{let c=S.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,o,r){let n=this.resolveDependencyMode(e),i=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=n==="isolated"?b.join(e,".workspai","cache","node"):b.join(i||e,".workspai","cache","node"),c=process.env.npm_config_cache,u=process.env.npm_config_store_dir,f=process.env.RAPIDKIT_DEP_SHARING_MODE,p=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,i&&(process.env.RAPIDKIT_WORKSPACE_PATH=i),o==="pnpm"?(process.env.npm_config_store_dir=b.join(a,"pnpm-store"),process.env.npm_config_cache=b.join(a,"pnpm-cache")):o==="yarn"?process.env.npm_config_cache=b.join(a,"yarn-cache"):process.env.npm_config_cache=b.join(a,"npm-cache"),r().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof u>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=u,typeof f>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=f,typeof p>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=p;})}detectPackageManager(e){if(S.existsSync(b.join(e,"package-lock.json")))return "npm";if(S.existsSync(b.join(e,"pnpm-lock.yaml")))return "pnpm";if(S.existsSync(b.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 S.existsSync(b.join(e,"package-lock.json"))||S.existsSync(b.join(e,"pnpm-lock.yaml"))||S.existsSync(b.join(e,"yarn.lock"))}availablePackageManagers(e){let o=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[o]:[o,...["npm","pnpm","yarn"].filter(n=>n!==o&&this.commandAvailable(n))]}commandAvailable(e){let o=e$6(e);return spawnSync(o.command,[...o.prefixArgs,"--version"],{stdio:"ignore",shell:c$6(),env:g$5()}).status===0}scriptArgs(e,o){return e==="npm"?["run-script",o,"--foreground-scripts"]:["run",o]}async runScriptWithFallback(e,o){let r={exitCode:1};for(let n of this.availablePackageManagers(e))if(r=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,o),e)),r.exitCode===0)return r;return r}async runLifecycle(e,o){let r=d$4(e),n=i$3(e,r),i=n$2(e,o,{framework:n.key});return i?this.runScriptWithFallback(e,i.scriptName):{exitCode:1,message:`No npm script available for \`${o}\`. Add a "${o}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let o=this.detectPackageManager(e);return this.withDependencyEnv(e,o,async()=>{try{return process.env.npm_config_cache&&S.mkdirSync(process.env.npm_config_cache,{recursive:true}),o==="pnpm"&&process.env.npm_config_store_dir&&S.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let o=this.detectPackageManager(e),r=this.resolveDependencyMode(e),n=r==="shared-runtime-caches"||r==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,o,()=>this.run(o,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var Qo=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,o){return {exitCode:await this.withPythonCacheEnv(o,()=>this.runCore(e,o))}}findWorkspaceRoot(e){let o=e;for(;;){if(S.existsSync(b.join(o,".workspai-workspace"))||S.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o$1=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o$1==="shared-runtime-caches"||o$1==="shared-node-deps"||o$1==="isolated")return o$1;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o(r,"policies.yml").find(i=>S.existsSync(i));if(!n)return "isolated";try{let c=S.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","python"):b.join(e,".workspai","cache","python"),a=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=b.join(i,"pip"),process.env.POETRY_CACHE_DIR=b.join(i,"poetry"),o().finally(()=>{typeof a>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=a,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),o=await this.run(["doctor","check"],e);return o.exitCode===0?o:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx 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."]}};function ul(){let t={...process.env},e=t.PATH||"";if(e){let o=e.split(b.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter);t.PATH=o;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||h$4(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Je(t,e){return t==="go"?new Ho((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="node"?new zo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="java"?new qo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="dotnet"?new Bo((o,r,n)=>e.runCommandInCwd(o,r,n)):new Qo((o,r)=>e.runCoreRapidkit(o,{cwd:r,env:ul()}))}var Ji=b.join(Er.homedir(),".workspai","cache"),Ki=1440*60*1e3;function sn(){let t=a$b("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?b.join(Ji,`vitest-${e}`):Ji}var Zo=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 b.join(sn(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let o=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${o}.tmp`}async get(e,o="1.0"){let r=this.memoryCache.get(e);if(r&&r.version===o&&Date.now()-r.timestamp<Ki)return f.debug(`Cache hit (memory): ${e}`),r.data;try{let n=this.getCachePath(e),i=await promises.readFile(n,"utf-8"),a=JSON.parse(i);if(a.version===o&&Date.now()-a.timestamp<Ki)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,a),a.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,o,r="1.0"){let n={data:o,timestamp:Date.now(),version:r};this.memoryCache.set(e,n);try{await promises.mkdir(sn(),{recursive:true});let i=this.getCachePath(e),a=this.getTempCachePath(i);await promises.writeFile(a,JSON.stringify(n),"utf-8"),await promises.rename(a,i),f.debug(`Cache set: ${e}`);}catch(i){f.debug(`Cache write failed: ${e}`,i);}}async invalidate(e){this.memoryCache.delete(e);try{let o=this.getCachePath(e);await promises.unlink(o),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=sn(),o=await promises.readdir(e);await Promise.all(o.map(r=>promises.unlink(b.join(e,r)))),f.debug("Cache cleared");}catch{}}};var er=["list","sync","registry","foundation","model","snapshot","diff","impact","verify","graph","watch","context","agent-sync","remediation-plan","explain","why","trace","feedback","mcp","policy","contract","share","export","archive","hydrate","import","run","init"],tr=["model","snapshot","diff","impact","verify","context","agent-sync","remediation-plan","explain","why","trace"];function Gi(t){return tr.includes(t)}var Ui="rapidkit-runtime-command-surface-v1";var Vi="doctor-remediation-plan-v2";function or(){return {runtimeCommandSurface:Ui,cliLogEvent:c$9,freshnessMetadata:a$k,factFreshness:c$8,blockerResolution:a$j,workspaceModel:j$1,workspaceImpact:e$3,workspaceVerify:c$7,workspaceContext:a$i,workspaceDependencyGraph:i$5,workspaceIntelligenceHistory:a$h,agentCustomizationPack:k$2,workspaceOperationalSkill:a$g,workspaceSkillsIndex:b$b,workspaceExplain:a$f,agentActionOutcome:a$e,doctorRemediationPlan:Vi,artifactRemediationPlan:a$d,doctorFixResult:a$c}}var hl=["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"],yl={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},wl={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"};function kl(t){return t[Math.floor(Math.random()*t.length)]}function an(t){let e=kl(hl),o=k$3(t);if(o){let i=wl[o.id]??"app";return `${e}-${i}`}let r=a$4(t),n=r?yl[r.id]??"service":"app";return `${e}-${n}`}async function Sl(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function Bi(t,e){await _.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
150
|
-
`,"utf-8");}function
|
|
151
|
-
`,"utf-8"),n}function _l(t,e){if(!e?.enabled)return {headers:{}};let o=process.env[e.hmacKeyEnv];if(!o)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let r=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",i=createHmac(r,o).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:i,"x-rapidkit-evidence-signature-alg":r}}}async function Al(t,e,o){let r=(o.algorithm||"sha256").toLowerCase(),n=Ke(t,o.publicKeyPath);if(!await _.pathExists(n))return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Public key not found: ${n}`};try{let i=await promises.readFile(n,"utf-8"),a=await promises.readFile(e),c=createVerify(r);c.update(a),c.end();let u=Buffer.from(o.signature,"base64"),f=c.verify(i,u),p=createHash("sha256").update(i).digest("hex");return {verified:f,algorithm:r,publicKeyPath:n,publicKeyFingerprint:p,signature:o.signature,message:f?"Attestation verified.":"Attestation signature verification failed."}}catch(i){return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Attestation verification error: ${i.message}`}}}async function Il(t,e,o,r){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};let i=o.signaturePath?Ke(t,o.signaturePath):null;if(!i||!await _.pathExists(i))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:i};let a=["verify-blob",e,"--signature",i],c=o.certificatePath?Ke(t,o.certificatePath):null;c&&a.push("--certificate",c);let u=o.bundlePath?Ke(t,o.bundlePath):null;u&&a.push("--bundle",u);let f=o.keyPath?Ke(t,o.keyPath):null;f&&a.push("--key",f),o.identity&&a.push("--certificate-identity",o.identity),o.issuer&&a.push("--certificate-oidc-issuer",o.issuer),o.rekorUrl&&a.push("--rekor-url",o.rekorUrl),r.requireTransparencyLog||a.push("--insecure-ignore-tlog");try{let p=await execa("cosign",a,{reject:false});return p.exitCode===0?{verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:u,certificatePath:c,signaturePath:i}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${p.stderr||p.stdout||"unknown error"}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:u,certificatePath:c,signaturePath:i}}catch(p){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${p.message}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:u,certificatePath:c,signaturePath:i}}}async function $l(t,e){let o=e.algorithm||"sha256",r=Ke(t,e.policyPath),n=Ke(t,e.signaturePath),i=Ke(t,e.publicKeyPath);if(!await _.pathExists(r))return {verified:false,message:`Governance policy bundle not found: ${r}`,policies:null};if(!await _.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await _.pathExists(i))return {verified:false,message:`Governance policy public key not found: ${i}`,policies:null};try{let a=await promises.readFile(r,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),u=await promises.readFile(i,"utf-8"),f=createVerify(o);return f.update(a),f.end(),f.verify(u,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(a).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(a){return {verified:false,message:`Governance policy bundle verification error: ${a.message}`,policies:null}}}async function cn(t,e){let o$1=[],r={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=o(t,"mirror-config.json").find(U=>existsSync(U))??l(t,"mirror-config.json"),i=l(t,"mirror.lock"),a=l(t,"mirror","artifacts"),c=l(t,"reports"),u=await Cl(t);if(!await _.pathExists(n))return o$1.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:o$1,details:r};let f={};try{f=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return o$1.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:o$1,details:r}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||f.mode==="offline-only"))return o$1.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:o$1,details:r};await _.ensureDir(a);let d=Math.max(0,f.prefetch?.retries??2),g=Math.max(0,f.prefetch?.backoffMs??250),m=Math.max(1e3,f.prefetch?.timeoutMs??15e3),l$1=f.security?.requireAttestation===true,y=f.security?.requireSigstore===true,k=f.security?.requireTransparencyLog===true,v=f.security?.requireSignedGovernance===true,h=f.security?.evidenceExport,w=(process.env.RAPIDKIT_ENV||f.security?.governance?.environment||"dev").toLowerCase(),x=f.security?.governance?.policies||{};if(f.security?.governanceBundle){let U=await $l(t,f.security.governanceBundle);if(o$1.push({id:"governance.bundle.verify",status:U.verified?"passed":"failed",message:U.message}),U.verified&&U.policies)x=U.policies,r.governanceBundleVerified=true;else if(v)return {checks:o$1,details:r}}let P=x[w],R=k||P?.requireTransparencyLog===true,I=[],Y=Array.isArray(f.artifacts)?f.artifacts:[],te=[];for(let U=0;U<Y.length;U+=1){let D=Y[U],E=D.id||`artifact-${U+1}`,ue=D.source?Ke(t,D.source):null,se=xl(D,E),H=b.join(a,se),Z=false,je={sourceType:"path",source:ue||D.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(ue&&await _.pathExists(ue))await _.ensureDir(b.dirname(H)),await _.copyFile(ue,H),r.syncedArtifacts+=1,Z=true,je={sourceType:"path",source:ue,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},o$1.push({id:`mirror.sync.${E}`,status:"passed",message:`Mirrored artifact ${E} from source path.`});else if(D.url){let Ee="";try{Ee=new URL(D.url).hostname.toLowerCase();}catch{o$1.push({id:`mirror.prefetch.${E}`,status:"failed",message:`Invalid URL for ${E}: ${D.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||u.has(Ee))){o$1.push({id:`mirror.prefetch.trust.${E}`,status:"failed",message:`Untrusted mirror host for ${E}: ${Ee}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await _.pathExists(H)?(Z=true,je={sourceType:"url",source:D.url,host:Ee,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},o$1.push({id:`mirror.prefetch.${E}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${E}.`})):o$1.push({id:`mirror.prefetch.${E}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${E} without an existing mirrored copy.`}),!Z))continue;if(!Z){let we=null,bt=0;for(let Ye=1;Ye<=d+1;Ye+=1){bt=Ye;try{await jl(D.url,H,m),r.syncedArtifacts+=1,Z=true,je={sourceType:"url",source:D.url,host:Ee,fetchedAt:new Date().toISOString(),attempts:bt,trusted:true},o$1.push({id:`mirror.prefetch.${E}`,status:"passed",message:bt>1?`Prefetched artifact ${E} from ${Ee} after ${bt} attempts.`:`Prefetched artifact ${E} from ${Ee}.`});break}catch(j){if(we=j,Ye<=d){await Hi(g*Ye);continue}}}if(!Z){o$1.push({id:`mirror.prefetch.${E}`,status:"failed",message:`Failed to prefetch ${E} after ${d+1} attempt(s): ${we?.message||"unknown error"}`});continue}}if(!Z){o$1.push({id:`mirror.prefetch.${E}`,status:"failed",message:`Failed to prefetch ${E}.`});continue}}if(!Z){D.required||e.offlineMode?o$1.push({id:`mirror.sync.${E}`,status:"failed",message:`Mirror source missing for ${E}${ue?`: ${ue}`:""}`}):o$1.push({id:`mirror.sync.${E}`,status:"skipped",message:`Mirror source not found for optional artifact ${E}.`});continue}let Ve=await Sl(H);if(D.sha256&&D.sha256.toLowerCase()!==Ve.toLowerCase()){o$1.push({id:`mirror.verify.${E}`,status:"failed",message:`Checksum mismatch for ${E}.`});continue}r.verifiedArtifacts+=1,o$1.push({id:`mirror.verify.${E}`,status:"passed",message:`Checksum verified for ${E}.`});let ye=D.attestation?await Al(t,H,D.attestation):null;if(D.attestation){if(o$1.push({id:`mirror.attest.${E}`,status:ye?.verified?"passed":"failed",message:ye?.message||"Attestation verification failed."}),!ye?.verified)continue}else if(l$1){o$1.push({id:`mirror.attest.${E}`,status:"failed",message:`Attestation is required but missing for ${E}.`});continue}else o$1.push({id:`mirror.attest.${E}`,status:"skipped",message:`No attestation provided for ${E}.`});let Re=D.attestation?.sigstore,G=Re?await Il(t,H,Re,{requireTransparencyLog:R}):null;if(Re){if(o$1.push({id:`mirror.sigstore.${E}`,status:G?.verified?"passed":"failed",message:G?.message||"Sigstore verification failed."}),I.push({artifactId:E,verified:!!G?.verified,tlogVerified:!!G?.tlogVerified,identity:G?.identity||null,issuer:G?.issuer||null,rekorUrl:G?.rekorUrl||null,timestamp:new Date().toISOString(),environment:w}),!G?.verified)continue}else if(y){o$1.push({id:`mirror.sigstore.${E}`,status:"failed",message:`Sigstore attestation is required but missing for ${E}.`});continue}else o$1.push({id:`mirror.sigstore.${E}`,status:"skipped",message:`No Sigstore attestation provided for ${E}.`});if(Re&&G?.verified&&P){let Ee=P.allowedIdentities||[];if(Ee.length>0){let we=!!G.identity&&Ee.includes(G.identity);if(o$1.push({id:`mirror.sigstore.policy.identity.${E}`,status:we?"passed":"failed",message:we?`Sigstore identity policy passed for ${E} in ${w}.`:`Sigstore identity policy failed for ${E} in ${w}.`}),!we)continue}let po=P.allowedIssuers||[];if(po.length>0){let we=!!G.issuer&&po.includes(G.issuer);if(o$1.push({id:`mirror.sigstore.policy.issuer.${E}`,status:we?"passed":"failed",message:we?`Sigstore issuer policy passed for ${E} in ${w}.`:`Sigstore issuer policy failed for ${E} in ${w}.`}),!we)continue}let Pt=P.allowedRekorUrls||[];if(Pt.length>0){let we=!!G.rekorUrl&&Pt.includes(G.rekorUrl);if(o$1.push({id:`mirror.sigstore.policy.rekor.${E}`,status:we?"passed":"failed",message:we?`Sigstore Rekor policy passed for ${E} in ${w}.`:`Sigstore Rekor policy failed for ${E} in ${w}.`}),!we)continue}}else P&&o$1.push({id:`mirror.sigstore.policy.${E}`,status:"skipped",message:`Sigstore governance policy configured for ${w} but no verified Sigstore attestation for ${E}.`});let $e=await promises.stat(H);te.push({id:E,path:b.relative(t,H),sha256:Ve,size:$e.size,provenance:je,attestation:{detached:{provided:!!D.attestation,verified:ye?.verified||false,algorithm:ye?.algorithm||null,publicKeyPath:ye?.publicKeyPath||null,publicKeyFingerprint:ye?.publicKeyFingerprint||null,signature:ye?.signature||null,verifiedAt:ye?.verified?new Date().toISOString():null},sigstore:{provided:!!Re,verified:G?.verified||false,tlogVerified:G?.tlogVerified||false,identity:G?.identity||null,issuer:G?.issuer||null,rekorUrl:G?.rekorUrl||null,bundlePath:G?.bundlePath||null,certificatePath:G?.certificatePath||null,signaturePath:G?.signaturePath||null,verifiedAt:G?.verified?new Date().toISOString():null}}});}let K=f.retention?.keepLast;if(typeof K=="number"&&K>0){let D=(await promises.readdir(a,{withFileTypes:true})).filter(E=>E.isFile()).map(E=>b.join(a,E.name));if(D.length>K){let E=await Promise.all(D.map(async se=>({filePath:se,stat:await promises.stat(se)})));E.sort((se,H)=>H.stat.mtimeMs-se.stat.mtimeMs);let ue=E.slice(K);for(let se of ue)await promises.unlink(se.filePath),r.rotatedFiles+=1;}}o$1.push({id:"mirror.rotate",status:"passed",message:r.rotatedFiles>0?`Mirror retention rotation removed ${r.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let B={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:f.mode||null,environment:w,artifacts:te};if(await promises.writeFile(i,`${JSON.stringify(B,null,2)}
|
|
152
|
-
`,"utf-8"),r.lockWritten=true,o$1.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${
|
|
153
|
-
`,"utf-8"),r.evidenceExported=true,r.evidenceExportTarget=H,o$1.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${H}.`});}catch(H){o$1.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${H.message}`});}else if(h.target==="http")if(!h.endpoint)o$1.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let H=Math.max(0,h.retries??0),Z=Math.max(0,h.backoffMs??500),je=_l(U,h.signing);je.error&&o$1.push({id:"sigstore.evidence.export.http",status:"failed",message:je.error});try{let Ve=h.authTokenEnv?process.env[h.authTokenEnv]:void 0,ye=false,Re=null;for(let G=1;G<=H+1;G+=1)try{if(je.error)throw new Error(je.error);await Rl(h.endpoint,U,se,Ve,je.headers),r.evidenceExported=true,r.evidenceExportTarget=h.endpoint,o$1.push({id:"sigstore.evidence.export.http",status:"passed",message:G>1?`Transparency evidence exported to HTTP endpoint ${h.endpoint} after ${G} attempts.`:`Transparency evidence exported to HTTP endpoint ${h.endpoint}.`}),ye=true;break}catch($e){Re=$e,G<=H&&await Hi(Z*G);}if(!ye)throw Re||new Error("unknown evidence export error")}catch(Ve){let ye=`Evidence HTTP export failed: ${Ve.message}`;o$1.push({id:"sigstore.evidence.export.http",status:"failed",message:ye});try{let Re=await El(t,h.deadLetterPath,U,ye);o$1.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${Re}.`});}catch(Re){o$1.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${Re.message}`});}}}if(h.failOnError&&o$1.some(Z=>Z.status==="failed"&&(Z.id==="sigstore.evidence.export.file"||Z.id==="sigstore.evidence.export.http")))return {checks:o$1,details:r}}else o$1.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else o$1.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),o$1.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:o$1,details:r}}function rr(t){let e=a$m(t.detection.runtime),o=o$3({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),r=[];r.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"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}),r.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),r.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit 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."}),r.push({id:"lifecycle-commands",status:o.lifecycleCommands.length>1?"pass":"warn",message:o.lifecycleCommands.length>1?`Lifecycle commands available: ${o.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:o.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=r.some(a=>a.status==="fail"),i=r.some(a=>a.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":i?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:o.lifecycleCommands,unsupportedLifecycleCommands:o.unsupportedLifecycleCommands,moduleCommands:o.moduleCommands},checks:r}}function Ol(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function nr(t){if(t.existingProjectJson?.module_support===true){let e=Ol(t.existingProjectJson),o=e?a$4(e):void 0;return o?.owner==="core"&&o.moduleSupport===true}return false}function Zi(t){return t.replace(/\\/g,"/")}function Ml(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function Nl(t,e){let o=Zi(b.relative(t,e));return !o||o.startsWith("..")?true:o.split("/").filter(Boolean).some(r=>r==="..")}function oo(t){let e=Zi(b.relative(t.workspacePath,t.projectPath)),o=Nl(t.workspacePath,t.projectPath),r=Ml(t.projectName,b.basename(t.projectPath)),n=o?`external/${r}`:e||r;return {relativePath:e||n,contractRelativePath:n,isExternal:o}}var oa={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},Tl={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"},Fl={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},ea=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function pn(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function dn(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function ro(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 sr(t){let e=new Set;for(let o of t)e.add(ro(o));return [...e].sort((o,r)=>ea.indexOf(o)-ea.indexOf(r))}function Ll(t){let e=sr(t).filter(o=>o!=="unknown");if(e.length!==0)return e.length===1?Fl[e[0]]:"polyglot"}function ta(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function Jl(t,e){return t?"none":e==="strict"?"error":"warning"}function no(t){let e=t.ok?void 0:Ll(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?ta(e):void 0,ciRecommendedCommand:e?ta(e,{ci:true}):void 0,severity:Jl(t.ok,t.mode)}}function ht(t){let e=dn(t.profile),o=sr(t.runtimes),r=t.mode??"warn",n=oa[e];if(n){let i=o.length===0||o.every(a=>pn(a)===n);return no({ok:i,checkId:`profile.${e}`,profile:e,runtimes:o,message:i?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${o.join(", ")}].`,mode:r})}if(e==="minimal"){let i=o.filter(u=>u!=="unknown"),c=new Set(i.map(u=>pn(u))).size<=1;return no({ok:c,checkId:"profile.minimal",profile:e,runtimes:o,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${i.join(", ")}].`,mode:r})}return no({ok:true,checkId:`profile.${e}`,profile:e,runtimes:o,message:`${e} profile accepts the detected runtime mix.`,mode:r})}function lt(t){let e=dn(t.profile),o=ro(t.runtime),r=t.mode??"warn",n=oa[e];if(!n||o==="unknown")return no({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[o],message:o==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:r});let i=pn(o)===n;return no({ok:i,checkId:`profile.${e}`,profile:e,runtimes:i?[o]:sr([n,o]),message:i?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${Tl[o]}, but workspace profile is "${e}".`,mode:r})}async function Ft(t){let e=(await Promise.all(o(t,"policies.yml").map(async o=>await ___default.pathExists(o)?o:null))).find(o=>typeof o=="string");if(!e)return "warn";try{return (await ___default.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function Lt(t){let e=(await Promise.all(o(t,"workspace.json").map(async o=>await ___default.pathExists(o)?o:null))).find(o=>typeof o=="string");if(!e)return "minimal";try{let o=await ___default.readJson(e);return dn(o.profile)}catch{return "minimal"}}async function yt(t,e={}){let o=new Set,r=[],n=new Set,i=[t];for(;i.length>0;){let a=i.pop();if(!a||n.has(a))continue;n.add(a);let c=[];try{c=await S.promises.readdir(a,{withFileTypes:true});}catch{continue}for(let u of c){if(!u.isDirectory()||u.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(u.name))continue;let f=b.join(a,u.name);if(f!==t&&f$5(f))continue;if((await Promise.all([...p(f,"context.json"),...p(f,"project.json")].map(async d=>___default.pathExists(d)))).some(Boolean)){r.push(f);continue}i.push(f);}}for(let a of r){let c=d$4(a);o.add(ro(i$3(a,c).runtime));}for(let a of await a$l(t))o.add(ro(a.runtime));for(let a of e.additionalRuntimes??[])o.add(ro(a));return sr(o)}function ir(t,e={}){let o=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return o?`Recommended: ${o}`:null}function ra(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Gl(t){let e=t.trim();if(!e)return "imported-project";let o=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),r=o[o.length-1]||e,n=r.split(":"),i=(n[n.length-1]||r).replace(/\.git$/i,"");return ra(i)||"imported-project"}function un(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function Ul(t){return un(t)?"git-url":"local-folder"}async function Vl(t,e){let o=ra(e)||"imported-project",r=0;for(;;){let n=r===0?o:r===1?`${o}-imported`:`${o}-imported-${r}`,i=b.join(t,n);if(!await ___default.pathExists(i))return i;r+=1;}}function Bl(t,e){let o=b.resolve(t),r=b.resolve(e),n=b.relative(o,r);return n===""||n.length>0&&!n.startsWith("..")&&!b.isAbsolute(n)}function Hl(t,e){if(Bl(t,e))throw new Error("Import source must be outside the current workspace root.")}function ql(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}function zl(t){let e=b.basename(t);return !([".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor","packages"].includes(e)||ql(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Yl(t){for(let e of p(t,"project.json"))if(await ___default.pathExists(e))try{return await ___default.readJson(e)}catch{return null}return null}async function Ql(t){let e=new Date().toISOString(),o=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),r=oo({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:o}),n=r.contractRelativePath,i=q$1(t.projectPath,"project.json"),a=q$1(t.projectPath,"import.json"),c=q$1(t.projectPath,"import-readiness.json"),u=nr({existingProjectJson:t.existingProjectJson}),f=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],p=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},d={...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:b.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:b.basename(t.projectPath),kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:u,modules:f,contracts:p,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:r.relativePath,is_external:r.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},g={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:b.basename(t.projectPath)},project:{name:d.name,slug:d.slug,relative_path:n,kind:t.projectKind,module_support:u},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:u,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}}},m=rr({projectName:String(d.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:u,projectPath:t.projectPath,generatedAt:new Date(e)});return await ___default.ensureDir(b.dirname(i)),await ___default.writeJson(i,d,{spaces:2}),await ___default.writeJson(a,g,{spaces:2}),await ___default.writeJson(c,m,{spaces:2}),{projectJsonPath:i,importJsonPath:a,importReadinessPath:c,moduleSupport:u}}async function Xl(t,e){let o={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,importedAt:new Date().toISOString()};await b$a(t,[o]);}async function na(t){await ___default.pathExists(t)&&await ___default.remove(t);}async function sa(t,e){await na(e),await c$3(t,[e]);}async function ia(t){let e=b.resolve(t.workspacePath),o=t.source.trim(),r=t.sourceType??Ul(o),n=t.name??(r==="git-url"?Gl(o):b.basename(o)),i=await Vl(e,n),a=false;try{if(r==="local-folder"){let h=b.resolve(o),w=await ___default.stat(h).catch(()=>null);if(!w||!w.isDirectory())throw new Error("Import source is not a directory.");if(f$5(h))throw new Error("This is a workspace. Import it as a workspace instead.");Hl(e,h),a=true,await ___default.copy(h,i,{overwrite:false,errorOnExist:true,filter:zl});}else a=true,await execa("git",["clone","--depth","1",o,i],{timeout:12e4,env:a$9()});let c=await Yl(i),u=i$3(i,c),f=await h$3(i,c),[p,d]=await Promise.all([Lt(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):Ft(e)]),g=lt({profile:p,runtime:u.runtime,subjectLabel:b.basename(i),mode:d}),m=ht({profile:p,runtimes:await yt(e,{additionalRuntimes:[u.runtime]}),mode:d}),l=g.ok?m:g;if(!l.ok&&d==="strict")throw new Error(l.message);let y=await Ql({workspacePath:e,projectPath:i,sourceType:r,detection:u,existingProjectJson:c,projectKind:f,profileCompatibility:l}),k=oo({workspacePath:e,projectPath:i,projectName:b.basename(i)}),v={name:b.basename(i),path:i,relativePath:k.contractRelativePath,stack:u.importStack,runtime:u.runtime,framework:u.key,frameworkDisplayName:u.displayName,supportTier:u.supportTier,moduleSupport:y.moduleSupport,confidence:u.confidence,source:r,projectJsonPath:y.projectJsonPath,importJsonPath:y.importJsonPath,importReadinessPath:y.importReadinessPath,profileCompatibility:l};return await Xl(e,v),v}catch(c){if(a)try{await na(i);}catch(u){let f=c instanceof Error?c.message:String(c),p=u instanceof Error?u.message:String(u);throw new Error(`Import failed: ${f}. Rollback also failed: ${p}`)}throw c}}function Zl(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function ep(t,e){return b.resolve(t)===b.resolve(e)}async function tp(t){for(let e of p(t,"project.json"))if(await ___default.pathExists(e))try{return await ___default.readJson(e)}catch{return null}return null}function op(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],o=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:o,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,discovered_relative_path:t.discoveredRelativePath,is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function aa(t,e,o){let r=p(e,"project.json"),n=q$1(e,"project.json"),i=p(e,"adopt.json"),a=p(e,"adopt-readiness.json");if(o)await ___default.ensureDir(b.dirname(n)),await ___default.writeJson(n,o,{spaces:2});else for(let u of r)await ___default.pathExists(u)&&await ___default.remove(u);for(let u of i)await ___default.pathExists(u)&&await ___default.remove(u);for(let u of a)await ___default.pathExists(u)&&await ___default.remove(u);let{removeImportedProjectsRegistryEntries:c}=await import('./imported-projects-registry-FOIE27WT.js');await c(t,[e]);}async function ca(t){let e=b.resolve(t.workspacePath),o=b.resolve(t.source),r=await ___default.stat(o).catch(()=>null);if(!r||!r.isDirectory())throw new Error("Adopt source is not a directory.");if(ep(e,o))throw new Error("Adopt source cannot be the workspace root itself.");if(f$5(o))throw new Error("This is a workspace. Import it as a workspace instead.");let n=await tp(o),i=i$3(o,n),a=await h$3(o,n),c=Zl(t.name||(typeof n?.name=="string"?n.name:"")||b.basename(o))||"adopted-project",u=oo({workspacePath:e,projectPath:o,projectName:c}),f=(t.now??new Date).toISOString(),p=q$1(o,"project.json"),d=q$1(o,"adopt.json"),g=q$1(o,"adopt-readiness.json"),m=nr({existingProjectJson:n}),[l,y]=await Promise.all([Lt(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):Ft(e)]),k=lt({profile:l,runtime:i.runtime,subjectLabel:c,mode:y}),v=ht({profile:l,runtimes:await yt(e,{additionalRuntimes:[i.runtime]}),mode:y}),h=k.ok?v:k;if(!h.ok&&y==="strict")throw new Error(h.message);let w=op({projectName:c,contractRelativePath:u.contractRelativePath,isExternal:u.isExternal,discoveredRelativePath:u.relativePath,detection:i,existingProjectJson:n,projectKind:a,moduleSupport:m,adoptedAt:f}),x={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:f,managed_by:"workspai",mode:"linked",workspace:{path:e},project:{name:c,path:o,relative_path:u.contractRelativePath,discovered_relative_path:u.relativePath,is_external:u.isExternal,kind:a,module_support:m},detection:{framework:i.key,framework_display_name:i.displayName,runtime:i.runtime,kind:a,confidence:i.confidence,support_tier:i.supportTier,import_stack:i.importStack,source:i.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:m,workspace_contract:"linked-project",profile_compatibility:{ok:h.ok,profile:h.profile,runtimes:h.runtimes,message:h.message,recommended_profile:h.recommendedProfile,recommended_command:h.recommendedCommand}}},P=rr({projectName:c,relativePath:u.contractRelativePath,projectKind:a,source:"adopted-local",detection:i,moduleSupport:m,projectPath:o,generatedAt:new Date(f)});if(t.dryRun!==true){await ___default.ensureDir(b.dirname(p)),await ___default.writeJson(p,w,{spaces:2}),await ___default.writeJson(d,x,{spaces:2}),await ___default.writeJson(g,P,{spaces:2});let R={name:c,path:o,relativePath:u.contractRelativePath,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:m,confidence:i.confidence,source:"adopted-local",importedAt:f};await b$a(e,[R]);}return {name:c,path:o,relativePath:u.relativePath,contractRelativePath:u.contractRelativePath,isExternal:u.isExternal,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:m,confidence:i.confidence,projectJsonPath:p,adoptJsonPath:d,adoptReadinessPath:g,profileCompatibility:h,wroteFiles:t.dryRun!==true}}function mn(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 sp(t=process.argv){let e=b.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function ao(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function ip(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function _e(t,e){let o=t.indexOf(e);if(o>=0&&o+1<t.length)return t[o+1];let r=t.find(n=>n.startsWith(`${e}=`));if(r)return r.slice(e.length+1)}async function pa(t){let e=oe(process.cwd()),o=t.trim().toLowerCase();if(!e||!o)return true;try{let[r,n]=await Promise.all([Lt(e),Ft(e)]),i=a$4(o),c=k$3(o)?"node":i?.runtime??"python",u=lt({profile:r,runtime:c,subjectLabel:o,mode:n}),f=ht({profile:r,runtimes:await yt(e,{additionalRuntimes:[c]}),mode:n}),p=u.ok?f:u;if(p.ok)return true;let d=ir(p);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${p.message}`)),d&&console.log(s.gray(`\u{1F4A1} ${d}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${p.message}`)),d&&console.log(s.gray(`\u{1F4A1} ${d}`));}catch{}return true}function Cn(){return i$6()}function da(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(b.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=h$4()),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 ap(t){return l$3(b.join(t,".venv"))}async function Aa(t,e){return await z(t,["--version"],e)===0}async function vt(t){let e=b.join(t,"go.mod");if(await ___default.pathExists(e))return "go";let o=b.join(t,"pom.xml"),r=b.join(t,"build.gradle"),n=b.join(t,"build.gradle.kts");if(await ___default.pathExists(o)||await ___default.pathExists(r)||await ___default.pathExists(n))return "java";if((await ___default.pathExists(t)?await S.promises.readdir(t,{withFileTypes:true}):[]).some(d=>d.isFile()&&d.name.toLowerCase().endsWith(".sln")))return "dotnet";let a=b.join(t,"src");if(await ___default.pathExists(a)&&(await S.promises.readdir(a,{withFileTypes:true})).some(g=>g.isFile()&&g.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=b.join(t,"package.json");if(await ___default.pathExists(c))return "node";let u=b.join(t,"pyproject.toml"),f=b.join(t,"requirements.txt"),p=b.join(t,"poetry.lock");return await ___default.pathExists(u)||await ___default.pathExists(f)||await ___default.pathExists(p)?"python":null}async function cp(t){for(let e of Cn())if(await z(e,e==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Ia(t){for(let e of Cn())if(await z(e,e==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function lp(t){let e=l$3(b.join(t,".venv"));if(!await ___default.pathExists(e)){let i=await Ia(t);if(i!==0)return i}if(!await Aa("poetry",t))return 0;let r=await z("poetry",["config","virtualenvs.in-project","true","--local"],t);if(r!==0)return r;let n=await z("poetry",["env","use",e],t);return n!==0?n:0}async function pp(t){let e=l$3(b.join(t,".venv"));if(!await ___default.pathExists(e)){let n=await Ia(t);if(n!==0)return n}await z(e,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let o=b.join(t,"requirements.txt");if(await ___default.pathExists(o)&&await z(e,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let r=b.join(t,"pyproject.toml");return await ___default.pathExists(r)&&(await z(e,["-m","pip","install","-e","."],t)===0||await z(e,["-m","pip","install","."],t)===0)?0:1}async function fn(t,e){return await lp(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 ___default.pathExists(b.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await pp(t))}async function gn(t){let e=await kt("init",t);if(e===0)return 0;let o=["npm","pnpm","yarn"];for(let r of o){if(!await Aa(r,t))continue;if(await z(r,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${r} install`)),0}return e}function dp(t,e){let o=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),r=_e([...e],"--port");if(r&&!/^\d+$/.test(r.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=_e([...e],"--java-version"),i=_e([...e],"--spring-boot-version"),a=_e([...e],"--springdoc-version"),c=_e([...e],"--group-id"),u=_e([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(i&&!o(i.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(a&&!o(a.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(u&&!/^[A-Za-z0-9_.-]+$/.test(u.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=_e([...e],"--target-framework"),i=_e([...e],"--root-namespace");if(n&&!/^net\d+\.\d+$/.test(n.trim()))return "Invalid --target-framework. Expected .NET target framework, e.g. net8.0";if(i&&!/^[A-Za-z0-9_.]+$/.test(i.trim()))return "Invalid --root-namespace. Use dot-separated .NET namespace identifiers only."}return null}async function kn(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],o=a$4(e),r=t[3];if(!o||o.owner!=="npm")return 1;if(!r)return process.stderr.write(`Usage: ${o.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
|
|
154
|
-
`),1;try{h(r);}catch(
|
|
155
|
-
`),1}let n=
|
|
156
|
-
`),1;let
|
|
157
|
-
`),1;await
|
|
158
|
-
`),1}}async function
|
|
147
|
+
`)),process.exit(1);}});}function Kl(t){try{let e=C.join(t,"Makefile");return S.existsSync(e)?S.readFileSync(e,"utf8"):""}catch{return ""}}function et(t,e){let o=Kl(t);return o?new RegExp(`^${e}\\s*:`,"m").test(o):false}var lr=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureDotnetInstalled(e){return (await this.run("dotnet",["--version"],e)).exitCode===0?null:{exitCode:1,message:".NET SDK is not installed or not available on PATH. Install .NET 8+ from https://dotnet.microsoft.com/download and retry."}}findFilesBySuffix(e,o,r=3){let n=[],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>r)continue;let l=[];try{l=S.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let p of l){let f=C.join(c.dir,p.name);if(p.isDirectory()){i.has(p.name)||a.push({dir:f,depth:c.depth+1});continue}p.name.toLowerCase().endsWith(o.toLowerCase())&&n.push(f);}}return n.sort()}findProjectFile(e){let o=this.findFilesBySuffix(e,".csproj");return o.find(r=>!r.toLowerCase().includes(".tests.csproj"))||o[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(r=>r.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let o=await this.ensureDotnetInstalled(e);return o||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=await this.run("dotnet",r?["restore",r]:["restore"],e);return n.exitCode===0?n:{exitCode:n.exitCode,message:"dotnet restore failed. Check NuGet connectivity, package references, and .NET SDK workload availability, then retry."}}async runDev(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=r?["watch","--project",r,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",r?["test",r]:["test"],e)}async runBuild(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["build",r,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["run","--project",r]:["run"],e)}async runLint(e){if(et(e,"lint"))return this.run("make",["lint"],e);let o=C.join(e,"Directory.Build.props");if(S.existsSync(o)&&S.readFileSync(o,"utf-8").includes("EnforceCodeStyleInBuild")){let r=await this.ensureDotnetInstalled(e);if(r)return r;let n=this.findProjectFile(e);return this.run("dotnet",n?["build",n,"-warnaserror"]:["build","-warnaserror"],e)}return {exitCode:1,message:"No .NET lint tooling detected. Add a Makefile lint target or enable EnforceCodeStyleInBuild in Directory.Build.props."}}async runFormat(e){if(et(e,"format"))return this.run("make",["format"],e);let o=await this.ensureDotnetInstalled(e);return o||(S.existsSync(C.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 pr=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureGoInstalled(e){return (await this.run("go",["version"],e)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findGoRunTarget(e){let o=C.join(e,"main.go");if(S.existsSync(o))return "./main.go";let r=C.join(e,"cmd");try{let n=S.readdirSync(r,{withFileTypes:true}).filter(a=>a.isDirectory()).map(a=>a.name).sort();for(let a of n)if(S.existsSync(C.join(r,a,"main.go")))return `./cmd/${a}`}catch{}return "./."}findWorkspaceRoot(e){let o=e;for(;;){if(S.existsSync(C.join(o,".workspai-workspace"))||S.existsSync(C.join(o,".rapidkit-workspace")))return o;let r=C.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o$1=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o$1==="shared-runtime-caches"||o$1==="shared-node-deps"||o$1==="isolated")return o$1;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o(r,"policies.yml").find(a=>S.existsSync(a));if(!n)return "isolated";try{let c=S.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withGoCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=r==="shared-runtime-caches"?C.join(n||e,".workspai","cache","go"):C.join(e,".workspai","cache","go"),i=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=C.join(a,"mod"),process.env.GOCACHE=C.join(a,"build"),o().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&&S.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&S.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let o=await this.ensureGoInstalled(e);if(o)return o;let r=C.join(e,"Makefile");return S.existsSync(r)?this.run("make",["run"],e):this.run("go",["run",this.findGoRunTarget(e)],e)})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let r=(b()?[C.join(e,"server.exe"),C.join(e,"server")]:[C.join(e,"server")]).find(a=>S.existsSync(a));if(r)return this.run(r,[],e);let n=await this.ensureGoInstalled(e);return n||this.run("go",["run",this.findGoRunTarget(e)],e)})}async runLint(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(et(e,"lint")?this.run("make",["lint"],e):S.existsSync(C.join(e,".golangci.yml"))||S.existsSync(C.join(e,".golangci.yaml"))?this.run("golangci-lint",["run","./..."],e):{exitCode:1,message:"No Go lint tooling detected. Add a Makefile lint target or .golangci.yml configuration."})})}async runFormat(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(et(e,"fmt")?this.run("make",["fmt"],e):et(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 dr=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return (S.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return S.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let o=process.env.JAVA_HOME?.trim();if(!o)return "java";let r=C.join(o,"bin",process.platform==="win32"?"java.exe":"java");return S.existsSync(r)?r:"java"}parseMajorJavaVersion(e){if(!e)return null;let r=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(r,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let o=C.join(e,"pom.xml");if(!S.existsSync(o))return 21;try{let n=S.readFileSync(o,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,o){try{let r=await execa(e,["-version"],{cwd:o,timeout:5e3,reject:false});if(r.exitCode!==0)return null;let n=`${r.stdout||""}
|
|
148
|
+
${r.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 o=e.match(/Apache Maven\s+(\d+)\.(\d+)\.(\d+)/i);return o?[Number.parseInt(o[1],10),Number.parseInt(o[2],10),Number.parseInt(o[3],10)]:null}isMavenVersionAtLeast(e,o){for(let r=0;r<3;r+=1){if(e[r]>o[r])return true;if(e[r]<o[r])return false}return true}async checkSystemMavenVersion(e){try{let o=await execa("mvn",["-version"],{cwd:e,timeout:5e3,reject:false});if(o.exitCode!==0)return {exitCode:o.exitCode||1,message:"Maven is required and must be available on PATH (3.9+)."};let r=this.parseMavenVersion(`${o.stdout||""}
|
|
149
|
+
${o.stderr||""}`);return r?this.isMavenVersionAtLeast(r,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${r.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let o=S.existsSync(C.join(e,"pom.xml")),r=S.existsSync(C.join(e,"mvnw"))||S.existsSync(C.join(e,"mvnw.cmd")),n=S.existsSync(C.join(e,"build.gradle"))||S.existsSync(C.join(e,"build.gradle.kts"))||S.existsSync(C.join(e,"settings.gradle"))||S.existsSync(C.join(e,"settings.gradle.kts")),a=S.existsSync(C.join(e,"gradlew"))||S.existsSync(C.join(e,"gradlew.bat"));return {hasMavenProject:o||r,hasMavenWrapper:r,hasGradleProject:n||a,hasGradleWrapper:a}}findWorkspaceRoot(e){let o=e;for(;;){if(S.existsSync(C.join(o,".workspai-workspace"))||S.existsSync(C.join(o,".rapidkit-workspace")))return o;let r=C.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o$1=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o$1==="shared-runtime-caches"||o$1==="shared-node-deps"||o$1==="isolated")return o$1;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o(r,"policies.yml").find(a=>S.existsSync(a));if(!n)return "isolated";try{let c=S.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let o=C.join(e,"mvnw.cmd");if(process.platform==="win32"&&S.existsSync(o))return {command:o,baseArgs:[]};let r=C.join(e,"mvnw");return S.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let o=C.join(e,"gradlew.bat");if(process.platform==="win32"&&S.existsSync(o))return {command:o,baseArgs:[]};let r=C.join(e,"gradlew");return S.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let o=[],r=new Set,n=[e];for(;n.length>0;){let a=n.shift();if(!a||r.has(a))continue;r.add(a);let i=[];try{i=S.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 l=C.join(a,c.name),p=this.inspectJavaProject(l);(p.hasMavenProject||p.hasGradleProject)&&o.push(l),n.push(l);}}return o}withJavaCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=r==="shared-runtime-caches"?C.join(n||e,".workspai","cache","java","m2"):C.join(e,".workspai","cache","java","m2"),i=r==="shared-runtime-caches"?C.join(n||e,".workspai","cache","java","gradle"):C.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,l=process.env.GRADLE_USER_HOME,p=`-Dmaven.repo.local=${a}`;return process.env.MAVEN_OPTS=c?`${c} ${p}`:p,process.env.GRADLE_USER_HOME=i,o().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof l>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=l;})}async runBuildTool(e,o,r=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:a}=this.buildToolCommand(e),i=await this.runCommand(n,[...a,...o],e);if(i===0||!r)return {exitCode:i};let c=S.existsSync(C.join(e,"pom.xml")),l=S.existsSync(C.join(e,"build.gradle"))||S.existsSync(C.join(e,"build.gradle.kts"));return {exitCode:i,message:c||l?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let o=[C.join(e,"target"),C.join(e,"build","libs")];for(let r of o){if(!S.existsSync(r))continue;let a=S.readdirSync(r).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 C.join(r,a)}return null}commandArgsFor(e,o){if(e==="gradle"){let r=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return o==="init"?[...r,"dependencies"]:o==="dev"?[...r,"bootRun"]:o==="test"?[...r,"test"]:[...r,"bootJar"]}return o==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:o==="dev"?["spring-boot:run"]:o==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),o=this.resolveJavaCommand(e),r=await this.runCommand(o,["-version"],e);if(r!==0)return {exitCode:r,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),l=await this.detectInstalledJavaMajor(o,e);if(l!==null&&l<c)return {exitCode:1,message:`Detected Java ${l}, but project requires Java ${c}+.`};let p=C.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&S.existsSync(p))try{let d=S.readFileSync(p,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),y=this.parseMajorJavaVersion(d?.[1]);if(y!==null&&y<c)return {exitCode:1,message:`Detected JAVA_HOME version ${y}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),l=c==="gradle"?["--version"]:["-version"],p=await this.runBuildTool(e,l);return p.exitCode!==0?p:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):p}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let l=c.reduce((d,y)=>Math.max(d,this.readRequiredJavaMajor(y)),0);if(l>0){let d=await this.detectInstalledJavaMajor(o,e);if(d!==null&&d<l){let y=c.filter(h=>this.readRequiredJavaMajor(h)>d).map(h=>C.relative(e,h)).join(", ");return {exitCode:1,message:`Detected Java ${d}, but workspace project(s) [${y}] require Java ${l}+.`}}}let p=false,f=false;for(let d of c){let y=this.inspectJavaProject(d);y.hasMavenProject&&!y.hasMavenWrapper&&(p=true),y.hasGradleProject&&!y.hasGradleWrapper&&(f=true);}if(p){let d=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(d!==0)return {exitCode:d,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 y=await this.checkSystemMavenVersion(e);if(y.exitCode!==0)return y}if(f){let d=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(d!==0)return {exitCode:d,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 o=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return o&&S.mkdirSync(o,{recursive:true}),process.env.GRADLE_USER_HOME&&S.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let o=this.resolveJarPath(e);if(o)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",o],e)};let r=await this.runBuild(e);if(r.exitCode!==0)return r;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(et(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let o=C.join(e,"pom.xml");return S.existsSync(o)&&S.readFileSync(o,"utf-8").includes("checkstyle")?this.runBuildTool(e,["checkstyle:check"]):{exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){return et(e,"format")?{exitCode:await this.runCommand("make",["format"],e)}:["build.gradle","build.gradle.kts"].map(r=>C.join(e,r)).filter(r=>S.existsSync(r)).some(r=>S.readFileSync(r,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure spotless in Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run 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 ur=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}findWorkspaceRoot(e){let o=e;for(;;){if(S.existsSync(C.join(o,".workspai-workspace"))||S.existsSync(C.join(o,".rapidkit-workspace")))return o;let r=C.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o$1=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o$1==="shared-runtime-caches"||o$1==="shared-node-deps"||o$1==="isolated")return o$1;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o(r,"policies.yml").find(a=>S.existsSync(a));if(!n)return "isolated";try{let c=S.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,o,r){let n=this.resolveDependencyMode(e),a=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=n==="isolated"?C.join(e,".workspai","cache","node"):C.join(a||e,".workspai","cache","node"),c=process.env.npm_config_cache,l=process.env.npm_config_store_dir,p=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),o==="pnpm"?(process.env.npm_config_store_dir=C.join(i,"pnpm-store"),process.env.npm_config_cache=C.join(i,"pnpm-cache")):o==="yarn"?process.env.npm_config_cache=C.join(i,"yarn-cache"):process.env.npm_config_cache=C.join(i,"npm-cache"),r().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof l>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=l,typeof p>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=p,typeof f>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=f;})}detectPackageManager(e){if(S.existsSync(C.join(e,"package-lock.json")))return "npm";if(S.existsSync(C.join(e,"pnpm-lock.yaml")))return "pnpm";if(S.existsSync(C.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 S.existsSync(C.join(e,"package-lock.json"))||S.existsSync(C.join(e,"pnpm-lock.yaml"))||S.existsSync(C.join(e,"yarn.lock"))}availablePackageManagers(e){let o=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[o]:[o,...["npm","pnpm","yarn"].filter(n=>n!==o&&this.commandAvailable(n))]}commandAvailable(e){let o=e$7(e);return spawnSync(o.command,[...o.prefixArgs,"--version"],{stdio:"ignore",shell:c$7(),env:g$5()}).status===0}scriptArgs(e,o){return e==="npm"?["run-script",o,"--foreground-scripts"]:["run",o]}async runScriptWithFallback(e,o){let r={exitCode:1};for(let n of this.availablePackageManagers(e))if(r=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,o),e)),r.exitCode===0)return r;return r}async runLifecycle(e,o){let r=d$5(e),n=i$3(e,r),a=n$2(e,o,{framework:n.key});return a?this.runScriptWithFallback(e,a.scriptName):{exitCode:1,message:`No npm script available for \`${o}\`. Add a "${o}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let o=this.detectPackageManager(e);return this.withDependencyEnv(e,o,async()=>{try{return process.env.npm_config_cache&&S.mkdirSync(process.env.npm_config_cache,{recursive:true}),o==="pnpm"&&process.env.npm_config_store_dir&&S.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let o=this.detectPackageManager(e),r=this.resolveDependencyMode(e),n=r==="shared-runtime-caches"||r==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,o,()=>this.run(o,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var fr=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,o){return {exitCode:await this.withPythonCacheEnv(o,()=>this.runCore(e,o))}}findWorkspaceRoot(e){let o=e;for(;;){if(S.existsSync(C.join(o,".workspai-workspace"))||S.existsSync(C.join(o,".rapidkit-workspace")))return o;let r=C.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o$1=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o$1==="shared-runtime-caches"||o$1==="shared-node-deps"||o$1==="isolated")return o$1;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o(r,"policies.yml").find(a=>S.existsSync(a));if(!n)return "isolated";try{let c=S.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=r==="shared-runtime-caches"?C.join(n||e,".workspai","cache","python"):C.join(e,".workspai","cache","python"),i=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=C.join(a,"pip"),process.env.POETRY_CACHE_DIR=C.join(a,"poetry"),o().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(),o=await this.run(["doctor","check"],e);return o.exitCode===0?o:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx 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."]}};function Gl(){let t={...process.env},e=t.PATH||"";if(e){let o=e.split(C.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(C.delimiter);t.PATH=o;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||h$4(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ge(t,e){return t==="go"?new pr((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="node"?new ur((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="java"?new dr((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="dotnet"?new lr((o,r,n)=>e.runCommandInCwd(o,r,n)):new fr((o,r)=>e.runCoreRapidkit(o,{cwd:r,env:Gl()}))}var yi=C.join(Yr.homedir(),".workspai","cache"),wi=1440*60*1e3;function jn(){let t=a$b("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?C.join(yi,`vitest-${e}`):yi}var hr=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 C.join(jn(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let o=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${o}.tmp`}async get(e,o="1.0"){let r=this.memoryCache.get(e);if(r&&r.version===o&&Date.now()-r.timestamp<wi)return f.debug(`Cache hit (memory): ${e}`),r.data;try{let n=this.getCachePath(e),a=await promises.readFile(n,"utf-8"),i=JSON.parse(a);if(i.version===o&&Date.now()-i.timestamp<wi)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,o,r="1.0"){let n={data:o,timestamp:Date.now(),version:r};this.memoryCache.set(e,n);try{await promises.mkdir(jn(),{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 o=this.getCachePath(e);await promises.unlink(o),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=jn(),o=await promises.readdir(e);await Promise.all(o.map(r=>promises.unlink(C.join(e,r)))),f.debug("Cache cleared");}catch{}}};var go=["list","sync","registry","foundation","model","snapshot","diff","impact","verify","graph","watch","context","agent-sync","remediation-plan","explain","why","trace","feedback","mcp","policy","contract","share","export","archive","hydrate","import","run","init"],yr=["model","snapshot","diff","impact","contract","verify","graph","watch","context","agent-sync","remediation-plan","explain","why","trace","feedback","mcp"];function ki(t){return yr.includes(t)}var vi="workspai-project-entry-capability-v1";var Cn="workspai-cli-runtime-command-inventory-v1",wr=[...e$4,"autopilot","pipeline","import","adopt","snapshot","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands","create","project"],Sn=["bootstrap","setup","cache","mirror"],xn="create",ql=[...Sn,xn],zl={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."},kr=[["ai","generate-embeddings"],["ai","info"],["ai","recommend"],["ai","update-embeddings"],["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","archives"],["project","archive"],["project","restore"],["project","delete"],["snapshot","create"],["snapshot","inspect"],["snapshot","list"],["snapshot","restore"]];function Yl(t,e,o,r){let n=new Set(t),a=new Set(e),i=t.filter(y=>!a.has(y)).sort(),c=e.filter(y=>!n.has(y)).sort(),l=new Set(o),p=new Set(r),f=o.filter(y=>!p.has(y)).sort(),d=r.filter(y=>!l.has(y)).sort();return {ok:i.length===0&&c.length===0&&f.length===0&&d.length===0,registeredButUndeclared:i,declaredButUnregistered:c,registeredScopedButUndeclared:f,declaredScopedButUnregistered:d}}function Pi(t,e=[]){return t.commands.flatMap(o=>{let r=o.name(),n=[...e,r];return [{path:n,command:r,parent:e.length>0?e.join(" "):null,registrationKind:"commander",aliases:o.aliases?.()??[],description:o.description?.()??"",hidden:o._hidden===true,arguments:(o.registeredArguments??[]).map(i=>({name:i.name(),required:i.required,variadic:i.variadic})),options:(o.options??[]).map(i=>({flags:i.flags,attributeName:i.attributeName?.()??null}))},...Pi(o,n)]})}function bi(t){let e=Pi(t),o=e.filter(c=>c.path.length===1).map(c=>c.command),r=new Set(o),n=ql.filter(c=>!r.has(c)).map(c=>({path:[c],command:c,parent:null,registrationKind:"manual-handler",aliases:[],description:zl[c],hidden:false,arguments:[],options:[]})),a=[...e,...n].sort((c,l)=>c.path.join(" ").localeCompare(l.path.join(" "))),i=[...new Set(a.filter(c=>c.path.length===1).map(c=>c.command))].sort();return {schemaVersion:Cn,commands:a,topLevelCommands:i,integrity:Yl(i,wr,e.filter(c=>c.path.length>1).map(c=>c.path.join(" ")),kr.map(c=>c.join(" ")))}}function ji(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(o=>o!==null).join("; ")})`}var Ci="rapidkit-runtime-command-surface-v1";var Si="doctor-remediation-plan-v2";var xi="workspai-workspace-intelligence-architecture-v1";var Ei={autopilotRelease:"autopilot-release-v1",workspaceList:"rapidkit-workspace-list-v1",workspaceSync:"rapidkit-workspace-sync-v1",compatibilityMatrix:"rapidkit.compatibility-matrix.v1",mcpDesign:"workspai-mcp-design.v1",agentHooks:"workspai-agent-hooks.v1",projectArchive:"rapidkit-project-archive-v1",workspaceSnapshot:"rapidkit-workspace-snapshot-v1",workspaceSnapshotV2:"rapidkit-workspace-snapshot-v2",infraPlan:"rapidkit.infra-plan.v1",privateProductManifest:"rapidkit.private-product-manifest.v1",productFactoryPlan:"rapidkit.product-factory-plan.v1",workspaceModelCache:"workspace-model-cache.v1",workspaceWatchEvent:"workspace-watch-event.v1",doctorProjectScan:"doctor-project-scan-v2",doctorWorkspaceCache:"doctor-workspace-cache-v2"};var Ql="workspai-published-contract-catalog-v1";function ho(){return {runtimeCommandSurface:Ci,cliRuntimeCommandInventory:Cn,cliOperationResult:a$n,publishedContractCatalog:Ql,workspaceArchiveCapabilities:a$m,workspaceArchiveManifest:b$c,workspaceArchiveOperationResult:c$3,projectEntryCapability:vi,workspaceIntelligenceArchitecture:xi,workspaceIntelligenceChain:a$l,workspaceIntelligenceArtifacts:b$a,cliLogEvent:c$c,freshnessMetadata:a$k,factFreshness:c$b,blockerResolution:a$j,workspaceModel:j$1,workspaceImpact:f$8,workspaceVerify:c$a,workspaceContext:c$9,workspaceDependencyGraph:i$5,workspaceIntelligenceHistory:a$i,agentCustomizationPackCapabilities:l$3,agentCustomizationPackReport:b$a.agentCustomizationPack,agentReportsIndex:b$a.agentIndex,workspaceOperationalSkill:a$h,workspaceSkillsIndex:b$b,workspaceExplain:a$g,agentActionOutcome:a$f,doctorRemediationPlan:Si,artifactRemediationPlan:a$e,doctorFixResult:a$d,...Ei}}function vr(){let t=ho(),e={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",projectEntryCapability:"contracts/project-entry-capability.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",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",artifactRemediationPlan:"contracts/artifact-remediation-plan.v1.json",doctorFixResult:"contracts/workspace-intelligence/doctor-fix-result.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(([o,r])=>{let n=e[o];return [o,{schemaVersion:r,contractPath:n,publication:n?o==="runtimeCommandSurface"||o==="cliRuntimeCommandInventory"||o.endsWith("Capabilities")?"capability-contract":"json-schema":"embedded-type",...o==="workspaceIntelligenceArtifacts"?{artifacts:Object.fromEntries(Object.keys(a$c).map(a=>[a,{path:a$c[a],schemaVersion:b$a[a],contractPath:c$8[a]}]))}:{}}]}))}var En="rapidkit-command-capabilities-v1",Ri="rapidkit-version-v1";var Xl=["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"],Zl={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},ep={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"};function tp(t){return t[Math.floor(Math.random()*t.length)]}function Rn(t){let e=tp(Xl),o=k$2(t);if(o){let a=ep[o.id]??"app";return `${e}-${a}`}let r=a$3(t),n=r?Zl[r.id]??"service":"app";return `${e}-${n}`}async function sp(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function ap(t){if(!await R.pathExists(t))return [];let e=[],o=[t];for(;o.length>0;){let r=o.shift();if(r)for(let n of await promises.readdir(r,{withFileTypes:true})){let a=C.join(r,n.name);n.isFile()?e.push(a):n.isDirectory()&&o.push(a);}}return e}async function _i(t,e){await R.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
150
|
+
`,"utf-8");}function Be(t,e){return C.isAbsolute(e)?e:C.join(t,e)}function ip(t,e){if(t.target)return t.target;if(t.source)return C.basename(t.source);if(t.url)try{let o=new URL(t.url).pathname,r=C.basename(o);if(r&&r!=="/")return r}catch{}return `${e}.artifact`}async function cp(t){let e=o(t,"trusted-sources.lock").find(r=>existsSync(r)),o$1=new Set(["localhost","127.0.0.1"]);if(!e)return o$1;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)o$1.add(a.toLowerCase());}catch{}return o$1}async function lp(t,e,o){await R.ensureDir(C.dirname(e)),await new Promise((r,n)=>{let i=(t.startsWith("https://")?Mi:Ni).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let l=createWriteStream(e);c.pipe(l),l.on("finish",()=>{l.close(),r();}),l.on("error",p=>{n(p);});});i.setTimeout(o,()=>{i.destroy(new Error(`Request timeout after ${o}ms`));}),i.on("error",c=>{n(c);});});}async function pp(t,e,o,r,n){let a=new URL(t),i=JSON.stringify(e),c=a.protocol==="https:"?Mi:Ni;await new Promise((l,p)=>{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),...r?{Authorization:`Bearer ${r}`}:{},...n||{}}},d=>{if(!d.statusCode||d.statusCode<200||d.statusCode>=300){p(new Error(`HTTP ${d.statusCode||"unknown"}`)),d.resume();return}d.resume(),l();});f.setTimeout(o,()=>{f.destroy(new Error(`Request timeout after ${o}ms`));}),f.on("error",d=>{p(d);}),f.write(i),f.end();});}function Ai(t){return new Promise(e=>setTimeout(e,t))}async function dp(t,e,o,r){let n=Be(t,e||".workspai/reports/evidence-export-dead-letter.ndjson");return await R.ensureDir(C.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:r,payload:o})}
|
|
151
|
+
`,"utf-8"),n}function up(t,e){if(!e?.enabled)return {headers:{}};let o=process.env[e.hmacKeyEnv];if(!o)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let r=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(r,o).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":r}}}async function mp(t,e,o){let r=(o.algorithm||"sha256").toLowerCase(),n=Be(t,o.publicKeyPath);if(!await R.pathExists(n))return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(r);c.update(i),c.end();let l=Buffer.from(o.signature,"base64"),p=c.verify(a,l),f=createHash("sha256").update(a).digest("hex");return {verified:p,algorithm:r,publicKeyPath:n,publicKeyFingerprint:f,signature:o.signature,message:p?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Attestation verification error: ${a.message}`}}}async function fp(t,e,o,r){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};let a=o.signaturePath?Be(t,o.signaturePath):null;if(!a||!await R.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=o.certificatePath?Be(t,o.certificatePath):null;c&&i.push("--certificate",c);let l=o.bundlePath?Be(t,o.bundlePath):null;l&&i.push("--bundle",l);let p=o.keyPath?Be(t,o.keyPath):null;p&&i.push("--key",p),o.identity&&i.push("--certificate-identity",o.identity),o.issuer&&i.push("--certificate-oidc-issuer",o.issuer),o.rekorUrl&&i.push("--rekor-url",o.rekorUrl),r.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let f=await execa("cosign",i,{reject:false});return f.exitCode===0?{verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${f.stderr||f.stdout||"unknown error"}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}catch(f){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${f.message}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}}async function gp(t,e){let o=e.algorithm||"sha256",r=Be(t,e.policyPath),n=Be(t,e.signaturePath),a=Be(t,e.publicKeyPath);if(!await R.pathExists(r))return {verified:false,message:`Governance policy bundle not found: ${r}`,policies:null};if(!await R.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await R.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(r,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),l=await promises.readFile(a,"utf-8"),p=createVerify(o);return p.update(i),p.end(),p.verify(l,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 _n(t,e){let o$1=[],r={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=o(t,"mirror-config.json").find(N=>existsSync(N))??l(t,"mirror-config.json"),a=l(t,"mirror.lock"),i=l(t,"mirror","artifacts"),c=l(t,"reports"),l$1=await cp(t);if(!await R.pathExists(n))return o$1.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:o$1,details:r};let p={};try{p=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return o$1.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:o$1,details:r}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||p.mode==="offline-only"))return o$1.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:o$1,details:r};await R.ensureDir(i);let d=Math.max(0,p.prefetch?.retries??2),y=Math.max(0,p.prefetch?.backoffMs??250),h=Math.max(1e3,p.prefetch?.timeoutMs??15e3),k=p.security?.requireAttestation===true,j=p.security?.requireSigstore===true,_=p.security?.requireTransparencyLog===true,w=p.security?.requireSignedGovernance===true,m=p.security?.evidenceExport,g=(process.env.RAPIDKIT_ENV||p.security?.governance?.environment||"dev").toLowerCase(),v=p.security?.governance?.policies||{};if(p.security?.governanceBundle){let N=await gp(t,p.security.governanceBundle);if(o$1.push({id:"governance.bundle.verify",status:N.verified?"passed":"failed",message:N.message}),N.verified&&N.policies)v=N.policies,r.governanceBundleVerified=true;else if(w)return {checks:o$1,details:r}}let u=v[g],b=_||u?.requireTransparencyLog===true,P=[],x=Array.isArray(p.artifacts)?p.artifacts:[],A=[];for(let N=0;N<x.length;N+=1){let D=x[N],M=D.id||`artifact-${N+1}`,ue=D.source?Be(t,D.source):null,se=ip(D,M),Y=C.join(i,se),ee=false,Ee={sourceType:"path",source:ue||D.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(ue&&await R.pathExists(ue))await R.ensureDir(C.dirname(Y)),await promises.copyFile(ue,Y),r.syncedArtifacts+=1,ee=true,Ee={sourceType:"path",source:ue,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},o$1.push({id:`mirror.sync.${M}`,status:"passed",message:`Mirrored artifact ${M} from source path.`});else if(D.url){let _e="";try{_e=new URL(D.url).hostname.toLowerCase();}catch{o$1.push({id:`mirror.prefetch.${M}`,status:"failed",message:`Invalid URL for ${M}: ${D.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||l$1.has(_e))){o$1.push({id:`mirror.prefetch.trust.${M}`,status:"failed",message:`Untrusted mirror host for ${M}: ${_e}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await R.pathExists(Y)?(ee=true,Ee={sourceType:"url",source:D.url,host:_e,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},o$1.push({id:`mirror.prefetch.${M}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${M}.`})):o$1.push({id:`mirror.prefetch.${M}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${M} without an existing mirrored copy.`}),!ee))continue;if(!ee){let we=null,wt=0;for(let tt=1;tt<=d+1;tt+=1){wt=tt;try{await lp(D.url,Y,h),r.syncedArtifacts+=1,ee=true,Ee={sourceType:"url",source:D.url,host:_e,fetchedAt:new Date().toISOString(),attempts:wt,trusted:true},o$1.push({id:`mirror.prefetch.${M}`,status:"passed",message:wt>1?`Prefetched artifact ${M} from ${_e} after ${wt} attempts.`:`Prefetched artifact ${M} from ${_e}.`});break}catch(O){if(we=O,tt<=d){await Ai(y*tt);continue}}}if(!ee){o$1.push({id:`mirror.prefetch.${M}`,status:"failed",message:`Failed to prefetch ${M} after ${d+1} attempt(s): ${we?.message||"unknown error"}`});continue}}if(!ee){o$1.push({id:`mirror.prefetch.${M}`,status:"failed",message:`Failed to prefetch ${M}.`});continue}}if(!ee){D.required||e.offlineMode?o$1.push({id:`mirror.sync.${M}`,status:"failed",message:`Mirror source missing for ${M}${ue?`: ${ue}`:""}`}):o$1.push({id:`mirror.sync.${M}`,status:"skipped",message:`Mirror source not found for optional artifact ${M}.`});continue}let ze=await sp(Y);if(D.sha256&&D.sha256.toLowerCase()!==ze.toLowerCase()){o$1.push({id:`mirror.verify.${M}`,status:"failed",message:`Checksum mismatch for ${M}.`});continue}r.verifiedArtifacts+=1,o$1.push({id:`mirror.verify.${M}`,status:"passed",message:`Checksum verified for ${M}.`});let ye=D.attestation?await mp(t,Y,D.attestation):null;if(D.attestation){if(o$1.push({id:`mirror.attest.${M}`,status:ye?.verified?"passed":"failed",message:ye?.message||"Attestation verification failed."}),!ye?.verified)continue}else if(k){o$1.push({id:`mirror.attest.${M}`,status:"failed",message:`Attestation is required but missing for ${M}.`});continue}else o$1.push({id:`mirror.attest.${M}`,status:"skipped",message:`No attestation provided for ${M}.`});let Re=D.attestation?.sigstore,H=Re?await fp(t,Y,Re,{requireTransparencyLog:b}):null;if(Re){if(o$1.push({id:`mirror.sigstore.${M}`,status:H?.verified?"passed":"failed",message:H?.message||"Sigstore verification failed."}),P.push({artifactId:M,verified:!!H?.verified,tlogVerified:!!H?.tlogVerified,identity:H?.identity||null,issuer:H?.issuer||null,rekorUrl:H?.rekorUrl||null,timestamp:new Date().toISOString(),environment:g}),!H?.verified)continue}else if(j){o$1.push({id:`mirror.sigstore.${M}`,status:"failed",message:`Sigstore attestation is required but missing for ${M}.`});continue}else o$1.push({id:`mirror.sigstore.${M}`,status:"skipped",message:`No Sigstore attestation provided for ${M}.`});if(Re&&H?.verified&&u){let _e=u.allowedIdentities||[];if(_e.length>0){let we=!!H.identity&&_e.includes(H.identity);if(o$1.push({id:`mirror.sigstore.policy.identity.${M}`,status:we?"passed":"failed",message:we?`Sigstore identity policy passed for ${M} in ${g}.`:`Sigstore identity policy failed for ${M} in ${g}.`}),!we)continue}let Co=u.allowedIssuers||[];if(Co.length>0){let we=!!H.issuer&&Co.includes(H.issuer);if(o$1.push({id:`mirror.sigstore.policy.issuer.${M}`,status:we?"passed":"failed",message:we?`Sigstore issuer policy passed for ${M} in ${g}.`:`Sigstore issuer policy failed for ${M} in ${g}.`}),!we)continue}let At=u.allowedRekorUrls||[];if(At.length>0){let we=!!H.rekorUrl&&At.includes(H.rekorUrl);if(o$1.push({id:`mirror.sigstore.policy.rekor.${M}`,status:we?"passed":"failed",message:we?`Sigstore Rekor policy passed for ${M} in ${g}.`:`Sigstore Rekor policy failed for ${M} in ${g}.`}),!we)continue}}else u&&o$1.push({id:`mirror.sigstore.policy.${M}`,status:"skipped",message:`Sigstore governance policy configured for ${g} but no verified Sigstore attestation for ${M}.`});let Le=await promises.stat(Y);A.push({id:M,path:C.relative(t,Y),sha256:ze,size:Le.size,provenance:Ee,attestation:{detached:{provided:!!D.attestation,verified:ye?.verified||false,algorithm:ye?.algorithm||null,publicKeyPath:ye?.publicKeyPath||null,publicKeyFingerprint:ye?.publicKeyFingerprint||null,signature:ye?.signature||null,verifiedAt:ye?.verified?new Date().toISOString():null},sigstore:{provided:!!Re,verified:H?.verified||false,tlogVerified:H?.tlogVerified||false,identity:H?.identity||null,issuer:H?.issuer||null,rekorUrl:H?.rekorUrl||null,bundlePath:H?.bundlePath||null,certificatePath:H?.certificatePath||null,signaturePath:H?.signaturePath||null,verifiedAt:H?.verified?new Date().toISOString():null}}});}let I=p.retention?.keepLast;if(typeof I=="number"&&I>0){let N=new Set(A.map(M=>C.resolve(t,M.path))),D=(await ap(i)).filter(M=>!N.has(C.resolve(M)));if(D.length>I){let M=await Promise.all(D.map(async se=>({filePath:se,stat:await promises.stat(se)})));M.sort((se,Y)=>Y.stat.mtimeMs-se.stat.mtimeMs);let ue=M.slice(I);for(let se of ue)await promises.unlink(se.filePath),r.rotatedFiles+=1;}}o$1.push({id:"mirror.rotate",status:"passed",message:r.rotatedFiles>0?`Mirror retention rotation removed ${r.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let W={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:p.mode||null,environment:g,artifacts:A};if(await promises.writeFile(a,`${JSON.stringify(W,null,2)}
|
|
152
|
+
`,"utf-8"),r.lockWritten=true,o$1.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${C.relative(t,a)}.`}),r.transparencyEvidenceRecords=P.length,P.length>0){let N={schemaVersion:"1.0",generatedAt:new Date().toISOString(),environment:g,records:P},D=new Date().toISOString().replace(/[:.]/g,"-"),M=C.join(c,`transparency-evidence-${D}.json`),ue=C.join(c,"transparency-evidence.latest.json");if(await R.ensureDir(c),await _i(M,N),await _i(ue,N),r.transparencyEvidenceWritten=true,o$1.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${C.relative(t,ue)}.`}),m?.enabled){let se=Math.max(1e3,m.timeoutMs??1e4);if(m.target==="file")if(!m.filePath)o$1.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let Y=Be(t,m.filePath);await R.ensureDir(C.dirname(Y)),await promises.appendFile(Y,`${JSON.stringify(N)}
|
|
153
|
+
`,"utf-8"),r.evidenceExported=true,r.evidenceExportTarget=Y,o$1.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${Y}.`});}catch(Y){o$1.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${Y.message}`});}else if(m.target==="http")if(!m.endpoint)o$1.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let Y=Math.max(0,m.retries??0),ee=Math.max(0,m.backoffMs??500),Ee=up(N,m.signing);Ee.error&&o$1.push({id:"sigstore.evidence.export.http",status:"failed",message:Ee.error});try{let ze=m.authTokenEnv?process.env[m.authTokenEnv]:void 0,ye=false,Re=null;for(let H=1;H<=Y+1;H+=1)try{if(Ee.error)throw new Error(Ee.error);await pp(m.endpoint,N,se,ze,Ee.headers),r.evidenceExported=true,r.evidenceExportTarget=m.endpoint,o$1.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}.`}),ye=true;break}catch(Le){Re=Le,H<=Y&&await Ai(ee*H);}if(!ye)throw Re||new Error("unknown evidence export error")}catch(ze){let ye=`Evidence HTTP export failed: ${ze.message}`;o$1.push({id:"sigstore.evidence.export.http",status:"failed",message:ye});try{let Re=await dp(t,m.deadLetterPath,N,ye);o$1.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${Re}.`});}catch(Re){o$1.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${Re.message}`});}}}if(m.failOnError&&o$1.some(ee=>ee.status==="failed"&&(ee.id==="sigstore.evidence.export.file"||ee.id==="sigstore.evidence.export.http")))return {checks:o$1,details:r}}else o$1.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else o$1.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),o$1.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:o$1,details:r}}function Pr(t){let e=a$p(t.detection.runtime),o=o$3({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),r=[];r.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"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}),r.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),r.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit 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."}),r.push({id:"lifecycle-commands",status:o.lifecycleCommands.length>1?"pass":"warn",message:o.lifecycleCommands.length>1?`Lifecycle commands available: ${o.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:o.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=r.some(i=>i.status==="fail"),a=r.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:o.lifecycleCommands,unsupportedLifecycleCommands:o.unsupportedLifecycleCommands,moduleCommands:o.moduleCommands},checks:r}}function hp(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function br(t){if(t.existingProjectJson?.module_support===true){let e=hp(t.existingProjectJson),o=e?a$3(e):void 0;return o?.owner==="core"&&o.moduleSupport===true}return false}function Ti(t){return t.replace(/\\/g,"/")}function yp(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function wp(t,e){let o=Ti(C.relative(t,e));return !o||o.startsWith("..")?true:o.split("/").filter(Boolean).some(r=>r==="..")}function yo(t){let e=Ti(C.relative(t.workspacePath,t.projectPath)),o=wp(t.workspacePath,t.projectPath),r=yp(t.projectName,C.basename(t.projectPath)),n=o?`external/${r}`:e||r;return {relativePath:e||n,contractRelativePath:n,isExternal:o}}var Li={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},Pp={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"},bp={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},Wi=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function In(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function $n(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function wo(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 jr(t){let e=new Set;for(let o of t)e.add(wo(o));return [...e].sort((o,r)=>Wi.indexOf(o)-Wi.indexOf(r))}function jp(t){let e=jr(t).filter(o=>o!=="unknown");if(e.length!==0)return e.length===1?bp[e[0]]:"polyglot"}function Di(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function Cp(t,e){return t?"none":e==="strict"?"error":"warning"}function ko(t){let e=t.ok?void 0:jp(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?Di(e):void 0,ciRecommendedCommand:e?Di(e,{ci:true}):void 0,severity:Cp(t.ok,t.mode)}}function St(t){let e=$n(t.profile),o=jr(t.runtimes),r=t.mode??"warn",n=Li[e];if(n){let a=o.length===0||o.every(i=>In(i)===n);return ko({ok:a,checkId:`profile.${e}`,profile:e,runtimes:o,message:a?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${o.join(", ")}].`,mode:r})}if(e==="minimal"){let a=o.filter(l=>l!=="unknown"),c=new Set(a.map(l=>In(l))).size<=1;return ko({ok:c,checkId:"profile.minimal",profile:e,runtimes:o,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${a.join(", ")}].`,mode:r})}return ko({ok:true,checkId:`profile.${e}`,profile:e,runtimes:o,message:`${e} profile accepts the detected runtime mix.`,mode:r})}function ht(t){let e=$n(t.profile),o=wo(t.runtime),r=t.mode??"warn",n=Li[e];if(!n||o==="unknown")return ko({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[o],message:o==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:r});let a=In(o)===n;return ko({ok:a,checkId:`profile.${e}`,profile:e,runtimes:a?[o]:jr([n,o]),message:a?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${Pp[o]}, but workspace profile is "${e}".`,mode:r})}async function qt(t){let e=(await Promise.all(o(t,"policies.yml").map(async o=>await R__default.pathExists(o)?o:null))).find(o=>typeof o=="string");if(!e)return "warn";try{return (await R__default.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function zt(t){let e=(await Promise.all(o(t,"workspace.json").map(async o=>await R__default.pathExists(o)?o:null))).find(o=>typeof o=="string");if(!e)return "minimal";try{let o=await R__default.readJson(e);return $n(o.profile)}catch{return "minimal"}}async function xt(t,e={}){let o=new Set,r=[],n=new Set,a=[t];for(;a.length>0;){let i=a.pop();if(!i||n.has(i))continue;n.add(i);let c=[];try{c=await S.promises.readdir(i,{withFileTypes:true});}catch{continue}for(let l of c){if(!l.isDirectory()||l.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(l.name))continue;let p$1=C.join(i,l.name);if(p$1!==t&&f$7(p$1))continue;if((await Promise.all([...p(p$1,"context.json"),...p(p$1,"project.json")].map(async d=>R__default.pathExists(d)))).some(Boolean)){r.push(p$1);continue}a.push(p$1);}}for(let i of r){let c=d$5(i);o.add(wo(i$3(i,c).runtime));}for(let i of await a$o(t))o.add(wo(i.runtime));for(let i of e.additionalRuntimes??[])o.add(wo(i));return jr(o)}function Cr(t,e={}){let o=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return o?`Recommended: ${o}`:null}function Fi(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function xp(t){let e=t.trim();if(!e)return "imported-project";let o=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),r=o[o.length-1]||e,n=r.split(":"),a=(n[n.length-1]||r).replace(/\.git$/i,"");return Fi(a)||"imported-project"}function On(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function Ep(t){return On(t)?"git-url":"local-folder"}async function Rp(t,e){let o=Fi(e)||"imported-project",r=0;for(;;){let n=r===0?o:r===1?`${o}-imported`:`${o}-imported-${r}`,a=C.join(t,n);if(!await R__default.pathExists(a))return a;r+=1;}}function _p(t,e){let o=C.resolve(t),r=C.resolve(e),n=C.relative(o,r);return n===""||n.length>0&&!n.startsWith("..")&&!C.isAbsolute(n)}function Ap(t,e){if(_p(t,e))throw new Error("Import source must be outside the current workspace root.")}function Ip(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}function $p(t){let e=C.basename(t);return !([".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor","packages"].includes(e)||Ip(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Op(t){for(let e of p(t,"project.json"))if(await R__default.pathExists(e))try{return await R__default.readJson(e)}catch{return null}return null}async function Np(t){let e=new Date().toISOString(),o=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:C.basename(t.projectPath),r=yo({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:o}),n=r.contractRelativePath,a=q$1(t.projectPath,"project.json"),i=q$1(t.projectPath,"import.json"),c=q$1(t.projectPath,"import-readiness.json"),l=br({existingProjectJson:t.existingProjectJson}),p=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:[]},d={...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:C.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:C.basename(t.projectPath),kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:l,modules:p,contracts:f,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:r.relativePath,is_external:r.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},y={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:C.basename(t.projectPath)},project:{name:d.name,slug:d.slug,relative_path:n,kind:t.projectKind,module_support:l},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:l,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}}},h=Pr({projectName:String(d.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:l,projectPath:t.projectPath,generatedAt:new Date(e)});return await R__default.ensureDir(C.dirname(a)),await R__default.writeJson(a,d,{spaces:2}),await R__default.writeJson(i,y,{spaces:2}),await R__default.writeJson(c,h,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:l}}async function Mp(t,e){let o={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,importedAt:new Date().toISOString()};await b$9(t,[o]);}async function Ji(t){await R__default.pathExists(t)&&await R__default.remove(t);}async function Vi(t,e){await Ji(e),await c$5(t,[e]);}async function Ki(t){let e=C.resolve(t.workspacePath),o=t.source.trim(),r=t.sourceType??Ep(o),n=t.name??(r==="git-url"?xp(o):C.basename(o)),a=await Rp(e,n),i=false;try{if(r==="local-folder"){let m=C.resolve(o),g=await R__default.stat(m).catch(()=>null);if(!g||!g.isDirectory())throw new Error("Import source is not a directory.");if(f$7(m))throw new Error("This is a workspace. Import it as a workspace instead.");Ap(e,m),i=true,await R__default.copy(m,a,{overwrite:false,errorOnExist:true,filter:$p});}else i=true,await execa("git",["clone","--depth","1",o,a],{timeout:12e4,env:a$9()});let c=await Op(a),l=i$3(a,c),p=await h$3(a,c),[f,d]=await Promise.all([zt(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):qt(e)]),y=ht({profile:f,runtime:l.runtime,subjectLabel:C.basename(a),mode:d}),h=St({profile:f,runtimes:await xt(e,{additionalRuntimes:[l.runtime]}),mode:d}),k=y.ok?h:y;if(!k.ok&&d==="strict")throw new Error(k.message);let j=await Np({workspacePath:e,projectPath:a,sourceType:r,detection:l,existingProjectJson:c,projectKind:p,profileCompatibility:k}),_=yo({workspacePath:e,projectPath:a,projectName:C.basename(a)}),w={name:C.basename(a),path:a,relativePath:_.contractRelativePath,stack:l.importStack,runtime:l.runtime,framework:l.key,frameworkDisplayName:l.displayName,supportTier:l.supportTier,moduleSupport:j.moduleSupport,confidence:l.confidence,source:r,projectJsonPath:j.projectJsonPath,importJsonPath:j.importJsonPath,importReadinessPath:j.importReadinessPath,profileCompatibility:k};return await Mp(e,w),w}catch(c){if(i)try{await Ji(a);}catch(l){let p=c instanceof Error?c.message:String(c),f=l instanceof Error?l.message:String(l);throw new Error(`Import failed: ${p}. Rollback also failed: ${f}`)}throw c}}function Tp(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Wp(t,e){return C.resolve(t)===C.resolve(e)}async function Dp(t){for(let e of p(t,"project.json"))if(await R__default.pathExists(e))try{return await R__default.readJson(e)}catch{return null}return null}function Lp(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],o=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:o,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,discovered_relative_path:t.discoveredRelativePath,is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function Ui(t,e,o){let r=p(e,"project.json"),n=q$1(e,"project.json"),a=p(e,"adopt.json"),i=p(e,"adopt-readiness.json");if(o)await R__default.ensureDir(C.dirname(n)),await R__default.writeJson(n,o,{spaces:2});else for(let l of r)await R__default.pathExists(l)&&await R__default.remove(l);for(let l of a)await R__default.pathExists(l)&&await R__default.remove(l);for(let l of i)await R__default.pathExists(l)&&await R__default.remove(l);let{removeImportedProjectsRegistryEntries:c}=await import('./imported-projects-registry-FOIE27WT.js');await c(t,[e]);}async function Gi(t){let e=C.resolve(t.workspacePath),o=C.resolve(t.source),r=await R__default.stat(o).catch(()=>null);if(!r||!r.isDirectory())throw new Error("Adopt source is not a directory.");if(Wp(e,o))throw new Error("Adopt source cannot be the workspace root itself.");if(f$7(o))throw new Error("This is a workspace. Import it as a workspace instead.");let n=await Dp(o),a=i$3(o,n),i=await h$3(o,n),c=Tp(t.name||(typeof n?.name=="string"?n.name:"")||C.basename(o))||"adopted-project",l=yo({workspacePath:e,projectPath:o,projectName:c}),p=(t.now??new Date).toISOString(),f=q$1(o,"project.json"),d=q$1(o,"adopt.json"),y=q$1(o,"adopt-readiness.json"),h=br({existingProjectJson:n}),[k,j]=await Promise.all([zt(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):qt(e)]),_=ht({profile:k,runtime:a.runtime,subjectLabel:c,mode:j}),w=St({profile:k,runtimes:await xt(e,{additionalRuntimes:[a.runtime]}),mode:j}),m=_.ok?w:_;if(!m.ok&&j==="strict")throw new Error(m.message);let g=Lp({projectName:c,contractRelativePath:l.contractRelativePath,isExternal:l.isExternal,discoveredRelativePath:l.relativePath,detection:a,existingProjectJson:n,projectKind:i,moduleSupport:h,adoptedAt:p}),v={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:p,managed_by:"workspai",mode:"linked",workspace:{path:e},project:{name:c,path:o,relative_path:l.contractRelativePath,discovered_relative_path:l.relativePath,is_external:l.isExternal,kind:i,module_support:h},detection:{framework:a.key,framework_display_name:a.displayName,runtime:a.runtime,kind:i,confidence:a.confidence,support_tier:a.supportTier,import_stack:a.importStack,source:a.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:h,workspace_contract:"linked-project",profile_compatibility:{ok:m.ok,profile:m.profile,runtimes:m.runtimes,message:m.message,recommended_profile:m.recommendedProfile,recommended_command:m.recommendedCommand}}},u=Pr({projectName:c,relativePath:l.contractRelativePath,projectKind:i,source:"adopted-local",detection:a,moduleSupport:h,projectPath:o,generatedAt:new Date(p)});if(t.dryRun!==true){await R__default.ensureDir(C.dirname(f)),await R__default.writeJson(f,g,{spaces:2}),await R__default.writeJson(d,v,{spaces:2}),await R__default.writeJson(y,u,{spaces:2});let b={name:c,path:o,relativePath:l.contractRelativePath,relationship:"adopted",stack:a.importStack,runtime:a.runtime,framework:a.key,frameworkDisplayName:a.displayName,supportTier:a.supportTier,moduleSupport:h,confidence:a.confidence,source:"adopted-local",importedAt:p};await b$9(e,[b]);}return {name:c,path:o,relativePath:l.relativePath,contractRelativePath:l.contractRelativePath,isExternal:l.isExternal,relationship:"adopted",stack:a.importStack,runtime:a.runtime,framework:a.key,frameworkDisplayName:a.displayName,supportTier:a.supportTier,moduleSupport:h,confidence:a.confidence,projectJsonPath:f,adoptJsonPath:d,adoptReadinessPath:y,profileCompatibility:m,wroteFiles:t.dryRun!==true}}var Vp=kr,Kp=wr;function Nn(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 Up(t=process.argv){let e=C.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function Qt(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function Gp(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function be(t,e){let o=t.indexOf(e);if(o>=0&&o+1<t.length)return t[o+1];let r=t.find(n=>n.startsWith(`${e}=`));if(r)return r.slice(e.length+1)}function Bp(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 o=Number(e);if(!Number.isSafeInteger(o)||o<1||o>16)throw new Error("--max-workers must be an integer between 1 and 16.");return o}function Fn(t){try{return Bp(t.raw)}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$2({operation:t.operation,code:"cli.option.max-workers.invalid",message:o,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${o}`)),process.exit(1);}}async function qn(t,e){let o=be(t,"--port")?.trim(),r=t[3];if(!o||!r||!/^\d+$/.test(o))return;let n=Number.parseInt(o,10);if(n<1||n>65535)return;let a=be(t,"--output")||".",i=C.resolve(e,a,r),c=p(i,"project.json").find(p=>S.existsSync(p))??q$1(i,"project.json");if(!await R__default.pathExists(c))return;let l=await R__default.readJson(c);await R__default.writeJson(c,{...l,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Hi(t){let e=re(process.cwd()),o=t.trim().toLowerCase();if(!e||!o)return true;try{let[r,n]=await Promise.all([zt(e),qt(e)]),a=a$3(o),c=k$2(o)?"node":a?.runtime??"python",l=ht({profile:r,runtime:c,subjectLabel:o,mode:n}),p=St({profile:r,runtimes:await xt(e,{additionalRuntimes:[c]}),mode:n}),f=l.ok?p:l;if(f.ok)return true;let d=Cr(f);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${f.message}`)),d&&console.log(s.gray(`\u{1F4A1} ${d}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${f.message}`)),d&&console.log(s.gray(`\u{1F4A1} ${d}`));}catch{}return true}function zn(){return i$7()}function qi(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(C.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(C.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=h$4()),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 Hp(t){return l$4(C.join(t,".venv"))}async function pc(t,e){return await Q(t,["--version"],e)===0}async function _t(t){let e=C.join(t,"go.mod");if(await R__default.pathExists(e))return "go";let o=C.join(t,"pom.xml"),r=C.join(t,"build.gradle"),n=C.join(t,"build.gradle.kts");if(await R__default.pathExists(o)||await R__default.pathExists(r)||await R__default.pathExists(n))return "java";if((await R__default.pathExists(t)?await S.promises.readdir(t,{withFileTypes:true}):[]).some(d=>d.isFile()&&d.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=C.join(t,"src");if(await R__default.pathExists(i)&&(await S.promises.readdir(i,{withFileTypes:true})).some(y=>y.isFile()&&y.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=C.join(t,"package.json");if(await R__default.pathExists(c))return "node";let l=C.join(t,"pyproject.toml"),p=C.join(t,"requirements.txt"),f=C.join(t,"poetry.lock");return await R__default.pathExists(l)||await R__default.pathExists(p)||await R__default.pathExists(f)?"python":null}async function qp(t){for(let e of zn())if(await Q(e,e==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function dc(t){for(let e of zn())if(await Q(e,e==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function zp(t){let e=l$4(C.join(t,".venv"));if(!await R__default.pathExists(e)){let a=await dc(t);if(a!==0)return a}if(!await pc("poetry",t))return 0;let r=await Q("poetry",["config","virtualenvs.in-project","true","--local"],t);if(r!==0)return r;let n=await Q("poetry",["env","use",e],t);return n!==0?n:0}async function Yp(t){let e=l$4(C.join(t,".venv"));if(!await R__default.pathExists(e)){let n=await dc(t);if(n!==0)return n}await Q(e,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let o=C.join(t,"requirements.txt");if(await R__default.pathExists(o)&&await Q(e,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let r=C.join(t,"pyproject.toml");return await R__default.pathExists(r)&&(await Q(e,["-m","pip","install","-e","."],t)===0||await Q(e,["-m","pip","install","."],t)===0)?0:1}async function Mn(t,e){return await zp(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await R__default.pathExists(C.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await Yp(t))}async function Tn(t){let e=await Rt("init",t);if(e===0)return 0;let o=["npm","pnpm","yarn"];for(let r of o){if(!await pc(r,t))continue;if(await Q(r,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${r} install`)),0}return e}function Qp(t,e){let o=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),r=be([...e],"--port");if(r&&!/^\d+$/.test(r.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=be([...e],"--java-version"),a=be([...e],"--spring-boot-version"),i=be([...e],"--springdoc-version"),c=be([...e],"--group-id"),l=be([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!o(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!o(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(l&&!/^[A-Za-z0-9_.-]+$/.test(l.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=be([...e],"--target-framework"),a=be([...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 Jn(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],o=a$3(e),r=t[3];if(!o||o.owner!=="npm")return 1;if(!r)return process.stderr.write(`Usage: ${o.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
|
|
154
|
+
`),1;try{h(r);}catch(p){let f=p instanceof Error?p.message:String(p);return process.stderr.write(`${f}
|
|
155
|
+
`),1}let n=Qp(o.id,t);if(n)return process.stderr.write(`${n}
|
|
156
|
+
`),1;let a=be(t,"--output")||process.cwd(),i=C.resolve(a,r),c=t.includes("--skip-git")||t.includes("--no-git"),l=t.includes("--skip-install");try{let{default:p}=await import('fs-extra');if(await p.ensureDir(C.dirname(i)),await p.pathExists(i))return process.stderr.write(`\u274C Directory "${i}" already exists
|
|
157
|
+
`),1;await p.ensureDir(i),await e$3(o,{projectName:r,projectPath:i,args:t,skipGit:c,skipInstall:l}),await qn(t,process.cwd());let f=re(process.cwd());if(f){let{syncWorkspaceProjects:d}=await import('./workspace-PLXOO6ST.js');await d(f,true);}return 0}catch(p){return process.stderr.write(`Workspai ${o.id} generator failed: ${p?.message??p}
|
|
158
|
+
`),1}}async function zi(t){let e=k$2(t[2]);if(!e)return 1;try{let o=await o$2({args:t});if(!o.dryRun){let r=re(process.cwd()),n=false;r||(r=(await Yn()).workspacePath,n=true);let{registerProjectInWorkspace:a,registerWorkspace:i,syncWorkspaceProjects:c}=await import('./workspace-PLXOO6ST.js'),l=i$6({workspacePath:r,result:o});await i(r,C.basename(r)),await b$9(r,[l]),await a(r,o.projectName,o.projectPath),await c(r,true),await it(r,{silent:true}),n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${e$5}" (${l.relationship}).`)),console.log(s.gray(` Registry: ${C.join(p$2(),"workspaces.json")}`)),console.log(s.gray(" Tip: run from inside a workspace next time, or create one with `workspai create workspace`.")));}return 0}catch(o){return process.stderr.write(`Workspai ${e.kitId} generator failed: ${o?.message??o}
|
|
159
159
|
`),t[3]||process.stderr.write(`Usage: ${n$1(e.id)}
|
|
160
|
-
`),1}}async function
|
|
160
|
+
`),1}}async function Sr(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\`.
|
|
161
161
|
Reason: ${e}.
|
|
162
162
|
Install Python 3.10+ to use the interactive wizard and full kit catalog.
|
|
163
|
-
`),1;let n=t[2],
|
|
163
|
+
`),1;let n=t[2],a=t[3];if(!n||!a)return process.stderr.write(`Usage: npx workspai create project <kit> <name> [--output <dir>]
|
|
164
164
|
Tip: offline fallback supports only fastapi* and nestjs* kits.
|
|
165
|
-
`),1;let
|
|
165
|
+
`),1;let i=Gp(n);if(!i)return process.stderr.write(`Workspai CLI could not run the Python core engine to create this kit.
|
|
166
166
|
Reason: ${e}.
|
|
167
167
|
Requested kit: ${n}
|
|
168
168
|
Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
|
|
169
169
|
Install Python 3.10+ to access all kits.
|
|
170
|
-
`),1;let c=
|
|
171
|
-
`),1;let d="pip",
|
|
172
|
-
`),1}}function
|
|
170
|
+
`),1;let c=be(t,"--output")||process.cwd(),l=C.resolve(c,a),p=t.includes("--skip-git")||t.includes("--no-git"),f$1=t.includes("--skip-install");try{if(await R__default.ensureDir(C.dirname(l)),await R__default.pathExists(l))return process.stderr.write(`\u274C Directory "${l}" already exists
|
|
171
|
+
`),1;let d="pip",y=re(process.cwd());if(y)try{let{readWorkspaceMarker:k}=await import('./workspace-marker-SMBC3Z2Q.js'),j=await k(y);j?.metadata?.npm?.installMethod&&(d=j.metadata.npm.installMethod,f.debug(`Detected workspace engine: ${d}`));}catch(k){f.debug("Failed to read workspace marker",k);}else f.debug("No workspace found, using default engine: pip");await R__default.ensureDir(l);let{generateDemoKit:h}=await import('./demo-kit-DZ7TPG7K.js');if(await h(l,{project_name:a,template:i,kit_name:n,skipGit:p,skipInstall:f$1,engine:d}),await qn(t,process.cwd()),y){let{syncWorkspaceProjects:k}=await import('./workspace-PLXOO6ST.js');await k(y,true),await it(y,{silent:true});}return 0}catch(d){return process.stderr.write(`Workspai CLI offline fallback failed: ${d?.message??d}
|
|
172
|
+
`),1}}function Xp(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("Workspai native create is not available for this request yet.")}
|
|
173
173
|
`),process.stderr.write(s.gray(`Requested: ${e}
|
|
174
174
|
`)),process.stderr.write(s.gray(`Lane: ${t.lane} (${t.status})
|
|
175
175
|
`)),process.stderr.write(s.gray(`Reason: ${t.reason}
|
|
176
|
-
`)),t.officialCommands?.length){process.stderr.write(s.gray(`
|
|
176
|
+
`)),t.officialCommands?.length){process.stderr.write(s.gray(`Official generator candidates:
|
|
177
177
|
`));for(let o of t.officialCommands)process.stderr.write(s.gray(` - ${o}
|
|
178
|
-
`));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx workspai adopt <project-path>` to add Workspace Intelligence.\n"));}function
|
|
178
|
+
`));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx workspai adopt <project-path>` to add Workspace Intelligence.\n"));}function Yi(){console.log(`Usage: npx workspai create project <kit> <name> [options]
|
|
179
179
|
|
|
180
180
|
Scaffold a project and register it with Workspace Intelligence.
|
|
181
181
|
|
|
@@ -206,7 +206,7 @@ Options:
|
|
|
206
206
|
|
|
207
207
|
Notes:
|
|
208
208
|
Python-backed kits delegate execution to RapidKit Core when needed, but the
|
|
209
|
-
Workspai CLI owns the command UX, workspace registration, and artifacts.`);}function
|
|
209
|
+
Workspai CLI owns the command UX, workspace registration, and artifacts.`);}function Zp(){console.log(`Usage: npx workspai create workspace [name] [options]
|
|
210
210
|
|
|
211
211
|
Create a Workspai workspace and initialize Workspace Intelligence files.
|
|
212
212
|
|
|
@@ -230,7 +230,7 @@ Mental model:
|
|
|
230
230
|
\u2193
|
|
231
231
|
Workspace Intelligence
|
|
232
232
|
\u2193
|
|
233
|
-
Developers \xB7 CI \xB7 IDEs \xB7 AI Agents`);}function
|
|
233
|
+
Developers \xB7 CI \xB7 IDEs \xB7 AI Agents`);}function ed(){console.log(`Usage: npx workspai create <workspace|project> [options]
|
|
234
234
|
|
|
235
235
|
Create a workspace or scaffold a project into Workspace Intelligence.
|
|
236
236
|
|
|
@@ -243,75 +243,74 @@ Shortcuts:
|
|
|
243
243
|
|
|
244
244
|
Run:
|
|
245
245
|
npx workspai create workspace --help
|
|
246
|
-
npx workspai create project --help`);}function
|
|
246
|
+
npx workspai create project --help`);}function td(t){let e=t[2]??"<kit>",o=t[3]??"<name>",r=be(t,"--output")||process.cwd();console.log("Workspai create project dry run"),console.log(` kit: ${e}`),console.log(` name: ${o}`),console.log(` output: ${C.resolve(r)}`),console.log(" execution: RapidKit Core bridge"),console.log(" writes: none"),console.log(""),console.log("Run without --dry-run to scaffold the project.");}async function uc(t){if(t[0]==="create"&&(t.includes("--help")||t.includes("-h")||t.includes("help")))return t[1]==="project"?Yi():t[1]==="workspace"?Zp():ed(),0;let e$1=t[0]==="create"&&t[1]==="frontend",o=m$1(t);if(o&&(t=o),e$1&&!l$2(t[2]))return process.stderr.write(`Unknown frontend generator: ${t[2]?.replace(/^frontend\./,"")}
|
|
247
247
|
`),process.stderr.write(`Usage: ${n$1()}
|
|
248
|
-
`),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return
|
|
249
|
-
`),1;try{h(
|
|
250
|
-
`),1;throw
|
|
251
|
-
`),
|
|
252
|
-
`),1;let
|
|
253
|
-
`),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return
|
|
254
|
-
`),f.debug(`Synced Python version ${
|
|
255
|
-
`),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$
|
|
256
|
-
`),1)}return await d$
|
|
257
|
-
`),1)}}var
|
|
248
|
+
`),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return Sr(t,"PYTHON_NOT_FOUND");let r=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;!process.stdin.isTTY||n?(i="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."))):(process.stdin.isTTY&&a("create"),i=(await b$3([{type:"rawlist",name:"createTarget",message:"What do you want to create?",choices:[{name:"workspace",value:"workspace"},{name:"project",value:"project"}]}])).createTarget);let c=["create",i,...a$1];return await uc(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$2=t.includes("--skip-python-engine")||t.includes("--no-python-engine"),c=t.includes("--dry-run"),l=t[2]&&!t[2].startsWith("-")?t[2]:void 0,p=be(t,"--install-method"),f=p==="poetry"||p==="venv"||p==="pipx"?p:void 0,d=be(t,"--profile"),y=d==="minimal"||d==="java-only"||d==="go-only"||d==="dotnet-only"||d==="python-only"||d==="node-only"||d==="polyglot"||d==="enterprise"?d:void 0,h$2=l;if(h$2||(n?h$2="my-workspace":(process.stdin.isTTY&&a("create workspace"),h$2=(await b$3([{type:"input",name:"workspaceName",message:"Workspace name:",default:"my-workspace"}])).workspaceName)),!h$2||!h$2.trim())return process.stderr.write(`Workspace name is required.
|
|
249
|
+
`),1;try{h(h$2);}catch(v){if(v instanceof a$1)return process.stderr.write(`${v.message}
|
|
250
|
+
`),1;throw v}let k=await i(t,{hasYes:n}),j=g(h$2.trim(),{argv:t,outputParent:k});c||await R__default.ensureDir(C.dirname(j));let _=i$1(h$2.trim());if(!c&&(h$1(_,j,{outputParent:k})&&_&&await R__default.pathExists(_)||await R__default.pathExists(j)))return process.stderr.write(`\u274C Workspace "${h$2}" already exists
|
|
251
|
+
`),_&&_!==j&&process.stderr.write(` Found at: ${_}
|
|
252
|
+
`),1;let w=await b$1(),m=w.author||process.env.USER||"Workspai User";if(!n){let v=await b$3([{type:"input",name:"author",message:"Author name:",default:m}]);v.author?.trim()&&(m=v.author.trim());}let{createProject:g$1}=await import('./create-KFR6FLRT.js');return await g$1(h$2,{skipGit:a$2,skipPythonEngine:i$2,yes:n,dryRun:c,userConfig:{...w,author:m},installMethod:f,profile:y,parentDirectory:C.dirname(j)}),c||(console.log(s.gray(`\u2139\uFE0F Workspace root: ${j}`)),console.log(s.gray(` Next: ${f$2(j)} && npx workspai create project`))),0}catch(n){return process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
|
|
253
|
+
`),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return Yi(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitChoice:m}=await b$3([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$6()}]);if(d$1(m)||l$2(m)){let u=Rn(m),{projectName:b}=await b$3([{type:"input",name:"projectName",message:"Project name:",default:u,validate:W=>W.trim().length>0||"Project name is required"}]),P=t.slice(2).filter(W=>W.startsWith("-")),x=["create","project",m,b.trim(),...P];if(!await Hi(m))return 1;let A=l$2(m)?await zi(x):await Jn(x),I=re(process.cwd());return A===0&&I&&await it(I),A}let g=Rn(m),{projectName:v}=await b$3([{type:"input",name:"projectName",message:"Project name:",default:g,validate:u=>u.trim().length>0||"Project name is required"}]);t.splice(2,0,m,v.trim());}let a$1=t[2],i=f$5({kitId:a$1,framework:a$1,runtime:a$1});if(g$2(i))return Xp(i),1;if(!await Hi(t[2]||""))return 1;if(d$1(t[2])){let m=await Jn(t),g=re(process.cwd());return m===0&&g&&await it(g),m}if(l$2(t[2]))return await zi(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 td(t),0;let c=t.includes("--create-workspace"),l=t.includes("--no-workspace"),p=t.includes("--yes")||t.includes("-y"),f$1=t.includes("--skip-git")||t.includes("--no-git");if(!!!Gn(process.cwd())){let{registerWorkspaceAtPath:m}=await import('./create-KFR6FLRT.js');if(c)await m(process.cwd(),{skipGit:f$1,yes:p,userConfig:await b$1()});else if(!l)if(p)await m(process.cwd(),{skipGit:f$1,yes:true,userConfig:await b$1()});else {let{createWs:g}=await b$3([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);g&&await m(process.cwd(),{skipGit:f$1,yes:false,userConfig:await b$1()});}}let h=[...t.filter(m=>{let g=m.split("=")[0];return !r.has(m)&&!r.has(g)})],k=re(process.cwd()),w=t.includes("--skip-install")||!!k?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$7();let m=await e(h,{cwd:process.cwd(),env:w});if(m===0&&k&&!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"))),m===0){await qn(t,process.cwd());let g=k||re(process.cwd());if(g){try{let u=t[3];if(u){let b=t.indexOf("--output"),P=b>=0?t[b+1]:".",x=C.resolve(process.cwd(),P,u),A=C.join(g,".python-version"),I=C.join(x,".python-version");if(S.existsSync(A)&&S.existsSync(x)){let W=S.readFileSync(A,"utf-8");S.writeFileSync(I,W.trim()+`
|
|
254
|
+
`),f.debug(`Synced Python version ${W.trim()} from workspace to ${u}`);}}}catch(u){f.debug("Could not sync Python version from workspace:",u);}let{syncWorkspaceProjects:v}=await import('./workspace-PLXOO6ST.js');await v(g,true),await it(g);}}return m}catch(m){let g=Nn(m);return g?await Sr(h,g):(process.stderr.write(`Workspai failed to run the Python core engine: ${m?.message??m}
|
|
255
|
+
`),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$7();let n=await e(t,{cwd:process.cwd()});if(n===0){let a=re(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-PLXOO6ST.js');await i(a,true);}}return n}catch(n){let a=Nn(n);return a?await Sr(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
|
|
256
|
+
`),1)}return await d$7(),await e(t,{cwd:process.cwd()})}catch(n){let a=Nn(n);return a?await Sr(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
|
|
257
|
+
`),1)}}var Qi=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],od=[...e$4,"autopilot","pipeline","import","adopt","snapshot","ai","config","product","infra","shell","commands"],rd=["init"],nd=k,Xi=[...nd,...l$1];function sd(t){return !!t&&Kp.includes(t)}function Vn(t){let e=t[0],o=t[1];return e==="project"&&(o==="--help"||o==="-h"||o==="help")?true:Vp.some(([r,n])=>e!==r?false:o?o===n:true)}function bo(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?Vn(t):sd(t[0])||Vn(t)}function ad(t){return !!t&&od.includes(t)}function Zi(t){return ad(t[0])||Vn(t)}function ec(t){return !!t&&Sn.includes(t)}async function tc(t,e){switch(t){case "bootstrap":return Cd(e);case "setup":return Sd(e);case "cache":return Ed(e);case "mirror":return _d(e);default:{let o=t;throw new Error(`Unreachable npm-only manual command: ${String(o)}`)}}}function id(t=process.env){let e=t.npm_config_user_agent||"",o=t.npm_execpath||"",r=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(o)||r==="exec"||r==="x"}function mc(t={}){let e=q(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 cd(){return {schemaVersion:Ri,cli:"workspai",version:c(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:En,contracts:ho(),contractCatalog:vr()}}function ld(){let t=bi(ne),e=[...t.topLevelCommands],o=[...a$7].filter(i=>!e.includes(i)),r=["init","dev","start","build","test","lint","format","help"],n=[...go],a=[...yr];return {schemaVersion:En,scope:"global",cli:"workspai",version:c(),cwd:process.cwd(),contracts:ho(),contractCatalog:vr(),commands:{npmOwned:e,coreBacked:o,projectScoped:r},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"}]),...o.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...r.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function pd(t={}){let e=ld();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(ji(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 Kn(t){return s$1(t)?(mc({json:t.includes("--json")||t.includes("--ci")}),true):false}function Un(t$1){let e=q(process.cwd());if(!e.projectRoot)return false;let o=r$1(t$1,process.cwd());if(!o||o.status!=="unsupported")return false;console.error(s.red(t(o,e))),process.exit(1);}function qe(t){return S.existsSync(C.join(t,".workspai-workspace"))||S.existsSync(C.join(t,".workspai","workspace.json"))||S.existsSync(C.join(t,".rapidkit-workspace"))||S.existsSync(C.join(t,".rapidkit","workspace.json"))}function fc(t){let e=t;for(;;){let o=p(e,"context.json").find(n=>S.existsSync(n));if(o)return o;let r=C.dirname(e);if(r===e)break;e=r;}return null}function Gn(t){let e=t,o=C.resolve(tmpdir());for(;;){let r=[C.join(e,".workspai-workspace"),C.join(e,".rapidkit-workspace")].find(a=>S.existsSync(a));if(r&&C.resolve(e)!==o)return r;let n=C.dirname(e);if(n===e)break;e=n;}return null}function re(t){let e=t,o=C.resolve(tmpdir());for(;;){if((S.existsSync(C.join(e,".workspai-workspace"))||S.existsSync(C.join(e,".workspai","workspace.json"))||S.existsSync(C.join(e,".rapidkit-workspace"))||S.existsSync(C.join(e,".rapidkit","workspace.json")))&&C.resolve(e)!==o)return e;let n=C.dirname(e);if(n===e)break;e=n;}return null}async function it(t,e){try{let{syncWorkspaceContract:o}=await import('./workspace-contract-LQJDZV36.js'),r=await o({workspacePath:t});if(!e?.silent&&(r.addedProjects.length>0||r.updatedProjects.length>0)&&console.log(s.gray(`\u2139\uFE0F Workspace contract synced (${r.contract.projects.length} project(s)).`)),!e?.silent&&r.verification.status!=="passed"){console.log(s.yellow("\u26A0\uFE0F Workspace contract verification failed after project sync."));for(let n of r.verification.violations)console.log(s.gray(` Violation: ${n}`));console.log(s.white(" Next: npx workspai workspace contract inspect"));}}catch(o){e?.silent||console.log(s.yellow(`\u26A0\uFE0F Workspace contract sync skipped: ${o.message}`));}}async function dd(t,e=process.cwd(),o=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b(o))return {detected:false};let n=o$1(e,o);for(let a of n){if(!await R__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 ud(t){let e=t;for(;;){let o=C.join(e,".rapidkit-workspace"),r=C.join(e,".rapidkit","workspace.json");if(!S.existsSync(o)&&S.existsSync(r))return e;let n=C.dirname(e);if(n===e)break;e=n;}return null}var gc={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function md(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Po(t,e){let o=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return o?o[1]==="true":gc[e]}function oc(t){let e=t??"";return {mode:md(e),dependency_sharing_mode:hc(e),rules:{enforce_workspace_marker:Po(e,"enforce_workspace_marker"),enforce_toolchain_lock:Po(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Po(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Po(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Po(e,"require_mirror_lock_for_offline")}}}function rc(t,e,o){let r=`${e}: ${o}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,r);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${r}
|
|
258
258
|
rules:`):`${t.endsWith(`
|
|
259
259
|
`)?t:`${t}
|
|
260
260
|
`}${r}
|
|
261
|
-
`}function
|
|
261
|
+
`}function fd(t,e,o){let r=` ${e}: ${o?"true":"false"}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]+${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,r);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`rules:
|
|
262
262
|
${r}`):`${t.endsWith(`
|
|
263
263
|
`)?t:`${t}
|
|
264
264
|
`}rules:
|
|
265
265
|
${r}
|
|
266
|
-
`}function
|
|
267
|
-
`)}async function
|
|
266
|
+
`}function gd(){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(`
|
|
267
|
+
`)}async function nc(t){for(let e of o(t,"policies.yml"))if(await R__default.pathExists(e))return S.promises.readFile(e,"utf-8");return gd()}async function hd(t,e){let o=l(t,"policies.yml");await R__default.ensureDir(C.dirname(o));let r=e.endsWith(`
|
|
268
268
|
`)?e:`${e}
|
|
269
|
-
`;await S.promises.writeFile(o,r,"utf-8");}function
|
|
270
|
-
`);try{return
|
|
271
|
-
`),1}}let
|
|
272
|
-
`):""}catch{return ""}},
|
|
273
|
-
`),
|
|
274
|
-
`),
|
|
275
|
-
`),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(
|
|
276
|
-
`)),
|
|
277
|
-
`,"utf-8");}async function Dp(t,e,o){let r=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?b.resolve(e.workspace):null,i=n??oe(process.cwd()),a=false,c=false;if(n){if(!Ue(n)){let d=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:d},null,2)):console.log(s.red(`\u274C ${d}`)),1}}else if(!i||!Ue(i)){let d=await jn();i=d.workspacePath,a=true,c=d.created;}if(!i||!Ue(i)){let d="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:d},null,2)):(console.log(s.red(`\u274C ${d}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let u=`cd ${i}`,f=o?.syncWorkspaceProjects??(async d=>{if(r)throw new Error("forced sync failure for command-level import rollback test");let{syncWorkspaceProjects:g}=await import('./workspace-DZHWB7BV.js');await g(d,true),await ot(d,{silent:true});}),p=o?.rollbackImportedProjectImport??sa;try{let d=await ia({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0});try{await f(i);}catch(g){await p(i,d.path);try{await f(i);}catch{}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${g instanceof Error?g.message:String(g)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?c:false,suggestedCdCommand:u,importedProject:d},null,2)),0;if(a&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${d.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${d.path}`)),console.log(s.gray(` Stack: ${d.stack} (${d.confidence})`)),console.log(s.gray(` Source: ${e.git===true||un(t)?"git-url":"local-folder"}`)),!d.profileCompatibility.ok){let g=ir(d.profileCompatibility);console.log(s.yellow(` Profile warning: ${d.profileCompatibility.message}`)),g&&console.log(s.gray(` ${g}`));}return console.log(s.gray(` Next shell step: ${u}`)),0}catch(d){let g=d instanceof Error?d.message:String(d);return e.json?console.log(JSON.stringify({error:g},null,2)):console.log(s.red(`\u274C Import failed: ${g}`)),1}}async function Tp(t,e,o){let r=b.resolve(t||process.cwd()),n=e.workspace?b.resolve(e.workspace):null,i=n??oe(process.cwd()),a=false,c=false;if(n){if(!Ue(n)){let m=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:m},null,2)):console.log(s.red(`\u274C ${m}`)),1}}else if(!i||!Ue(i)){let m=await jn();i=m.workspacePath,a=true,c=m.created;}if(!i||!Ue(i)){let m="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:m},null,2)):(console.log(s.red(`\u274C ${m}`)),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"),f=o?.syncWorkspaceProjects??(async m=>{if(u)throw new Error("forced sync failure for command-level adopt rollback test");let{syncWorkspaceProjects:l}=await import('./workspace-DZHWB7BV.js');await l(m,true),await ot(m,{silent:true});}),p$1=o?.registerProjectInWorkspace??(async(m,l,y)=>{let{registerProjectInWorkspace:k}=await import('./workspace-DZHWB7BV.js');await k(m,l,y);}),d=o?.registerWorkspace??(async(m,l)=>{let{registerWorkspace:y}=await import('./workspace-DZHWB7BV.js');await y(m,l);}),g=o?.rollbackAdoptedProjectImport??aa;try{let m=null;for(let y of p(r,"project.json"))if(await ___default.pathExists(y)){m=await ___default.readJson(y);break}let l=await ca({workspacePath:i,source:r,name:e.name,dryRun:e.dryRun===true});if(e.dryRun!==true)try{await d(i,b.basename(i)),await p$1(i,l.name,l.path),await f(i);}catch(y){throw await g(i,l.path,m),new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${y instanceof Error?y.message:String(y)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?c:false,dryRun:e.dryRun===true,adoptedProject:l},null,2)),0;if(a&&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.green(`\u2714 Adopted project: ${l.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${l.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${l.stack} (${l.confidence})`)),!l.profileCompatibility.ok){let y=ir(l.profileCompatibility);console.log(s.yellow(` Profile warning: ${l.profileCompatibility.message}`)),y&&console.log(s.gray(` ${y}`));}return console.log(s.gray(` Report: ${l.adoptReadinessPath}`)),console.log(s.gray(" Next: npx workspai workspace model --json")),0}catch(m){let l=m instanceof Error?m.message:String(m);return e.json?console.log(JSON.stringify({error:l},null,2)):console.log(s.red(`\u274C Adopt failed: ${l}`)),1}}async function Sn(t){let e=new Set(["python-only","polyglot","enterprise"]),o$1=Fp(),r="minimal",n=false;try{let u=o(t,"workspace.json").find(p=>S.existsSync(p))??l(t,"workspace.json"),f=JSON.parse(await S.promises.readFile(u,"utf-8"));r=f.profile??"minimal",n=f.bootstrap_note==="python-engine-skipped"||f.engine?.python_core?.status==="skipped";}catch{r="minimal";}if(!await(async()=>{if(!n&&e.has(r))return true;let u=await Ka(t);if(u.length===0)return false;for(let f of u){let p=d$4(f),d=p?.module_support,g=j(f);if(n){if(g?.moduleSupport===true)return true;continue}if(!(e$1(p,f)||g$2(p,f)||h$2(p,f))&&d!==false)return i$2(p,f)||f$3(p,f),true}return false})())return 0;let a="poetry";try{let{readWorkspaceMarker:u}=await import('./workspace-marker-SMBC3Z2Q.js'),p=(await u(t))?.metadata?.npm?.installMethod;(p==="poetry"||p==="venv"||p==="pipx"||p==="pip")&&(a=p);}catch{}let c=async()=>{let u=ap(t);if(!await ___default.pathExists(u)){let g=await cp(t);if(g!==0)return g}let f=a$b("DEV_PATH"),d=(f?await ___default.pathExists(f):false)&&f?["-m","pip","install",f,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await z(u,d,t,{timeoutMs:o$1})};if(a==="venv"){let u=await c();if(u!==0)return u}else if(a==="poetry"){let u=b.join(t,"pyproject.toml"),f=false;try{f=(await S.promises.readFile(u,"utf-8")).includes("rapidkit-core");}catch{f=false;}if(f){let p=await c();if(p!==0)return p}else {let p=await z("poetry",["install","--no-root"],t,{timeoutMs:o$1});if(p!==0)return p;let d=await z("poetry",["add","rapidkit-core"],t,{timeoutMs:o$1});if(d!==0)return d}}else return 0;try{let{writeWorkspaceLauncher:u}=await import('./create-42RTNLH2.js');await u(t,a==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:u}=await import('./workspace-python-engine-state-MTWIIZPY.js');await u(t,{installMethod:a==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function Fp(){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 Ka(t){let e=[],o=new Set,r=[t];for(;r.length>0;){let n=r.pop();if(!n||o.has(n))continue;o.add(n);let i=[];try{i=await S.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){if(!a.isDirectory()||a.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(a.name))continue;let c=b.join(n,a.name);if((await Promise.all([...p(c,"context.json"),...p(c,"project.json")].map(f=>___default.pathExists(f)))).some(Boolean)){e.push(c);continue}r.push(c);}}return e}function Lp(t){return j$2(t)}async function jn(){let t=k$1(),e=b.basename(t),o=Ue(t);await b$9(t,d$6(e,c()));let r=l(t,"workspace.json");return await ___default.pathExists(r)||await et(r,{name:e,workspace_name:e,profile:"minimal",createdAt:new Date().toISOString(),createdBy:"workspai-cli-import-fallback"}),{workspacePath:t,created:!o}}async function hn(t){let o=await Je("go",{runCommandInCwd:z,runCoreRapidkit:e}).initProject(t);return ee(o)}function ee(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function kt(t,e$1){let o=Je("node",{runCommandInCwd:z,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return ee(n)}if(t==="dev"){let n=await o.runDev(e$1);return ee(n)}if(t==="test"){let n=await o.runTest(e$1);return ee(n)}if(t==="build"){let n=await o.runBuild(e$1);return ee(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return ee(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return ee(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return ee(r)}async function tt(t,e$1){let o=Je("java",{runCommandInCwd:z,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return ee(n)}if(t==="dev"){let n=await o.runDev(e$1);return ee(n)}if(t==="test"){let n=await o.runTest(e$1);return ee(n)}if(t==="build"){let n=await o.runBuild(e$1);return ee(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return ee(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return ee(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return ee(r)}function yn(t,e,o){let r=o.filter(n=>n.status==="failed").map(n=>{let i=n.id||"check";return n.message?`${i}: ${n.message}`:i}).slice(0,12);return f$6(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:r,runId:e$4()})}async function Pa(t,e=xn){let o$1=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o$1>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let i=function(j){if(!j)return null;let $=j.trim().toLowerCase();return $==="minimal"||$==="java-only"||$==="go-only"||$==="dotnet-only"||$==="python-only"||$==="node-only"||$==="polyglot"||$==="enterprise"?$:null},a=function(j){let Oe=j.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",ve=(ae,Ae)=>{let De=j.match(new RegExp(`^\\s*${ae}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return De?De[1].toLowerCase()==="true":Ae};return {mode:Oe,dependency_sharing_mode:Fa(j),rules:{enforce_workspace_marker:ve("enforce_workspace_marker",true),enforce_toolchain_lock:ve("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:ve("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:ve("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:ve("require_mirror_lock_for_offline",true)}}};let c=["init"],u,f=false,p=false,d=false,g=false;for(let j=1;j<t.length;j+=1){let $=t[j];if($==="--ci"){f=true;continue}if($==="--offline"){p=true;continue}if($==="--json"){d=true;continue}if($==="--compliance-only"){g=true;continue}if($==="--profile"){let Q=t[j+1];if(!Q||Q.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;u=Q,j+=1;continue}if($.startsWith("--profile=")){u=$.slice(10);continue}c.push($);}let m=i(u);if(u&&!m)return console.log(s.red(`Invalid profile: ${u}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let l$1=process.cwd(),y=c.slice(1).filter(j=>!j.startsWith("-"));if(y.length>0){let j=b.resolve(l$1,y[0]),$=d$4(j),Q=S.existsSync(j)?await vt(j):"unknown";if(!Ue(j)&&(e$1($,j)||g$2($,j)||h$2($,j)||f$3($,j)||i$2($,j)||Q!=="unknown"))return await e(c)}let k=b.join(l$1,".rapidkit-workspace"),v=b.join(l$1,".rapidkit","workspace.json"),h;!S.existsSync(k)&&S.existsSync(v)?h=l$1:(h=oe(l$1),h||(h=_p(l$1)));let w=[],x=null,P=null;if(h)try{let j=o(h,"workspace.json").find(Oe=>S.existsSync(Oe))??l(h,"workspace.json"),$=await S.promises.readFile(j,"utf-8"),Q=JSON.parse($);P=i(Q.profile);}catch{P=null;}let R=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],I={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"},Y=m;if(!!h&&!m&&!f&&!d&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let j=P||"minimal",{chosenProfile:$}=await b$4([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${j})`,choices:R.map(Q=>({name:Q===j?`${I[Q]} \u2190 current`:I[Q],value:Q})),default:R.indexOf(j)}]);Y=$;}let K=Y||P||"minimal";if(h)try{let $=K==="python-only"||K==="polyglot"||K==="enterprise"?"poetry":"venv",Q;try{let Ae=(await S.promises.readFile(b.join(h,".python-version"),"utf-8")).trim();Ae&&(Q=Ae);}catch{}let{syncWorkspaceFoundationFiles:Oe}=await import('./create-42RTNLH2.js'),ve=await Oe(h,{workspaceName:b.basename(h),installMethod:$,pythonVersion:Q,profile:K,writeMarker:true,writeGitignore:true,onlyIfMissing:true});w.push({id:"workspace.foundation.sync",status:ve.length>0?"passed":"skipped",message:ve.length>0?`Workspace foundation synchronized: ${ve.join(", ")}`:"Workspace foundation files are already up to date."});}catch(j){w.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${j.message}`});}if(h&&Y&&Y!==P)try{let j=l(h,"workspace.json"),$=await S.promises.readFile(j,"utf-8"),Q=JSON.parse($);Q.profile=Y,await ___default.ensureDir(b.dirname(j)),await S.promises.writeFile(j,JSON.stringify(Q,null,2)+`
|
|
278
|
-
`,"utf-8");}catch{}let
|
|
279
|
-
`):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${
|
|
280
|
-
`),1}let Re=async
|
|
281
|
-
`);else {let
|
|
282
|
-
`):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]")),1;let n=async(
|
|
283
|
-
`,"utf-8");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:e$1,result:
|
|
284
|
-
`),
|
|
285
|
-
${
|
|
286
|
-
${
|
|
287
|
-
${
|
|
269
|
+
`;await S.promises.writeFile(o,r,"utf-8");}function yd(t){let e=t.trim().toLowerCase();return e==="true"||e==="1"||e==="on"?true:e==="false"||e==="0"||e==="off"?false:null}function hc(t){if(!t)return "isolated";let o=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated"?o:"isolated"}function yc(t){if(!t)return {mode:"isolated",status:"skipped",message:"No policies.yml found; dependency_sharing_mode defaults to isolated."};let e=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m);if(!e)return {mode:"isolated",status:"skipped",message:"dependency_sharing_mode is not set; defaulting to isolated."};let o=e[1].toLowerCase();return o==="isolated"||o==="shared-runtime-caches"||o==="shared-node-deps"?{mode:o,status:"passed",message:`dependency_sharing_mode is valid: ${o}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${o}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function wc(t,e){let o$1=re(t),r=o$1?o(o$1,"policies.yml").find(c=>S.existsSync(c)):null,n="isolated";if(r&&await R__default.pathExists(r))try{let c=await S.promises.readFile(r,"utf-8"),l=yc(c);if(l.status==="failed")return console.log(s.red(`\u274C ${l.message}`)),{ok:false,code:1};n=l.mode;}catch{return console.log(s.red("\u274C Failed to read workspace policy file (.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,o$1&&(process.env.RAPIDKIT_WORKSPACE_PATH=o$1);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 Q(t,e,o,r={}){let{buildPackageRunnerSubprocessEnv:n,resolvePackageRunnerInvocation:a}=await import('./platform-capabilities-YICBF4FA.js'),i=wd(t,e,o),c=i?{command:process.execPath,prefixArgs:["-e",i]}:a(t),l=c.command,p=i?c.prefixArgs:[...c.prefixArgs,...e],f=n();if(i){Qt()&&process.stderr.write(`[workspai-cli] runCommandInCwd.nodeEval=${JSON.stringify({cwd:o,scriptBytes:i.length})}
|
|
270
|
+
`);try{return Jp.runInThisContext(i,{filename:C.join(o,"package.json#script")}),0}catch(_){return process.stderr.write(`${_ instanceof Error?_.stack||_.message:String(_)}
|
|
271
|
+
`),1}}let y=!(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"),h=()=>{let _=f.npm_config_cache;if(!_)return "";let w=C.join(_,"_logs");try{let g=S.readdirSync(w).filter(u=>u.endsWith(".log")).map(u=>{let b=C.join(w,u);return {filePath:b,mtimeMs:S.statSync(b).mtimeMs}}).sort((u,b)=>b.mtimeMs-u.mtimeMs)[0]?.filePath;return g?S.readFileSync(g,"utf-8").split(/\r?\n/).map(u=>u.trim()).filter(u=>/(?:^|\s)(?:npm\s+)?(?:error|verbose\s+(?:stack|cwd|os|node|npm|exit|code))\b/i.test(u)).slice(0,12).join(`
|
|
272
|
+
`):""}catch{return ""}},k=Number.parseInt(process.env.RAPIDKIT_CHILD_COMMAND_TIMEOUT_MS||"",10),j=r.timeoutMs&&r.timeoutMs>0?r.timeoutMs:Number.isFinite(k)&&k>0?k:void 0;return await new Promise(_=>{let w=[],m=[],g=false,v=null,u=null,b$1=()=>{try{u?.stdout?.destroy();}catch{}try{u?.stderr?.destroy();}catch{}try{u?.stdin?.destroy();}catch{}try{u?.removeAllListeners("close"),u?.removeAllListeners("error"),u?.unref();}catch{}};Qt()&&process.stderr.write(`[workspai-cli] runCommandInCwd=${JSON.stringify({executable:l,args:p,cwd:o,directNodeEvalScript:i!==null,npmEnv:Object.fromEntries(Object.entries(f).filter(([P])=>["npm_config_if_present","npm_config_ignore_scripts","npm_config_loglevel","npm_config_silent","npm_config_json","npm_lifecycle_event","npm_lifecycle_script"].includes(P)))})}
|
|
273
|
+
`),u=spawn(l,p,{stdio:y?"inherit":["ignore","pipe","pipe"],cwd:o,shell:c$7(),env:f,detached:!b()}),j&&j>0&&(v=setTimeout(()=>{if(!g){if(g=true,!b()&&u.pid)try{process.kill(-u.pid,"SIGTERM");}catch{u.kill("SIGTERM");}else u.kill("SIGTERM");b$1(),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`RapidKit command timed out after ${j}ms: ${l} ${p.join(" ")}
|
|
274
|
+
`),_(124);}},j)),y||(u.stdout?.on("data",P=>{w.push(P);}),u.stderr?.on("data",P=>{m.push(P);})),u.on("close",P=>{if(g)return;g=true,v&&clearTimeout(v);let x=Buffer.concat(w),A=Buffer.concat(m),I=P&&P!==0&&x.length===0&&A.length===0&&t==="npm"?h():"";Qt()&&process.stderr.write(`[workspai-cli] runCommandInCwd.close=${JSON.stringify({code:P,stdoutBytes:x.length,stderrBytes:A.length,npmFailureExcerptBytes:I.length})}
|
|
275
|
+
`),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(x.length>0&&process.stdout.write(x),A.length>0?process.stderr.write(A):I&&process.stderr.write(`${I}
|
|
276
|
+
`)),_(P??1);}),u.on("error",()=>{g||(g=true,v&&clearTimeout(v),_(1));});})}function wd(t,e,o){if(t!=="npm")return null;let r=e[0];if(r!=="run"&&r!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=C.join(o,"package.json");if(!S.existsSync(a))return null;try{let c=JSON.parse(S.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:kd(c)}catch{return null}}function kd(t){let e=t.trim(),o=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(o)return o[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let r=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return r?r[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function st(t,e){await R__default.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
277
|
+
`,"utf-8");}async function vd(t,e,o){let r=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?C.resolve(e.workspace):null,a=n??re(process.cwd()),i=false,c=false;if(n){if(!qe(n)){let d=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:d},null,2)):console.log(s.red(`\u274C ${d}`)),1}}else if(!a||!qe(a)){let d=await Yn();a=d.workspacePath,i=true,c=d.created;}if(!a||!qe(a)){let d="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:d},null,2)):(console.log(s.red(`\u274C ${d}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let l=`cd ${a}`,p=o?.syncWorkspaceProjects??(async d=>{if(r)throw new Error("forced sync failure for command-level import rollback test");let{syncWorkspaceProjects:y}=await import('./workspace-PLXOO6ST.js');await y(d,true),await it(d,{silent:true});}),f=o?.rollbackImportedProjectImport??Vi;try{let d=await Ki({workspacePath:a,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0});try{await p(a);}catch(y){await f(a,d.path);try{await p(a);}catch{}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${y instanceof Error?y.message:String(y)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:a,workspaceResolution:i?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:i?c:false,suggestedCdCommand:l,importedProject:d},null,2)),0;if(i&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${a}`)),console.log(s.green(`\u2714 Imported project: ${d.name}`)),console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Destination: ${d.path}`)),console.log(s.gray(` Stack: ${d.stack} (${d.confidence})`)),console.log(s.gray(` Source: ${e.git===true||On(t)?"git-url":"local-folder"}`)),!d.profileCompatibility.ok){let y=Cr(d.profileCompatibility);console.log(s.yellow(` Profile warning: ${d.profileCompatibility.message}`)),y&&console.log(s.gray(` ${y}`));}return console.log(s.gray(` Next shell step: ${l}`)),0}catch(d){let y=d instanceof Error?d.message:String(d);return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C Import failed: ${y}`)),1}}async function Pd(t,e,o){let r=C.resolve(t||process.cwd()),n=e.workspace?C.resolve(e.workspace):null,a=n??re(process.cwd()),i=false,c=false;if(n){if(!qe(n)){let h=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:h},null,2)):console.log(s.red(`\u274C ${h}`)),1}}else if(!a||!qe(a)){let h=await Yn();a=h.workspacePath,i=true,c=h.created;}if(!a||!qe(a)){let h="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:h},null,2)):(console.log(s.red(`\u274C ${h}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let l=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),p$1=o?.syncWorkspaceProjects??(async h=>{if(l)throw new Error("forced sync failure for command-level adopt rollback test");let{syncWorkspaceProjects:k}=await import('./workspace-PLXOO6ST.js');await k(h,true),await it(h,{silent:true});}),f=o?.registerProjectInWorkspace??(async(h,k,j)=>{let{registerProjectInWorkspace:_}=await import('./workspace-PLXOO6ST.js');await _(h,k,j);}),d=o?.registerWorkspace??(async(h,k)=>{let{registerWorkspace:j}=await import('./workspace-PLXOO6ST.js');await j(h,k);}),y=o?.rollbackAdoptedProjectImport??Ui;try{let h=null;for(let j of p(r,"project.json"))if(await R__default.pathExists(j)){h=await R__default.readJson(j);break}let k=await Gi({workspacePath:a,source:r,name:e.name,dryRun:e.dryRun===true});if(e.dryRun!==true)try{await d(a,C.basename(a)),await f(a,k.name,k.path),await p$1(a);}catch(j){throw await y(a,k.path,h),new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${j instanceof Error?j.message:String(j)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:a,workspaceResolution:i?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:i?c:false,dryRun:e.dryRun===true,adoptedProject:k},null,2)),0;if(i&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${a}`)),e.dryRun===true&&console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.green(`\u2714 Adopted project: ${k.name}`)),console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Project: ${k.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${k.stack} (${k.confidence})`)),!k.profileCompatibility.ok){let j=Cr(k.profileCompatibility);console.log(s.yellow(` Profile warning: ${k.profileCompatibility.message}`)),j&&console.log(s.gray(` ${j}`));}return console.log(s.gray(` Report: ${k.adoptReadinessPath}`)),console.log(s.gray(" Next: npx workspai workspace model --json")),0}catch(h){let k=h instanceof Error?h.message:String(h);return e.json?console.log(JSON.stringify({error:k},null,2)):console.log(s.red(`\u274C Adopt failed: ${k}`)),1}}async function Bn(t){let e=new Set(["python-only","polyglot","enterprise"]),o$1=bd(),r="minimal",n=false;try{let l$1=o(t,"workspace.json").find(f=>S.existsSync(f))??l(t,"workspace.json"),p=JSON.parse(await S.promises.readFile(l$1,"utf-8"));r=p.profile??"minimal",n=p.bootstrap_note==="python-engine-skipped"||p.engine?.python_core?.status==="skipped";}catch{r="minimal";}if(!await(async()=>{if(!n&&e.has(r))return true;let l=await kc(t);if(l.length===0)return false;for(let p of l){let f=d$5(p),d=f?.module_support,y=j(p);if(n){if(y?.moduleSupport===true)return true;continue}if(!(e$2(f,p)||g$1(f,p)||h$2(f,p))&&d!==false)return i$2(f,p)||f$4(f,p),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:l}=await import('./workspace-marker-SMBC3Z2Q.js'),f=(await l(t))?.metadata?.npm?.installMethod;(f==="poetry"||f==="venv"||f==="pipx"||f==="pip")&&(i=f);}catch{}let c=async()=>{let l=Hp(t);if(!await R__default.pathExists(l)){let y=await qp(t);if(y!==0)return y}let p=a$b("DEV_PATH"),d=(p?await R__default.pathExists(p):false)&&p?["-m","pip","install",p,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await Q(l,d,t,{timeoutMs:o$1})};if(i==="venv"){let l=await c();if(l!==0)return l}else if(i==="poetry"){let l=C.join(t,"pyproject.toml"),p=false;try{p=(await S.promises.readFile(l,"utf-8")).includes("rapidkit-core");}catch{p=false;}if(p){let f=await c();if(f!==0)return f}else {let f=await Q("poetry",["install","--no-root"],t,{timeoutMs:o$1});if(f!==0)return f;let d=await Q("poetry",["add","rapidkit-core"],t,{timeoutMs:o$1});if(d!==0)return d}}else return 0;try{let{writeWorkspaceLauncher:l}=await import('./create-KFR6FLRT.js');await l(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:l}=await import('./workspace-python-engine-state-MTWIIZPY.js');await l(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function bd(){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 kc(t){let e=[],o=new Set,r=[t];for(;r.length>0;){let n=r.pop();if(!n||o.has(n))continue;o.add(n);let a=[];try{a=await S.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=C.join(n,i.name);if((await Promise.all([...p(c,"context.json"),...p(c,"project.json")].map(p=>R__default.pathExists(p)))).some(Boolean)){e.push(c);continue}r.push(c);}}return e}function jd(t){return j$2(t)}async function Yn(){let t=k$1(),e=C.basename(t),o=qe(t);await b$8(t,d$8(e,c()));let r=l(t,"workspace.json");return await R__default.pathExists(r)||await st(r,{name:e,workspace_name:e,profile:"minimal",createdAt:new Date().toISOString(),createdBy:"workspai-cli-import-fallback"}),{workspacePath:t,created:!o}}async function Wn(t){let o=await Ge("go",{runCommandInCwd:Q,runCoreRapidkit:e}).initProject(t);return te(o)}function te(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Rt(t,e$1){let o=Ge("node",{runCommandInCwd:Q,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return te(n)}if(t==="dev"){let n=await o.runDev(e$1);return te(n)}if(t==="test"){let n=await o.runTest(e$1);return te(n)}if(t==="build"){let n=await o.runBuild(e$1);return te(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return te(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return te(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return te(r)}async function at(t,e$1){let o=Ge("java",{runCommandInCwd:Q,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return te(n)}if(t==="dev"){let n=await o.runDev(e$1);return te(n)}if(t==="test"){let n=await o.runTest(e$1);return te(n)}if(t==="build"){let n=await o.runBuild(e$1);return te(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return te(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return te(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return te(r)}function Dn(t,e,o){let r=o.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$a(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:r,runId:e$6()})}async function Cd(t,e=Hn){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 o$1=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o$1>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(O){if(!O)return null;let L=O.trim().toLowerCase();return L==="minimal"||L==="java-only"||L==="go-only"||L==="dotnet-only"||L==="python-only"||L==="node-only"||L==="polyglot"||L==="enterprise"?L:null},i=function(O){let Oe=O.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",je=(ae,Ae)=>{let Fe=O.match(new RegExp(`^\\s*${ae}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return Fe?Fe[1].toLowerCase()==="true":Ae};return {mode:Oe,dependency_sharing_mode:hc(O),rules:{enforce_workspace_marker:je("enforce_workspace_marker",true),enforce_toolchain_lock:je("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:je("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:je("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:je("require_mirror_lock_for_offline",true)}}};let c=["init"],l$1,p=false,f=false,d=false,y=false;for(let O=1;O<t.length;O+=1){let L=t[O];if(L==="--ci"){p=true;continue}if(L==="--offline"){f=true;continue}if(L==="--json"){d=true;continue}if(L==="--compliance-only"){y=true;continue}if(L==="--profile"){let X=t[O+1];if(!X||X.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;l$1=X,O+=1;continue}if(L.startsWith("--profile=")){l$1=L.slice(10);continue}c.push(L);}let h=a(l$1);if(l$1&&!h)return console.log(s.red(`Invalid profile: ${l$1}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let k=process.cwd(),j=c.slice(1).filter(O=>!O.startsWith("-"));if(j.length>0){let O=C.resolve(k,j[0]),L=d$5(O),X=S.existsSync(O)?await _t(O):"unknown";if(!qe(O)&&(e$2(L,O)||g$1(L,O)||h$2(L,O)||f$4(L,O)||i$2(L,O)||X!=="unknown"))return await e(c)}let _=C.join(k,".rapidkit-workspace"),w=C.join(k,".rapidkit","workspace.json"),m;!S.existsSync(_)&&S.existsSync(w)?m=k:(m=re(k),m||(m=ud(k)));let g=[],v=null,u=null;if(m)try{let O=o(m,"workspace.json").find(Oe=>S.existsSync(Oe))??l(m,"workspace.json"),L=await S.promises.readFile(O,"utf-8"),X=JSON.parse(L);u=a(X.profile);}catch{u=null;}let b=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],P={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"},x=h;if(!!m&&!h&&!p&&!d&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let O=u||"minimal",{chosenProfile:L}=await b$3([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${O})`,choices:b.map(X=>({name:X===O?`${P[X]} \u2190 current`:P[X],value:X})),default:b.indexOf(O)}]);x=L;}let I=x||u||"minimal";if(m&&!y)try{let L=I==="python-only"||I==="polyglot"||I==="enterprise"?"poetry":"venv",X;try{let Ae=(await S.promises.readFile(C.join(m,".python-version"),"utf-8")).trim();Ae&&(X=Ae);}catch{}let{syncWorkspaceFoundationFiles:Oe}=await import('./create-KFR6FLRT.js'),je=await Oe(m,{workspaceName:C.basename(m),installMethod:L,pythonVersion:X,profile:I,writeMarker:true,writeGitignore:true,onlyIfMissing:true});g.push({id:"workspace.foundation.sync",status:je.length>0?"passed":"skipped",message:je.length>0?`Workspace foundation synchronized: ${je.join(", ")}`:"Workspace foundation files are already up to date."});}catch(O){g.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${O.message}`});}else m&&g.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(m&&!y&&x&&x!==u)try{let O=l(m,"workspace.json"),L=await S.promises.readFile(O,"utf-8"),X=JSON.parse(L);X.profile=x,await R__default.ensureDir(C.dirname(O)),await S.promises.writeFile(O,JSON.stringify(X,null,2)+`
|
|
278
|
+
`,"utf-8");}catch{}let W={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}},N=null;if(m)try{let O=o(m,"policies.yml").find(X=>S.existsSync(X));if(!O)throw new Error("policy file missing");let L=await S.promises.readFile(O,"utf-8");N=L,W=i(L);}catch{g.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else g.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(m){let O=yc(N);W.dependency_sharing_mode=O.mode,g.push({id:"policy.schema.dependency_sharing_mode",status:O.status,message:O.message}),g.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:W.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":W.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 L=S.existsSync(C.join(m,".workspai-workspace"))||S.existsSync(C.join(m,".rapidkit-workspace"));g.push({id:"policy.enforce_workspace_marker",status:!W.rules.enforce_workspace_marker||L?"passed":"failed",message:!W.rules.enforce_workspace_marker||L?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let X=o(m,"toolchain.lock").some(me=>S.existsSync(me));g.push({id:"policy.enforce_toolchain_lock",status:!W.rules.enforce_toolchain_lock||X?"passed":"failed",message:!W.rules.enforce_toolchain_lock||X?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let Oe=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||o(m,"trusted-sources.lock").some(me=>S.existsSync(me));g.push({id:"policy.disallow_untrusted_tool_sources",status:!W.rules.disallow_untrusted_tool_sources||Oe?"passed":"failed",message:!W.rules.disallow_untrusted_tool_sources||Oe?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let je=o(m,"compatibility-matrix.json").find(me=>S.existsSync(me))??l(m,"compatibility-matrix.json"),ae=S.existsSync(je),Ae=W.rules.enforce_compatibility_matrix;if(g.push({id:"policy.enforce_compatibility_matrix",status:!Ae||ae?"passed":"failed",message:!Ae||ae?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),ae)try{let me=await S.promises.readFile(je,"utf-8"),ot=JSON.parse(me),Xn=!!ot&&typeof ot=="object";g.push({id:"compatibility.matrix.parse",status:Xn?"passed":"failed",message:Xn?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{g.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let Fe=o(m,"mirror-config.json").find(me=>S.existsSync(me))??l(m,"mirror-config.json"),Xt=o(m,"mirror.lock").find(me=>S.existsSync(me))??l(m,"mirror.lock"),Rr=S.existsSync(Fe),_r=S.existsSync(Xt),Qn={};if(Rr)try{Qn=JSON.parse(await S.promises.readFile(Fe,"utf-8")),g.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{g.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(y)g.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let me=await _n(m,{ciMode:p,offlineMode:f});g.push(...me.checks.map(ot=>({id:ot.id,status:ot.status,message:ot.message}))),v=me.details,me.details.lockWritten&&(_r=true);}if(f){let me=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||Qn.enabled===true;g.push({id:"offline.mirror.enabled",status:me?"passed":"failed",message:me?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let ot=W.rules.require_mirror_lock_for_offline;g.push({id:"offline.mirror.lock",status:!ot||_r?"passed":"failed",message:!ot||_r?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else g.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let So=St({profile:I,runtimes:await xt(m),mode:W.mode});So.profile!=="enterprise"?g.push({id:So.checkId,status:So.status,message:So.message}):(g.push({id:"profile.enterprise.ci",status:p?"passed":y?"skipped":"failed",message:p?"enterprise profile running with --ci.":y?"Enterprise runtime execution skipped by --compliance-only; --ci is not required.":"enterprise profile expects --ci for deterministic non-interactive mode."}),g.push({id:"profile.enterprise.compatibility-matrix",status:ae?"passed":"failed",message:ae?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),g.push({id:"profile.enterprise.mirror-config",status:Rr?"passed":"failed",message:Rr?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}p&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),f&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let M=g.some(O=>O.id.startsWith("policy.schema.")&&O.status==="failed")||W.mode==="strict"&&g.some(O=>O.status==="failed"),se=l(m||k,"reports"),Y=new Date().toISOString().replace(/[:.]/g,"-"),ee=C.join(se,`bootstrap-compliance-${Y}.json`),Ee=C.join(se,"bootstrap-compliance.latest.json"),ze={command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:m,profile:I,options:{ci:p,offline:f,strict:W.mode==="strict",complianceOnly:y},policyMode:W.mode,policyRules:W.rules,mirrorLifecycle:v,checks:g};if(M){let O=Dn({...ze,result:"blocked",initExitCode:null},1,g);return await R__default.ensureDir(se),await st(ee,O),await st(Ee,O),d?process.stdout.write(`${JSON.stringify(O,null,2)}
|
|
279
|
+
`):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${ee}`))),1}if(d&&I==="enterprise"&&!p&&!y){let O=Dn({...ze,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,g);return await R__default.ensureDir(se),await st(ee,O),await st(Ee,O),process.stdout.write(`${JSON.stringify(O,null,2)}
|
|
280
|
+
`),1}let Re=async O=>{let L=process.stdout.write.bind(process.stdout),X=process.stderr.write.bind(process.stderr),Oe=[],je=[];process.stdout.write=((ae,Ae,Fe)=>{let Xt=typeof Ae=="function"?Ae:typeof Fe=="function"?Fe:void 0;return Oe.push(typeof ae=="string"?ae:ae instanceof Uint8Array?Buffer.from(ae).toString("utf8"):String(ae)),Xt?.(),true}),process.stderr.write=((ae,Ae,Fe)=>{let Xt=typeof Ae=="function"?Ae:typeof Fe=="function"?Fe:void 0;return je.push(typeof ae=="string"?ae:ae instanceof Uint8Array?Buffer.from(ae).toString("utf8"):String(ae)),Xt?.(),true});try{return {exitCode:await O(),stdout:Oe.join(""),stderr:je.join("")}}finally{process.stdout.write=L,process.stderr.write=X;}},H=O=>{let L=O.split(/\r?\n/).map(X=>X.trim()).filter(Boolean);return {bytes:Buffer.byteLength(O),excerpt:L.slice(0,12)}},Le=0,_e;if(!y)if(d){let O=await Re(()=>e(c));Le=O.exitCode,_e={captured:true,stdout:H(O.stdout),stderr:H(O.stderr)};}else Le=await e(c);let At=g.filter(O=>O.status==="failed").length,we=Le!==0?"failed":At>0?"ok_with_warnings":"ok",wt=Le!==0?Le:At>0?1:0,tt=Dn({...ze,result:we,initExitCode:Le,complianceOnly:y,..._e?{initOutput:_e}:{}},wt,g);if(await R__default.ensureDir(se),await st(ee,tt),await st(Ee,tt),m&&!y&&Le===0)try{let{syncWorkspaceProjects:O}=await import('./workspace-PLXOO6ST.js');await O(m,d),await it(m,{silent:d});}catch{}if(d)process.stdout.write(`${JSON.stringify(tt,null,2)}
|
|
281
|
+
`);else {let O=g.filter(L=>L.status==="failed").length;O>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${O} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${ee}`));}return wt}finally{typeof o$1>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=o$1;}}async function Sd(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]")),0;let e$1=(t[1]||"").toLowerCase(),o$1=t.includes("--json"),r=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!e$1||!["python","node","go","java","dotnet"].includes(e$1))return o$1?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]"},null,2)}
|
|
282
|
+
`):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]")),1;let n=async(y,h)=>{if(y==="node"){if(!S.existsSync(C.join(h,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let j=S.existsSync(C.join(h,"pnpm-lock.yaml")),_=S.existsSync(C.join(h,"yarn.lock"));return j?{exitCode:await Q("pnpm",["install","--lockfile-only","--ignore-scripts"],h)}:_?{exitCode:await Q("yarn",["install","--ignore-scripts"],h)}:{exitCode:await Q("npm",["install","--package-lock-only","--ignore-scripts"],h)}}if(y==="go")return S.existsSync(C.join(h,"go.mod"))?{exitCode:await Q("go",["mod","download"],h)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(y==="java"){let k=S.existsSync(C.join(h,"pom.xml")),j=S.existsSync(C.join(h,"build.gradle"))||S.existsSync(C.join(h,"build.gradle.kts")),_=C.join(h,process.platform==="win32"?"gradlew.bat":"gradlew"),w=S.existsSync(_);return !k&&!j?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:k?{exitCode:await Q("mvn",["-B","-q","-DskipTests","dependency:go-offline"],h)}:{exitCode:await Q(w?_:"gradle",["--no-daemon","dependencies"],h)}}return y==="dotnet"?(()=>{let j=[{dir:h,depth:0}],_=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;j.length>0;){let w=j.shift();if(!w||w.depth>3)continue;let m=[];try{m=S.readdirSync(w.dir,{withFileTypes:true});}catch{continue}for(let g of m)if(g.isFile()){let v=g.name.toLowerCase();if(v.endsWith(".sln")||v.endsWith(".csproj"))return true}else g.isDirectory()&&!_.has(g.name)&&j.push({dir:C.join(w.dir,g.name),depth:w.depth+1});}return false})()?{exitCode:await Q("dotnet",["restore"],h)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:{exitCode:0,message:"Dependency warm-up currently applies to node/go/java/dotnet runtimes."}};if(o$1){let y=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let k=await Ge(e$1,{runCommandInCwd:Q,runCoreRapidkit:async(w,m)=>(await g$4(w,{...m,cwd:void 0})).exitCode}).checkPrereqs(),j=re(process.cwd()),_=null;if(e$1==="node"&&k.exitCode===0&&(_=process.version),j&&_){let w=o(j,"toolchain.lock").find(v=>S.existsSync(v))??l(j,"toolchain.lock"),m=l(j,"toolchain.lock"),g={};try{g=JSON.parse(await S.promises.readFile(w,"utf-8"));}catch{}(!g.runtime||typeof g.runtime!="object")&&(g.runtime={}),g.runtime[e$1]={version:_,detectedAt:new Date().toISOString()},await R__default.ensureDir(C.dirname(m)),await S.promises.writeFile(m,JSON.stringify(g,null,2)+`
|
|
283
|
+
`,"utf-8");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:e$1,result:k.exitCode===0?"ok":"failed",exitCode:k.exitCode,workspacePath:j,version:_,warmDeps:r},null,2)}
|
|
284
|
+
`),k.exitCode}finally{typeof y>"u"?delete process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT:process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT=y;}}let a=Ge(e$1,{runCommandInCwd:Q,runCoreRapidkit:(y,h)=>e(y,{...h,cwd:void 0})}),i=await a.checkPrereqs(),c=await a.doctorHints(process.cwd()),l$1=re(process.cwd()),p=l$1||process.cwd(),f=null,d=async()=>e$1!=="java"||!l$1?[]:f||(f=(await kc(l$1)).filter(h=>{let k=d$5(h);return g$1(k,h)}),f);if(i.exitCode===0){console.log(s.green(`\u2705 ${e$1} prerequisites look good.`));let y=["python","node","go","java","dotnet"].filter(h=>h!==e$1).join("/");if(console.log(s.gray(` Scope: validated ${e$1} runtime only. ${y} checks are optional unless your workspace profile uses them.`)),e$1==="python"&&console.log(s.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),a.warmSetupCache&&((await a.warmSetupCache(p)).exitCode===0?console.log(s.gray(` ${e$1} cache warm-up completed.`)):console.log(s.yellow(` ${e$1} cache warm-up skipped (non-fatal).`))),r)if(e$1==="java"&&l$1){let h=await d();if(h.length>0){let k=0,j=0,_=0;for(let w of h){let m=await n("java",w),g=/skipped/i.test(m.message||""),v=C.relative(l$1,w)||C.basename(w);m.message&&console.log(s.gray(` [${v}] ${m.message}`)),m.exitCode===0&&!g?k+=1:m.exitCode===0&&g?_+=1:j+=1;}k>0&&console.log(s.gray(` java dependency warm-up completed for ${k} project(s) (--warm-deps).`)),j>0&&console.log(s.yellow(` java dependency warm-up failed for ${j} project(s) (non-fatal).`)),k===0&&j===0&&_>0&&console.log(s.gray(" java dependency warm-up skipped for discovered workspace projects."));}else {let k=await n("java",p),j=/skipped/i.test(k.message||"");k.message&&console.log(s.gray(` ${k.message}`)),k.exitCode===0&&!j?console.log(s.gray(` ${e$1} dependency warm-up completed (--warm-deps).`)):k.exitCode!==0&&console.log(s.yellow(` ${e$1} dependency warm-up failed (non-fatal).`));}}else {let h=await n(e$1,p),k=/skipped/i.test(h.message||"");h.message&&console.log(s.gray(` ${h.message}`)),h.exitCode===0&&!k?console.log(s.gray(` ${e$1} dependency warm-up completed (--warm-deps).`)):h.exitCode!==0&&console.log(s.yellow(` ${e$1} dependency warm-up failed (non-fatal).`));}if(l$1)try{let h=o(l$1,"toolchain.lock").find(w=>S.existsSync(w))??l(l$1,"toolchain.lock"),k=l(l$1,"toolchain.lock"),j={};try{j=JSON.parse(await S.promises.readFile(h,"utf-8"));}catch{}(!j.runtime||typeof j.runtime!="object")&&(j.runtime={});let _=j.runtime;if(e$1==="python"){let w=null;try{let{execa:m}=await import('execa');for(let g of zn()){let u=await m(g,g==="py"?["-3","--version"]:["--version"],{cwd:l$1,stdio:"pipe",reject:false,timeout:3e3});if(u.exitCode===0){let P=(u.stdout||u.stderr||"").match(/Python\s+(\S+)/);if(w=P?P[1]:null,w)break}}}catch{}_.python={..._.python||{},version:w,last_setup:new Date().toISOString()};}else if(e$1==="node")_.node={..._.node||{},version:process.version,last_setup:new Date().toISOString()};else if(e$1==="go"){let w=null;try{let{execa:m}=await import('execa'),v=((await m("go",["version"],{cwd:l$1,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);w=v?v[1]:null;}catch{}_.go={..._.go||{},version:w,last_setup:new Date().toISOString()};}else if(e$1==="java"){let w=null,m=null,g=null,v=await d(),b=S.existsSync(C.join(p,"pom.xml"))||S.existsSync(C.join(p,"build.gradle"))||S.existsSync(C.join(p,"build.gradle.kts"))?p:v[0]||p;try{let{execa:P}=await import('execa'),x=await P("java",["-version"],{cwd:l$1,stdio:"pipe",reject:false,timeout:3e3}),I=`${x.stdout||""}
|
|
285
|
+
${x.stderr||""}`.match(/version\s+"([^"]+)"/i);w=I?I[1]:null;let W=S.existsSync(C.join(b,"pom.xml")),N=S.existsSync(C.join(b,"build.gradle"))||S.existsSync(C.join(b,"build.gradle.kts"));if(W){m="maven";let D=(()=>{let Y=C.join(b,"mvnw.cmd");if(process.platform==="win32"&&S.existsSync(Y))return Y;let ee=C.join(b,"mvnw");return S.existsSync(ee)?ee:"mvn"})(),M=await P(D,["-version"],{cwd:b,stdio:"pipe",reject:false,timeout:3e3}),se=`${M.stdout||""}
|
|
286
|
+
${M.stderr||""}`.match(/Apache Maven\s+(\S+)/i);g=se?se[1]:null;}else if(N){m="gradle";let D=(()=>{let Y=C.join(b,"gradlew.bat");if(process.platform==="win32"&&S.existsSync(Y))return Y;let ee=C.join(b,"gradlew");return S.existsSync(ee)?ee:"gradle"})(),M=await P(D,["--version"],{cwd:b,stdio:"pipe",reject:false,timeout:3e3}),se=`${M.stdout||""}
|
|
287
|
+
${M.stderr||""}`.match(/Gradle\s+(\S+)/i);g=se?se[1]:null;}}catch{}_.java={..._.java||{},version:w,build_tool:m,build_tool_version:g,last_setup:new Date().toISOString()};}else if(e$1==="dotnet"){let w=null;try{let{execa:m}=await import('execa'),v=((await m("dotnet",["--version"],{cwd:l$1,stdio:"pipe",reject:false,timeout:3e3})).stdout||"").trim();w=v.length>0?v:null;}catch{}_.dotnet={..._.dotnet||{},version:w,sdk:w,last_setup:new Date().toISOString()};}j.updated_at=new Date().toISOString(),await S.promises.writeFile(k,JSON.stringify(j,null,2)+`
|
|
288
288
|
`,"utf-8"),console.log(s.gray(" toolchain.lock updated (.workspai/toolchain.lock)"));}catch{}}else console.log(s.red(`\u274C ${e$1} prerequisites check failed.`));if(c.length>0){console.log(s.gray(`
|
|
289
|
-
Hints:`));for(let
|
|
290
|
-
`)){let r=o.trim(),n=r.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]]/g,""));let
|
|
291
|
-
`),0):(console.log(s.cyan("Workspai cache is enabled")),console.log(s.cyan("Workspai cache status")),
|
|
292
|
-
`),0):(console.log(s.green("Cache clear completed")),console.log(s.green("\u2705 Cache cleared (all entries removed).")),0)):e==="prune"?(r||await n.clear(),o$1?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:
|
|
293
|
-
`),0):r?(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).")),
|
|
294
|
-
`),0):(console.log(s.green("\u2705 Cache repaired (self-heal applied, stale entries evicted).")),
|
|
295
|
-
`),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
|
|
296
|
-
`),0):(console.log(s.cyan(`Policy file: ${
|
|
297
|
-
`),1):(console.log(s.red(`Unknown workspace policy action: ${e||""}`)),console.log(s.gray("Available: show, set")),1);if(!o||typeof r>"u")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:
|
|
298
|
-
`),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=o.trim(),
|
|
299
|
-
`),1):(console.log(s.red("\u274C Invalid mode. Use: warn | strict")),1);
|
|
300
|
-
`),1):(console.log(s.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1);
|
|
301
|
-
`),1):(console.log(s.red(`\u274C Unknown policy rule: ${d}`)),1);let
|
|
302
|
-
`),1):(console.log(s.red("\u274C Rule values must be boolean: true | false")),1);
|
|
303
|
-
`),1):(console.log(s.red(`\u274C Unknown policy key: ${c}`)),1);await
|
|
304
|
-
`),0):(console.log(s.green(`\u2705 Updated ${c} in .workspai/policies.yml`)),console.log(s.gray(` mode: ${
|
|
305
|
-
|
|
306
|
-
`),
|
|
307
|
-
`),1;console.log(s.
|
|
308
|
-
`),
|
|
309
|
-
`)
|
|
310
|
-
`)
|
|
311
|
-
`);for(let
|
|
312
|
-
`);
|
|
313
|
-
`);for(let
|
|
314
|
-
`);process.exit(1);}}if(v&&r&&fa.includes(r)&&!h&&!n&&!g){f.debug(`Delegating to local CLI: ${v} ${o.join(" ")}`);let w=r==="init"?da():process.env,x=spawn(v,o,{stdio:"inherit",cwd:e$2,shell:y,env:w});return x.on("close",P=>{process.exit(P??0);}),x.on("error",P=>{f.error(`Failed to run local rapidkit: ${P.message}`),process.exit(1);}),true}if(l&&await ___default.pathExists(l))try{let w=await ___default.readJson(l);if(Ws(w.engine)){let x=o[0],P=m?[]:o$1(e$2),R=null;for(let I of P)if(await ___default.pathExists(I)){if(await t(I)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${I}. Falling back to core bridge.`);continue}R=I;break}if(R&&x&&fa.includes(x)&&x!=="init"&&!g){f.debug(`Delegating to local CLI (early detection): ${R} ${o.join(" ")}`);let I=x==="init"?da():process.env,Y=spawn(R,o,{stdio:"inherit",cwd:e$2,env:I});return Y.on("close",te=>process.exit(te??0)),Y.on("error",te=>{f.error(`Failed to run local rapidkit: ${te.message}`),process.exit(1);}),true}if(x==="shell"&&o[1]==="activate"){let I=b$1()?`# RapidKit Core activation snippet (PowerShell)
|
|
289
|
+
Hints:`));for(let y of c)console.log(s.gray(`- ${y}`));}return i.exitCode}function xd(t){let e={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let o of t.split(`
|
|
290
|
+
`)){let r=o.trim(),n=r.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]]/g,""));let a=r.match(/^prune_on_bootstrap:\s*(true|false)/);a&&(e.prune_on_bootstrap=a[1]==="true");let i=r.match(/^self_heal:\s*(true|false)/);i&&(e.self_heal=i[1]==="true");let c=r.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function Ed(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(),o$1=t.includes("--json"),r=t.includes("--dry-run"),n=hr.getInstance(),a=re(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(a)try{let c=o(a,"cache-config.yml").find(p=>S.existsSync(p));if(!c)throw new Error("cache config missing");let l=await S.promises.readFile(c,"utf-8");i=xd(l);}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 o$1?(process.stdout.write(`${JSON.stringify(c,null,2)}
|
|
291
|
+
`),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(),o$1?(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)}
|
|
292
|
+
`),0):(console.log(s.green("Cache clear completed")),console.log(s.green("\u2705 Cache cleared (all entries removed).")),0)):e==="prune"?(r||await n.clear(),o$1?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,dryRun:r,cache:{pruned:!r,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)}
|
|
293
|
+
`),0):r?(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(),o$1?(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)}
|
|
294
|
+
`),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)):o$1?(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)}
|
|
295
|
+
`),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 Rd(t,e,o,r,n=false){let a=(e||"show").toLowerCase(),i=l(t,"policies.yml");if(a==="show"||a==="status"||a==="get"){let d=await nc(t),y=oc(d);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,policy:y},null,2)}
|
|
296
|
+
`),0):(console.log(s.cyan(`Policy file: ${i}`)),console.log(s.gray(` mode: ${y.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${y.dependency_sharing_mode}`)),console.log(s.gray(" rules:")),console.log(s.gray(` enforce_workspace_marker: ${y.rules.enforce_workspace_marker}`)),console.log(s.gray(` enforce_toolchain_lock: ${y.rules.enforce_toolchain_lock}`)),console.log(s.gray(` disallow_untrusted_tool_sources: ${y.rules.disallow_untrusted_tool_sources}`)),console.log(s.gray(` enforce_compatibility_matrix: ${y.rules.enforce_compatibility_matrix}`)),console.log(s.gray(` require_mirror_lock_for_offline: ${y.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)}
|
|
297
|
+
`),1):(console.log(s.red(`Unknown workspace policy action: ${e||""}`)),console.log(s.gray("Available: show, set")),1);if(!o||typeof r>"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)}
|
|
298
|
+
`),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=o.trim(),p=await nc(t);if(c==="mode"){let d=r.trim().toLowerCase();if(d!=="warn"&&d!=="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)}
|
|
299
|
+
`),1):(console.log(s.red("\u274C Invalid mode. Use: warn | strict")),1);p=rc(p,"mode",`${d} # "warn" or "strict"`);}else if(c==="dependency_sharing_mode"){let d=r.trim().toLowerCase();if(d!=="isolated"&&d!=="shared-runtime-caches"&&d!=="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)}
|
|
300
|
+
`),1):(console.log(s.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1);p=rc(p,"dependency_sharing_mode",`${d} # "isolated" or "shared-runtime-caches" or "shared-node-deps"`);}else if(c.startsWith("rules.")){let d=c.slice(6);if(!(d in gc))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: ${d}`}},null,2)}
|
|
301
|
+
`),1):(console.log(s.red(`\u274C Unknown policy rule: ${d}`)),1);let y=yd(r);if(y===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)}
|
|
302
|
+
`),1):(console.log(s.red("\u274C Rule values must be boolean: true | false")),1);p=fd(p,d,y);}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)}
|
|
303
|
+
`),1):(console.log(s.red(`\u274C Unknown policy key: ${c}`)),1);await hd(t,p);let f=oc(p);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)}
|
|
304
|
+
`),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 _d(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(),o$1=t.includes("--json"),r=re(process.cwd());if(!r)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=o(r,"mirror-config.json").find(d=>S.existsSync(d))??l(r,"mirror-config.json"),a=o(r,"mirror.lock").find(d=>S.existsSync(d))??l(r,"mirror.lock"),i=l(r,"mirror","artifacts"),c=l(r,"reports");async function l$1(d){if(!await R__default.pathExists(d))return 0;let y=0,h=[d];for(;h.length>0;){let k=h.shift();if(!k)continue;let j=await S.promises.readdir(k,{withFileTypes:true});for(let _ of j)_.isFile()?y+=1:_.isDirectory()&&h.push(C.join(k,_.name));}return y}async function p(d){let y=new Date().toISOString().replace(/[:.]/g,"-"),h=C.join(c,`mirror-ops-${y}.json`),k=C.join(c,"mirror-ops.latest.json");await R__default.ensureDir(c),await st(h,d),await st(k,d);}async function f(){let d=await R__default.pathExists(n),y=await R__default.pathExists(a),h=await l$1(i);return {configExists:d,lockExists:y,artifactsCount:h}}if(e==="status"){let d=await R__default.pathExists(n),y=await R__default.pathExists(a),h=await l$1(i),k={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:{configExists:d,lockExists:y,artifactsCount:h}};return await p(k),o$1?(process.stdout.write(`${JSON.stringify(k,null,2)}
|
|
305
|
+
`),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Config: ${d?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${y?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${h}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let d=await _n(r,{ciMode:true,offlineMode:e==="verify",forceRun:true}),y=d.checks.filter(j=>j.status==="failed"),h=d.checks.some(j=>j.id.startsWith("mirror.verify.")&&j.status==="failed");if(e==="verify"&&h){let j={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await f(),details:d.details,checks:d.checks};if(await p(j),o$1)return process.stdout.write(`${JSON.stringify(j,null,2)}
|
|
306
|
+
`),1;console.log(s.red("\u274C Mirror verify failed."));for(let _ of d.checks.filter(w=>w.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${_.id}: ${_.message}`));return 1}if(y.length>0){let j={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await f(),details:d.details,checks:d.checks};if(await p(j),o$1)return process.stdout.write(`${JSON.stringify(j,null,2)}
|
|
307
|
+
`),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${y.length} issue(s).`));for(let _ of y)console.log(s.gray(`- ${_.id}: ${_.message}`));return 1}let k={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:await f(),details:d.details,checks:d.checks};return await p(k),o$1?(process.stdout.write(`${JSON.stringify(k,null,2)}
|
|
308
|
+
`),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${d.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${d.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${d.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Hn(t){let e$1=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$1>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let o=process.cwd(),r=await wc(o,async()=>{let n=re(o),a=Ge("python",{runCommandInCwd:Q,runCoreRapidkit:e}),i=Ge("dotnet",{runCommandInCwd:Q,runCoreRapidkit:e}),c=t.slice(1).filter(k=>!k.startsWith("-"));if(c.length>0){let k=C.resolve(o,c[0]),j=d$5(k),_=await _t(k);return e$2(j,k)||_==="go"?await Wn(k):g$1(j,k)||_==="java"?await at("init",k):h$2(j,k)||_==="dotnet"?te(await i.initProject(k)):f$4(j,k)||_==="node"?await Tn(k):i$2(j,k)||_==="python"?await Mn(k,a):await e(t,{cwd:o})}let l=d$5(o),p=!!re(o)&&o===re(o);if(!p&&e$2(l,o))return await Wn(o);let f=await _t(o);if(!p&&(g$1(l,o)||f==="java"))return await at("init",o);if(!p&&(h$2(l,o)||f==="dotnet"))return te(await i.initProject(o));if(!p&&(f$4(l,o)||f==="node"))return await Tn(o);if(!p&&(i$2(l,o)||f==="python"))return await Mn(o,a);let d=n||re(o),y=fc(o),h=y?C.dirname(C.dirname(y)):null;if(h&&h!==d){let k=d$5(h),j=await _t(h);return e$2(k,h)||j==="go"?await Wn(h):g$1(k,h)||j==="java"?await at("init",h):h$2(k,h)||j==="dotnet"?te(await i.initProject(h)):f$4(k,h)||j==="node"?await Tn(h):i$2(k,h)||j==="python"?await Mn(h,a):await e(["init"],{cwd:h})}if(d&&o===d){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 k=await Bn(d);if(k!==0)return k;let{runWorkspaceStage:j}=await import('./workspace-run-WEQYIERE.js');return (await j({workspacePath:d,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!d){let k=await b$1(),j=g$3(),{name:_}=jd(j);await R__default.ensureDir(j);let{createProject:w}=await import('./create-KFR6FLRT.js');return await w(_,{yes:true,userConfig:k,parentDirectory:j}),0}return await e(t,{cwd:o})});return r.ok?r.value:r.code}finally{typeof e$1>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$1;}}async function sc(t){let e=re(t);if(!e)return [];let o$1="warn";try{let l=o(e,"policies.yml").find(d=>S.existsSync(d));if(!l)return [];let p=await S.promises.readFile(l,"utf-8");(p.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??p.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(o$1="strict");}catch{return []}if(o$1!=="strict")return [];let r=[],n=o(e,"toolchain.lock").find(l=>S.existsSync(l));if(!n||!S.existsSync(n))return r.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),r;let a={};try{a=JSON.parse(await S.promises.readFile(n,"utf-8"));}catch{return r.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),r}let i=a.runtime??{},c=d$5(t);e$2(c,t)&&!i.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):f$4(c,t)&&!i.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):g$1(c,t)&&!i.java?.version?r.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):h$2(c,t)&&!i.dotnet?.version?r.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):i$2(c,t)&&!i.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let l=o(e,"workspace.json").find(h=>S.existsSync(h));if(!l)throw new Error("workspace manifest missing");let f=JSON.parse(await S.promises.readFile(l,"utf-8")).profile??"",d=i$3(t,c),y=ht({profile:f,runtime:d.runtime,subjectLabel:C.basename(t),mode:"strict"});y.ok||r.push(`${y.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return r}async function Ad(){let t=async g=>{if(!b()||!g.toLowerCase().endsWith(".cmd"))return false;try{let u=(await R__default.readFile(g,"utf8")).replace(/\r\n/g,`
|
|
309
|
+
`).toLowerCase(),b=u.includes("\\.rapidkit\\rapidkit"),P=u.includes("\\.rapidkit\\rapidkit.cmd")||u.includes("\\.rapidkit\\rapidkit.exe")||u.includes("\\.venv\\scripts\\rapidkit.exe");return b&&!P}catch{return false}},e$1=process.cwd(),o=process.argv.slice(2),r=o[0],n=r==="init",a=new Set(k),i=!r||r==="--help"||r==="-h"||r==="help",c=qe(e$1),l=p(e$1,"project.json").some(g=>S.existsSync(g)),p$1=d$5(e$1),f$1=await _t(e$1),d=e$2(p$1,e$1)||f$4(p$1,e$1)||i$2(p$1,e$1)||g$1(p$1,e$1)||h$2(p$1,e$1)||c$6(f$1??void 0),y=!!r&&a.has(r)&&d,h=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(bo(o)||o[0]==="create")return false;if(Kn(o))return true;if(o[0]==="init"&&c&&!l)return false;if(Un(o))return true;try{let g=r==="shell"&&o[1]==="activate",v=r==="create",u=await sa(e$1,{cwd:e$1,timeoutMs:1200});if(u.ok&&u.data?.isRapidkitProject&&u.data.engine==="python"){let b=v||bo(o);if(!i&&!g&&!b&&!n&&!y&&Hr(o)){if(r&&Xi.includes(r)){let x=await sc(e$1).catch(()=>[]);if(x.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
|
|
310
|
+
`);for(let A of x)process.stderr.write(s.red(` \u2022 ${A}`)+`
|
|
311
|
+
`);process.exit(1);}}let P=await e(process.argv.slice(2),{cwd:e$1});process.exit(P);}}}catch{}let k$1=fc(e$1),j=b(),_=h?[]:o$1(e$1),w=null;for(let g of _)if(await R__default.pathExists(g)){if(await t(g)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${g}. Falling back to core bridge.`);continue}w=g;break}let m=r==="create";if(r==="init"&&c&&!l)return false;if(r&&Xi.includes(r)){let g=await sc(e$1);if(g.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
|
|
312
|
+
`);for(let v of g)process.stderr.write(s.red(` \u2022 ${v}`)+`
|
|
313
|
+
`);process.exit(1);}}if(w&&r&&Qi.includes(r)&&!m&&!n&&!y){f.debug(`Delegating to local CLI: ${w} ${o.join(" ")}`);let g=r==="init"?qi():process.env,v=spawn(w,o,{stdio:"inherit",cwd:e$1,shell:j,env:g});return v.on("close",u=>{process.exit(u??0);}),v.on("error",u=>{f.error(`Failed to run local rapidkit: ${u.message}`),process.exit(1);}),true}if(k$1&&await R__default.pathExists(k$1))try{let g=await R__default.readJson(k$1);if(ia(g.engine)){let v=o[0],u=h?[]:o$1(e$1),b$1=null;for(let P of u)if(await R__default.pathExists(P)){if(await t(P)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${P}. Falling back to core bridge.`);continue}b$1=P;break}if(b$1&&v&&Qi.includes(v)&&v!=="init"&&!y){f.debug(`Delegating to local CLI (early detection): ${b$1} ${o.join(" ")}`);let P=v==="init"?qi():process.env,x=spawn(b$1,o,{stdio:"inherit",cwd:e$1,env:P});return x.on("close",A=>process.exit(A??0)),x.on("error",A=>{f.error(`Failed to run local rapidkit: ${A.message}`),process.exit(1);}),true}if(v==="shell"&&o[1]==="activate"){let P=b()?`# RapidKit Core activation snippet (PowerShell)
|
|
315
314
|
$venv = ".venv"
|
|
316
315
|
if (Test-Path "$venv\\Scripts\\Activate.ps1") { . "$venv\\Scripts\\Activate.ps1" }
|
|
317
316
|
$env:RAPIDKIT_PROJECT_ROOT = (Get-Location).Path
|
|
@@ -331,44 +330,44 @@ export RAPIDKIT_PROJECT_ROOT="$(pwd)"
|
|
|
331
330
|
export PATH="$(pwd)/.workspai:$(pwd)/.rapidkit:$(pwd):$PATH"
|
|
332
331
|
`;console.log(s.green.bold(`
|
|
333
332
|
\u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
|
|
334
|
-
`)),console.log(
|
|
333
|
+
`)),console.log(P),console.log(s.gray(`
|
|
335
334
|
\u{1F4A1} After activation you can run: workspai dev
|
|
336
|
-
`)),process.exit(0);}if(!
|
|
335
|
+
`)),process.exit(0);}if(!i&&!bo(o)&&v!=="init"&&!y&&Hr(o)){let P=await e(o,{cwd:e$1});process.exit(P);}}}catch{}return false}var yt=null,xr=false,Id=Up(),le="workspai",he="npx workspai",ne=new Command,$d=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function Od(t){if(t.length===0)return false;let e=t[0],o=t[1];if(s$1(t)||rd.includes(e))return false;if(l$1.includes(e)){if(e==="lint"||e==="format"){let n=d$5(process.cwd()),a=await _t(process.cwd());if(f$4(n,process.cwd())||a==="node"){let i=i$3(process.cwd(),n);if(n$2(process.cwd(),e,{framework:i.key})!==null)return false}if(i$2(n,process.cwd())||a==="python")return true;if(p$1(process.cwd()))return false}return true}if(bo(t)||e==="shell"&&o==="activate")return false;if(t.includes("--tui"))return true;if(e==="--help"||e==="-h"||e==="help"||e==="--version"||e==="-V"||e==="-v"||t.includes("--template")||t.includes("-t"))return false;let r=await i$4();return Br(e,r)?true:t.some(n=>Gr.has(n))?false:r?r.has(e):!!(a$7.has(e)||t.length>1)}ne.name(le).description("Workspai workspace intelligence CLI").version(c());var Nd=b()?`${he} init; ${he} dev`:`${he} init && ${he} dev`,Md="~/.workspai/workspaces/my-workspace";ne.addHelpText("beforeAll",`Workspai CLI
|
|
337
336
|
|
|
338
337
|
Create workspaces, scaffold projects, and manage your development toolchain.
|
|
339
338
|
`);ne.addHelpText("afterAll",`
|
|
340
339
|
Workspace Setup Commands
|
|
341
|
-
${
|
|
342
|
-
${
|
|
343
|
-
${
|
|
344
|
-
${
|
|
345
|
-
${
|
|
346
|
-
${
|
|
347
|
-
${
|
|
348
|
-
${
|
|
349
|
-
${
|
|
350
|
-
${
|
|
351
|
-
${
|
|
352
|
-
${
|
|
340
|
+
${le} bootstrap Bootstrap projects in workspace (--profile java-only|python-only|node-only|go-only|dotnet-only|polyglot|enterprise)
|
|
341
|
+
${le} analyze Analyze workspace/project health and generate enterprise evidence
|
|
342
|
+
${le} setup <runtime> Set up runtime toolchain (runtime: python | node | go | java | dotnet)
|
|
343
|
+
${le} readiness Build release-readiness evidence (use --json for CI)
|
|
344
|
+
${le} autopilot release Run end-to-end release gate orchestration (audit|safe-fix|enforce)
|
|
345
|
+
${le} workspace list List registered workspaces on this system
|
|
346
|
+
${le} snapshot create Create a recoverable workspace snapshot
|
|
347
|
+
${le} snapshot inspect Inspect snapshot payload and manifest details
|
|
348
|
+
${le} project archive Safely archive a workspace project
|
|
349
|
+
${le} project restore Restore an archived workspace project
|
|
350
|
+
${le} mirror Manage registry mirrors (mirror status --json | sync | verify | rotate)
|
|
351
|
+
${le} cache Manage package cache (cache status | clear | prune | repair)
|
|
353
352
|
|
|
354
353
|
Observability:
|
|
355
354
|
--log-format json Emit structured NDJSON log events on stderr (or RAPIDKIT_LOG_FORMAT=json)
|
|
356
355
|
--log-json Alias for --log-format json
|
|
357
356
|
|
|
358
357
|
Project Commands
|
|
359
|
-
${
|
|
360
|
-
${
|
|
361
|
-
${
|
|
362
|
-
${
|
|
363
|
-
${
|
|
358
|
+
${le} create Scaffold a new project (${le} create project)
|
|
359
|
+
${le} init Install project dependencies
|
|
360
|
+
${le} dev Start dev server
|
|
361
|
+
${le} build Build for production
|
|
362
|
+
${le} test Run tests
|
|
364
363
|
|
|
365
364
|
Quick start:
|
|
366
365
|
${he} my-workspace # Create workspace in ~/.workspai/workspaces
|
|
367
366
|
${he} my-workspace --here # Create workspace in the current directory
|
|
368
367
|
${he} create workspace --output .
|
|
369
|
-
cd ${
|
|
368
|
+
cd ${Md} # Or cd my-workspace when using --here
|
|
370
369
|
${he} create project # Interactive kit picker
|
|
371
|
-
${
|
|
370
|
+
${Nd} # Install deps + run
|
|
372
371
|
|
|
373
372
|
Notes:
|
|
374
373
|
--here Create workspace in the current directory (alias for --output .)
|
|
@@ -376,35 +375,46 @@ Notes:
|
|
|
376
375
|
--skip-install (npm wrapper) enables fast-path for lock/dependency steps.
|
|
377
376
|
It is different from core --skip-essentials (essential module installation).
|
|
378
377
|
|
|
379
|
-
Use "${
|
|
380
|
-
`);ne.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-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 create a workspace").hideHelp()).option("--no-update-check","Skip checking for updates").action(async(t,e$1)=>{try{e$1.debug&&(f.setDebug(true),f.debug("Debug mode enabled"));let o=await b$
|
|
381
|
-
\u274C ${
|
|
382
|
-
`),process.exit(1)),
|
|
383
|
-
\u274C Directory "${t}" already exists`),
|
|
378
|
+
Use "${le} help <command>" for more information.
|
|
379
|
+
`);ne.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-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 create a workspace").hideHelp()).option("--no-update-check","Skip checking for updates").action(async(t,e$1)=>{try{e$1.debug&&(f.setDebug(true),f.debug("Debug mode enabled"));let o=await b$1();f.debug("User config loaded",o);let r=await c$1();f.debug("Workspai config loaded",r);let n=d(o,r,{author:e$1.author,pythonVersion:void 0,skipGit:e$1.skipGit});f.debug("Merged config",n),e$1.updateCheck!==false&&await b$2(),a("workspace"),t||(vc(),process.exit(0));try{h(t);}catch(l){throw l instanceof a$1&&(f.error(`
|
|
380
|
+
\u274C ${l.message}`),l.details&&f.warn(`\u{1F4A1} ${l.details}
|
|
381
|
+
`),process.exit(1)),l}let a$2=!!e$1.template,i$2;a$2||(e$1.here?i$2=process.cwd():e$1.output?i$2=C.resolve(e$1.output):i$2=await i([],{hasYes:e$1.yes}));let c=a$2?C.resolve(process.cwd(),t):g(t,{outputParent:i$2});if(yt=c,!e$1.dryRun){a$2||await R__default.ensureDir(C.dirname(c));let l=a$2?void 0:i$1(t);(!a$2&&h$1(l,c,{outputParent:i$2})&&l&&await R__default.pathExists(l)||await R__default.pathExists(c))&&(f.error(`
|
|
382
|
+
\u274C Directory "${t}" already exists`),l&&l!==c&&console.log(s.gray(` Found at: ${l}`)),console.log(s.cyan(`
|
|
384
383
|
\u{1F4A1} Choose a different name or delete the existing directory.
|
|
385
384
|
`)),process.exit(1));}if(e$1.dryRun){console.log(s.cyan(`
|
|
386
385
|
\u{1F50D} Dry-run mode - showing what would be created:
|
|
387
|
-
`)),console.log(s.white("\u{1F4C2} Path:"),c),console.log(s.white("\u{1F4E6} Type:"),
|
|
388
|
-
`)),
|
|
389
|
-
`),f.debug(`Synced Python version ${
|
|
390
|
-
`),f.debug(`Re-synced Python version ${
|
|
386
|
+
`)),console.log(s.white("\u{1F4C2} Path:"),c),console.log(s.white("\u{1F4E6} Type:"),a$2?`Project (${e$1.template})`:"Workspace"),console.log();return}if(!e$1.yes&&!a$2?await b$3([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"Workspai User"}]):e$1.yes&&console.log(s.gray(`Using default values (--yes flag)
|
|
387
|
+
`)),a$2){let l=String(e$1.template||"").trim(),p=b$4(l);if(d$1(p)){let m=await Jn(["create","project",p,t,...e$1.skipGit?["--skip-git"]:[]]);m!==0&&process.exit(m);return}if(!!!Gn(process.cwd())){let{registerWorkspaceAtPath:m}=await import('./create-KFR6FLRT.js');if(e$1.createWorkspace)await m(process.cwd(),{skipGit:e$1.skipGit,yes:e$1.yes,userConfig:o});else if(!e$1.noWorkspace)if(e$1.yes)await m(process.cwd(),{skipGit:e$1.skipGit,yes:true,userConfig:o});else {let{createWs:g}=await b$3([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);g&&await m(process.cwd(),{skipGit:e$1.skipGit,yes:false,userConfig:o});}}let d=["create","project",p,t,"--output",process.cwd()];e$1.yes&&d.push("--yes");let y=re(process.cwd()),h=!!e$1.skipInstall,k=h||!!y;h&&d.push("--skip-essentials");let j=k?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,_=await f$1(d,{cwd:process.cwd(),env:j});_!==0&&process.exit(_),y&&!e$1.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init")));let w=Gn(process.cwd());if(w){let m=C.dirname(w),g=C.join(m,".python-version"),v=C.join(c,".python-version");try{if(await R__default.pathExists(g)){let u=S.readFileSync(g,"utf-8");S.writeFileSync(v,u.trim()+`
|
|
388
|
+
`),f.debug(`Synced Python version ${u.trim()} from workspace to project`);}}catch(u){f.debug("Could not sync Python version from workspace:",u);}}if(!e$1.skipInstall){let m=await e(["init",c],{cwd:process.cwd()});if(m!==0&&process.exit(m),w){let g=C.dirname(w),v=C.join(g,".python-version"),u=C.join(c,".python-version");try{if(await R__default.pathExists(v)){let b=S.readFileSync(v,"utf-8");S.writeFileSync(u,b.trim()+`
|
|
389
|
+
`),f.debug(`Re-synced Python version ${b.trim()} after init`);}}catch(b){f.debug("Could not re-sync Python version after init:",b);}}}}else {let{createProject:l}=await import('./create-KFR6FLRT.js');await l(t,{skipGit:e$1.skipGit,skipPythonEngine:e$1.skipPythonEngine,dryRun:e$1.dryRun,yes:e$1.yes,userConfig:n,installMethod:e$1.installMethod,profile:e$1.profile,parentDirectory:C.dirname(c)}),console.log(s.gray(`\u2139\uFE0F Workspace root: ${c}`)),console.log(s.gray(` Next: ${f$2(c)} && npx workspai create project`));}}catch(o){o instanceof a$1?(f.error(`
|
|
391
390
|
\u274C ${o.message}`),o.details&&f.warn(`\u{1F4A1} ${o.details}`),f.debug("Error code:",o.code)):(f.error(`
|
|
392
|
-
\u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{pt=null;}});oi(ne);ai(ne);Di(ne);ne.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{Rp({json:t.json});});ne.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:o}=await import('./analyze-5BU4QIPK.js'),r=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(r,null,2)):o(r),r.summary.verdict==="blocked"&&process.exit(2);}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify({schemaVersion:"rapidkit-analyze-error-v1",ok:false,error:{message:o}},null,2)):console.error(s.red(`Analyze failed: ${o}`)),process.exit(1);}});Ts(ne);ne.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(u){let f=u;for(;;){let p$1=p(f,"context.json").find(g=>S.existsSync(g));if(p$1)return p$1;let d=b.dirname(f);if(d===f)break;f=d;}return null}let r=o(e);function n$1(u){let f=u;for(;;){let p=b.join(f,".venv"),d=[b.join(f,".workspai","activate"),b.join(f,".rapidkit","activate")].find(m=>S.existsSync(m))??b.join(f,".workspai","activate");if(S.existsSync(d)||S.existsSync(p))return {venv:p,activateFile:d};let g=b.dirname(f);if(g===f)break;f=g;}return null}let i=n$1(e);!r&&!i&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let a;i&&S.existsSync(i.activateFile)?a=i.activateFile:i&&S.existsSync(i.venv)?a=n(i.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$1();console.log(c?`call "${a}"`:`. "${a}"`);});ne.command("readiness").description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$6({json:t.json,strict:t.strict,skipVerify:t.skipVerify});});ne.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:o}=await import('./pipeline-HQ57V6OZ.js');await o({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.noAgentSync===true,agentSync:t.agentSync===true?true:t.noAgentSync?false:void 0});});ne.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let o=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(o)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let r=Number(e.maxWorkers??""),n=Number.isFinite(r)?Math.max(1,Math.trunc(r)):void 0,{runAutopilotRelease:i}=await import('./autopilot-release-45YVOBQO.js'),a;try{a=await i({workspacePath:process.cwd(),mode:o,since:e.since,parallel:e.parallel===true,maxWorkers:n,json:e.json===true,output:e.output});}catch(c){let u=c instanceof Error?c.message:String(c);console.log(s.red(`Autopilot release failed: ${u}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});ne.command("import <source>").description("Import a local backend project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest 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").option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await Dp(t,e);o!==0&&process.exit(o);});ne.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").option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await Tp(t,e);o!==0&&process.exit(o);});var lr=ne.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");lr.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 o=await $t({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot create failed: ${o.message}`)),process.exit(1);}});lr.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 fi({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let o of e)console.log(s.cyan(o.name)),console.log(s.gray(` ${o.createdAt} | ${o.mode} | ${o.projects.length} project(s)`)),console.log(s.gray(` ${o.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});lr.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 o=await mi({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.cyan(`Snapshot: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Created: ${o.manifest.createdAt}`)),console.log(s.gray(` Projects: ${o.manifest.projects.length}`)),console.log(s.gray(` Files: ${o.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${o.estimatedBytes}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot inspect failed: ${o.message}`)),process.exit(1);}});lr.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 o=await gi({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(o,null,2));return}o.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${o.snapshotPath}`)),console.log(s.gray(` Restored paths: ${o.restoredPaths.join(", ")}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot restore failed: ${o.message}`)),process.exit(1);}});var lo=ne.command("project").description("Safe workspace project lifecycle operations");lo.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{Na({json:t.json});});lo.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 Br({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let o of e)console.log(s.cyan(o.projectName)),console.log(s.gray(` Archived: ${o.archivedAt}`)),console.log(s.gray(` Path: ${o.archivePath}`)),o.reason&&console.log(s.gray(` Reason: ${o.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});lo.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 o=await Hr({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project archive dry-run: ${o.projectName}`):s.green(`\u2714 Project archived: ${o.projectName}`)),console.log(s.gray(` From: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` To: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project archive failed: ${o.message}`)),process.exit(1);}});lo.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 o=await vi({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project restore dry-run: ${o.projectName}`):s.green(`\u2714 Project restored: ${o.projectName}`)),console.log(s.gray(` From: ${o.archivePath}`)),console.log(s.gray(` To: ${o.projectPath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project restore failed: ${o.message}`)),process.exit(1);}});lo.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 o=await ki({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}let r=o.action==="archive"?"archived":"deleted";console.log(o.dryRun?s.cyan(`Project ${r} dry-run: ${o.projectName}`):s.green(`\u2714 Project ${r}: ${o.projectName}`)),console.log(s.gray(` Path: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` Archive: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project delete failed: ${o.message}`)),process.exit(1);}});ne.command("doctor [scope]").description("\u{1FA7A} Check 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","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let o=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!o.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let r=await Ep({scope:t,workspaceFlag:e.workspace});r.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),r.candidatePath&&console.log(s.gray(` Candidate: ${r.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-DK4BON3N.js'),i=await n({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});i!==0&&process.exit(i);});ne.command("workspace <action> [subaction] [key] [value]").description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
|
|
391
|
+
\u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{yt=null;}});Ea(ne);Oa(ne);mi(ne);ne.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{pd({json:t.json});});ne.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:o}=await import('./analyze-YLV7NVLF.js'),r=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(r,null,2)):o(r),r.summary.verdict==="blocked"&&process.exit(2);}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$2({operation:"analyze",code:"analyze.failed",message:o}),null,2)):console.error(s.red(`Analyze failed: ${o}`)),process.exit(1);}});la(ne);ne.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(l){let p$1=l;for(;;){let f=p(p$1,"context.json").find(y=>S.existsSync(y));if(f)return f;let d=C.dirname(p$1);if(d===p$1)break;p$1=d;}return null}let r=o(e);function n$1(l){let p=l;for(;;){let f=C.join(p,".venv"),d=[C.join(p,".workspai","activate"),C.join(p,".rapidkit","activate")].find(h=>S.existsSync(h))??C.join(p,".workspai","activate");if(S.existsSync(d)||S.existsSync(f))return {venv:f,activateFile:d};let y=C.dirname(p);if(y===p)break;p=y;}return null}let a=n$1(e);!r&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&S.existsSync(a.activateFile)?i=a.activateFile:a&&S.existsSync(a.venv)?i=n(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b();console.log(c?`call "${i}"`:`. "${i}"`);});ne.command(d$2.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 e$1({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});ne.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:o}=await import('./pipeline-FEDYO3IA.js');await o({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});ne.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let o=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(o)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let r=Fn({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-YBN3SWAA.js'),a;try{a=await n({workspacePath:process.cwd(),mode:o,since:e.since,parallel:e.parallel===true,maxWorkers:r,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);});ne.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").option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await vd(t,e);o!==0&&process.exit(o);});ne.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").option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await Pd(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});o!==0&&process.exit(o);});var Er=ne.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");Er.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 o=await rr({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot create failed: ${o.message}`)),process.exit(1);}});Er.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 Va({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let o of e)console.log(s.cyan(o.name)),console.log(s.gray(` ${o.createdAt} | ${o.mode} | ${o.projects.length} project(s)`)),console.log(s.gray(` ${o.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});Er.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 o=await Ja({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.cyan(`Snapshot: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Created: ${o.manifest.createdAt}`)),console.log(s.gray(` Projects: ${o.manifest.projects.length}`)),console.log(s.gray(` Files: ${o.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${o.estimatedBytes}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot inspect failed: ${o.message}`)),process.exit(1);}});Er.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 o=await Ua({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(o,null,2));return}o.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${o.snapshotPath}`)),console.log(s.gray(` Restored paths: ${o.restoredPaths.join(", ")}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot restore failed: ${o.message}`)),process.exit(1);}});var jo=ne.command("project").description("Safe workspace project lifecycle operations");jo.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{mc({json:t.json});});jo.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 pn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let o of e)console.log(s.cyan(o.projectName)),console.log(s.gray(` Archived: ${o.archivedAt}`)),console.log(s.gray(` Path: ${o.archivePath}`)),o.reason&&console.log(s.gray(` Reason: ${o.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});jo.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 o=await dn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project archive dry-run: ${o.projectName}`):s.green(`\u2714 Project archived: ${o.projectName}`)),console.log(s.gray(` From: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` To: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){let r=o.message;e.json?console.log(JSON.stringify(c$2({operation:"project archive",code:"project.archive.failed",message:r}),null,2)):console.log(s.red(`\u274C Project archive failed: ${r}`)),process.exit(1);}});jo.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 o=await Ya({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(o,null,2));return}console.log(o.dryRun?s.cyan(`Project restore dry-run: ${o.projectName}`):s.green(`\u2714 Project restored: ${o.projectName}`)),console.log(s.gray(` From: ${o.archivePath}`)),console.log(s.gray(` To: ${o.projectPath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){let r=o.message;e.json?console.log(JSON.stringify(c$2({operation:"project restore",code:"project.restore.failed",message:r}),null,2)):console.log(s.red(`\u274C Project restore failed: ${r}`)),process.exit(1);}});jo.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 o=await za({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}let r=o.action==="archive"?"archived":"deleted";console.log(o.dryRun?s.cyan(`Project ${r} dry-run: ${o.projectName}`):s.green(`\u2714 Project ${r}: ${o.projectName}`)),console.log(s.gray(` Path: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` Archive: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){let r=o.message;e.json?console.log(JSON.stringify(c$2({operation:"project delete",code:"project.delete.failed",message:r}),null,2)):console.log(s.red(`\u274C Project delete failed: ${r}`)),process.exit(1);}});ne.command(d$2.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","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let o=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!o.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let r=await dd({scope:t,workspaceFlag:e.workspace});r.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),r.candidatePath&&console.log(s.gray(` Candidate: ${r.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-YJDM5XBH.js'),a=await n({...e,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);});ne.command(d$2.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
|
|
393
392
|
workspace run <stage> \u2014 fleet stage execution across discovered projects
|
|
394
393
|
stages: init | test | build | start | <custom-from-context>
|
|
395
394
|
workspace explain|why \u2014 blocker/project narrative (--write for artifact)
|
|
396
395
|
workspace trace \u2014 diff \u2192 blast radius \u2192 gates narrative (--from <diff>)
|
|
397
|
-
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("--cache","Reuse cached workspace model when inputs are unchanged (keyed by inputsHash)").option("--incremental","Rebuild only changed projects and re-infer only their incident graph edges (graph-aware)").option("--once","For workspace watch: do the initial in-memory build and exit (no watcher)").option("--for-agent [agent]","Build an agent-ready workspace context pack").option("--agent-sync","After --write on context, sync cross-tool agent grounding files (AGENTS.md, Copilot, Cursor, Claude)").option("--no-agent-sync","Skip automatic agent grounding sync after context --write").option("--target <targets>","Agent customization targets for agent-sync (all|vscode|agents,copilot,cursor,claude,codex,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").option("--refresh-context","Rebuild workspace-context-agent.json during agent-sync").option("--experimental-hooks","Generate advisory VS Code agent hook design files during enterprise agent-sync").option("--hydrate-prompts","Hydrate matching Copilot prompt files with workspace-specific verification steps during agent-sync").option("--scope <scope>","Scope workspace intelligence output, e.g. project:<name>").option("--no-doctor","Exclude doctor evidence in workspace share bundle").option("--no-blueprint","Exclude reproducibility blueprint from workspace share bundle").option("--include-env","Include .env/private key files in workspace export archive").option("--force","Overwrite an existing hydrate output directory").option("--refresh","Publish workspace registry summary before reading status").option("--dry-run","Preview hydrate without writing files").option("--affected","Run only affected projects (requires git diff context)").option("--blast-radius","Include downstream dependents from workspace dependency graph").option("--since <ref>","Git ref for affected calculation (default: HEAD~1)").option("--parallel","Run project stages in parallel").option("--max-workers <count>","Maximum parallel workers (default: min(4, selected))").option("--continue-on-error","Continue running remaining projects after a failure").option("--reuse-passed","Skip projects that already passed this stage in workspace-run-last.json").option("--json","Emit machine-readable JSON output").option("--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").action(async function(t,e,o,r){let n=this.opts(),i=p=>{let g=(n.workspace?b.resolve(n.workspace):null)??a$5(process.cwd())??oe(process.cwd());(!g||!Ue(g))&&(console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run from a workspace directory or pass --workspace <path>.")),process.exit(1));let m=b.resolve(process.cwd()),l=b.resolve(g);return m!==l&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${g} for "${p}" (current directory: ${m}).`)),g},a=p=>process.argv.includes(p),c=p=>_e(process.argv,p),u=()=>n.output||c("--output"),f=()=>{if(!n.scanDepth)return;let p=Number.parseInt(n.scanDepth,10);return Number.isFinite(p)?p:void 0};if((Gi(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||a("--json"),strict:n.strict===true||a("--strict")}}),t==="list"){let{listWorkspaces:p}=await import('./workspace-DZHWB7BV.js');await p({json:n.json===true||a("--json")});}else if(t==="model"){let p=i("model"),{buildWorkspaceModelCached:d,buildWorkspaceModelIncremental:g,writeWorkspaceModel:m}=await import('./workspace-model-F3B75TYT.js'),l=n.incremental===true||a("--incremental"),y=n.cache===true||a("--cache")||l,k={workspacePath:p,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:f(),strict:n.strict===true||a("--strict")},v,h;if(l){let P=await g(k);v=P.model,h=P.mode;}else {let P=await d({...k,cache:y});v=P.model,h=P.cache;}let w;(n.write===true||a("--write"))&&(w=await m(v,p));let x=(n.strict===true||a("--strict"))&&v.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...v,...w?{outputPath:w}:{}},null,2)),x&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${v.workspace.name}`)),l?console.log(s.gray(` Build: ${h} (incremental)`)):y&&console.log(s.gray(` Cache: ${h}`)),console.log(s.gray(` Projects: ${v.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${v.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${v.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${v.identity.workspaceType}`)),console.log(s.gray(` Validation: ${v.validation?.status??"unknown"} (${v.validation?.errors??0} error, ${v.validation?.warnings??0} warning)`)),console.log(w?s.gray(` Written: ${w}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),x&&process.exit(1);}else if(t==="agent-sync"){let p=i("agent-sync"),{syncWorkspaceAgentGrounding:d,parseAgentGroundingTargets:g}=await import('./workspace-agent-sync-5ADIQS7B.js'),m=n.strict===true||a("--strict"),l=n.write===true||a("--write"),y=a("--dry-run"),k=await d({workspacePath:p,scope:n.scope,agent:n.forAgent,write:l&&!y,dryRun:y,strict:m,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||a("--refresh-context")||a("--refresh"),targets:g(n.target),experimentalHooks:n.experimentalHooks===true||a("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||a("--hydrate-prompts"),staleAfterHours:24});if(n.json)console.log(JSON.stringify(k,null,2));else {console.log(s.green(`\u2714 Agent grounding ${l&&!y?"synced":"planned"}`)),console.log(s.gray(` Index: ${k.indexPath}`)),k.contextPath&&console.log(s.gray(` Context: ${k.contextPath}`)),k.blockers.length>0&&console.log(s.yellow(` Blockers: ${k.blockers.slice(0,3).join(" \xB7 ")}`));let v=l&&!y?k.writtenFiles:k.skippedFiles;if(v.length>0&&console.log(s.gray(` Files: ${v.join(", ")}`)),k.strictViolations.length>0)for(let h of k.strictViolations)console.log(s.red(`\u274C ${h}`));}m&&k.strictViolations.length>0&&process.exit(1);}else if(t==="remediation-plan"){let p=i("remediation-plan"),{buildArtifactRemediationPlan:d,writeArtifactRemediationPlan:g}=await import('./artifact-remediation-plan-244S5K6I.js'),m=await d({workspacePath:p,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),ciMode:n.ci===true||a("--ci")}),l;if((n.write===true||a("--write"))&&(l=await g(m,p)),n.json===true||a("--json")){console.log(JSON.stringify({...m,...l?{outputPath:l}:{}},null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${m.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${m.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${m.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${m.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${m.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${m.summary.risk.safe}, guarded=${m.summary.risk.guarded}, invasive=${m.summary.risk.invasive}`));for(let y of m.actions.slice(0,8))console.log(s.gray(` \u2022 ${y.cardId}: ${y.title} (${y.mode}, ${y.risk})`));m.actions.length>8&&console.log(s.gray(` \u2026 ${m.actions.length-8} more action(s)`)),console.log(l?s.gray(` Written: ${l}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let p=i("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:d,writeWorkspaceAgentContext:g}=await import('./workspace-context-GEXDHA7A.js'),m=n.strict===true||a("--strict"),l=await d({workspacePath:p,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:f(),strict:false}),y,k;if((n.write===true||a("--write"))&&(y=await g(l,p),(n.agentSync===true||a("--agent-sync")||n.noAgentSync!==true)&&!a("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:w,parseAgentGroundingTargets:x}=await import('./workspace-agent-sync-5ADIQS7B.js');if(k=await w({workspacePath:p,scope:n.scope,agent:l.agent,write:true,refreshContext:false,strict:m,preset:n.preset==="minimal"?"minimal":"enterprise",targets:x(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${k.writtenFiles.length} file(s) updated`)),m&&k.strictViolations.length>0){for(let P of k.strictViolations)console.log(s.red(`\u274C ${P}`));process.exit(1);}}let v=m&&l.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...l,...y?{outputPath:y}:{},...k?{agentGroundingSync:k}:{}},null,2)),v&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${l.workspace.name}`)),console.log(s.gray(` Agent: ${l.agent}`)),console.log(s.gray(` Scope: ${l.scope.activeProject??l.scope.requested}`)),console.log(s.gray(` Projects included: ${l.projects.length}`)),console.log(s.gray(` Safe commands: ${l.safeCommands.length}`)),console.log(s.gray(` Validation: ${l.validation.status} (${l.validation.errors} error, ${l.validation.warnings} warning)`)),console.log(y?s.gray(` Written: ${y}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),v){for(let h of l.validation.issues)console.log(s.red(`\u274C ${h.severity}:${h.code}:${h.target}`));process.exit(1);}}else if(t==="snapshot"){let p=i("snapshot"),{buildWorkspaceModelSnapshot:d,writeWorkspaceModelSnapshot:g}=await import('./workspace-intelligence-BEM6WGCZ.js'),m=await d({workspacePath:p,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:f()}),l=await g(m,p);if(n.json){console.log(JSON.stringify({...m,outputPath:l},null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${m.model.workspace.name}`)),console.log(s.gray(` Hash: ${m.modelHash}`)),console.log(s.gray(` Projects: ${m.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${m.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${l}`));}else if(t==="diff"){let p=i("diff"),d=n.from||e;d||((n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-diff-error-v1",command:"workspace diff",status:"error",workspacePath:p,error:{code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>."},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:g,writeWorkspaceModelDiff:m}=await import('./workspace-intelligence-BEM6WGCZ.js'),l;try{l=await g({workspacePath:p,fromPath:d,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:f()});}catch(v){throw (n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-diff-error-v1",command:"workspace diff",status:"error",workspacePath:p,fromPath:d,error:{code:"workspace.diff.input_unreadable",message:v.message},nextActions:["npx workspai workspace snapshot create --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]},null,2)),process.exit(1)),v}let y=await m(l,p);if(n.json){console.log(JSON.stringify({...l,outputPath:y},null,2));return}let k=l.summary.changed?s.yellow:s.green;console.log(k(`\u2714 Workspace model diff: ${l.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${l.fromRef}`)),console.log(s.gray(` Added projects: ${l.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${l.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${l.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${l.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${l.summary.validationChanges}`)),l.git?.available&&console.log(s.gray(` Git: ${l.git.dirty?"dirty":"clean"} (${l.summary.gitChangedFiles} mapped change(s))`));for(let v of l.changes.slice(0,12))console.log(s.gray(` \u2022 ${v.type} ${v.target}: ${v.message}`));l.changes.length>12&&console.log(s.gray(` \u2026 ${l.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${y}`));}else if(t==="impact"){let p=i("impact"),d=n.from||e;d||((n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-impact-error-v1",command:"workspace impact",status:"error",workspacePath:p,error:{code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>."},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 <snapshot-model-or-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:g,writeWorkspaceImpact:m}=await import('./workspace-intelligence-BEM6WGCZ.js'),l;try{l=await g({workspacePath:p,fromPath:d,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:f()});}catch(v){throw (n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-impact-error-v1",command:"workspace impact",status:"error",workspacePath:p,fromPath:d,error:{code:"workspace.impact.input_unreadable",message:v.message},nextActions:["npx workspai workspace snapshot create --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)),v}let y=await m(l,p);if(n.json){console.log(JSON.stringify({...l,outputPath:y},null,2));return}let k=l.summary.risk==="critical"||l.summary.risk==="high"?s.red:l.summary.risk==="medium"?s.yellow:s.green;console.log(k(`\u2714 Workspace impact: ${l.summary.risk}`)),console.log(s.gray(` From: ${l.fromRef}`)),console.log(s.gray(` Affected projects: ${l.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${l.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${l.summary.recommendedCommands}`));for(let v of l.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${v.title}: ${v.summary}`));l.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${l.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${y}`));}else if(t==="verify"){let p=i("verify"),{buildWorkspaceVerify:d,writeWorkspaceVerify:g,evaluateWorkspaceVerifyGate:m}=await import('./workspace-verify-OAATQV5T.js'),l=await d({workspacePath:p,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:f()}),y=await g(l,p),k=m(l,{strict:n.strict===true||a("--strict")}),v=k.exitCode,{recordWorkspaceHistory:h,historyEntryFromVerify:w}=await import('./workspace-history-CGCK2DJI.js');if(await h(p,w(l,k.passed)),n.json){console.log(JSON.stringify({...l,gate:k,outputPath:y},null,2)),v!==0&&process.exit(v);return}let x=l.summary.verdict==="ready"?s.green:l.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(x(`\u2714 Workspace verify: ${l.summary.verdict}`)),console.log(s.gray(` Freshness: ${l.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${l.impact.risk}`)),console.log(s.gray(` Steps: ${l.steps.length}`)),console.log(s.gray(` Passed ${l.summary.stepsPassed}, warn ${l.summary.stepsWarn}, failed ${l.summary.stepsFailed}, missing ${l.summary.stepsMissing}`));for(let P of l.steps.slice(0,10))console.log(s.gray(` \u2022 ${P.id}: ${P.status} \u2014 ${P.message}`));if(l.steps.length>10&&console.log(s.gray(` \u2026 ${l.steps.length-10} more step(s)`)),l.policyViolations.length>0){console.log(s.gray(` Policy (${l.policyMode}): ${l.policyViolations.length} violation(s)`));for(let P of l.policyViolations.slice(0,5)){let R=P.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${R} [${P.source}] ${P.code}: ${P.message}`);}}console.log(s.gray(` Gate (${k.mode}): ${k.passed?"passed":"blocked"}`));for(let P of k.reasons.slice(0,5))console.log(s.red(` \u2717 ${P}`));console.log(s.gray(` Written: ${y}`)),v!==0&&process.exit(v);}else if(t==="graph"){let p=i("graph"),{buildWorkspaceModel:d}=await import('./workspace-model-F3B75TYT.js'),{buildGraphEmit:g,renderGraphDot:m,renderGraphMermaid:l,explainGraphNode:y}=await import('./workspace-graph-2A5THUCI.js'),v=(await d({workspacePath:p,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:f()})).graph,h=(e||"emit").toLowerCase();if(v||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:h,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)),h==="dot"){console.log(m(v));return}if(h==="mermaid"){console.log(l(v));return}if(h==="explain"){let x=(n.scope?.replace(/^project:/,"")||o||"").trim();x||(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 P=y(v,x);if(n.json){console.log(JSON.stringify(P,null,2)),P.found||process.exit(1);return}P.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${x}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${P.project}`)),P.centrality&&console.log(s.gray(` Centrality: fanIn ${P.centrality.fanIn}, fanOut ${P.centrality.fanOut}, reach ${P.centrality.reach}, betweenness ${P.centrality.betweenness}${P.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${P.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${P.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${P.transitiveDependents.length}`));for(let R of P.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${R.id} (d${R.distance}, via ${R.via??"\u2014"})`));return}let w=g(v);if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${w.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${w.graph.stats.edgeCount} (inferred ${w.graph.stats.inferredEdges}, contract ${w.graph.stats.contractEdges}, manual ${w.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${w.integrity.ok?"ok":"issues"} (cycles ${w.integrity.stats.cycleCount}, dangling ${w.integrity.stats.danglingCount}, orphans ${w.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${w.hotspots.join(", ")||"none"}`)),console.log(s.gray(" Render: workspace graph dot | workspace graph mermaid"));}else if(t==="watch"){let p=i("watch"),{runWorkspaceWatch:d}=await import('./workspace-watch-HU2OTQ52.js'),g=n.once===true||a("--once"),m=n.json===true,l=new AbortController,y=()=>l.abort();process.once("SIGINT",y),process.once("SIGTERM",y),m||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await d({workspacePath:p,once:g,signal:l.signal,buildOptions:{workspacePath:p,observableScanDepth:f()},onProgress:k=>{m||console.error(s.gray(` ${k}`));},emit:k=>{if(m){console.log(JSON.stringify(k));return}if(k.kind==="ready"){console.log(s.gray(` Ready: ${k.graph.nodeCount} nodes, ${k.graph.edgeCount} edges (hash ${k.modelHash.slice(0,12)})`));return}if(k.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${k.error??"unknown error"}`));return}if(k.kind==="unchanged"){console.log(s.gray(` No structural change (${k.mode}, ${k.durationMs}ms)`));return}let v=[];k.changedProjects.length>0&&v.push(`changed: ${k.changedProjects.join(", ")}`),k.addedProjects.length>0&&v.push(`added: ${k.addedProjects.join(", ")}`),k.removedProjects.length>0&&v.push(`removed: ${k.removedProjects.join(", ")}`),k.graph.edgesAdded.length>0&&v.push(`+${k.graph.edgesAdded.length} edges`),k.graph.edgesRemoved.length>0&&v.push(`-${k.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${k.mode}, ${k.durationMs}ms): ${v.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",y),process.removeListener("SIGTERM",y),!m&&!g&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let p=i("sync"),{syncWorkspaceProjects:d}=await import('./workspace-DZHWB7BV.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${b.basename(p)}`));let g=await d(p,n.json===true);await ot(p,{silent:n.json===true});let{readWorkspaceRegistrySummary:m}=await import('./workspace-registry-summary-6MFBRWDS.js'),l=await m(p);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:p,registry:g,contractSynced:true,registrySummary:l},null,2));}else if(t==="registry"){let p=i("registry"),d=e||"status";d!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${d}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:g,resolveWorkspaceRegisteredProjects:m}=await import('./workspace-registry-summary-6MFBRWDS.js'),l=await g(p);if(n.json){console.log(JSON.stringify(l,null,2));return}let y=await m(p);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${l.authority}`)),console.log(s.gray(` Projects: ${l.projectCount}`)),console.log(s.gray(` Summary: ${l.registrySummaryPath}`)),y.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let p=i("foundation"),d=e||"ensure";d!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${d}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:g}=await import('./workspace-foundation-FQWHPQGX.js'),m=await g(p,{force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(m,null,2));return}m.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${m.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let p=i("policy"),d=await Kp(p,e,o,r,n.json===true||a("--json"));d!==0&&process.exit(d);}else if(t==="contract"){let p=i("contract"),{buildWorkspaceContractGraph:d,readWorkspaceContract:g,verifyWorkspaceContract:m,writeWorkspaceContract:l,WORKSPACE_CONTRACT_PATH:y}=await import('./workspace-contract-2TA27LGT.js'),k=e||"inspect",v=n.output;try{if(k==="init"){let h=await l({workspacePath:p,outputPath:v,force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(h,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${h.contractPath}`)),console.log(s.gray(` Projects: ${h.contract.projects.length}`));return}if(k==="inspect"){let h=await g({workspacePath:p,contractPath:v});if(n.json){console.log(JSON.stringify(h,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${h.contractPath}`)),console.log(s.gray(` Workspace: ${h.contract.workspace.name}`)),console.log(s.gray(` Projects: ${h.contract.projects.length}`)),console.log(s.gray(` Schema: v${h.contract.schemaVersion}`));return}if(k==="verify"){let h=await m({workspacePath:p,contractPath:v,strict:n.strict===true||a("--strict")}),{writeWorkspaceContractVerifyEvidence:w}=await import('./workspace-contract-2TA27LGT.js'),x=await w({workspacePath:p,result:h});if(n.json)console.log(JSON.stringify({...h,evidencePath:x},null,2));else {let P=h.status==="passed"?s.green:s.red;console.log(P(`\u2714 Workspace contract verification ${h.status}: ${h.contractPath}`)),console.log(s.gray(` Projects: ${h.projectCount}`));for(let R of h.checks){let I=R.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${I} ${R.id}: ${R.message}`));}for(let R of h.violations)console.log(s.gray(` Violation: ${R}`));}(h.status==="failed"||h.status!=="passed"&&n.strict)&&process.exit(1);return}if(k==="graph"){let h=await d({workspacePath:p,contractPath:v});if(n.json){console.log(JSON.stringify(h,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${h.contractPath}`)),console.log(s.gray(` Workspace: ${h.graph.workspace.name}`)),console.log(s.gray(` Projects: ${h.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${h.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${h.graph.summary.eventEdges}`)),console.log(s.gray(` Ports: ${h.graph.summary.portCount}`));for(let w of h.graph.nodes){let x=w.ports.map(P=>`${P.name}:${P.port}`).join(", ")||"none";console.log(s.gray(` \u2022 ${w.id} (${w.runtime||"unknown"}${w.framework?`/${w.framework}`:""}) ports=${x}`));}for(let w of h.graph.edges){let x=w.type==="event"?`event:${w.label}`:w.label;console.log(s.gray(` ${w.from} -> ${w.to} [${x}]`));}return}console.log(s.red(`\u274C Unknown workspace contract action: ${k}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${y}]`)),process.exit(1);}catch(h){n.json&&(console.log(JSON.stringify({command:`workspace contract ${k}`,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${k}.failed`,message:h.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${k} failed: ${h.message}`)),process.exit(1);}}else if(t==="share"){let p=i("share"),d=u()||e,{createWorkspaceShareBundle:g}=await import('./workspace-DZHWB7BV.js'),m=await g(p,{outputPath:d,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:m,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: ${m}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let p=i("export"),{exportWorkspaceArchive:d}=await import('./workspace-archive-GCZNI44O.js'),g=await d({workspacePath:p,outputPath:u()||e,includeEnv:n.includeEnv===true||a("--include-env")});if(n.json){console.log(JSON.stringify(g,null,2));return}let m=(g.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${g.archivePath}`)),console.log(s.gray(` Files: ${g.manifest.files.length}`)),console.log(s.gray(` Size: ${m} MB`)),g.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let p=o;p||(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:d,inspectWorkspaceArchive:g,verifyWorkspaceArchive:m}=await import('./workspace-archive-GCZNI44O.js');try{if(e==="inspect"){let y=await g({archivePathOrUrl:p});if(n.json){console.log(JSON.stringify(y,null,2));return}let k=(y.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${y.archivePath}`)),console.log(s.gray(` Workspace: ${y.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${y.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${y.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${y.fileCount}`)),console.log(s.gray(` Payload: ${k} MB`));return}if(e==="doctor"){let y=await d({archivePathOrUrl:p,strict:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(y,null,2));else {let k=y.status==="passed"?s.green:y.status==="warning"?s.yellow:s.red;console.log(k(`\u2714 Workspace archive doctor ${y.status}: ${y.archivePath}`)),console.log(s.gray(` Workspace: ${y.workspaceName}`)),console.log(s.gray(` Files: ${y.fileCount}`));for(let v of y.checks){let h=v.status==="passed"?"\u2714":v.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${h} ${v.id}: ${v.message}`));}for(let v of y.recommendedActions)console.log(s.gray(` Next: ${v}`));}(y.status==="failed"||y.status==="warning"&&n.strict)&&process.exit(1);return}let l=await m({archivePathOrUrl:p,requireChecksums:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(l,null,2));else if(l.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${l.archivePath}`)),console.log(s.gray(` Files: ${l.verifiedFiles}/${l.fileCount}`));else {let y=l.status==="failed"?s.red:s.yellow;console.log(y(`\u274C Workspace archive verification ${l.status}: ${l.archivePath}`)),l.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${l.missingArchiveEntries.join(", ")}`)),l.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${l.extraArchiveEntries.join(", ")}`)),l.mismatches.length&&console.log(s.gray(` Mismatches: ${l.mismatches.map(k=>k.path).join(", ")}`)),l.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${l.missingChecksumFiles.join(", ")}`));}(l.status==="failed"||l.status==="warning"&&n.strict)&&process.exit(1);}catch(l){n.json&&(console.log(JSON.stringify({schemaVersion:"workspace-archive-error-v1",command:`workspace archive ${e}`,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:p,error:{code:`workspace.archive.${e}.failed`,message:l.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${l.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let p=e;p||(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));let{hydrateWorkspaceArchive:d}=await import('./workspace-archive-GCZNI44O.js');try{let g=await d({archivePathOrUrl:p,outputPath:n.output,force:n.force===true||a("--force"),dryRun:n.dryRun===true||a("--dry-run"),strict:n.strict===true||a("--strict")});if(n.json){console.log(JSON.stringify(g,null,2));return}console.log(s.green(g.dryRun?`\u2714 Workspace archive hydrate preview: ${g.outputPath}`:`\u2714 Workspace archive hydrated: ${g.outputPath}`)),console.log(s.gray(` Files: ${g.files.length}`)),g.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${g.manifest.workspaceName}`));}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:"workspace-archive-error-v1",command:`workspace ${t}`,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:p,outputPath:n.output??null,dryRun:n.dryRun===true||a("--dry-run"),error:{code:`workspace.${t}.failed`,message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${g.message}`)),process.exit(1);}}else if(t==="run"){let p=i(`run ${e||""}`.trim()),d=new Set(["init","test","build","start"]),g=e?.trim()??"";g||(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)),d.has(g)||(!/^[a-z][a-z0-9_-]*$/i.test(g)||g==="dev"||g==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${g}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),process.exit(2));let m=Number(n.maxWorkers??""),l=Number.isFinite(m)?Math.max(1,Math.trunc(m)):void 0;if(g==="init"&&n.json!==true){let v=await Sn(p);v!==0&&process.exit(v);}let{runWorkspaceStage:y}=await import('./workspace-run-3WJXIQKR.js'),k=await y({workspacePath:p,stage:g,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:l,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(k,null,2)),k.summary.exitCode!==0&&process.exit(k.summary.exitCode);}else if(t==="explain"||t==="why"){let p=i(t),{parseWorkspaceExplainTarget:d}=await import('./workspace-explain-contract-DNS2YEL7.js'),{buildWorkspaceExplain:g,writeWorkspaceExplainReport:m}=await import('./workspace-explain-D5NNL3NG.js'),l=(e??o??"").trim();!l&&n.scope&&(l=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),l||(console.log(s.red(`\u274C workspace ${t} requires a target.`)),console.log(s.gray(" npx workspai workspace explain project:<name>|release-blocked [--json] [--write]")),console.log(s.gray(" npx workspai workspace why <project>|release-blocked [--json]")),process.exit(1));let y=d(l);y||(console.log(s.red(`\u274C Invalid explain target: ${l}`)),process.exit(1));let k=await g({workspacePath:p,target:y}),v=n.write===true||a("--write"),h;if(v&&(h=await m(k,p,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify({...k,outputPath:h},null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${k.summary}`));for(let w of k.sections)console.log(s.bold(`
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
396
|
+
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("--cache","Reuse cached workspace model when inputs are unchanged (keyed by inputsHash)").option("--incremental","Rebuild only changed projects and re-infer only their incident graph edges (graph-aware)").option("--once","For workspace watch: do the initial in-memory build and exit (no watcher)").option("--for-agent [agent]","Build an agent-ready workspace context pack").option("--agent-sync","After --write on context, sync cross-tool agent grounding files (AGENTS.md, Copilot, Cursor, Claude)").option("--no-agent-sync","Skip automatic agent grounding sync after context --write").option("--target <targets>","Agent customization targets for agent-sync (all|vscode|agents,copilot,cursor,claude,codex,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").option("--refresh-context","Rebuild workspace-context-agent.json during agent-sync").option("--experimental-hooks","Generate advisory VS Code agent hook design files during enterprise agent-sync").option("--hydrate-prompts","Hydrate matching Copilot prompt files with workspace-specific verification steps during agent-sync").option("--scope <scope>","Scope workspace intelligence output, e.g. project:<name>").option("--no-doctor","Exclude doctor evidence in workspace share bundle").option("--no-blueprint","Exclude reproducibility blueprint from workspace share bundle").option("--include-env","Include .env/private key files in workspace export archive").option(f$3.archiveCompression.signature,f$3.archiveCompression.description).option(f$3.maxDownloadSize.signature,f$3.maxDownloadSize.description).option(f$3.maxExpandedSize.signature,f$3.maxExpandedSize.description).option(f$3.downloadTimeoutMs.signature,f$3.downloadTimeoutMs.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("--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").addHelpText("after",`
|
|
397
|
+
Workspace Actions:
|
|
398
|
+
Discovery & registry list | sync | registry | foundation
|
|
399
|
+
Intelligence loop model | snapshot | diff | impact | verify | context
|
|
400
|
+
Intelligence consumers agent-sync | remediation-plan | explain | why | trace | feedback | mcp
|
|
401
|
+
Graph & observation graph | watch
|
|
402
|
+
Contracts & policy contract | policy
|
|
403
|
+
Portability share | export | archive | hydrate | import
|
|
404
|
+
Fleet lifecycle run | init
|
|
405
|
+
|
|
406
|
+
Use "workspai commands --json" for the contract-backed runtime inventory.
|
|
407
|
+
See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,o,r){let n=this.opts(),a=w=>{let m=n.workspace?C.resolve(n.workspace):null,g=m??a$5(process.cwd())??re(process.cwd());(!g||!qe(g))&&((n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$2({operation:`workspace ${w}`,code:"workspace.root.required",message:"Not inside a Workspai workspace. Run from a workspace directory or pass --workspace <path>.",context:{cwd:C.resolve(process.cwd()),...m?{requestedWorkspace:m}:{}}}),null,2)),process.exit(1)),console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run from a workspace directory or pass --workspace <path>.")),process.exit(1));let v=C.resolve(process.cwd()),u=C.resolve(g);return v!==u&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${g} for "${w}" (current directory: ${v}).`)),g},i=w=>process.argv.includes(w),c=w=>be(process.argv,w),l=()=>n.output||c("--output"),p=()=>{if(!n.scanDepth)return;let w=Number.parseInt(n.scanDepth,10);return Number.isFinite(w)?w:void 0},f=(w,m)=>{if(!w)return;let g=w.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!g)throw new Error(`${m} must be a byte size such as 500gb or 2tb.`);let v={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},u=Number(g[1])*v[g[2]||"b"];if(!Number.isSafeInteger(Math.floor(u))||u<=0)throw new Error(`${m} is outside the supported numeric range.`);return Math.floor(u)},d=()=>{let w=n.downloadTimeoutMs,m=w===void 0?void 0:Number.parseInt(w,10);if(m!==void 0&&(!Number.isFinite(m)||m<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:m}},y={list:["--json"],model:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--cache","--incremental","--write","--strict"],"agent-sync":["--workspace","--json","--scope","--for-agent","--write","--dry-run","--strict","--preset","--refresh-context","--refresh","--target","--experimental-hooks","--hydrate-prompts"],"remediation-plan":["--workspace","--json","--include-paths","--ci","--write"],context:["--workspace","--json","--for-agent","--scope","--include-evidence","--scan-depth","--write","--agent-sync","--no-agent-sync","--preset","--target","--strict"],snapshot:["--workspace","--json","--include-paths","--include-evidence","--scan-depth"],diff:["--workspace","--json","--from","--include-paths","--include-evidence","--scan-depth","--strict"],impact:["--workspace","--json","--from","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],verify:["--workspace","--json","--from-impact","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],graph:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--scope"],watch:["--workspace","--json","--once","--scan-depth"],sync:["--workspace","--json"],registry:["--workspace","--json","--refresh"],foundation:["--workspace","--json","--force"],policy:["--workspace","--json"],contract:["--workspace","--json","--output","--force","--strict"],share:["--workspace","--json","--output","--include-paths","--no-doctor","--no-blueprint"],export:["--workspace","--json","--output","--include-env","--archive-compression"],archive:["--json","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms"],hydrate:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms"],import:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms"],run:["--workspace","--json","--scope","--affected","--blast-radius","--since","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],explain:["--workspace","--json","--scope","--write"],why:["--workspace","--json","--scope","--write"],trace:["--workspace","--json","--from","--write"],feedback:["--workspace","--json"],mcp:["--workspace","--json"],init:["--workspace","--json","--scope","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"]},h=new Set(Object.values(y).flatMap(w=>[...w])),k=new Set(process.argv.slice(2).filter(w=>w.startsWith("--")).map(w=>w.split("=",1)[0]).filter(w=>h.has(w))),j=y[t],_=j?[...k].filter(w=>!j.includes(w)):[];if(_.length>0){let w=`${_.join(", ")} ${_.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||k.has("--json")?console.log(JSON.stringify(c$2({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:w,exitCode:2,context:{action:t,unsupportedFlags:_,allowedFlags:j}}),null,2)):(console.log(s.red(`\u274C ${w}`)),console.log(s.gray(` Allowed flags: ${j.join(", ")||"none"}`))),process.exit(2);}if((ki(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$3({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:w}=await import('./workspace-PLXOO6ST.js');await w({json:n.json===true||i("--json")});}else if(t==="model"){let w=a("model"),{buildWorkspaceModelCached:m,buildWorkspaceModelIncremental:g,writeWorkspaceModel:v}=await import('./workspace-model-NG45SRM5.js'),u=n.incremental===true||i("--incremental"),b=n.cache===true||i("--cache")||u,P={workspacePath:w,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p(),strict:n.strict===true||i("--strict")},x,A;if(u){let N=await g(P);x=N.model,A=N.mode;}else {let N=await m({...P,cache:b});x=N.model,A=N.cache;}let I;(n.write===true||i("--write"))&&(I=await v(x,w));let W=(n.strict===true||i("--strict"))&&x.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...x,...I?{outputPath:I}:{}},null,2)),W&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${x.workspace.name}`)),u?console.log(s.gray(` Build: ${A} (incremental)`)):b&&console.log(s.gray(` Cache: ${A}`)),console.log(s.gray(` Projects: ${x.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${x.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${x.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${x.identity.workspaceType}`)),console.log(s.gray(` Validation: ${x.validation?.status??"unknown"} (${x.validation?.errors??0} error, ${x.validation?.warnings??0} warning)`)),console.log(I?s.gray(` Written: ${I}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),W&&process.exit(1);}else if(t==="agent-sync"){let w=a("agent-sync"),{syncWorkspaceAgentGrounding:m,parseAgentGroundingTargets:g}=await import('./workspace-agent-sync-G5YVI3BJ.js'),v=n.strict===true||i("--strict"),u=n.write===true||i("--write"),b=i("--dry-run"),P=await m({workspacePath:w,scope:n.scope,agent:n.forAgent,write:u&&!b,dryRun:b,strict:v,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:g(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),staleAfterHours:24});if(n.json)console.log(JSON.stringify(P,null,2));else {console.log(s.green(`\u2714 Agent grounding ${u&&!b?"synced":"planned"}`)),console.log(s.gray(` Index: ${P.indexPath}`)),P.contextPath&&console.log(s.gray(` Context: ${P.contextPath}`)),P.blockers.length>0&&console.log(s.yellow(` Blockers: ${P.blockers.slice(0,3).join(" \xB7 ")}`));let x=u&&!b?P.writtenFiles:P.skippedFiles;if(x.length>0&&console.log(s.gray(` Files: ${x.join(", ")}`)),P.strictViolations.length>0)for(let A of P.strictViolations)console.log(s.red(`\u274C ${A}`));}v&&P.strictViolations.length>0&&process.exit(1);}else if(t==="remediation-plan"){let w=a("remediation-plan"),{buildArtifactRemediationPlan:m,writeArtifactRemediationPlan:g}=await import('./artifact-remediation-plan-WLZGROUU.js'),v=await m({workspacePath:w,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),u;if((n.write===true||i("--write"))&&(u=await g(v,w)),n.json===true||i("--json")){console.log(JSON.stringify(b$5("workspace remediation-plan",v,u),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${v.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${v.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${v.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${v.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${v.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${v.summary.risk.safe}, guarded=${v.summary.risk.guarded}, invasive=${v.summary.risk.invasive}`));for(let b of v.actions.slice(0,8))console.log(s.gray(` \u2022 ${b.cardId}: ${b.title} (${b.mode}, ${b.risk})`));v.actions.length>8&&console.log(s.gray(` \u2026 ${v.actions.length-8} more action(s)`)),console.log(u?s.gray(` Written: ${u}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let w=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:m,writeWorkspaceAgentContext:g}=await import('./workspace-context-E3UFWL5X.js'),v=n.strict===true||i("--strict"),u=await m({workspacePath:w,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p(),strict:false}),b,P;if((n.write===true||i("--write"))&&(b=await g(u,w),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:I,parseAgentGroundingTargets:W}=await import('./workspace-agent-sync-G5YVI3BJ.js');if(P=await I({workspacePath:w,scope:n.scope,agent:u.agent,write:true,refreshContext:false,strict:v,preset:n.preset==="minimal"?"minimal":"enterprise",targets:W(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${P.writtenFiles.length} file(s) updated`)),v&&P.strictViolations.length>0){for(let N of P.strictViolations)console.log(s.red(`\u274C ${N}`));process.exit(1);}}let x=v&&u.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...u,...b?{outputPath:b}:{},...P?{agentGroundingSync:P}:{}},null,2)),x&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${u.workspace.name}`)),console.log(s.gray(` Agent: ${u.agent}`)),console.log(s.gray(` Scope: ${u.scope.activeProject??u.scope.requested}`)),console.log(s.gray(` Projects included: ${u.projects.length}`)),console.log(s.gray(` Safe commands: ${u.safeCommands.length}`)),console.log(s.gray(` Validation: ${u.validation.status} (${u.validation.errors} error, ${u.validation.warnings} warning)`)),console.log(b?s.gray(` Written: ${b}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),x){for(let A of u.validation.issues)console.log(s.red(`\u274C ${A.severity}:${A.code}:${A.target}`));process.exit(1);}}else if(t==="snapshot"){let w=a("snapshot"),{buildWorkspaceModelSnapshot:m,writeWorkspaceModelSnapshot:g}=await import('./workspace-intelligence-3GG7GEDQ.js'),v=await m({workspacePath:w,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()}),u=await g(v,w);if(n.json){console.log(JSON.stringify(b$5("workspace snapshot",v,u),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${v.model.workspace.name}`)),console.log(s.gray(` Hash: ${v.modelHash}`)),console.log(s.gray(` Projects: ${v.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${v.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${u}`));}else if(t==="diff"){let w=a("diff"),m=n.from||e;m||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:w},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:g,writeWorkspaceModelDiff:v}=await import('./workspace-intelligence-3GG7GEDQ.js'),u;try{u=await g({workspacePath:w,fromPath:m,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:x.message,context:{workspacePath:w,fromPath:m},nextActions:["npx workspai workspace snapshot create --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),x}let b=await v(u,w);if(n.json){console.log(JSON.stringify(b$5("workspace diff",u,b),null,2));return}let P=u.summary.changed?s.yellow:s.green;console.log(P(`\u2714 Workspace model diff: ${u.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${u.fromRef}`)),console.log(s.gray(` Added projects: ${u.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${u.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${u.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${u.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${u.summary.validationChanges}`)),u.git?.available&&console.log(s.gray(` Git: ${u.git.dirty?"dirty":"clean"} (${u.summary.gitChangedFiles} mapped change(s))`));for(let x of u.changes.slice(0,12))console.log(s.gray(` \u2022 ${x.type} ${x.target}: ${x.message}`));u.changes.length>12&&console.log(s.gray(` \u2026 ${u.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${b}`));}else if(t==="impact"){let w=a("impact"),m=n.from||e;m||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:w},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:g,writeWorkspaceImpact:v}=await import('./workspace-intelligence-3GG7GEDQ.js'),u;try{u=await g({workspacePath:w,fromPath:m,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:x.message,context:{workspacePath:w,fromPath:m},nextActions:["npx workspai workspace snapshot create --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 b=await v(u,w);if(n.json){console.log(JSON.stringify(b$5("workspace impact",u,b),null,2));return}let P=u.summary.risk==="critical"||u.summary.risk==="high"?s.red:u.summary.risk==="medium"?s.yellow:s.green;console.log(P(`\u2714 Workspace impact: ${u.summary.risk}`)),console.log(s.gray(` From: ${u.fromRef}`)),console.log(s.gray(` Affected projects: ${u.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${u.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${u.summary.recommendedCommands}`));for(let x of u.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${x.title}: ${x.summary}`));u.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${u.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${b}`));}else if(t==="verify"){let w=a("verify"),{buildWorkspaceVerify:m,writeWorkspaceVerify:g,evaluateWorkspaceVerifyGate:v}=await import('./workspace-verify-ZNT6JX7D.js'),u=await m({workspacePath:w,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()}),b=await g(u,w),P=v(u,{strict:n.strict===true||i("--strict")}),x=P.exitCode,{recordWorkspaceHistory:A,historyEntryFromVerify:I}=await import('./workspace-history-VF3CHDYQ.js');if(await A(w,I(u,P.passed)),n.json){console.log(JSON.stringify(b$5("workspace verify",{...u,gate:P},b),null,2)),x!==0&&process.exit(x);return}let W=u.summary.verdict==="ready"?s.green:u.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(W(`\u2714 Workspace verify: ${u.summary.verdict}`)),console.log(s.gray(` Freshness: ${u.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${u.impact.risk}`)),console.log(s.gray(` Steps: ${u.steps.length}`)),console.log(s.gray(` Passed ${u.summary.stepsPassed}, warn ${u.summary.stepsWarn}, failed ${u.summary.stepsFailed}, missing ${u.summary.stepsMissing}`));for(let N of u.steps.slice(0,10))console.log(s.gray(` \u2022 ${N.id}: ${N.status} \u2014 ${N.message}`));if(u.steps.length>10&&console.log(s.gray(` \u2026 ${u.steps.length-10} more step(s)`)),u.policyViolations.length>0){console.log(s.gray(` Policy (${u.policyMode}): ${u.policyViolations.length} violation(s)`));for(let N of u.policyViolations.slice(0,5)){let D=N.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${D} [${N.source}] ${N.code}: ${N.message}`);}}console.log(s.gray(` Gate (${P.mode}): ${P.passed?"passed":"blocked"}`));for(let N of P.reasons.slice(0,5))console.log(s.red(` \u2717 ${N}`));console.log(s.gray(` Written: ${b}`)),x!==0&&process.exit(x);}else if(t==="graph"){let w=a("graph"),{buildWorkspaceModel:m}=await import('./workspace-model-NG45SRM5.js'),{buildGraphEmit:g,renderGraphDot:v,renderGraphMermaid:u,explainGraphNode:b}=await import('./workspace-graph-2A5THUCI.js'),x=(await m({workspacePath:w,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()})).graph,A=(e||"emit").toLowerCase();if(x||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:A,result:"error",workspacePath:w,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)),A==="dot"){console.log(v(x));return}if(A==="mermaid"){console.log(u(x));return}if(A==="explain"){let W=(n.scope?.replace(/^project:/,"")||o||"").trim();W||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:w,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 N=b(x,W);if(n.json){console.log(JSON.stringify(N,null,2)),N.found||process.exit(1);return}N.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${W}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${N.project}`)),N.centrality&&console.log(s.gray(` Centrality: fanIn ${N.centrality.fanIn}, fanOut ${N.centrality.fanOut}, reach ${N.centrality.reach}, betweenness ${N.centrality.betweenness}${N.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${N.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${N.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${N.transitiveDependents.length}`));for(let D of N.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${D.id} (d${D.distance}, via ${D.via??"\u2014"})`));return}let I=g(x);if(n.json){console.log(JSON.stringify(I,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${I.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${I.graph.stats.edgeCount} (inferred ${I.graph.stats.inferredEdges}, contract ${I.graph.stats.contractEdges}, manual ${I.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${I.integrity.ok?"ok":"issues"} (cycles ${I.integrity.stats.cycleCount}, dangling ${I.integrity.stats.danglingCount}, orphans ${I.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${I.hotspots.join(", ")||"none"}`)),console.log(s.gray(" Render: workspace graph dot | workspace graph mermaid"));}else if(t==="watch"){let w=a("watch"),{runWorkspaceWatch:m}=await import('./workspace-watch-W47T4RX2.js'),g=n.once===true||i("--once"),v=n.json===true,u=new AbortController,b=()=>u.abort();process.once("SIGINT",b),process.once("SIGTERM",b),v||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await m({workspacePath:w,once:g,signal:u.signal,buildOptions:{workspacePath:w,observableScanDepth:p()},onProgress:P=>{v||console.error(s.gray(` ${P}`));},emit:P=>{if(v){console.log(JSON.stringify(P));return}if(P.kind==="ready"){console.log(s.gray(` Ready: ${P.graph.nodeCount} nodes, ${P.graph.edgeCount} edges (hash ${P.modelHash.slice(0,12)})`));return}if(P.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${P.error??"unknown error"}`));return}if(P.kind==="unchanged"){console.log(s.gray(` No structural change (${P.mode}, ${P.durationMs}ms)`));return}let x=[];P.changedProjects.length>0&&x.push(`changed: ${P.changedProjects.join(", ")}`),P.addedProjects.length>0&&x.push(`added: ${P.addedProjects.join(", ")}`),P.removedProjects.length>0&&x.push(`removed: ${P.removedProjects.join(", ")}`),P.graph.edgesAdded.length>0&&x.push(`+${P.graph.edgesAdded.length} edges`),P.graph.edgesRemoved.length>0&&x.push(`-${P.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${P.mode}, ${P.durationMs}ms): ${x.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",b),process.removeListener("SIGTERM",b),!v&&!g&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let w=a("sync"),{syncWorkspaceProjects:m}=await import('./workspace-PLXOO6ST.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${C.basename(w)}`));let g=await m(w,n.json===true);await it(w,{silent:n.json===true});let{readWorkspaceRegistrySummary:v}=await import('./workspace-registry-summary-JM2XY52C.js'),u=await v(w);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:w,registry:g,contractSynced:true,registrySummary:u},null,2));}else if(t==="registry"){let w=a("registry"),m=e||"status";m!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${m}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:g,resolveWorkspaceRegisteredProjects:v}=await import('./workspace-registry-summary-JM2XY52C.js'),u=await g(w);if(n.json){console.log(JSON.stringify(u,null,2));return}let b=await v(w);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${u.authority}`)),console.log(s.gray(` Projects: ${u.projectCount}`)),console.log(s.gray(` Summary: ${u.registrySummaryPath}`)),b.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let w=a("foundation"),m=e||"ensure";m!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${m}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:g}=await import('./workspace-foundation-3C2DLCVI.js'),v=await g(w,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(v,null,2));return}v.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${v.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let w=a("policy"),m=await Rd(w,e,o,r,n.json===true||i("--json"));m!==0&&process.exit(m);}else if(t==="contract"){let w=a("contract"),{buildWorkspaceContractGraph:m,readWorkspaceContract:g,verifyWorkspaceContract:v,writeWorkspaceContract:u,WORKSPACE_CONTRACT_PATH:b}=await import('./workspace-contract-LQJDZV36.js'),P=e||"inspect",x=l();try{if(P==="init"){let A=await u({workspacePath:w,outputPath:x,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(A,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${A.contractPath}`)),console.log(s.gray(` Projects: ${A.contract.projects.length}`));return}if(P==="inspect"){let A=await g({workspacePath:w,contractPath:x});if(n.json){console.log(JSON.stringify(A,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${A.contractPath}`)),console.log(s.gray(` Workspace: ${A.contract.workspace.name}`)),console.log(s.gray(` Projects: ${A.contract.projects.length}`)),console.log(s.gray(` Schema: v${A.contract.schemaVersion}`));return}if(P==="verify"){let A=await v({workspacePath:w,contractPath:x,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:I}=await import('./workspace-contract-LQJDZV36.js'),W=await I({workspacePath:w,result:A});if(n.json)console.log(JSON.stringify({...A,evidencePath:W},null,2));else {let N=A.status==="passed"?s.green:s.red;console.log(N(`\u2714 Workspace contract verification ${A.status}: ${A.contractPath}`)),console.log(s.gray(` Projects: ${A.projectCount}`));for(let D of A.checks){let M=D.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${M} ${D.id}: ${D.message}`));}for(let D of A.violations)console.log(s.gray(` Violation: ${D}`));}(A.status==="failed"||A.status!=="passed"&&n.strict)&&process.exit(1);return}if(P==="graph"){let A=await m({workspacePath:w,contractPath:x});if(n.json){console.log(JSON.stringify(A,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${A.contractPath}`)),console.log(s.gray(` Workspace: ${A.graph.workspace.name}`)),console.log(s.gray(` Projects: ${A.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${A.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${A.graph.summary.eventEdges}`)),console.log(s.gray(` Ports: ${A.graph.summary.portCount}`));for(let I of A.graph.nodes){let W=I.ports.map(N=>`${N.name}:${N.port}`).join(", ")||"none";console.log(s.gray(` \u2022 ${I.id} (${I.runtime||"unknown"}${I.framework?`/${I.framework}`:""}) ports=${W}`));}for(let I of A.graph.edges){let W=I.type==="event"?`event:${I.label}`:I.label;console.log(s.gray(` ${I.from} -> ${I.to} [${W}]`));}return}console.log(s.red(`\u274C Unknown workspace contract action: ${P}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${b}]`)),process.exit(1);}catch(A){n.json&&(console.log(JSON.stringify({command:`workspace contract ${P}`,result:"error",workspacePath:w,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${P}.failed`,message:A.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${P} failed: ${A.message}`)),process.exit(1);}}else if(t==="share"){let w=a("share"),m=l()||e,{createWorkspaceShareBundle:g}=await import('./workspace-PLXOO6ST.js'),v=await g(w,{outputPath:m,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:w,bundlePath:v,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: ${v}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let w=a("export");try{let{exportWorkspaceArchive:m}=await import('./workspace-archive-EEGLHZDW.js'),g=n.archiveCompression?.trim().toLowerCase()??"store";if(g!=="store"&&g!=="deflate")throw new Error("--archive-compression must be store or deflate.");let v=await m({workspacePath:w,outputPath:l()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:g});if(n.json){console.log(JSON.stringify(v,null,2));return}let u=(v.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${v.archivePath}`)),console.log(s.gray(` Files: ${v.manifest.files.length}`)),console.log(s.gray(` Size: ${u} MB`)),v.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(m){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:m.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${m.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let w=o;w||(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:m,inspectWorkspaceArchive:g,verifyWorkspaceArchive:v}=await import('./workspace-archive-EEGLHZDW.js');try{if(e==="inspect"){let b=await g({archivePathOrUrl:w,safety:d()});if(n.json){console.log(JSON.stringify(b,null,2));return}let P=(b.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${b.archivePath}`)),console.log(s.gray(` Workspace: ${b.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${b.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${b.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${b.fileCount}`)),console.log(s.gray(` Payload: ${P} MB`));return}if(e==="doctor"){let b=await m({archivePathOrUrl:w,strict:n.strict===true||i("--strict"),safety:d()});if(n.json)console.log(JSON.stringify(b,null,2));else {let P=b.status==="passed"?s.green:b.status==="warning"?s.yellow:s.red;console.log(P(`\u2714 Workspace archive doctor ${b.status}: ${b.archivePath}`)),console.log(s.gray(` Workspace: ${b.workspaceName}`)),console.log(s.gray(` Files: ${b.fileCount}`));for(let x of b.checks){let A=x.status==="passed"?"\u2714":x.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${A} ${x.id}: ${x.message}`));}for(let x of b.recommendedActions)console.log(s.gray(` Next: ${x}`));}(b.status==="failed"||b.status==="warning"&&n.strict)&&process.exit(1);return}let u=await v({archivePathOrUrl:w,requireChecksums:n.strict===true||i("--strict"),safety:d()});if(n.json)console.log(JSON.stringify(u,null,2));else if(u.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${u.archivePath}`)),console.log(s.gray(` Files: ${u.verifiedFiles}/${u.fileCount}`));else {let b=u.status==="failed"?s.red:s.yellow;console.log(b(`\u274C Workspace archive verification ${u.status}: ${u.archivePath}`)),u.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${u.missingArchiveEntries.join(", ")}`)),u.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${u.extraArchiveEntries.join(", ")}`)),u.mismatches.length&&console.log(s.gray(` Mismatches: ${u.mismatches.map(P=>P.path).join(", ")}`)),u.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${u.missingChecksumFiles.join(", ")}`));}(u.status==="failed"||u.status==="warning"&&n.strict)&&process.exit(1);}catch(u){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:w,error:{code:`workspace.archive.${e}.failed`,message:u.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${u.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let w=e;w||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.${t}.input-required`,message:`workspace ${t} 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));let{hydrateWorkspaceArchive:m}=await import('./workspace-archive-EEGLHZDW.js');try{let g=await m({archivePathOrUrl:w,outputPath:l(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:d()});if(n.json){console.log(JSON.stringify(g,null,2));return}console.log(s.green(g.dryRun?`\u2714 Workspace archive hydrate preview: ${g.outputPath}`:`\u2714 Workspace archive hydrated: ${g.outputPath}`)),console.log(s.gray(` Files: ${g.files.length}`)),g.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${g.manifest.workspaceName}`));}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:w,...l()?{outputPath:l()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${g.message}`)),process.exit(1);}}else if(t==="run"){let w=a(`run ${e||""}`.trim()),m=new Set(["init","test","build","start"]),g=e?.trim()??"";g||(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)),m.has(g)||(!/^[a-z][a-z0-9_-]*$/i.test(g)||g==="dev"||g==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${g}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),process.exit(2));let v=Fn({raw:n.maxWorkers,operation:`workspace run ${g}`,json:n.json===true||i("--json")});if(g==="init"&&n.json!==true){let P=await Bn(w);P!==0&&process.exit(P);}let{runWorkspaceStage:u}=await import('./workspace-run-WEQYIERE.js'),b=await u({workspacePath:w,stage:g,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,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(b,null,2)),b.summary.exitCode!==0&&process.exit(b.summary.exitCode);}else if(t==="explain"||t==="why"){let w=a(t),{parseWorkspaceExplainTarget:m}=await import('./workspace-explain-contract-KT757JGQ.js'),{buildWorkspaceExplain:g,writeWorkspaceExplainReport:v}=await import('./workspace-explain-G74ZIF23.js'),u=(e??o??"").trim();!u&&n.scope&&(u=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),u||(console.log(s.red(`\u274C workspace ${t} requires a target.`)),console.log(s.gray(" npx workspai workspace explain project:<name>|release-blocked [--json] [--write]")),console.log(s.gray(" npx workspai workspace why <project>|release-blocked [--json]")),process.exit(1));let b=m(u);b||(console.log(s.red(`\u274C Invalid explain target: ${u}`)),process.exit(1));let P=await g({workspacePath:w,target:b}),x=n.write===true||i("--write"),A;if(x&&(A=await v(P,w,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$5(`workspace ${t}`,P,A),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${P.summary}`));for(let I of P.sections)console.log(s.bold(`
|
|
408
|
+
${I.title}`)),console.log(I.body);A&&console.log(s.gray(`
|
|
409
|
+
Written: ${A}`));}else if(t==="trace"){let w=a("trace"),m=n.from||e;m||(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:g}=await import('./workspace-explain-contract-KT757JGQ.js'),{buildWorkspaceExplain:v,writeWorkspaceExplainReport:u}=await import('./workspace-explain-G74ZIF23.js'),b=g(m);(!b||b.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${m}`)),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 P=await v({workspacePath:w,target:b}),x=n.write===true||i("--write"),A;if(x&&(A=await u(P,w,"trace")),n.json){console.log(JSON.stringify(b$5("workspace trace",P,A),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${P.summary}`));for(let I of P.sections)console.log(s.bold(`
|
|
410
|
+
${I.title}`)),console.log(I.body);A&&console.log(s.gray(`
|
|
411
|
+
Written: ${A}`));}else if(t==="feedback"){let w=a("feedback"),m=(e||"record").toLowerCase();m!=="record"&&(console.log(s.red(`Unknown feedback action: ${m}`)),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:g,parseFeedbackStdinPayload:v,readStdinAll:u}=await import('./workspace-feedback-YY6WQPWQ.js'),b=await u(),P=v(b);P||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let x=await g({workspacePath:w,payload:P});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==="mcp"){let w=a("mcp"),m=(e||"serve").toLowerCase();m!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:m,result:"error",workspacePath:w,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${m}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${m}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:g}=await import('./workspace-mcp-serve-MJMUV4RY.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await g({workspacePath:w});}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:
|
|
402
412
|
npx workspai init | npx workspai workspace init | npx workspai workspace run init
|
|
403
|
-
`));let
|
|
404
|
-
`)),console.log(s.cyan(` ${he} <command> [options]`)),console.log(s.gray(` ${he} <workspace-name> [options] # shortcut: create workspace`)),
|
|
413
|
+
`)));let w=a("init"),m=Fn({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let u=await Bn(w);u!==0&&process.exit(u);}let{runWorkspaceStage:g}=await import('./workspace-run-WEQYIERE.js'),v=await g({workspacePath:w,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:m,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(v,null,2)),v.summary.exitCode!==0&&process.exit(v.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:go}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${go.join(", ")}`)),process.exit(1);});function Yt(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function vc(){let t=n=>n.replace(/\bnpx (?:rapidkit|workspai)\b/g,he),e=n=>s.gray(t(n)),o=n=>s.cyan(t(n)),r=b()?`${he} init; ${he} dev`:`${he} init && ${he} dev`;console.log(s.white(`Usage:
|
|
414
|
+
`)),console.log(s.cyan(` ${he} <command> [options]`)),console.log(s.gray(` ${he} <workspace-name> [options] # shortcut: create workspace`)),Id==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${he}.
|
|
405
415
|
`)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems
|
|
406
416
|
`)),console.log(s.white("Most AI tools understand files.")),console.log(s.white("Workspai helps developers, CI pipelines, IDEs, and AI agents share the same understanding of a software system.")),console.log(s.dim(`One workspace. One truth. Humans and AI aligned.
|
|
407
|
-
`)),
|
|
417
|
+
`)),Yt("Workspace Lifecycle"),console.log(s.white(`
|
|
408
418
|
1. Create or adopt a workspace
|
|
409
419
|
`)),console.log(s.cyan(t(" npx workspai my-workspace"))),console.log(s.cyan(t(" npx workspai adopt /path/to/project"))),console.log(s.cyan(t(` npx workspai import <path|git-url>
|
|
410
420
|
`))),console.log(s.white(`2. Build a workspace model
|
|
@@ -412,18 +422,18 @@ Written: ${h}`));}else if(t==="feedback"){let p=i("feedback"),d=(e||"record").to
|
|
|
412
422
|
`))),console.log(s.white(`3. Generate agent-ready context
|
|
413
423
|
`)),console.log(s.cyan(t(` npx workspai workspace context --for-agent --json --write
|
|
414
424
|
`))),console.log(s.white(`4. Analyze change impact
|
|
415
|
-
`)),console.log(s.cyan(t(` npx workspai workspace impact --from <
|
|
425
|
+
`)),console.log(s.cyan(t(` npx workspai workspace impact --from <diff>
|
|
416
426
|
`))),console.log(s.white(`5. Verify release readiness
|
|
417
427
|
`)),console.log(s.cyan(t(" npx workspai workspace verify --strict"))),console.log(s.cyan(t(` npx workspai pipeline --strict
|
|
418
428
|
`))),console.log(s.white(`6. Explain blockers and trace change impact
|
|
419
429
|
`)),console.log(s.cyan(t(" npx workspai workspace explain release-blocked --json --write"))),console.log(s.cyan(t(` npx workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --json --write
|
|
420
|
-
`))),
|
|
430
|
+
`))),Yt("Workspace Intelligence"),console.log(s.white(`
|
|
421
431
|
What projects exist?
|
|
422
432
|
`)),console.log(s.cyan(t(` npx workspai workspace model --json
|
|
423
433
|
`))),console.log(s.white(`What should AI agents know?
|
|
424
434
|
`)),console.log(s.cyan(t(` npx workspai workspace context --for-agent --json --write
|
|
425
435
|
`))),console.log(s.white(`What breaks if this changes?
|
|
426
|
-
`)),console.log(s.cyan(t(` npx workspai workspace impact --from <
|
|
436
|
+
`)),console.log(s.cyan(t(` npx workspai workspace impact --from <diff>
|
|
427
437
|
`))),console.log(s.white(`Is this change safe?
|
|
428
438
|
`)),console.log(s.cyan(t(` npx workspai workspace verify --strict
|
|
429
439
|
`))),console.log(s.white(`Why is release blocked?
|
|
@@ -434,7 +444,7 @@ What projects exist?
|
|
|
434
444
|
`)),console.log(s.cyan(t(` npx workspai workspace agent-sync --write
|
|
435
445
|
`))),console.log(s.white(`Expose evidence to MCP clients?
|
|
436
446
|
`)),console.log(s.cyan(t(` npx workspai workspace mcp serve
|
|
437
|
-
`))),
|
|
447
|
+
`))),Yt("Workspace Operations"),console.log(s.white(`
|
|
438
448
|
Create workspace
|
|
439
449
|
`)),console.log(s.cyan(t(` npx workspai my-workspace
|
|
440
450
|
`))),console.log(s.white(`Bootstrap toolchains
|
|
@@ -446,7 +456,7 @@ Create workspace
|
|
|
446
456
|
`)),console.log(s.cyan(t(` npx workspai adopt /path/to/project
|
|
447
457
|
`))),console.log(s.white(`Import repository
|
|
448
458
|
`)),console.log(s.cyan(t(` npx workspai import <path|git-url>
|
|
449
|
-
`))),
|
|
459
|
+
`))),Yt("Governance & Release"),console.log(s.white(`
|
|
450
460
|
Analyze workspace
|
|
451
461
|
`)),console.log(s.cyan(t(` npx workspai analyze
|
|
452
462
|
`))),console.log(s.white(`Check readiness
|
|
@@ -457,7 +467,7 @@ Analyze workspace
|
|
|
457
467
|
`)),console.log(s.cyan(t(` npx workspai snapshot create
|
|
458
468
|
`))),console.log(s.white(`Archive project
|
|
459
469
|
`)),console.log(s.cyan(t(` npx workspai project archive
|
|
460
|
-
`))),
|
|
470
|
+
`))),Yt("Agent Grounding"),console.log(s.white(`
|
|
461
471
|
Generate context pack
|
|
462
472
|
`)),console.log(s.cyan(t(` npx workspai workspace context --for-agent
|
|
463
473
|
`))),console.log(s.white(`Sync agent surfaces
|
|
@@ -466,26 +476,26 @@ Generate context pack
|
|
|
466
476
|
`)),console.log(s.cyan(t(` npx workspai workspace mcp serve
|
|
467
477
|
`))),console.log(s.white(`Supported ecosystems:
|
|
468
478
|
`)),console.log(s.gray(` Copilot \xB7 Cursor \xB7 Claude Code \xB7 Codex \xB7 MCP-ready tools
|
|
469
|
-
`)),
|
|
479
|
+
`)),Yt("Mental Model"),console.log(s.gray(`
|
|
470
480
|
Repository`)),console.log(s.gray(" \u2193")),console.log(s.gray(" Workspace Intelligence")),console.log(s.gray(" \u2193")),console.log(s.gray(` Developers \xB7 CI \xB7 IDEs \xB7 AI Agents
|
|
471
481
|
`)),console.log(s.dim(`Workspai turns projects and repositories into a shared, evidence-backed understanding of a software system.
|
|
472
|
-
`)),console.log(s.bold("Quick start \u2014 workspace workflow:")),console.log(s.cyan(`${he} my-workspace `)+s.gray("# Create workspace (interactive profile picker)")),console.log(s.cyan(
|
|
482
|
+
`)),console.log(s.bold("Quick start \u2014 workspace workflow:")),console.log(s.cyan(`${he} my-workspace `)+s.gray("# Create workspace (interactive profile picker)")),console.log(s.cyan(" cd ~/.workspai/workspaces/my-workspace")+s.gray(" # default managed location")),console.log(o(" npx workspai my-workspace --here ")+s.gray("# Create in current directory, then cd my-workspace")),console.log(o(" npx workspai bootstrap ")+s.gray("# Bootstrap all runtime toolchains")),console.log(o(" npx workspai create project nextjs web ")+s.gray("# Frontend (Next.js)")),console.log(o(" npx workspai create project fastapi.standard api ")+s.gray("# Backend (FastAPI)")),console.log(s.cyan(" cd api")),console.log(s.cyan(` ${r}
|
|
473
483
|
`)),console.log(s.bold("Installed command:")),console.log(s.gray(" npm install -g workspai")),console.log(s.gray(" workspai create project Scaffold a new project")),console.log(s.gray(" workspai init Install project dependencies")),console.log(s.gray(" workspai dev Start dev server")),console.log(s.gray(" workspai workspace list List registered workspaces")),console.log(s.gray(" workspai import <path|git-url> Copy or clone a project")),console.log(s.gray(` workspai adopt [path] Link an existing local project
|
|
474
484
|
`)),console.log(s.bold("Workspace profiles (asked during creation):")),console.log(s.gray(" minimal Foundation files only \u2014 fastest bootstrap (default)")),console.log(s.gray(" java-only Java runtime (Spring Boot services)")),console.log(s.gray(" python-only Python + Poetry (FastAPI, Django, ML)")),console.log(s.gray(" node-only Node.js runtime (NestJS, Express, Next.js)")),console.log(s.gray(" go-only Go runtime (Fiber, Gin, gRPC)")),console.log(s.gray(" dotnet-only .NET runtime (ASP.NET Core services)")),console.log(s.gray(" polyglot Python + Node.js + Go + Java + .NET multi-runtime")),console.log(s.gray(` enterprise Polyglot + governance + Sigstore
|
|
475
485
|
`)),console.log(s.gray(` Tip: use --skip-python-engine for a Python-aware Workspace Intelligence shell first; after creating a RapidKit Core module-enabled project, run workspace run init to install the local Python engine.
|
|
476
|
-
`)),console.log(s.bold("Workspace commands (inside a workspace):")),console.log(e(" npx workspai bootstrap [--profile <p>] Re-bootstrap toolchains")),console.log(e(" npx workspai analyze [--json --strict] Analyze workspace health and gaps")),console.log(e(" npx workspai pipeline [--json --strict]
|
|
486
|
+
`)),console.log(s.bold("Workspace commands (inside a workspace):")),console.log(e(" npx workspai bootstrap [--profile <p>] Re-bootstrap toolchains")),console.log(e(" npx workspai analyze [--json --strict] Analyze workspace health and gaps")),console.log(e(" npx workspai pipeline [--json --strict --no-agent-sync] Governance loop: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot")),console.log(e(" npx workspai readiness [--workspace <path>] [--json --strict] Release readiness gates (env/doctor/analyze/verify/deps)")),console.log(e(" npx workspai doctor workspace [--ci] Workspace health with CI exit codes")),console.log(e(" npx workspai workspace list List registered workspaces")),console.log(e(" npx workspai workspace model --json Build workspace intelligence model")),console.log(e(" npx workspai workspace context --for-agent --json --write Build agent context + sync grounding")),console.log(e(" npx workspai workspace agent-sync --write --refresh-context Sync the Agent Customization Pack")),console.log(e(" npx workspai workspace snapshot --json Persist workspace intelligence snapshot")),console.log(e(" npx workspai workspace diff --from <file|git[:ref]> --json Diff current model against a snapshot")),console.log(e(" npx workspai workspace impact --from <diff> --json Build blast radius from model diff")),console.log(e(" npx workspai workspace verify [--strict] --json Evaluate impact verification evidence")),console.log(e(" npx workspai workspace explain <target> [--write] --json Narrative for blockers/projects (alias: why)")),console.log(e(" npx workspai workspace trace --from <diff> [--write] --json Diff \u2192 blast radius \u2192 gates narrative")),console.log(e(" npx workspai workspace feedback record --json Append agent action outcome to intelligence history")),console.log(e(" npx workspai workspace mcp serve Read-mostly stdio MCP over workspace evidence")),console.log(e(" npx workspai workspace graph [emit|explain|dot|mermaid] Inspect/visualize dependency graph")),console.log(e(" npx workspai workspace watch [--once] [--json] Keep model+graph in memory; stream change events")),console.log(e(" npx workspai workspace run <stage> [--scope project:<name>] [--reuse-passed] Fleet init/test/build/start or custom stage")),console.log(e(" npx workspai workspace sync [--json] Sync registry + contract from projects")),console.log(e(" npx workspai workspace registry status [--refresh] [--json] Canonical project registry summary")),console.log(e(" npx workspai import <path|git-url> Copy or clone a project into this workspace")),console.log(e(" npx workspai adopt [path] Link an existing local project to a workspace")),console.log(e(" npx workspai snapshot create [name] Create a recoverable workspace snapshot")),console.log(e(" npx workspai snapshot restore <name> Restore snapshot metadata with safety guard")),console.log(e(" npx workspai snapshot inspect <name> Inspect snapshot manifest and size")),console.log(e(" npx workspai project archive <name> Archive a project with a safety snapshot")),console.log(e(" npx workspai project restore <archive> Restore an archived project safely")),console.log(e(" npx workspai workspace share [--output <file>] Export collaboration bundle")),console.log(e(" npx workspai workspace foundation ensure Ensure workspace.json/policies/toolchain files")),console.log(e(" npx workspai workspace contract init Create workspace service contract")),console.log(e(" npx workspai workspace contract verify Verify service ports/dependencies")),console.log(e(" npx workspai workspace contract graph Show service dependency graph")),console.log(e(" npx workspai workspace export --output <file> Export portable workspace archive")),console.log(e(" npx workspai workspace archive verify <file> Verify archive integrity")),console.log(e(" npx workspai workspace archive doctor <file> Diagnose archive readiness")),console.log(e(" npx workspai workspace hydrate <archive> --output <dir> Hydrate workspace archive")),console.log(e(" npx workspai workspace policy show Show effective workspace policies")),console.log(e(" npx workspai workspace policy set <k> <v> Update workspace policy values")),console.log(e(" npx workspai setup python|node|go|java|dotnet [--warm-deps] Set up runtime (+ optional deps warm-up)")),console.log(e(" npx workspai mirror [status|sync|verify|rotate] Registry mirror management")),console.log(e(" npx workspai cache [status|clear|prune|repair] Package cache management")),console.log(e(" npx workspai infra plan Discover and generate infra compose")),console.log(e(` npx workspai infra up|down|status Manage Docker sidecar infrastructure
|
|
477
487
|
`)),console.log(s.bold("Options (workspace creation):")),console.log(s.gray(" -y, --yes Skip prompts and use defaults")),console.log(s.gray(" --author <name> Author/team name for workspace metadata")),console.log(s.gray(" --skip-git Skip git initialization")),console.log(s.gray(" --debug Enable debug logging")),console.log(s.gray(" --dry-run Show what would be created")),console.log(s.gray(" --create-workspace When creating a project outside a workspace: create and register a workspace in the current directory")),console.log(s.gray(" --no-workspace When creating a project outside a workspace: do not create a workspace")),console.log(s.gray(` --no-update-check Skip checking for updates
|
|
478
|
-
`)),console.log(s.bold("Project commands (inside a project):")),console.log(e(" npx workspai create project Scaffold a new project")),console.log(s.gray(" cd my-
|
|
488
|
+
`)),console.log(s.bold("Project commands (inside a project):")),console.log(e(" npx workspai create project Scaffold a new project")),console.log(s.gray(" cd my-project Change directory to the new project")),console.log(e(" npx workspai init Install project dependencies")),console.log(e(" npx workspai dev Start dev server")),console.log(e(" npx workspai build Build for production")),console.log(e(` npx workspai test Run tests
|
|
479
489
|
`)),console.log(s.bold("Flags clarification:")),console.log(s.gray(" --skip-install npm fast-path for lock/dependency steps")),console.log(s.gray(` --skip-essentials core flag for skipping essential module installation
|
|
480
|
-
`))
|
|
490
|
+
`)),$d?(console.log(s.bold("Legacy (shown because RAPIDKIT_SHOW_LEGACY=1):")),console.log(s.gray(" npx workspai my-project --template fastapi")),console.log(s.gray(" npx workspai my-project --template nestjs")),console.log(s.gray(" npx workspai my-project --template springboot")),console.log(s.gray(" npx workspai my-project --template gofiber")),console.log(s.gray(" npx workspai my-project --template gogin")),console.log(s.gray(" npx workspai my-project --template dotnet")),console.log(s.gray(` --skip-install Fast-path lock/deps (legacy template mode) \u2014 not same as --skip-essentials
|
|
481
491
|
`))):console.log(s.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
|
|
482
|
-
`));}var
|
|
492
|
+
`));}var ac="__rapidkit_signal_handlers_registered__",ic=globalThis;ic[ac]||(ic[ac]=true,process.on("SIGINT",async()=>{if(!xr){if(xr=true,console.log(s.yellow(`
|
|
483
493
|
|
|
484
|
-
\u26A0\uFE0F Interrupted by user`)),
|
|
485
|
-
`):await
|
|
486
|
-
`)),
|
|
487
|
-
`),process.exit(1);}):
|
|
488
|
-
`),process.exit(1);}):
|
|
489
|
-
`),process.exit(1);}):
|
|
490
|
-
`),
|
|
491
|
-
`),
|
|
494
|
+
\u26A0\uFE0F Interrupted by user`)),yt&&await R__default.pathExists(yt)){console.log(s.gray("Cleaning up partial installation..."));try{await R__default.remove(yt),console.log(s.green("\u2713 Cleanup complete"));}catch(t){f.debug("Cleanup failed:",t);}}b$6(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!xr){if(xr=true,f.debug("Received SIGTERM"),yt&&await R__default.pathExists(yt))try{await R__default.remove(yt);}catch(t){f.debug("Cleanup failed:",t);}b$6(143,"Terminated"),process.exit(143);}}));var Td=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Wd=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),o=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return S.realpathSync(t)===S.realpathSync(fileURLToPath(import.meta.url))||o}catch{return C.resolve(t)===C.resolve(fileURLToPath(import.meta.url))||o}})(),Dd=!Td||Wd;function Ld(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}function Fd(){for(let t of [process.stdout,process.stderr]){if(t.isTTY)continue;let e=t;if(e.__rapidkitSyncWriteInstalled)continue;let o=t.fd;if(typeof o!="number")continue;let r=t.write.bind(t);e.write=((n,a,i)=>{let c=typeof a=="string"?a:"utf8",l=typeof a=="function"?a:typeof i=="function"?i:void 0;try{let p=typeof n=="string"?Buffer.from(n,c):n instanceof Uint8Array?Buffer.from(n):Buffer.from(String(n),c);return S.writeSync(o,p),l?.(),true}catch{return r(n,c,l)}}),e.__rapidkitSyncWriteInstalled=true;}}async function Pe(t){b$6(t),await new Promise(e=>setImmediate(e)),await new Promise(e=>setTimeout(e,25)),await Promise.all([process.stdout,process.stderr].map(e=>new Promise(o=>{e.write("",()=>o());}))),process.exit(t);}async function cc(t,e=0){return S.writeSync(process.stdout.fd??1,t),Pe(e)}if(Dd){Ld(),Fd(),d$4(),a$2({argv:process.argv,cwd:process.cwd(),rapidkitVersion:c()}),c$4(process.argv);let t=process.argv.slice(2),e$1=t[0],o$1=process.cwd(),r=qe(o$1),n=p(o$1,"project.json").some(f=>S.existsSync(f)),a$1=id(),i=Zi(t),c$1=a$1&&bo(t),l=e$1==="init"&&r&&!n;(t.length===0||t.length===1&&(e$1==="--help"||e$1==="-h"||e$1==="help"))&&(a("npm cli"),vc(),await Pe(0)),t.some(f=>f==="--version"||f==="-V"||f==="-v")&&!t.some(f=>f==="--help"||f==="-h"||f==="help")&&(t.includes("--json")?await cc(`${JSON.stringify(cd(),null,2)}
|
|
495
|
+
`):await cc(`${c()}
|
|
496
|
+
`)),Kn(t)&&await Pe(0),c$1&&ec(e$1)?(async()=>{await Pe(await tc(e$1,t));})().catch(f=>{process.stderr.write(`Workspai CLI failed to run ${e$1}: ${f?.message??f}
|
|
497
|
+
`),process.exit(1);}):i||c$1?ne.parseAsync().then(()=>Pe(0)).catch(f=>{let d=Qt()&&f instanceof Error&&f.stack?f.stack:f?.message??f;process.stderr.write(`Workspai CLI failed: ${d}
|
|
498
|
+
`),process.exit(1);}):l?Hn(t).then(f=>Pe(f)).catch(f=>{process.stderr.write(`Workspai CLI failed to run workspace init: ${f?.message??f}
|
|
499
|
+
`),process.exit(1);}):Ad().then(async f=>{if(!f){let d=process.argv.slice(2);if(Qt()&&process.stderr.write(`[workspai-cli] argv=${JSON.stringify(d)}
|
|
500
|
+
`),Zi(d)){await ne.parseAsync();return}if(Kn(d)&&await Pe(0),d[0]===xn){let h=await uc(d);await Pe(h);}if(d[0]==="init"){let h=await Hn(d);await Pe(h);}if(ec(d[0])){let h=await tc(d[0],d);await Pe(h);}if(m(d[0])){if(Un(d))return;let h=d[0],k=d$5(process.cwd()),j=await _t(process.cwd()),_=re(process.cwd()),w=false;if(_){let u=o(_,"policies.yml").find(b=>S.existsSync(b));if(u&&await R__default.pathExists(u))try{let b=await S.promises.readFile(u,"utf-8");if(w=((b.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??b.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict",w){let A=o(_,"toolchain.lock").find(N=>S.existsSync(N)),I=[];if(!A||!await R__default.pathExists(A))I.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain).");else try{let D=JSON.parse(await S.promises.readFile(A,"utf-8")).runtime??{};e$2(k,process.cwd())&&!D.go?.version&&I.push("Go runtime version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."),f$4(k,process.cwd())&&!D.node?.version&&I.push("Node runtime version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."),g$1(k,process.cwd())&&!D.java?.version&&I.push("Java runtime version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."),h$2(k,process.cwd())&&!D.dotnet?.version&&I.push(".NET runtime version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."),i$2(k,process.cwd())&&!D.python?.version&&I.push("Python runtime version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");}catch{I.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode.");}let W=o(_,"workspace.json").find(N=>S.existsSync(N));if(W&&await R__default.pathExists(W))try{let D=JSON.parse(await S.promises.readFile(W,"utf-8")).profile??"",M=i$3(process.cwd(),k),ue=ht({profile:D,runtime:M.runtime,subjectLabel:C.basename(process.cwd()),mode:"strict"});ue.ok||I.push(`${ue.message} Update the workspace profile or use a polyglot workspace.`);}catch{}if(I.length>0){console.log(s.red(`\u274C Strict policy violations block \`${h}\`:`));for(let N of I)console.log(s.red(` \u2022 ${N}`));console.log(s.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .workspai/policies.yml")),await Pe(1);}}}catch{}}let m=await d$6({startPath:process.cwd(),action:h,writeReport:true}),g=w||process.env.RAPIDKIT_LIFECYCLE_ENFORCE_READINESS==="1"||process.env.RAPIDKIT_ENFORCE_READINESS==="1";if(m.blocking&&g){console.log(s.red(`\u274C Release readiness blocks \`${h}\`:`));for(let u of m.blockingReasons)console.log(s.red(` \u2022 ${u}`));m.evidencePath&&console.log(s.gray(`\u2139\uFE0F Readiness evidence: ${m.evidencePath}`)),await Pe(1);}m.overallStatus!=="pass"&&!g&&(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 v=await wc(process.cwd(),async()=>{if(e$2(k,process.cwd())||j==="go"){let u=Ge("go",{runCommandInCwd:Q,runCoreRapidkit:e});if(h==="lint")return te(await u.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(h==="format")return te(await u.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let b=h==="dev"?await u.runDev(process.cwd()):h==="test"?await u.runTest(process.cwd()):h==="build"?await u.runBuild(process.cwd()):await u.runStart(process.cwd());return b.message&&console.log(s.red(`\u274C ${b.message}`)),b.exitCode}if(g$1(k,process.cwd())||j==="java")return h==="dev"?await at("dev",process.cwd()):h==="test"?await at("test",process.cwd()):h==="build"?await at("build",process.cwd()):h==="lint"?await at("lint",process.cwd()):h==="format"?await at("format",process.cwd()):await at("start",process.cwd());if(h$2(k,process.cwd())||j==="dotnet"){let u=Ge("dotnet",{runCommandInCwd:Q,runCoreRapidkit:e});if(h==="lint")return te(await u.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(h==="format")return te(await u.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let b=h==="dev"?await u.runDev(process.cwd()):h==="test"?await u.runTest(process.cwd()):h==="build"?await u.runBuild(process.cwd()):await u.runStart(process.cwd());return b.message&&console.log(s.red(`\u274C ${b.message}`)),b.exitCode}if(f$4(k,process.cwd())||j==="node")return h==="dev"?await Rt("dev",process.cwd()):h==="test"?await Rt("test",process.cwd()):h==="build"?await Rt("build",process.cwd()):h==="lint"?await Rt("lint",process.cwd()):h==="format"?await Rt("format",process.cwd()):await Rt("start",process.cwd());if(i$2(k,process.cwd())||j==="python"){if(h==="lint"||h==="format")return await e([h],{cwd:process.cwd()});let u=Ge("python",{runCommandInCwd:Q,runCoreRapidkit:e});return te(h==="dev"?await u.runDev(process.cwd()):h==="test"?await u.runTest(process.cwd()):h==="build"?await u.runBuild(process.cwd()):await u.runStart(process.cwd()))}return -1});if(!v.ok){await Pe(v.code);return}if(v.ok&&v.value>=0){await Pe(v.value);return}if(v.ok&&v.value===-1){console.error(s.red(`\u274C Workspai cannot run \`${h}\` for this project runtime.`)),console.error(s.gray("Run `workspai project commands` to inspect supported commands.")),await Pe(1);return}}if(Un(d))return;let y=await Od(d);if(Qt()&&process.stderr.write(`[workspai-cli] shouldForwardToCore=${y}
|
|
501
|
+
`),y){let h=await e(d,{cwd:process.cwd()});await Pe(h);}await ne.parseAsync();}});}export{En as COMMAND_CAPABILITIES_SCHEMA_VERSION,Vp as NPM_ONLY_SCOPED_COMMANDS,Kp as NPM_ONLY_TOP_LEVEL_COMMANDS,Ri as VERSION_CONTRACT_SCHEMA_VERSION,rd as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,dd as detectWindowsDoctorWorkspaceShadow,ld as getGlobalCommandCapabilities,vr as getPublishedContractCatalog,ho as getPublishedContractVersions,cd as getVersionContract,Pd as handleAdoptCommand,Cd as handleBootstrapCommand,Ed as handleCacheCommand,uc as handleCreateOrFallback,vd as handleImportCommand,Hn as handleInitCommand,_d as handleMirrorCommand,Sd as handleSetupCommand,Bn as installWorkspaceDependencies,id as isNpmExecInvocation,Od as shouldForwardToCore};
|