workspai 0.54.0 → 0.55.1

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.
Files changed (47) hide show
  1. package/contracts/extension-cli-compatibility.v1.json +1 -1
  2. package/contracts/studio-card-repair-capabilities.v1.json +65 -1
  3. package/contracts/workspace-intelligence/workspace-explain.v1.json +3 -0
  4. package/contracts/workspace-intelligence/workspace-repair-proposal.v1.json +8 -0
  5. package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +28 -0
  6. package/contracts/workspace-repair-capabilities.v1.json +57 -0
  7. package/dist/{artifact-remediation-plan-A2PRCUNA.js → artifact-remediation-plan-O3YIULQN.js} +1 -1
  8. package/dist/autopilot-release-3H5FTF6H.js +1 -0
  9. package/dist/chunk-CEIJIFY7.js +88 -0
  10. package/dist/chunk-D37NEYV6.js +1 -0
  11. package/dist/{chunk-BPACED27.js → chunk-DPMO4U3Z.js} +1 -1
  12. package/dist/chunk-DS4UYMLX.js +1 -0
  13. package/dist/{chunk-2FJW6GSW.js → chunk-HUPLAFZQ.js} +1 -1
  14. package/dist/chunk-IBPPMOHM.js +1 -0
  15. package/dist/{chunk-OLX6LX77.js → chunk-NWQ5VWUW.js} +3 -3
  16. package/dist/chunk-TEHQ7XKK.js +3 -0
  17. package/dist/{chunk-3GRKUP5W.js → chunk-W3HXTCSY.js} +6 -6
  18. package/dist/{chunk-HRN5J6PW.js → chunk-WSAFBPS5.js} +1 -1
  19. package/dist/chunk-YTLUT6IA.js +13 -0
  20. package/dist/{create-R6A7EHQZ.js → create-3NSOY7CA.js} +1 -1
  21. package/dist/{doctor-HJ3O7SAO.js → doctor-UEFFNAUD.js} +1 -1
  22. package/dist/index.js +147 -147
  23. package/dist/{pipeline-TDQK5QYQ.js → pipeline-B5S6P36F.js} +1 -1
  24. package/dist/{pythonRapidkitExec-YR7P5LWG.js → pythonRapidkitExec-4YTAMLBD.js} +1 -1
  25. package/dist/{verified-goal-S2PEBJUV.js → verified-goal-KOU3WJYN.js} +1 -1
  26. package/dist/{workspace-B53XH35L.js → workspace-C4UETGY7.js} +1 -1
  27. package/dist/{workspace-explain-SZI2WAAD.js → workspace-explain-ZEWVKDBF.js} +1 -1
  28. package/dist/{workspace-explain-contract-N2XQHAPM.js → workspace-explain-contract-6CCC26QT.js} +1 -1
  29. package/dist/{workspace-foundation-FFNCK5ZD.js → workspace-foundation-3EVAQ5X6.js} +1 -1
  30. package/dist/{workspace-intelligence-runner-EQFLRVRL.js → workspace-intelligence-runner-SMEAB4CO.js} +1 -1
  31. package/dist/{workspace-mcp-serve-COA4FMCA.js → workspace-mcp-serve-X6C3AWTA.js} +1 -1
  32. package/dist/{workspace-onboarding-2B7CYZ5H.js → workspace-onboarding-5KO7Z7AD.js} +1 -1
  33. package/dist/workspace-repair-engine-GWTXVVKB.js +3 -0
  34. package/dist/workspace-run-FJTBX4JQ.js +1 -0
  35. package/docs/ci-workflows.md +1 -1
  36. package/docs/workspace-repair-engine.md +42 -2
  37. package/package.json +3 -3
  38. package/dist/autopilot-release-63XHNGR6.js +0 -1
  39. package/dist/chunk-4HTSZGEU.js +0 -88
  40. package/dist/chunk-EBKYSDCX.js +0 -1
  41. package/dist/chunk-I5CGTCP5.js +0 -1
  42. package/dist/chunk-IQQWQ3II.js +0 -3
  43. package/dist/chunk-WZA5ISAQ.js +0 -13
  44. package/dist/chunk-ZLYEYHMH.js +0 -1
  45. package/dist/workspace-repair-engine-OZXOXVVV.js +0 -3
  46. package/dist/workspace-run-VPXRRHDK.js +0 -1
  47. /package/dist/{chunk-3LVJBH7V.js → chunk-7S4QNH5A.js} +0 -0
package/dist/index.js CHANGED
@@ -1,66 +1,66 @@
1
1
  #!/usr/bin/env node
2
- import {c as c$9,b as b$h,a as a$q}from'./chunk-NYHVCFBT.js';import {a as a$m}from'./chunk-ICGWHIMK.js';import {a as a$k,f as f$4,d as d$c}from'./chunk-I5CGTCP5.js';import {a as a$l}from'./chunk-5XDPQ3CB.js';import {a as a$t}from'./chunk-FB7SCXAZ.js';import {c as c$1,b as b$7,a as a$A}from'./chunk-FPJNWPKU.js';import {b as b$5,a as a$7}from'./chunk-RMXXK64P.js';import {a as a$j,d as d$d}from'./chunk-KFKZOPZC.js';import {b as b$9,d as d$7,a as a$6,c as c$5,f as f$7,e as e$8}from'./chunk-T3GJ7YVG.js';import {b as b$1,c,d,j,h as h$2,i as i$1,a as a$i}from'./chunk-M5ICGR55.js';import {a,b as b$2}from'./chunk-KVSYBHUR.js';import {c as c$4,d as d$6,e as e$4,b as b$f,g as g$3}from'./chunk-HRN5J6PW.js';import {a as a$y,b as b$i}from'./chunk-QZ7PNMVP.js';import {a as a$n}from'./chunk-EBKYSDCX.js';import {a as a$p}from'./chunk-GDU7VP6G.js';import {a as a$r}from'./chunk-7T4TSV5C.js';import {a as a$s}from'./chunk-PS5F4DCT.js';import {d as d$3,c as c$2,p as p$2,b as b$j,a as a$z}from'./chunk-HY3RMPW5.js';import {b as b$g,a as a$o,c as c$8}from'./chunk-OUBBBC7T.js';import {b as b$b,a as a$a}from'./chunk-THIOE2PB.js';import {e as e$2,d as d$4}from'./chunk-AMB42V2F.js';import {a as a$v}from'./chunk-P7K5RHJC.js';import {a as a$x}from'./chunk-RA24WQLF.js';import {c as c$a,a as a$w}from'./chunk-XVRJVKOX.js';import {f as f$5}from'./chunk-S7Z4DP3P.js';import {f as f$3}from'./chunk-H7P7SSUW.js';import {b as b$6,a as a$2,d as d$2}from'./chunk-FQLB4BIC.js';import {a as a$h}from'./chunk-2FJW6GSW.js';import {a as a$c}from'./chunk-3DONU3DU.js';import {a as a$8}from'./chunk-A5FBGRJA.js';import {a as a$u}from'./chunk-7KKP7RNB.js';import {b as b$d,a as a$e,c as c$6,d as d$a,j as j$4,g as g$5,e as e$7}from'./chunk-7AR5PDLD.js';import {h as h$1,a as a$1,l as l$1,k as k$1,m as m$2,q as q$1,j as j$5,p as p$4,n as n$1,s as s$3,r as r$2}from'./chunk-WJVB6SSD.js';import {a as a$g}from'./chunk-27UR373Z.js';import {c as c$3,g as g$1,b as b$e,l as l$2,e as e$6,a as a$C}from'./chunk-MQ73VS4E.js';import {b as b$3,d as d$1,a as a$4,e as e$3,w,i as i$2,p as p$3,j as j$2,l,m as m$1,n,k,s as s$2,o as o$2,y,q as q$2,h as h$4,r as r$1,x,z,t as t$1,v as v$1,f as f$6,u as u$1}from'./chunk-6HJJHEL6.js';export{r as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-6HJJHEL6.js';import {j as j$3}from'./chunk-2PY65U6X.js';import {a as a$f}from'./chunk-GR6442P7.js';import {d as d$8,a as a$b,b as b$c}from'./chunk-WIO6L24E.js';import {b as b$l}from'./chunk-BYVTHIC3.js';import {a as a$5}from'./chunk-AFIFZTOY.js';import {g,e as e$1,a as a$3,b as b$8,d as d$9,c as c$7,h as h$5}from'./chunk-44VJHNZB.js';import {i,f,h,d as d$5,b as b$a,g as g$4}from'./chunk-VRW6KXNK.js';import {a as a$d}from'./chunk-TQEMLBAG.js';import {c as c$b}from'./chunk-RO73VVHW.js';import {f as f$1,e,a as a$9,d as d$b,i as i$4,g as g$6}from'./chunk-3GRKUP5W.js';import {m,f as f$2,t,o as o$1,v,p,j as j$1,s as s$1,u,i as i$3,g as g$2,h as h$3,e as e$5,a as a$B,b as b$k,k as k$2,n as n$2}from'./chunk-MOSXTVPU.js';import {o,b as b$4,p as p$1,q,r,m as m$3,i as i$5,j as j$6,e as e$9,g as g$7,c as c$c}from'./chunk-RJIYCDVC.js';import {c as c$d}from'./chunk-2FIX2MDC.js';import {Command,Option}from'commander';import s from'chalk';import b from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Mu from'vm';import*as O from'fs-extra';import O__default from'fs-extra';import A,{existsSync,promises,createWriteStream}from'fs';import $n,{tmpdir,homedir}from'os';import {execa}from'execa';import Pt,{randomUUID,createVerify,createHash,createHmac}from'crypto';import ul from'http';import ml from'https';function op(){return j$6()}function np(t,e){return t==="py"?["-3",...e]:e}function sp(t){return typeof t=="object"&&t!==null}async function ap(t,e,r,o=c$d()){try{let n=await execa(t,e,{cwd:r,timeout:o,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function ip(t,e){let r=["-m","rapidkit",...t],o=op();for(let n of o){let a=await ap(n,np(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return sp(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 Ri(t,e){let r=await ip(["project","detect","--path",t,"--json"],e);return !r.ok||!r.data||r.data.schema_version!==1?{ok:false,command:r.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:r}var Ai=new Set(["create"]),Rn=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),cp=new Set(["pip","poetry","venv","pipx","python"]);function _i(t){return typeof t=="string"&&cp.has(t)}function An(t,e){return !t||Ai.has(t)?false:a$9.has(t)?true:e?.has(t)??false}function _n(t,e=null){let r=t[0];return !r||r.startsWith("-")||Ai.has(r)||r==="init"?false:An(r,e)?true:t.filter(n=>!n.startsWith("-")&&!Rn.has(n)).length<=1?false:t.length>1}var Ut=b.join($n.homedir(),".workspairc.json"),lp=b.join($n.homedir(),".rapidkitrc.json"),pp=b.join($n.homedir(),".rapidkit","config.json");function In(t){try{if(!A.existsSync(t))return {};let e=A.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Ii(t){if(process.platform!=="win32")try{A.chmodSync(t,384);}catch{}}function Ht(){let t=In(Ut),e=In(lp),r=In(pp);return A.existsSync(Ut)&&Ii(Ut),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function fo(t){let r={...Ht(),...t};A.writeFileSync(Ut,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Ii(Ut);}function Cr(){return process.env.OPENAI_API_KEY||Ht().openaiApiKey||null}function Nn(){return Ht().aiEnabled!==false}function Tn(){return Ut}function Oi(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async r=>{let o=r.key;o?o.startsWith("sk-")||(console.log(s.red(`
2
+ import {c as c$a,b as b$h,a as a$q}from'./chunk-NYHVCFBT.js';import {a as a$m}from'./chunk-ICGWHIMK.js';import {c as c$8,h as h$5,f as f$4,a as a$k}from'./chunk-D37NEYV6.js';import {a as a$l}from'./chunk-5XDPQ3CB.js';import {a as a$t}from'./chunk-FB7SCXAZ.js';import {c as c$1,b as b$7,a as a$A}from'./chunk-FPJNWPKU.js';import {b as b$5,a as a$7}from'./chunk-RMXXK64P.js';import {a as a$j,d as d$c}from'./chunk-KFKZOPZC.js';import {b as b$9,d as d$7,a as a$6,c as c$5,f as f$7,e as e$8}from'./chunk-T3GJ7YVG.js';import {b as b$1,c,d,j,h as h$2,i as i$1,a as a$i}from'./chunk-M5ICGR55.js';import {a,b as b$2}from'./chunk-KVSYBHUR.js';import {c as c$4,d as d$6,e as e$4,b as b$f,g as g$3}from'./chunk-WSAFBPS5.js';import {a as a$y,b as b$i}from'./chunk-QZ7PNMVP.js';import {a as a$n}from'./chunk-IBPPMOHM.js';import {a as a$p}from'./chunk-GDU7VP6G.js';import {a as a$r}from'./chunk-7T4TSV5C.js';import {a as a$s}from'./chunk-PS5F4DCT.js';import {d as d$3,c as c$2,p as p$2,b as b$j,a as a$z}from'./chunk-HY3RMPW5.js';import {b as b$g,a as a$o,c as c$9}from'./chunk-OUBBBC7T.js';import {b as b$b,a as a$a}from'./chunk-THIOE2PB.js';import {e as e$2,d as d$4}from'./chunk-AMB42V2F.js';import {a as a$v}from'./chunk-P7K5RHJC.js';import {a as a$x}from'./chunk-RA24WQLF.js';import {c as c$b,a as a$w}from'./chunk-XVRJVKOX.js';import {f as f$5}from'./chunk-S7Z4DP3P.js';import {f as f$3}from'./chunk-H7P7SSUW.js';import {b as b$6,a as a$2,d as d$2}from'./chunk-FQLB4BIC.js';import {a as a$h}from'./chunk-HUPLAFZQ.js';import {a as a$c}from'./chunk-3DONU3DU.js';import {a as a$8}from'./chunk-A5FBGRJA.js';import {a as a$u}from'./chunk-7KKP7RNB.js';import {b as b$d,a as a$e,c as c$6,d as d$a,j as j$4,g as g$5,e as e$7}from'./chunk-7AR5PDLD.js';import {h as h$1,a as a$1,l as l$1,k as k$1,m as m$2,q as q$1,j as j$5,p as p$4,n as n$1,s as s$3,r as r$2}from'./chunk-WJVB6SSD.js';import {a as a$g}from'./chunk-27UR373Z.js';import {c as c$3,g as g$1,b as b$e,l as l$2,e as e$6,a as a$C}from'./chunk-MQ73VS4E.js';import {b as b$3,d as d$1,a as a$4,e as e$3,w,i as i$2,p as p$3,j as j$2,l,m as m$1,n,k,s as s$2,o as o$2,y,q as q$2,h as h$4,r as r$1,x,z,t as t$1,v as v$1,f as f$6,u as u$1}from'./chunk-6HJJHEL6.js';export{r as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-6HJJHEL6.js';import {j as j$3}from'./chunk-2PY65U6X.js';import {a as a$f}from'./chunk-GR6442P7.js';import {d as d$8,a as a$b,b as b$c}from'./chunk-WIO6L24E.js';import {b as b$l}from'./chunk-BYVTHIC3.js';import {a as a$5}from'./chunk-AFIFZTOY.js';import {g,e as e$1,a as a$3,b as b$8,d as d$9,c as c$7,h as h$6}from'./chunk-44VJHNZB.js';import {i,f,h,d as d$5,b as b$a,g as g$4}from'./chunk-VRW6KXNK.js';import {a as a$d}from'./chunk-TQEMLBAG.js';import {c as c$c}from'./chunk-RO73VVHW.js';import {f as f$1,e,a as a$9,d as d$b,i as i$4,g as g$6}from'./chunk-W3HXTCSY.js';import {m,f as f$2,t,o as o$1,v,p,j as j$1,s as s$1,u,i as i$3,g as g$2,h as h$3,e as e$5,a as a$B,b as b$k,k as k$2,n as n$2}from'./chunk-MOSXTVPU.js';import {o,b as b$4,p as p$1,q,r,m as m$3,i as i$5,j as j$6,e as e$9,g as g$7,c as c$d}from'./chunk-RJIYCDVC.js';import {c as c$e}from'./chunk-2FIX2MDC.js';import {Command,Option}from'commander';import s from'chalk';import b from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Ou from'vm';import*as O from'fs-extra';import O__default from'fs-extra';import A,{existsSync,promises,createWriteStream}from'fs';import _n,{tmpdir,homedir}from'os';import {execa}from'execa';import wt,{randomUUID,createVerify,createHash,createHmac}from'crypto';import cl from'http';import ll from'https';function Zl(){return j$6()}function ep(t,e){return t==="py"?["-3",...e]:e}function tp(t){return typeof t=="object"&&t!==null}async function rp(t,e,r,o=c$e()){try{let n=await execa(t,e,{cwd:r,timeout:o,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function op(t,e){let r=["-m","rapidkit",...t],o=Zl();for(let n of o){let a=await rp(n,ep(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return tp(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 xi(t,e){let r=await op(["project","detect","--path",t,"--json"],e);return !r.ok||!r.data||r.data.schema_version!==1?{ok:false,command:r.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:r}var Ei=new Set(["create"]),Sn=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),np=new Set(["pip","poetry","venv","pipx","python"]);function Ri(t){return typeof t=="string"&&np.has(t)}function xn(t,e){return !t||Ei.has(t)?false:a$9.has(t)?true:e?.has(t)??false}function En(t,e=null){let r=t[0];return !r||r.startsWith("-")||Ei.has(r)||r==="init"?false:xn(r,e)?true:t.filter(n=>!n.startsWith("-")&&!Sn.has(n)).length<=1?false:t.length>1}var Gt=b.join(_n.homedir(),".workspairc.json"),sp=b.join(_n.homedir(),".rapidkitrc.json"),ap=b.join(_n.homedir(),".rapidkit","config.json");function Rn(t){try{if(!A.existsSync(t))return {};let e=A.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Ai(t){if(process.platform!=="win32")try{A.chmodSync(t,384);}catch{}}function Kt(){let t=Rn(Gt),e=Rn(sp),r=Rn(ap);return A.existsSync(Gt)&&Ai(Gt),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function uo(t){let r={...Kt(),...t};A.writeFileSync(Gt,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Ai(Gt);}function Pr(){return process.env.OPENAI_API_KEY||Kt().openaiApiKey||null}function In(){return Kt().aiEnabled!==false}function On(){return Gt}function _i(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async r=>{let o=r.key;o?o.startsWith("sk-")||(console.log(s.red(`
3
3
  \u274C Invalid API key format (should start with sk-)
4
- `)),process.exit(1)):o=(await b$2([{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,fo({openaiApiKey:o}),console.log(s.green(`
4
+ `)),process.exit(1)):o=(await b$2([{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,uo({openaiApiKey:o}),console.log(s.green(`
5
5
  \u2705 OpenAI API key saved successfully!
6
- `)),console.log(s.gray(`Stored in: ${Tn()}`)),console.log(s.cyan(`
6
+ `)),console.log(s.gray(`Stored in: ${On()}`)),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 r=Ht();if(console.log(s.bold(`
9
+ `));}),e.command("show").description("Show current configuration").action(()=>{let r=Kt();if(console.log(s.bold(`
10
10
  \u2699\uFE0F Workspai Configuration
11
11
  `)),r.openaiApiKey){let o=r.openaiApiKey.substring(0,8)+"..."+r.openaiApiKey.slice(-4);console.log(s.cyan("OpenAI API Key:"),s.white(o));}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:"),r.aiEnabled!==false?s.green("Enabled"):s.red("Disabled")),console.log(s.gray(`
12
- \u{1F4C1} Config file: ${Tn()}
13
- `));}),e.command("remove-api-key").description("Remove stored OpenAI API key").option("--yes","Remove without an interactive confirmation prompt").action(async r=>{if(!Ht().openaiApiKey){console.log(s.yellow(`
12
+ \u{1F4C1} Config file: ${On()}
13
+ `));}),e.command("remove-api-key").description("Remove stored OpenAI API key").option("--yes","Remove without an interactive confirmation prompt").action(async r=>{if(!Kt().openaiApiKey){console.log(s.yellow(`
14
14
  \u26A0\uFE0F No API key is currently stored
15
- `));return}let n=r.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$2([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(fo({openaiApiKey:void 0}),console.log(s.green(`
15
+ `));return}let n=r.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$2([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(uo({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(r=>{r!=="enable"&&r!=="disable"&&(console.log(s.red(`
20
20
  \u274C Invalid action: ${r}`)),console.log(s.gray(`Use: workspai config ai enable|disable
21
- `)),process.exit(1));let o=r==="enable";fo({aiEnabled:o}),console.log(s.green(`
21
+ `)),process.exit(1));let o=r==="enable";uo({aiEnabled:o}),console.log(s.green(`
22
22
  \u2705 AI features ${o?"enabled":"disabled"}
23
- `));});}var Sr=null,ho=false,Mn=null;async function dp(){return Mn||(Mn=(await import('openai')).default),Mn}function $i(){ho=true;}function Ni(t){let r=new Array(1536),o=0;for(let a=0;a<t.length;a++)o=(o<<5)-o+t.charCodeAt(a),o=o&o;for(let a=0;a<1536;a++)o=o*1664525+1013904223&4294967295,r[a]=o/4294967295*2-1;let n=Math.sqrt(r.reduce((a,i)=>a+i*i,0));return r.map(a=>a/n)}async function wo(t){if(!t.trim()){Sr=null;return}let e=await dp();Sr=new e({apiKey:t});}function Ti(){if(!Sr)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return Sr}async function Wn(t){return ho?Ni(t):(await Ti().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function Mi(t){return ho?t.map(Ni):(await Ti().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(o=>o.embedding)}function Wi(){return Sr!==null}function Bt(){return ho}function Dn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function up(t){return !t||typeof t!="object"?{}:t}var Fn=[{id:"authentication-core",name:"Authentication Core",category:"auth",description:"Complete authentication system with password hashing, JWT tokens, OAuth 2.0, and secure session management",longDescription:"Production-ready authentication with bcrypt password hashing, JWT access/refresh tokens, OAuth 2.0 providers (Google, GitHub, etc), rate limiting, and security best practices.",keywords:["auth","login","password","jwt","oauth","token","authentication","security","signin","signup"],framework:"both",dependencies:[],useCases:["User login and logout","Password reset flow","OAuth social login (Google, GitHub)","JWT authentication","Secure session management","Token refresh","Rate limiting"]},{id:"users-core",name:"Users Core",category:"auth",description:"User management system with profiles, roles, permissions, and user CRUD operations",longDescription:"Complete user management with user profiles, role-based access control (RBAC), permissions, user search, soft delete, and audit trails.",keywords:["user","profile","role","permission","rbac","management","admin","accounts"],framework:"both",dependencies:["authentication-core"],useCases:["User registration","User profile management","Role management (admin, user, etc)","Permission system","User administration dashboard","Soft delete users"]},{id:"session-management",name:"Session Management",category:"auth",description:"Secure session handling with Redis storage, session rotation, and device tracking",longDescription:"Advanced session management with Redis-backed storage, automatic session rotation, device fingerprinting, IP tracking, and session revocation.",keywords:["session","redis","cookie","storage","device","tracking"],framework:"both",dependencies:["authentication-core","redis-cache"],useCases:["User session management","Remember me functionality","Device tracking","Session security","Logout from all devices","Session expiration"]},{id:"db-postgres",name:"PostgreSQL",category:"database",description:"PostgreSQL integration with async SQLAlchemy, migrations, connection pooling, and query optimization",longDescription:"Production-ready PostgreSQL with async SQLAlchemy 2.0, Alembic migrations, connection pooling, query optimization, JSON support, and full-text search.",keywords:["postgres","postgresql","database","sql","sqlalchemy","migration","orm","relational"],framework:"both",dependencies:[],useCases:["Relational database","Complex SQL queries","Database transactions","Data integrity","Production-grade database","ACID compliance"]},{id:"db-mongodb",name:"MongoDB",category:"database",description:"MongoDB integration with Motor async driver, schema validation, and aggregation pipelines",longDescription:"Async MongoDB with Motor driver, Pydantic schema validation, aggregation pipelines, indexes, and Atlas integration.",keywords:["mongodb","mongo","nosql","document","database","motor"],framework:"both",dependencies:[],useCases:["Document storage","Flexible schema","Real-time data","JSON documents","Unstructured data","Analytics"]},{id:"stripe-payment",name:"Stripe Payment",category:"payment",description:"Stripe integration with payment intents, subscriptions, webhooks, and customer portal",longDescription:"Complete Stripe integration with Payment Intents API, subscription management, automatic webhooks, customer portal, refunds, and SCA compliance.",keywords:["stripe","payment","subscription","billing","checkout","webhook","credit card"],framework:"both",dependencies:[],useCases:["Accept credit card payments","Subscription billing","One-time payments","Checkout flow","Payment webhooks","Refunds and disputes"]},{id:"email",name:"Email",category:"communication",description:"Email sending with templates, SMTP/SendGrid/AWS SES support, and queue management",longDescription:"Production email system with Jinja2 templates, multiple providers (SMTP, SendGrid, AWS SES), queue management, retry logic, and bounce handling.",keywords:["email","mail","smtp","sendgrid","ses","template","notification"],framework:"both",dependencies:[],useCases:["Welcome emails","Password reset emails","Notifications","Marketing emails","Transactional emails","Email templates"]},{id:"sms",name:"SMS",category:"communication",description:"SMS sending with Twilio, verification codes, and delivery tracking",longDescription:"SMS integration with Twilio, verification codes, two-factor authentication, delivery tracking, and international support.",keywords:["sms","twilio","text","message","2fa","verification","otp"],framework:"both",dependencies:[],useCases:["2FA verification codes","SMS notifications","Phone verification","OTP generation","SMS alerts"]},{id:"redis-cache",name:"Redis Cache",category:"infrastructure",description:"Redis caching with decorators, TTL management, and cache invalidation patterns",longDescription:"Redis integration with async client, caching decorators, TTL management, cache invalidation, pub/sub, and rate limiting.",keywords:["redis","cache","memory","performance","speed","pubsub"],framework:"both",dependencies:[],useCases:["API response caching","Session storage","Rate limiting","Real-time features","Performance optimization","Pub/sub messaging"]},{id:"celery",name:"Celery",category:"infrastructure",description:"Background task processing with Celery, periodic tasks, and monitoring",longDescription:"Celery task queue with Redis/RabbitMQ backend, periodic tasks (cron), task monitoring, retry logic, and failure handling.",keywords:["celery","task","background","queue","async","worker","job","cron"],framework:"fastapi",dependencies:["redis-cache"],useCases:["Background email sending","Data processing","Report generation","Scheduled tasks","Long-running jobs"]},{id:"storage",name:"Storage",category:"infrastructure",description:"File storage with S3, local filesystem, and image processing",longDescription:"Unified storage interface for AWS S3, local files, image resizing, format conversion, CDN integration, and presigned URLs.",keywords:["storage","s3","file","upload","image","cdn","aws"],framework:"both",dependencies:[],useCases:["File uploads","Image storage","Document management","Profile pictures","Media files","CDN integration"]}],kt=null,Ln=0,mp=300*1e3;function gp(t){let e=up(t),r=e.slug||e.name||e.id||e.module_id||"",o=Dn(e.keywords??e.tags);return {id:r,name:e.display_name||e.name||"",category:fp(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:o.map(n=>n.toLowerCase()),framework:hp(e.framework),dependencies:Dn(e.dependencies),useCases:Dn(e.use_cases??e.useCases)}}function fp(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function hp(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 wp(){try{let t=await g$6(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.trim(),r;try{r=JSON.parse(e);}catch{let n=e.indexOf("{"),a=e.indexOf("["),i=[n,a].filter(g=>g>=0);if(i.length===0)throw new Error("Python Core modules response did not contain JSON");let c=Math.min(...i),p=e[c]==="["?"]":"}",d=e.lastIndexOf(p);if(d<c)throw new Error("Python Core modules response contained incomplete JSON");r=JSON.parse(e.slice(c,d+1));}let o=[];if(Array.isArray(r))o=r;else if(r&&typeof r=="object"){let n=r;Array.isArray(n.modules)?o=n.modules:Array.isArray(n.data)&&(o=n.data);}return o.map(gp).filter(n=>n.id&&n.name)}catch(t){return console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",t.message),console.warn(" Using fallback module catalog (11 modules)"),Fn}}async function yo(){let t=Date.now();return Bt()?(kt=Fn,Ln=t,kt):(kt&&t-Ln<mp||(kt=await wp(),Ln=t,kt.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),kt=Fn)),kt)}var kp=fileURLToPath(import.meta.url),Li=b.dirname(kp),qt=null,Fi=new Map;function vp(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function Pp(t){let e=Fi.get(t.id);if(e)return e;let r=await Wn(vp(t));return Fi.set(t.id,r),r}function jp(){if(qt)return qt;let t=[b.join(Li,"../../data/modules-embeddings.json"),b.join(Li,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(A.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let r=A.readFileSync(e,"utf-8"),o=JSON.parse(r);if(Array.isArray(o)?qt={model:"mock-or-text-embedding-3-small",dimension:o[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:o}:qt=o,!qt)throw new Error("failed to load embeddings data");return qt}function Ji(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let r=0,o=0,n=0;for(let i=0;i<t.length;i++)r+=t[i]*e[i],o+=t[i]*t[i],n+=e[i]*e[i];let a=Math.sqrt(o)*Math.sqrt(n);return a===0?0:r/a}function Gi(t,e){let r=e.toLowerCase(),o=t.keywords.filter(n=>r.includes(n)||n.includes(r));return o.length>0?`Matches: ${o.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function Ki(t,e=5){let r=await yo(),o=await Wn(t);if(Bt()){let i=await Promise.all(r.map(async c=>{let p=await Pp(c);return {module:c,score:Ji(o,p),reason:Gi(c,t)}}));return i.sort((c,p)=>p.score-c.score),i.slice(0,e)}let a=jp().modules.map(i=>{let c=r.find(d=>d.id===i.id);if(!c)return null;let p=Ji(o,i.embedding);return {module:c,score:p,reason:Gi(c,t)}}).filter(i=>i!==null);return a.sort((i,c)=>c.score-i.score),a.slice(0,e)}var Cp=fileURLToPath(import.meta.url),Vi=b.dirname(Cp);function Ui(t){return t instanceof Error?t.message:String(t)}function Sp(){return [b.join(Vi,"../../data/modules-embeddings.json"),b.join(Vi,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")]}function Hi(){let t=Sp();for(let e of t)if(A.existsSync(e))try{let r=JSON.parse(A.readFileSync(e,"utf-8")),o=Array.isArray(r)?r:r.modules||[];return {exists:true,path:e,moduleCount:o.length,generatedAt:r.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function vo(t=true,e){try{if(!Wi()&&!Bt())return console.log(s.red(`
23
+ `));});}var jr=null,mo=false,$n=null;async function ip(){return $n||($n=(await import('openai')).default),$n}function Ii(){mo=true;}function Oi(t){let r=new Array(1536),o=0;for(let a=0;a<t.length;a++)o=(o<<5)-o+t.charCodeAt(a),o=o&o;for(let a=0;a<1536;a++)o=o*1664525+1013904223&4294967295,r[a]=o/4294967295*2-1;let n=Math.sqrt(r.reduce((a,i)=>a+i*i,0));return r.map(a=>a/n)}async function go(t){if(!t.trim()){jr=null;return}let e=await ip();jr=new e({apiKey:t});}function $i(){if(!jr)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return jr}async function Nn(t){return mo?Oi(t):(await $i().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function Ni(t){return mo?t.map(Oi):(await $i().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(o=>o.embedding)}function Ti(){return jr!==null}function Vt(){return mo}function Tn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function cp(t){return !t||typeof t!="object"?{}:t}var Wn=[{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"]}],ht=null,Mn=0,lp=300*1e3;function pp(t){let e=cp(t),r=e.slug||e.name||e.id||e.module_id||"",o=Tn(e.keywords??e.tags);return {id:r,name:e.display_name||e.name||"",category:dp(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:o.map(n=>n.toLowerCase()),framework:up(e.framework),dependencies:Tn(e.dependencies),useCases:Tn(e.use_cases??e.useCases)}}function dp(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function up(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 mp(){try{let t=await g$6(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.trim(),r;try{r=JSON.parse(e);}catch{let n=e.indexOf("{"),a=e.indexOf("["),i=[n,a].filter(g=>g>=0);if(i.length===0)throw new Error("Python Core modules response did not contain JSON");let c=Math.min(...i),p=e[c]==="["?"]":"}",d=e.lastIndexOf(p);if(d<c)throw new Error("Python Core modules response contained incomplete JSON");r=JSON.parse(e.slice(c,d+1));}let o=[];if(Array.isArray(r))o=r;else if(r&&typeof r=="object"){let n=r;Array.isArray(n.modules)?o=n.modules:Array.isArray(n.data)&&(o=n.data);}return o.map(pp).filter(n=>n.id&&n.name)}catch(t){return console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",t.message),console.warn(" Using fallback module catalog (11 modules)"),Wn}}async function fo(){let t=Date.now();return Vt()?(ht=Wn,Mn=t,ht):(ht&&t-Mn<lp||(ht=await mp(),Mn=t,ht.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),ht=Wn)),ht)}var fp=fileURLToPath(import.meta.url),Wi=b.dirname(fp),Ut=null,Di=new Map;function hp(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function yp(t){let e=Di.get(t.id);if(e)return e;let r=await Nn(hp(t));return Di.set(t.id,r),r}function wp(){if(Ut)return Ut;let t=[b.join(Wi,"../../data/modules-embeddings.json"),b.join(Wi,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(A.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let r=A.readFileSync(e,"utf-8"),o=JSON.parse(r);if(Array.isArray(o)?Ut={model:"mock-or-text-embedding-3-small",dimension:o[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:o}:Ut=o,!Ut)throw new Error("failed to load embeddings data");return Ut}function Li(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let r=0,o=0,n=0;for(let i=0;i<t.length;i++)r+=t[i]*e[i],o+=t[i]*t[i],n+=e[i]*e[i];let a=Math.sqrt(o)*Math.sqrt(n);return a===0?0:r/a}function Fi(t,e){let r=e.toLowerCase(),o=t.keywords.filter(n=>r.includes(n)||n.includes(r));return o.length>0?`Matches: ${o.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function Ji(t,e=5){let r=await fo(),o=await Nn(t);if(Vt()){let i=await Promise.all(r.map(async c=>{let p=await yp(c);return {module:c,score:Li(o,p),reason:Fi(c,t)}}));return i.sort((c,p)=>p.score-c.score),i.slice(0,e)}let a=wp().modules.map(i=>{let c=r.find(d=>d.id===i.id);if(!c)return null;let p=Li(o,i.embedding);return {module:c,score:p,reason:Fi(c,t)}}).filter(i=>i!==null);return a.sort((i,c)=>c.score-i.score),a.slice(0,e)}var vp=fileURLToPath(import.meta.url),Gi=b.dirname(vp);function Ki(t){return t instanceof Error?t.message:String(t)}function Pp(){return [b.join(Gi,"../../data/modules-embeddings.json"),b.join(Gi,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")]}function Vi(){let t=Pp();for(let e of t)if(A.existsSync(e))try{let r=JSON.parse(A.readFileSync(e,"utf-8")),o=Array.isArray(r)?r:r.modules||[];return {exists:true,path:e,moduleCount:o.length,generatedAt:r.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function yo(t=true,e){try{if(!Ti()&&!Vt())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 r=await yo();console.log(s.green(`\u2713 Found ${r.length} modules
27
+ `)),console.log(s.gray("\u{1F4E1} Fetching modules from Workspai..."));let r=await fo();console.log(s.green(`\u2713 Found ${r.length} modules
28
28
  `));let o=r.length*50/1e6*.02;if(console.log(s.cyan(`\u{1F4B0} Estimated cost: ~$${o.toFixed(3)}`)),console.log(s.gray(` (Based on ${r.length} modules at $0.02/1M tokens)
29
29
  `)),t){let{confirm:i}=await b$2([{type:"confirm",name:"confirm",message:"Generate embeddings now?",default:true}]);if(!i)return console.log(s.yellow(`
30
30
  \u26A0\uFE0F Embeddings generation cancelled
31
- `)),false}let n=r.map(i=>`${i.name}. ${i.description}. ${i.longDescription}. Keywords: ${i.keywords.join(", ")}. Use cases: ${i.useCases.join(", ")}.`),a=b$a(`Generating embeddings for ${r.length} modules...`,{component:"ai",phase:"embeddings.generate"});try{let i=await Mi(n);a.succeed(`Generated embeddings for ${r.length} modules`);let c={model:"text-embedding-3-small",dimension:i[0].length,generated_at:new Date().toISOString(),modules:r.map((g,m)=>({id:g.id,name:g.name,embedding:i[m]}))},p=e||b.join(process.cwd(),"data","modules-embeddings.json"),d=b.dirname(p);return A.existsSync(d)||A.mkdirSync(d,{recursive:true}),A.writeFileSync(p,JSON.stringify(c,null,2)),console.log(s.green(`
31
+ `)),false}let n=r.map(i=>`${i.name}. ${i.description}. ${i.longDescription}. Keywords: ${i.keywords.join(", ")}. Use cases: ${i.useCases.join(", ")}.`),a=b$a(`Generating embeddings for ${r.length} modules...`,{component:"ai",phase:"embeddings.generate"});try{let i=await Ni(n);a.succeed(`Generated embeddings for ${r.length} modules`);let c={model:"text-embedding-3-small",dimension:i[0].length,generated_at:new Date().toISOString(),modules:r.map((g,m)=>({id:g.id,name:g.name,embedding:i[m]}))},p=e||b.join(process.cwd(),"data","modules-embeddings.json"),d=b.dirname(p);return A.existsSync(d)||A.mkdirSync(d,{recursive:true}),A.writeFileSync(p,JSON.stringify(c,null,2)),console.log(s.green(`
32
32
  \u2705 Embeddings generated successfully!`)),console.log(s.gray(`\u{1F4C1} Saved to: ${p}`)),console.log(s.gray(`\u{1F4CA} Size: ${r.length} modules, ${i[0].length} dimensions
33
- `)),true}catch(i){a.fail("Failed to generate embeddings");let c=Ui(i);return c.includes("429")?(console.log(s.red(`
33
+ `)),true}catch(i){a.fail("Failed to generate embeddings");let c=Ki(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(r){return console.log(s.red(`
40
- \u274C Failed to generate embeddings: ${Ui(r)}
41
- `)),false}}async function Bi(t=true){if(Hi().exists)return true;if(console.log(s.yellow(`
40
+ \u274C Failed to generate embeddings: ${Ki(r)}
41
+ `)),false}}async function Ui(t=true){if(Vi().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:r}=await b$2([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"\u{1F680} Generate embeddings now (OpenAI key for production, or mock mode for testing)",value:"generate"},{name:"\u{1F4DD} Show me how to generate them manually",value:"manual"},{name:"\u274C Cancel",value:"cancel"}]}]);return r==="generate"?await vo(true):(r==="manual"&&(console.log(s.cyan(`
44
+ `)),false;let{action:r}=await b$2([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"\u{1F680} Generate embeddings now (OpenAI key for production, or mock mode for testing)",value:"generate"},{name:"\u{1F4DD} Show me how to generate them manually",value:"manual"},{name:"\u274C Cancel",value:"cancel"}]}]);return r==="generate"?await yo(true):(r==="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 qi(){let t=Hi();return t.exists?(console.log(s.blue(`
49
+ `))),false)}async function Hi(){let t=Vi();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 vo(true,t.path):false):(console.log(s.yellow(`
51
+ `)),t.path?await yo(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 Jn(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 zi(t,e=0){console.log(JSON.stringify(t,null,2)),e!==0&&process.exit(e);}function Yi(t){let e=t.command("ai").description("AI-powered features");e.command("recommend").description("Get AI-powered module recommendations").argument("[query]",'What do you want to build? (e.g., "user authentication with email")').option("-n, --number <count>","Number of recommendations","5").option("--json","Output as JSON").action(async(r,o)=>{try{Nn()||(o.json&&zi({ok:false,error:{code:"AI_DISABLED",message:"AI features are disabled",remediation:"workspai config ai enable"}},1),console.log(s.yellow(`
53
+ `)),false)}function Dn(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 Bi(t,e=0){console.log(JSON.stringify(t,null,2)),e!==0&&process.exit(e);}function qi(t){let e=t.command("ai").description("AI-powered features");e.command("recommend").description("Get AI-powered module recommendations").argument("[query]",'What do you want to build? (e.g., "user authentication with email")').option("-n, --number <count>","Number of recommendations","5").option("--json","Output as JSON").action(async(r,o)=>{try{In()||(o.json&&Bi({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=Cr();n?await wo(n):(o.json||(console.log(s.yellow(`
55
+ `)),process.exit(1));let n=Pr();n?await go(n):(o.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
- `))),$i());let a=r;a||(a=(await b$2([{type:"input",name:"query",message:"\u{1F916} What do you want to build?",validate:k=>k.length===0?"Please enter a description":k.length<3?"Please be more specific (at least 3 characters)":true}])).query),o.json||console.log(s.blue(`
59
+ `))),Ii());let a=r;a||(a=(await b$2([{type:"input",name:"query",message:"\u{1F916} What do you want to build?",validate:k=>k.length===0?"Please enter a description":k.length<3?"Please be more specific (at least 3 characters)":true}])).query),o.json||console.log(s.blue(`
60
60
  \u{1F916} Analyzing your request...
61
- `)),!n||await Bi(!o.json)||(o.json&&zi({ok:false,query:a,error:{code:"EMBEDDINGS_MISSING",message:"Module embeddings are not available",remediation:"workspai ai generate-embeddings"}},1),console.log(s.yellow(`
61
+ `)),!n||await Ui(!o.json)||(o.json&&Bi({ok:false,query:a,error:{code:"EMBEDDINGS_MISSING",message:"Module embeddings are not available",remediation:"workspai ai generate-embeddings"}},1),console.log(s.yellow(`
62
62
  \u26A0\uFE0F Cannot proceed without embeddings
63
- `)),process.exit(1));let c=parseInt(o.number,10),p=await Ki(a,c);if(p.length===0||p[0].score<.3)if(console.log(s.yellow(`
63
+ `)),process.exit(1));let c=parseInt(o.number,10),p=await Ji(a,c);if(p.length===0||p[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
@@ -68,8 +68,8 @@ Cancelled
68
68
  `)),console.log(s.white("3. Request feature:")),console.log(s.gray(` https://github.com/chistiq/workspai/issues
69
69
  `)),p.length>0)console.log(s.yellow(`\u26A0\uFE0F Low confidence matches found:
70
70
  `));else return;if(o.json){console.log(JSON.stringify({query:a,recommendations:p},null,2));return}console.log(s.green.bold(`\u{1F4E6} Recommended Modules:
71
- `)),p.forEach((m,k)=>{let w=(m.score*100).toFixed(1),j=m.score>.8?" \u2B50":"";console.log(s.bold(`${k+1}. ${m.module.name}${j}`)),console.log(s.gray(` ${m.module.description}`)),console.log(s.cyan(` Match: ${w}%`)+s.gray(` - ${m.reason}`)),console.log(s.yellow(` Category: ${m.module.category}`)),m.module.dependencies.length>0&&console.log(s.magenta(` Requires: ${m.module.dependencies.join(", ")}`)),console.log();});let d=p.slice(0,3).map(m=>m.module.id);console.log(s.cyan("\u{1F4A1} Quick install (top 3):")),console.log(s.white(` npx workspai add module ${d.join(" ")}
72
- `));let{shouldInstall:g}=await b$2([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(g){let{selectedModules:m}=await b$2([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:p.map(w=>({name:`${w.module.name} - ${w.module.description}`,value:w.module.id,checked:w.score>.7}))}]),k=m;if(k.length>0){console.log(s.blue(`
71
+ `)),p.forEach((m,k)=>{let y=(m.score*100).toFixed(1),j=m.score>.8?" \u2B50":"";console.log(s.bold(`${k+1}. ${m.module.name}${j}`)),console.log(s.gray(` ${m.module.description}`)),console.log(s.cyan(` Match: ${y}%`)+s.gray(` - ${m.reason}`)),console.log(s.yellow(` Category: ${m.module.category}`)),m.module.dependencies.length>0&&console.log(s.magenta(` Requires: ${m.module.dependencies.join(", ")}`)),console.log();});let d=p.slice(0,3).map(m=>m.module.id);console.log(s.cyan("\u{1F4A1} Quick install (top 3):")),console.log(s.white(` npx workspai add module ${d.join(" ")}
72
+ `));let{shouldInstall:g}=await b$2([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(g){let{selectedModules:m}=await b$2([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:p.map(y=>({name:`${y.module.name} - ${y.module.description}`,value:y.module.id,checked:y.score>.7}))}]),k=m;if(k.length>0){console.log(s.blue(`
73
73
  \u{1F4E6} Installing ${k.length} modules...
74
74
  `)),console.log(s.gray(`Command: npx workspai add module ${k.join(" ")}`));let j=w(process.cwd()).commandMap.add;if(!j||j.status!=="supported"){console.log(s.red(`
75
75
  \u274C RapidKit Core modules are not available for this project.`)),console.log(s.gray(` ${j?.reason??"Module commands require RapidKit Core module-enabled project metadata."}
@@ -79,12 +79,12 @@ Cancelled
79
79
  \u274C Module installation failed (exit code: ${x})
80
80
  `));}else console.log(s.gray(`
81
81
  No modules selected
82
- `));}}catch(n){let a=Jn(n);f.error(`
82
+ `));}}catch(n){let a=Dn(n);f.error(`
83
83
  \u274C Error:`,a.message),a.code==="invalid_api_key"?(console.log(s.yellow(`
84
84
  \u{1F4A1} Your API key may be invalid or expired`)),console.log(s.cyan(` Update it: workspai config set-api-key
85
85
  `))):a.message.includes("embeddings file not found")&&(console.log(s.yellow(`
86
86
  \u{1F4A1} Module embeddings not generated yet`)),console.log(s.cyan(" Generate them (one-time):")),console.log(s.white(" cd packages/cli")),console.log(s.white(' export OPENAI_API_KEY="sk-proj-..."')),console.log(s.white(` npx tsx src/ai/generate-embeddings.ts
87
- `))),process.exit(1);}}),e.command("info").description("Show AI features information").action(()=>{let r=Cr(),o=Nn();console.log(s.bold(`
87
+ `))),process.exit(1);}}),e.command("info").description("Show AI features information").action(()=>{let r=Pr(),o=In();console.log(s.bold(`
88
88
  \u{1F916} Workspai AI Features
89
89
  `)),console.log(s.cyan("Status:"),o?s.green("Enabled"):s.red("Disabled")),console.log(s.cyan("API Key:"),r?s.green("Configured \u2713"):s.red("Not configured \u2717")),console.log(s.bold(`
90
90
  \u{1F4E6} Available Features:
@@ -92,95 +92,95 @@ No modules selected
92
92
  \u{1F4B0} Pricing:
93
93
  `)),console.log(s.white("\u2022 Per query: ~$0.0002")+s.gray(" (practically free)")),console.log(s.white("\u2022 100 queries: ~$0.02")+s.gray(" (2 cents)")),console.log(s.white("\u2022 1000 queries: ~$0.20")+s.gray(" (20 cents)")),console.log(s.bold(`
94
94
  \u{1F680} Getting Started:
95
- `)),r?(console.log(s.green("\u2713 You're all set!")),console.log(s.white(' Try: workspai ai recommend "user authentication"'))):(console.log(s.white("1. Get OpenAI API key: https://platform.openai.com/api-keys")),console.log(s.white("2. Configure: workspai config set-api-key")),console.log(s.white('3. Try: workspai ai recommend "user authentication"'))),console.log();}),e.command("generate-embeddings").description("Generate AI embeddings for all modules (one-time setup)").option("--force","Force regeneration even if embeddings exist").action(async()=>{try{let r=Cr();r||(console.log(s.red(`
95
+ `)),r?(console.log(s.green("\u2713 You're all set!")),console.log(s.white(' Try: workspai ai recommend "user authentication"'))):(console.log(s.white("1. Get OpenAI API key: https://platform.openai.com/api-keys")),console.log(s.white("2. Configure: workspai config set-api-key")),console.log(s.white('3. Try: workspai ai recommend "user authentication"'))),console.log();}),e.command("generate-embeddings").description("Generate AI embeddings for all modules (one-time setup)").option("--force","Force regeneration even if embeddings exist").action(async()=>{try{let r=Pr();r||(console.log(s.red(`
96
96
  \u274C OpenAI API key not configured
97
97
  `)),console.log(s.cyan(`To generate embeddings, you need an OpenAI API key:
98
98
  `)),console.log(s.white("1. Get your key from: https://platform.openai.com/api-keys")),console.log(s.white("2. Configure it: workspai config set-api-key")),console.log(s.gray(`
99
99
  OR set environment variable:`)),console.log(s.white(` export OPENAI_API_KEY="sk-proj-..."
100
- `)),process.exit(1)),wo(r);let o=await vo(true);o&&(console.log(s.green("\u2705 Ready to use AI recommendations!")),console.log(s.cyan(`Try: workspai ai recommend "authentication"
101
- `))),process.exit(o?0:1);}catch(r){let o=Jn(r);f.error("Failed to generate embeddings:",o.message),process.exit(1);}}),e.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let r=Cr();r||(console.log(s.red(`
100
+ `)),process.exit(1)),go(r);let o=await yo(true);o&&(console.log(s.green("\u2705 Ready to use AI recommendations!")),console.log(s.cyan(`Try: workspai ai recommend "authentication"
101
+ `))),process.exit(o?0:1);}catch(r){let o=Dn(r);f.error("Failed to generate embeddings:",o.message),process.exit(1);}}),e.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let r=Pr();r||(console.log(s.red(`
102
102
  \u274C OpenAI API key not configured
103
103
  `)),console.log(s.white(`Set your API key: workspai config set-api-key
104
- `)),process.exit(1)),wo(r);let o=await qi();process.exit(o?0:1);}catch(r){let o=Jn(r);f.error("Failed to update embeddings:",o.message),process.exit(1);}});}var Ep="rapidkit.product-factory-plan.v1",Rp="rapidkit.private-product-manifest.v1";function Xi(t){let e=process.argv;for(let r=0;r<e.length;r+=1){let o=e[r];if(o===t){let n=e[r+1];return n&&!n.startsWith("-")?n:void 0}if(o.startsWith(`${t}=`))return o.slice(t.length+1)}}function Er(t,e=""){return typeof t=="string"&&t.trim()?t.trim():e}function Gn(t){return typeof t=="string"&&t.trim()?t.trim():null}function Ap(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function Qi(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function ec(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 _p(t,e,r){let o=Er(t.slug);if(!o)throw new Error(`Backlog product at index ${e} is missing slug.`);ec(o);let n=Qi(t.modules),a=Qi(t.moduleGaps);return {rank:Ap(t.rank,e+1),slug:o,title:Er(t.title,o),category:Er(t.category,"Uncategorized"),tier:Er(t.tier,"pro"),summary:Er(t.summary),modules:n,moduleGaps:a,recommendedKit:r,workspaceProfile:"enterprise",readiness:{status:a.length>0?"blocked-by-module-gaps":"ready-for-private-manifest",blockingGaps:a}}}function Ip(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Backlog must be a JSON object.");return t}async function Op(t){let e=b.resolve(process.cwd(),t),r=Ip(await O__default.readJson(e));if(!Array.isArray(r.products))throw new Error("Backlog must contain a products array.");return {absolutePath:e,payload:r}}function $p(t,e){let r=[...t];if(e.tier){let o=e.tier.toLowerCase();r=r.filter(n=>n.tier.toLowerCase()===o);}if(e.category){let o=e.category.toLowerCase();r=r.filter(n=>n.category.toLowerCase()===o);}if(e.limit){let o=Number.parseInt(e.limit,10);if(!Number.isInteger(o)||o<1)throw new Error("--limit must be a positive integer.");r=r.slice(0,o);}return r}async function tc(t){let e=t.kit?.trim()||"fastapi.standard",{absolutePath:r,payload:o}=await Op(t.backlogPath),n=o.products,a=n.map((g,m)=>_p(g,m,e)),i=$p(a,t),c=new Set(i.flatMap(g=>g.modules)),p=i.flatMap(g=>g.moduleGaps),d=i.filter(g=>g.readiness.status==="ready-for-private-manifest").length;return {schemaVersion:Ep,generatedAt:(t.now??new Date).toISOString(),source:{backlogPath:r,backlogSchemaVersion:Gn(o.schemaVersion),purpose:Gn(o.purpose),publicationRule:Gn(o.publicationRule)},defaults:{kit:e,workspaceProfile:"enterprise",projectSlug:"api"},stats:{totalProducts:n.length,plannedProducts:i.length,readyProducts:d,blockedProducts:i.length-d,uniqueModules:c.size,knownModuleGaps:p.length},products:i}}function Yt(t){return JSON.stringify(t,null,2)}function Np(t){return `sha256:${Pt.createHash("sha256").update(Yt(t)).digest("hex")}`}function Tp(t){return t.replace(/\\/g,"/")}async function Mp(t){let e=await tc({backlogPath:t.backlogPath,kit:t.kit,now:t.now}),r=e.products.find(a=>a.slug===t.slug);if(!r)throw new Error(`Product "${t.slug}" was not found in backlog.`);let o=t.outputRoot||"../workspai-examples-pro",n={schemaVersion:Rp,generatedAt:e.generatedAt,product:{rank:r.rank,slug:r.slug,title:r.title,category:r.category,tier:r.tier,summary:r.summary},workspace:{name:r.slug,profile:"enterprise",outputHint:Tp(b.join(o,r.slug))},projects:[{slug:"api",kit:r.recommendedKit,runtime:"python",framework:"fastapi",modules:r.modules,moduleGaps:r.moduleGaps}],factory:{sourceBacklogPath:e.source.backlogPath,manifestChecksum:"",requiredCommands:[`npx workspai create workspace ${r.slug} --yes --profile enterprise`,`npx workspai create project ${r.recommendedKit} api --yes --skip-install`,"npx workspai init","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"],releaseEvidencePath:`.workspai/product-factory/${r.slug}/release-evidence.json`}};return {...n,factory:{...n.factory,manifestChecksum:Np({...n,factory:{...n.factory,manifestChecksum:""}})}}}async function Zi(t,e,r=false){let o=b.resolve(process.cwd(),t);if(!r&&await O__default.pathExists(o))throw new Error(`Refusing to overwrite existing file: ${o}. Use --force.`);await O__default.ensureDir(b.dirname(o)),await O__default.writeFile(o,`${Yt(e)}
105
- `,"utf-8");}function Wp(t,e){let r=b.join(".workspai","product-factory","manifests",`${e}.manifest.json`);return t?t.endsWith(".json")?t:b.join(t,`${e}.manifest.json`):r}function Dp(t,e){console.log(s.bold(`
104
+ `)),process.exit(1)),go(r);let o=await Hi();process.exit(o?0:1);}catch(r){let o=Dn(r);f.error("Failed to update embeddings:",o.message),process.exit(1);}});}var bp="rapidkit.product-factory-plan.v1",Cp="rapidkit.private-product-manifest.v1";function zi(t){let e=process.argv;for(let r=0;r<e.length;r+=1){let o=e[r];if(o===t){let n=e[r+1];return n&&!n.startsWith("-")?n:void 0}if(o.startsWith(`${t}=`))return o.slice(t.length+1)}}function Cr(t,e=""){return typeof t=="string"&&t.trim()?t.trim():e}function Ln(t){return typeof t=="string"&&t.trim()?t.trim():null}function Sp(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function Yi(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function Qi(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 xp(t,e,r){let o=Cr(t.slug);if(!o)throw new Error(`Backlog product at index ${e} is missing slug.`);Qi(o);let n=Yi(t.modules),a=Yi(t.moduleGaps);return {rank:Sp(t.rank,e+1),slug:o,title:Cr(t.title,o),category:Cr(t.category,"Uncategorized"),tier:Cr(t.tier,"pro"),summary:Cr(t.summary),modules:n,moduleGaps:a,recommendedKit:r,workspaceProfile:"enterprise",readiness:{status:a.length>0?"blocked-by-module-gaps":"ready-for-private-manifest",blockingGaps:a}}}function Ep(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Backlog must be a JSON object.");return t}async function Rp(t){let e=b.resolve(process.cwd(),t),r=Ep(await O__default.readJson(e));if(!Array.isArray(r.products))throw new Error("Backlog must contain a products array.");return {absolutePath:e,payload:r}}function Ap(t,e){let r=[...t];if(e.tier){let o=e.tier.toLowerCase();r=r.filter(n=>n.tier.toLowerCase()===o);}if(e.category){let o=e.category.toLowerCase();r=r.filter(n=>n.category.toLowerCase()===o);}if(e.limit){let o=Number.parseInt(e.limit,10);if(!Number.isInteger(o)||o<1)throw new Error("--limit must be a positive integer.");r=r.slice(0,o);}return r}async function Zi(t){let e=t.kit?.trim()||"fastapi.standard",{absolutePath:r,payload:o}=await Rp(t.backlogPath),n=o.products,a=n.map((g,m)=>xp(g,m,e)),i=Ap(a,t),c=new Set(i.flatMap(g=>g.modules)),p=i.flatMap(g=>g.moduleGaps),d=i.filter(g=>g.readiness.status==="ready-for-private-manifest").length;return {schemaVersion:bp,generatedAt:(t.now??new Date).toISOString(),source:{backlogPath:r,backlogSchemaVersion:Ln(o.schemaVersion),purpose:Ln(o.purpose),publicationRule:Ln(o.publicationRule)},defaults:{kit:e,workspaceProfile:"enterprise",projectSlug:"api"},stats:{totalProducts:n.length,plannedProducts:i.length,readyProducts:d,blockedProducts:i.length-d,uniqueModules:c.size,knownModuleGaps:p.length},products:i}}function Bt(t){return JSON.stringify(t,null,2)}function _p(t){return `sha256:${wt.createHash("sha256").update(Bt(t)).digest("hex")}`}function Ip(t){return t.replace(/\\/g,"/")}async function Op(t){let e=await Zi({backlogPath:t.backlogPath,kit:t.kit,now:t.now}),r=e.products.find(a=>a.slug===t.slug);if(!r)throw new Error(`Product "${t.slug}" was not found in backlog.`);let o=t.outputRoot||"../workspai-examples-pro",n={schemaVersion:Cp,generatedAt:e.generatedAt,product:{rank:r.rank,slug:r.slug,title:r.title,category:r.category,tier:r.tier,summary:r.summary},workspace:{name:r.slug,profile:"enterprise",outputHint:Ip(b.join(o,r.slug))},projects:[{slug:"api",kit:r.recommendedKit,runtime:"python",framework:"fastapi",modules:r.modules,moduleGaps:r.moduleGaps}],factory:{sourceBacklogPath:e.source.backlogPath,manifestChecksum:"",requiredCommands:[`npx workspai create workspace ${r.slug} --yes --profile enterprise`,`npx workspai create project ${r.recommendedKit} api --yes --skip-install`,"npx workspai init","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"],releaseEvidencePath:`.workspai/product-factory/${r.slug}/release-evidence.json`}};return {...n,factory:{...n.factory,manifestChecksum:_p({...n,factory:{...n.factory,manifestChecksum:""}})}}}async function Xi(t,e,r=false){let o=b.resolve(process.cwd(),t);if(!r&&await O__default.pathExists(o))throw new Error(`Refusing to overwrite existing file: ${o}. Use --force.`);await O__default.ensureDir(b.dirname(o)),await O__default.writeFile(o,`${Bt(e)}
105
+ `,"utf-8");}function $p(t,e){let r=b.join(".workspai","product-factory","manifests",`${e}.manifest.json`);return t?t.endsWith(".json")?t:b.join(t,`${e}.manifest.json`):r}function Np(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
108
  Wrote plan: ${b.resolve(process.cwd(),e)}`)),console.log(s.gray(`
109
109
  Next: npx workspai product manifest create <slug> --from-backlog <file>
110
- `));}function Lp(t,e){console.log(s.bold(`
110
+ `));}function Tp(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
113
  Wrote manifest: ${b.resolve(process.cwd(),e)}
114
- `));}function rc(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(r,o)=>{try{let n=o.output||Xi("--output"),a=await tc({backlogPath:r,kit:o.kit,tier:o.tier,category:o.category,limit:o.limit});a$5(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await Zi(n,a,true),o.json?console.log(Yt(a)):Dp(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Yt({ok:false,error:{message:a}})):console.error(s.red(`Product plan failed: ${a}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(r,o)=>{try{let n=o.output||Xi("--output");ec(r);let a=await Mp({backlogPath:o.fromBacklog,slug:r,kit:o.kit,outputRoot:o.workspaceOutput});a$5(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=Wp(n,r);await Zi(i,a,o.force===true),o.json?console.log(Yt(a)):Lp(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Yt({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var sc="rapidkit-workspace-snapshot-v1",Ar="rapidkit-workspace-snapshot-v2",Fp=sc,ac="rapidkit-project-archive-v1",ut="workspai-archive.json",jo="rapidkit-archive.json",Jp=[".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"],Gp=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),Rr={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function Qt(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function bo(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 Kp(t){try{let e=await O__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Vp(t,e){if(!t)return e;let r=t.trim().toLowerCase();return ["true","yes","1","on"].includes(r)?true:["false","no","0","off"].includes(r)?false:e}async function Up(t){let e=s$1(t,"policies.yml").find(r=>existsSync(r))??p(t,"policies.yml");if(!await O__default.pathExists(e))return {...Rr};try{let r=await O__default.readFile(e,"utf-8"),o=(n,a)=>{let i=r.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return Vp(i?.[1],a)};return {requireReasonForDestructiveOps:o("require_reason_for_destructive_ops",Rr.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:o("require_safety_snapshot_for_destructive_ops",Rr.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:o("allow_permanent_delete",Rr.allowPermanentDelete)}}catch{return {...Rr}}}function Hp(t){return p(t,"audit","events.jsonl")}async function et(t,e){let r={schema:"rapidkit-workspace-audit-event-v1",id:Pt.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},o=Hp(t);return await O__default.ensureDir(b.dirname(o)),await O__default.appendFile(o,`${JSON.stringify(r)}
115
- `,"utf-8"),r}async function Co(t,e,r){let o=await Up(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function Kn(t=process.cwd()){let e=b.resolve(t),r=b.resolve($n.tmpdir());for(;;){if(e!==r&&j$1(e))return e;let o=b.dirname(e);if(o===e)return null;e=o;}}function jt(t){let e=t?b.resolve(t):Kn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!j$1(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function ic(t){let e=await Kp(s$1(t,"workspace.json").find(o=>existsSync(o))??p(t,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():b.basename(t)}function Zt(t){return p(t,"snapshots")}function _r(t){return p(t,"archive","projects")}function Xt(t){return b.join(t,"files")}function Bp(t){return b.join($n.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${Pt.randomBytes(4).toString("hex")}`)}function qp(t,e){return b.join(Zt(t),`.tmp-${process.pid}-${e}-${Pt.randomBytes(4).toString("hex")}`)}function So(t,e){let r=b.relative(t,e);if(!r)return true;let o=r.split(b.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>Gp.has(n)||a$f(n))}async function zp(t){return (await a$g(t,{descendIntoMatchedProjects:false})).map(r=>({name:b.basename(r),relativePath:b.relative(t,r)}))}async function Yp(t,e){let r=[],o=new Set;for(let n of Jp){let a=b.join(t,n);if(!await O__default.pathExists(a))continue;let i=v(n);if(o.has(i))continue;let c=b.join(e,i);await O__default.copy(a,c,{filter:p=>So(t,p)}),r.push(i),o.add(i);}return r}async function cc(t){let e=[];async function r(o){let n=[];try{n=await O__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=b.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=b.join(b.dirname(o),b.basename(v(b.basename(o))));await O__default.copy(o,n,{overwrite:false,errorOnExist:false}),await O__default.remove(o);}}async function lc(t,e){let r=e.schema===Ar?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$5(e,r,"Workspace snapshot manifest"),await O__default.writeJson(b.join(t,"snapshot.json"),e,{spaces:2});}async function Vn(t){let e=b.join(t,"snapshot.json"),r=await O__default.readJson(e);if(!r||typeof r!="object"||![sc,Ar].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===Ar?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$5(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==Ar||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function Xp(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await O__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=b.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let p=await O__default.stat(c);e+=1,r+=p.size;}catch{}}}return {files:e,bytes:r}}async function xo(t={}){let e=jt(t.workspacePath),r=t.name?t.name:`snapshot-${Qt()}`,o=bo(r),n=b.join(Zt(e),o),a=Bp(o);if(await O__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=Xt(a);try{await O__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",p=c==="full"?["."]:await Yp(e,i);c==="full"&&(await O__default.copy(e,i,{filter:g=>So(e,g)}),await cc(i));let d={schema:Fp,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await ic(e),workspacePath:e,copiedPaths:p,projects:await zp(e)};return await lc(a,d),await O__default.ensureDir(b.dirname(n)),await O__default.move(a,n,{overwrite:false}),await et(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:p,snapshotPath:n,projectCount:d.projects.length}}),{manifest:d,snapshotPath:n}}catch(c){throw await O__default.remove(a),await et(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function Eo(t){let e=b.resolve(t.workspacePath),r=b.resolve(t.projectPath),o=b.relative(e,r);if(!o||o.startsWith("..")||b.isAbsolute(o)||o.split(b.sep).some(g=>g===".workspai"||g===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=b.basename(r),a=bo(`${t.namePrefix}-${n}-${Qt()}-${Pt.randomBytes(3).toString("hex")}`),i=b.join(Zt(e),a),c=qp(e,a),p=b.join(Xt(c),o),d=false;try{await O__default.ensureDir(b.dirname(p)),t.moveSource?(await O__default.move(r,p,{overwrite:false}),d=true):await O__default.copy(r,p,{overwrite:false,errorOnExist:true,filter:m=>So(r,m)});let g={schema:Ar,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await ic(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await lc(c,g),await O__default.move(c,i,{overwrite:false}),await et(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:g,snapshotPath:i}}catch(g){if(d&&!await O__default.pathExists(r)){let m=await O__default.pathExists(p)?p:b.join(Xt(i),o);await O__default.pathExists(m)&&(await O__default.ensureDir(b.dirname(r)),await O__default.move(m,r,{overwrite:false}));}throw await O__default.remove(c),await O__default.remove(i),await et(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:g instanceof Error?g.message:String(g)}}),g}}async function pc(t){let e=jt(t.workspacePath),r=b.join(Zt(e),bo(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Vn(r),n=Xt(r),a=await Xp(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function dc(t={}){let e=jt(t.workspacePath),r=Zt(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=b.join(r,a.name);try{n.push({...await Vn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var Qp=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function Zp(t){let e=b.dirname(t.workspacePath),r=b.basename(t.workspacePath),o=`${Qt()}-${Pt.randomBytes(4).toString("hex")}`,n=b.join(e,`.${r}.restore-staging-${o}`),a=b.join(e,`.${r}.pre-restore-${o}`),i=b.join(e,`.${r}.restore-failed-${o}`),c=[],p=false,d=false;try{await O__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:g=>So(t.filesRoot,g)}),await cc(n),await O__default.rename(t.workspacePath,a),p=true,await O__default.rename(n,t.workspacePath),d=true;for(let g of Qp){let m=b.join(a,g);if(!await O__default.pathExists(m))continue;let k=b.join(t.workspacePath,g);if(await O__default.pathExists(k))throw new Error(`Full restore operational path collision: ${g}`);await O__default.ensureDir(b.dirname(k)),await O__default.rename(m,k),c.push(g);}return a}catch(g){for(let m of [...c].reverse()){let k=b.join(t.workspacePath,m),w=b.join(a,m);await O__default.pathExists(k)&&(await O__default.ensureDir(b.dirname(w)),await O__default.rename(k,w));}throw d&&await O__default.pathExists(t.workspacePath)&&await O__default.rename(t.workspacePath,i),p&&await O__default.pathExists(a)&&await O__default.rename(a,t.workspacePath),await O__default.remove(i),await O__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${g instanceof Error?g.message:String(g)}`)}}async function uc(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=b.join(Xt(t.snapshotPath),r),n=b.join(e,r);await O__default.pathExists(o)&&!await O__default.pathExists(n)&&(await O__default.ensureDir(b.dirname(n)),await O__default.move(o,n,{overwrite:false})),await O__default.remove(t.snapshotPath);}async function mc(t){let e=jt(t.workspacePath),r=b.join(Zt(e),bo(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Vn(r),n=Xt(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(p=>{let d=v(p);return d.startsWith(".workspai/")?".workspai":d})));if(t.dryRun)return await et(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await Co(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await Zp({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let p=o.recoveryScope?.relativePath;if(!p)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let d=b.join(n,p),g=b.join(e,p),m=await O__default.pathExists(g),k,w=b.join(b.dirname(g),`.${b.basename(g)}.pre-restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`),j=false;m&&t.safetySnapshot!==false?(k=await Eo({workspacePath:e,projectPath:g,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=k.snapshotPath):m&&(await O__default.rename(g,w),j=true);let x=b.join(b.dirname(g),`.${b.basename(g)}.restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`);try{await O__default.copy(d,x,{overwrite:false,errorOnExist:true}),await O__default.rename(x,g),j&&await O__default.remove(w);}catch(l){throw await O__default.remove(x),j&&await O__default.pathExists(w)&&(await O__default.remove(g),await O__default.rename(w,g)),k&&await uc(k,e),l}}else t.safetySnapshot!==false&&(i=(await xo({workspacePath:e,name:`pre-restore-${o.name}-${Qt()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let p=new Set;for(let d of o.copiedPaths){let g=v(d);p.has(g)||(await O__default.copy(b.join(n,d),b.join(e,g),{overwrite:true,errorOnExist:false}),p.add(g));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await et(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function gc(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function fc(t,e){let r=gc(e),o=b.isAbsolute(r)?b.resolve(r):b.resolve(t,r);if(o.startsWith(`${b.resolve(t)}${b.sep}`)&&await O__default.pathExists(o))return o;let a=(await a$g(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=b.relative(t,i);return b.basename(i)===r||c===r});if(a.length===0)throw new Error(`Project not found in workspace: ${e}`);if(a.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return a[0]}async function Un(t){let{syncWorkspaceProjects:e}=await import('./workspace-B53XH35L.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-AYFTZIKM.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-ZOAWXYC5.js');await o({workspacePath:t,mode:"managed"});}function ed(t,e){let r=Pt.randomBytes(4).toString("hex");return b.join(_r(t),`${e}-${Qt()}-${r}`)}async function hc(t){let e=wc(t),r=await O__default.readJson(e);if(!r||typeof r!="object"||r.schema!==ac)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$5(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function wc(t){return [ut,jo].map(e=>b.join(t,e)).find(e=>O__default.existsSync(e))??b.join(t,ut)}async function Hn(t={}){let e=jt(t.workspacePath),r=_r(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=b.join(r,a.name),c=[ut,jo].map(p=>b.join(i,p)).find(p=>O__default.existsSync(p))??b.join(i,ut);try{n.push({...await hc(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function td(t,e){let r=gc(e),o=b.isAbsolute(r)?b.resolve(r):b.resolve(_r(t),r);if(o.startsWith(`${b.resolve(_r(t))}${b.sep}`)&&(await O__default.pathExists(b.join(o,ut))||await O__default.pathExists(b.join(o,jo))))return o;let a=(await Hn({workspacePath:t})).filter(i=>b.basename(i.archivePath)===r||i.projectName===r||b.relative(_r(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function Bn(t){let e=jt(t.workspacePath),r=await fc(e,t.project),o=b.basename(r),n=ed(e,o),a=b.join(n,ut),i=`${n}.tmp-${process.pid}`,c=b.join(i,ut);for(let m of [ut,jo])if(await O__default.pathExists(b.join(r,m)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${m}`);if(t.dryRun)return await et(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await Co(e,"project.archive",{reason:t.reason,safetySnapshot:true});let p=await Eo({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),d={schema:ac,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:p.snapshotPath};a$5(d,"contracts/project-archive.v1.json","Project archive manifest");let g=false;try{await O__default.ensureDir(b.dirname(n)),await O__default.move(r,i,{overwrite:false}),g=true,await O__default.writeJson(c,d,{spaces:2}),await O__default.rename(i,n);}catch(m){if(g&&!await O__default.pathExists(r)){let k=await O__default.pathExists(i)?i:n;await O__default.pathExists(k)&&(await O__default.remove(b.join(k,ut)),await O__default.move(k,r,{overwrite:false}));}throw await O__default.remove(i),m}return await c$3(e,[r]),await Un(e),await et(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath,dryRun:false}}async function yc(t){if(!t.permanent)return Bn(t);let e=jt(t.workspacePath),r=await fc(e,t.project),o=b.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await et(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await Co(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Eo({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$3(e,[r]),await Un(e),await et(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function kc(t){let e=jt(t.workspacePath),r=await td(e,t.archive),o=await hc(r),n=t.targetName?.trim()||o.projectName,a=b.join(e,n);if(!a.startsWith(`${b.resolve(e)}${b.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await O__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await et(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:b.join(r,ut),dryRun:true};await Co(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await O__default.pathExists(a),c=i?await Eo({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await xo({workspacePath:e,name:`pre-restore-project-${n}-${Qt()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),p$1=wc(r),d=p(e,"audit","restores",`${b.basename(r)}.json`);try{await O__default.move(r,a,{overwrite:false}),await O__default.ensureDir(b.dirname(d)),await O__default.move(b.join(a,b.basename(p$1)),d,{overwrite:false});}catch(g){throw await O__default.pathExists(a)&&(await O__default.pathExists(d)&&await O__default.move(d,b.join(a,b.basename(p$1)),{overwrite:false}),await O__default.pathExists(r)||await O__default.move(a,r,{overwrite:false})),i&&await uc(c,e),g}return await Un(e),await et(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:d,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:d,safetySnapshotPath:c.snapshotPath,dryRun:false}}var od="rapidkit.infra-stack.v1",Pc=d$9.infraPlan.schemaVersion,er=".workspai/infra/docker-compose.yml",tr=e$1.infraPlan,Yn=".workspai/infra/.env.example";function nd(){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 r of e)if(A.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var zn=null;function _t(t){if(zn)return zn;let e=nd(),r=A.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==od)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return sd(o),(zn=o),o}function sd(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function jc(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function rr(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function bc(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function id(t){let e=b.join(t,"registry.json");if(!await O__default.pathExists(e))return [];try{let o=(await O__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function cd(t){let e=b.join(t,".env.example");if(!await O__default.pathExists(e))return [];try{let r=await O__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
116
- `)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&o.push(i[1]);}return o}catch{return []}}async function ld(t){let e=s$1(t,"infra","overrides.json").find(r=>existsSync(r));if(!e)return [];try{let r=await O__default.readJson(e);return Array.isArray(r.services)?[...new Set(r.services.filter(o=>typeof o=="string"&&o.trim().length>0))]:[]}catch{return []}}async function pd(t){let e=await d$8(t,e$1.workspaceContract);if(!e)return [];try{let r=await O__default.readJson(e),o=[];for(let n of r.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&o.push({project:a,env:i.trim().toUpperCase()});}return o}catch{return []}}function Ro(t,e,r,o){t.add(r),e.push(o);}async function Cc(t){let e=b.resolve(t.workspacePath),r=t.contract||_t(),o=new Set,n=[],a=new Set,i=new Set,c=new Set,p=await l$2(e);for(let d of p){let g=b.dirname(b.dirname(d)),m=b.basename(g);for(let k of await id(g)){a.add(k);for(let w of jc(r,k))Ro(o,n,w,{kind:"module",value:k,project:m});}for(let k of await cd(g)){i.add(k);for(let w of rr(r,k))Ro(o,n,w,{kind:"env-var",value:k,project:m});}}for(let d of await pd(e)){i.add(d.env);for(let g of rr(r,d.env))Ro(o,n,g,{kind:"contract-env",value:d.env,project:d.project});}for(let d of await ld(e))c.add(d),Ro(o,n,d,{kind:"override",value:d});return {modules:[...a].sort(),envVars:[...i].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...o].sort()}}function dd(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let r=e.indexOf("=");if(r<=0)return null;let o=e.slice(0,r).trim();if(!/^[A-Z0-9_]+$/.test(o))return null;let n=e.slice(r+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let a=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),i=(a?a[1]:n).trim();return i?{key:o,value:i}:null}async function ud(t){if(!await O__default.pathExists(t))return {};try{let e=await O__default.readFile(t,"utf-8"),r={};for(let o of e.split(`
117
- `)){let n=dd(o);n&&(r[n.key]=n.value);}return r}catch{return {}}}async function xc(t){let e={},r=await l$2(t.workspacePath);for(let o of r){let n=b.dirname(b.dirname(o)),a=await ud(b.join(n,".env.example"));for(let[i,c]of Object.entries(a))rr(t.contract,i).length>0&&(e[i]=c);}return e}function Ec(t,e){return t.filter(r=>rr(e,r).length>0).sort()}function Rc(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let r=new URL(e),o=r.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(r.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(r.password||"postgres"),POSTGRES_DB:o||"postgres"}}catch{return}}function Ac(t){let e=t.POSTGRES_USER||"postgres",r=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${r}`]}function md(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
118
- `)?JSON.stringify(t):t}function _c(t,e){return Object.entries(t).map(([r,o])=>`${e}${r}: ${md(o)}`).join(`
119
- `)}function gd(t,e){let r=t.test.map(o=>JSON.stringify(o)).join(", ");return [`${e}healthcheck:`,`${e} test: [${r}]`,`${e} interval: ${t.interval}`,`${e} timeout: ${t.timeout}`,`${e} retries: ${t.retries}`].join(`
120
- `)}function Ic(t){let e=["# Generated by Workspai infra plan \u2014 do not edit manually.",`# Workspace: ${t.workspaceName}`,`# Generated at: ${t.plan.generatedAt}`,"name: workspai-infra"],r=new Set;if(t.plan.services.length===0)return e.push("services: {}"),e.push(""),e.join(`
121
- `);e.push("services:");for(let o of t.plan.services){let n=t.contract.services[o.id];if(n){if(e.push(` ${o.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: workspai-${o.id}`),n.command?.length){let a=n.command.map(i=>JSON.stringify(i)).join(", ");e.push(` command: [${a}]`);}if(n.env&&Object.keys(n.env).length>0){e.push(" environment:");let a={...n.env,...t.plan.serviceEnvOverrides?.[o.id]||{}};e.push(_c(a," "));}else t.plan.serviceEnvOverrides?.[o.id]&&(e.push(" environment:"),e.push(_c(t.plan.serviceEnvOverrides[o.id]," ")));if(n.ports.length>0){e.push(" ports:");for(let a of n.ports)e.push(` - "${a.host}:${a.container}"`);}if(n.volumes?.length){e.push(" volumes:");for(let a of n.volumes){e.push(` - ${a}`);let i=a.split(":")[0];i&&!i.startsWith("/")&&r.add(i);}}if(n.healthcheck){let a=t.plan.serviceEnvOverrides?.[o.id];if(o.id==="postgres"&&a){let i=Ac(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(gd(n.healthcheck," "));}e.push(" restart: unless-stopped");}}if(r.size>0){e.push("volumes:");for(let o of [...r].sort())e.push(` ${o}:`),e.push(" driver: local");}return e.push(""),e.join(`
122
- `)}function hd(t,e,r){return t.kind==="override"?t.value===e:t.kind==="module"?r.moduleMappings[t.value]?.includes(e)??false:r.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function wd(t){let e=new Map,r=[];for(let o of t)for(let n of o.ports){let a=e.get(n.host);a&&a!==o.id?r.push(`Port collision on host ${n.host} between services '${a}' and '${o.id}'`):e.set(n.host,o.id);}return r}async function yd(t){let e=s$1(t,"workspace.json").find(r=>existsSync(r));if(e)try{let r=await O__default.readJson(e);return r.workspace_name||r.name}catch{return}}async function Qn(t){let e=b.resolve(t.workspacePath),r=_t(),o=await Cc({workspacePath:e,contract:r}),n=o.serviceIds.map(k=>{let w=r.services[k];return w?{id:k,displayName:w.displayName,category:w.category,image:w.image,ports:w.ports,sources:o.sources.filter(j=>hd(j,k,r))}:null}).filter(k=>k!==null),a=wd(n);n.length===0&&a.push("No infrastructure services detected. Install modules with infra dependencies or add .workspai/infra/overrides.json");for(let k of o.overrides)r.services[k]||a.push(`Override references unknown service '${k}'`);let i=await d$8(e,e$1.workspaceContract)?e$1.workspaceContract:void 0,c=bc(r,o.serviceIds),p=await xc({workspacePath:e,contract:r}),d={...c,...p};p.RAPIDKIT_DB_POSTGRES_URL&&(d.DATABASE_URL=p.RAPIDKIT_DB_POSTGRES_URL);let g={},m=Rc(d);return m&&o.serviceIds.includes("postgres")&&(g.postgres=m),{schemaVersion:Pc,generatedAt:(t.now||(()=>new Date))().toISOString(),workspacePath:e,workspaceName:await yd(e),contractPath:i,strategy:"sidecar",composePath:er,envExamplePath:Yn,services:n,connectionEnv:d,serviceEnvOverrides:Object.keys(g).length>0?g:void 0,sources:{modules:o.modules,envVars:o.envVars,overrides:o.overrides},warnings:a}}async function Zn(t){let e=b.resolve(t.workspacePath),r=b.join(e,er),o=b.join(e,tr),n=b.join(e,Yn),a=_t();a$5(t.plan,"contracts/infra-plan.v1.json","Workspai infrastructure plan");let i=Ic({plan:t.plan,contract:a,workspaceName:t.plan.workspaceName||b.basename(e)}),c=["# Generated by: npx workspai infra plan","# Copy values into project .env files as needed.",...Object.entries(t.plan.connectionEnv).map(([p,d])=>`${p}=${d}`),""].join(`
114
+ `));}function ec(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(r,o)=>{try{let n=o.output||zi("--output"),a=await Zi({backlogPath:r,kit:o.kit,tier:o.tier,category:o.category,limit:o.limit});a$5(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await Xi(n,a,true),o.json?console.log(Bt(a)):Np(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Bt({ok:false,error:{message:a}})):console.error(s.red(`Product plan failed: ${a}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(r,o)=>{try{let n=o.output||zi("--output");Qi(r);let a=await Op({backlogPath:o.fromBacklog,slug:r,kit:o.kit,outputRoot:o.workspaceOutput});a$5(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=$p(n,r);await Xi(i,a,o.force===true),o.json?console.log(Bt(a)):Tp(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Bt({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var oc="rapidkit-workspace-snapshot-v1",xr="rapidkit-workspace-snapshot-v2",Mp=oc,nc="rapidkit-project-archive-v1",lt="workspai-archive.json",ko="rapidkit-archive.json",Wp=[".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"],Dp=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),Sr={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function zt(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function vo(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 Lp(t){try{let e=await O__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Fp(t,e){if(!t)return e;let r=t.trim().toLowerCase();return ["true","yes","1","on"].includes(r)?true:["false","no","0","off"].includes(r)?false:e}async function Jp(t){let e=s$1(t,"policies.yml").find(r=>existsSync(r))??p(t,"policies.yml");if(!await O__default.pathExists(e))return {...Sr};try{let r=await O__default.readFile(e,"utf-8"),o=(n,a)=>{let i=r.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return Fp(i?.[1],a)};return {requireReasonForDestructiveOps:o("require_reason_for_destructive_ops",Sr.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:o("require_safety_snapshot_for_destructive_ops",Sr.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:o("allow_permanent_delete",Sr.allowPermanentDelete)}}catch{return {...Sr}}}function Gp(t){return p(t,"audit","events.jsonl")}async function Xe(t,e){let r={schema:"rapidkit-workspace-audit-event-v1",id:wt.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},o=Gp(t);return await O__default.ensureDir(b.dirname(o)),await O__default.appendFile(o,`${JSON.stringify(r)}
115
+ `,"utf-8"),r}async function Po(t,e,r){let o=await Jp(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function Fn(t=process.cwd()){let e=b.resolve(t),r=b.resolve(_n.tmpdir());for(;;){if(e!==r&&j$1(e))return e;let o=b.dirname(e);if(o===e)return null;e=o;}}function kt(t){let e=t?b.resolve(t):Fn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!j$1(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function sc(t){let e=await Lp(s$1(t,"workspace.json").find(o=>existsSync(o))??p(t,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():b.basename(t)}function Yt(t){return p(t,"snapshots")}function Er(t){return p(t,"archive","projects")}function qt(t){return b.join(t,"files")}function Kp(t){return b.join(_n.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${wt.randomBytes(4).toString("hex")}`)}function Vp(t,e){return b.join(Yt(t),`.tmp-${process.pid}-${e}-${wt.randomBytes(4).toString("hex")}`)}function jo(t,e){let r=b.relative(t,e);if(!r)return true;let o=r.split(b.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>Dp.has(n)||a$f(n))}async function Up(t){return (await a$g(t,{descendIntoMatchedProjects:false})).map(r=>({name:b.basename(r),relativePath:b.relative(t,r)}))}async function Hp(t,e){let r=[],o=new Set;for(let n of Wp){let a=b.join(t,n);if(!await O__default.pathExists(a))continue;let i=v(n);if(o.has(i))continue;let c=b.join(e,i);await O__default.copy(a,c,{filter:p=>jo(t,p)}),r.push(i),o.add(i);}return r}async function ac(t){let e=[];async function r(o){let n=[];try{n=await O__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=b.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=b.join(b.dirname(o),b.basename(v(b.basename(o))));await O__default.copy(o,n,{overwrite:false,errorOnExist:false}),await O__default.remove(o);}}async function ic(t,e){let r=e.schema===xr?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$5(e,r,"Workspace snapshot manifest"),await O__default.writeJson(b.join(t,"snapshot.json"),e,{spaces:2});}async function Jn(t){let e=b.join(t,"snapshot.json"),r=await O__default.readJson(e);if(!r||typeof r!="object"||![oc,xr].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===xr?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$5(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==xr||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function Bp(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await O__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=b.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let p=await O__default.stat(c);e+=1,r+=p.size;}catch{}}}return {files:e,bytes:r}}async function bo(t={}){let e=kt(t.workspacePath),r=t.name?t.name:`snapshot-${zt()}`,o=vo(r),n=b.join(Yt(e),o),a=Kp(o);if(await O__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=qt(a);try{await O__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",p=c==="full"?["."]:await Hp(e,i);c==="full"&&(await O__default.copy(e,i,{filter:g=>jo(e,g)}),await ac(i));let d={schema:Mp,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await sc(e),workspacePath:e,copiedPaths:p,projects:await Up(e)};return await ic(a,d),await O__default.ensureDir(b.dirname(n)),await O__default.move(a,n,{overwrite:false}),await Xe(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:p,snapshotPath:n,projectCount:d.projects.length}}),{manifest:d,snapshotPath:n}}catch(c){throw await O__default.remove(a),await Xe(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function Co(t){let e=b.resolve(t.workspacePath),r=b.resolve(t.projectPath),o=b.relative(e,r);if(!o||o.startsWith("..")||b.isAbsolute(o)||o.split(b.sep).some(g=>g===".workspai"||g===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=b.basename(r),a=vo(`${t.namePrefix}-${n}-${zt()}-${wt.randomBytes(3).toString("hex")}`),i=b.join(Yt(e),a),c=Vp(e,a),p=b.join(qt(c),o),d=false;try{await O__default.ensureDir(b.dirname(p)),t.moveSource?(await O__default.move(r,p,{overwrite:false}),d=true):await O__default.copy(r,p,{overwrite:false,errorOnExist:true,filter:m=>jo(r,m)});let g={schema:xr,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await sc(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await ic(c,g),await O__default.move(c,i,{overwrite:false}),await Xe(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:g,snapshotPath:i}}catch(g){if(d&&!await O__default.pathExists(r)){let m=await O__default.pathExists(p)?p:b.join(qt(i),o);await O__default.pathExists(m)&&(await O__default.ensureDir(b.dirname(r)),await O__default.move(m,r,{overwrite:false}));}throw await O__default.remove(c),await O__default.remove(i),await Xe(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:g instanceof Error?g.message:String(g)}}),g}}async function cc(t){let e=kt(t.workspacePath),r=b.join(Yt(e),vo(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Jn(r),n=qt(r),a=await Bp(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function lc(t={}){let e=kt(t.workspacePath),r=Yt(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=b.join(r,a.name);try{n.push({...await Jn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var qp=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function zp(t){let e=b.dirname(t.workspacePath),r=b.basename(t.workspacePath),o=`${zt()}-${wt.randomBytes(4).toString("hex")}`,n=b.join(e,`.${r}.restore-staging-${o}`),a=b.join(e,`.${r}.pre-restore-${o}`),i=b.join(e,`.${r}.restore-failed-${o}`),c=[],p=false,d=false;try{await O__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:g=>jo(t.filesRoot,g)}),await ac(n),await O__default.rename(t.workspacePath,a),p=true,await O__default.rename(n,t.workspacePath),d=true;for(let g of qp){let m=b.join(a,g);if(!await O__default.pathExists(m))continue;let k=b.join(t.workspacePath,g);if(await O__default.pathExists(k))throw new Error(`Full restore operational path collision: ${g}`);await O__default.ensureDir(b.dirname(k)),await O__default.rename(m,k),c.push(g);}return a}catch(g){for(let m of [...c].reverse()){let k=b.join(t.workspacePath,m),y=b.join(a,m);await O__default.pathExists(k)&&(await O__default.ensureDir(b.dirname(y)),await O__default.rename(k,y));}throw d&&await O__default.pathExists(t.workspacePath)&&await O__default.rename(t.workspacePath,i),p&&await O__default.pathExists(a)&&await O__default.rename(a,t.workspacePath),await O__default.remove(i),await O__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${g instanceof Error?g.message:String(g)}`)}}async function pc(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=b.join(qt(t.snapshotPath),r),n=b.join(e,r);await O__default.pathExists(o)&&!await O__default.pathExists(n)&&(await O__default.ensureDir(b.dirname(n)),await O__default.move(o,n,{overwrite:false})),await O__default.remove(t.snapshotPath);}async function dc(t){let e=kt(t.workspacePath),r=b.join(Yt(e),vo(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Jn(r),n=qt(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(p=>{let d=v(p);return d.startsWith(".workspai/")?".workspai":d})));if(t.dryRun)return await Xe(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await Po(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await zp({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let p=o.recoveryScope?.relativePath;if(!p)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let d=b.join(n,p),g=b.join(e,p),m=await O__default.pathExists(g),k,y=b.join(b.dirname(g),`.${b.basename(g)}.pre-restore-${process.pid}-${wt.randomBytes(4).toString("hex")}`),j=false;m&&t.safetySnapshot!==false?(k=await Co({workspacePath:e,projectPath:g,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=k.snapshotPath):m&&(await O__default.rename(g,y),j=true);let x=b.join(b.dirname(g),`.${b.basename(g)}.restore-${process.pid}-${wt.randomBytes(4).toString("hex")}`);try{await O__default.copy(d,x,{overwrite:false,errorOnExist:true}),await O__default.rename(x,g),j&&await O__default.remove(y);}catch(l){throw await O__default.remove(x),j&&await O__default.pathExists(y)&&(await O__default.remove(g),await O__default.rename(y,g)),k&&await pc(k,e),l}}else t.safetySnapshot!==false&&(i=(await bo({workspacePath:e,name:`pre-restore-${o.name}-${zt()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let p=new Set;for(let d of o.copiedPaths){let g=v(d);p.has(g)||(await O__default.copy(b.join(n,d),b.join(e,g),{overwrite:true,errorOnExist:false}),p.add(g));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await Xe(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function uc(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function mc(t,e){let r=uc(e),o=b.isAbsolute(r)?b.resolve(r):b.resolve(t,r);if(o.startsWith(`${b.resolve(t)}${b.sep}`)&&await O__default.pathExists(o))return o;let a=(await a$g(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=b.relative(t,i);return b.basename(i)===r||c===r});if(a.length===0)throw new Error(`Project not found in workspace: ${e}`);if(a.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return a[0]}async function Gn(t){let{syncWorkspaceProjects:e}=await import('./workspace-C4UETGY7.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-AYFTZIKM.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-ZOAWXYC5.js');await o({workspacePath:t,mode:"managed"});}function Yp(t,e){let r=wt.randomBytes(4).toString("hex");return b.join(Er(t),`${e}-${zt()}-${r}`)}async function gc(t){let e=fc(t),r=await O__default.readJson(e);if(!r||typeof r!="object"||r.schema!==nc)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$5(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function fc(t){return [lt,ko].map(e=>b.join(t,e)).find(e=>O__default.existsSync(e))??b.join(t,lt)}async function Kn(t={}){let e=kt(t.workspacePath),r=Er(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=b.join(r,a.name),c=[lt,ko].map(p=>b.join(i,p)).find(p=>O__default.existsSync(p))??b.join(i,lt);try{n.push({...await gc(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function Xp(t,e){let r=uc(e),o=b.isAbsolute(r)?b.resolve(r):b.resolve(Er(t),r);if(o.startsWith(`${b.resolve(Er(t))}${b.sep}`)&&(await O__default.pathExists(b.join(o,lt))||await O__default.pathExists(b.join(o,ko))))return o;let a=(await Kn({workspacePath:t})).filter(i=>b.basename(i.archivePath)===r||i.projectName===r||b.relative(Er(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function Vn(t){let e=kt(t.workspacePath),r=await mc(e,t.project),o=b.basename(r),n=Yp(e,o),a=b.join(n,lt),i=`${n}.tmp-${process.pid}`,c=b.join(i,lt);for(let m of [lt,ko])if(await O__default.pathExists(b.join(r,m)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${m}`);if(t.dryRun)return await Xe(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await Po(e,"project.archive",{reason:t.reason,safetySnapshot:true});let p=await Co({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),d={schema:nc,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:p.snapshotPath};a$5(d,"contracts/project-archive.v1.json","Project archive manifest");let g=false;try{await O__default.ensureDir(b.dirname(n)),await O__default.move(r,i,{overwrite:false}),g=true,await O__default.writeJson(c,d,{spaces:2}),await O__default.rename(i,n);}catch(m){if(g&&!await O__default.pathExists(r)){let k=await O__default.pathExists(i)?i:n;await O__default.pathExists(k)&&(await O__default.remove(b.join(k,lt)),await O__default.move(k,r,{overwrite:false}));}throw await O__default.remove(i),m}return await c$3(e,[r]),await Gn(e),await Xe(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath,dryRun:false}}async function hc(t){if(!t.permanent)return Vn(t);let e=kt(t.workspacePath),r=await mc(e,t.project),o=b.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await Xe(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await Po(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Co({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$3(e,[r]),await Gn(e),await Xe(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function yc(t){let e=kt(t.workspacePath),r=await Xp(e,t.archive),o=await gc(r),n=t.targetName?.trim()||o.projectName,a=b.join(e,n);if(!a.startsWith(`${b.resolve(e)}${b.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await O__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await Xe(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:b.join(r,lt),dryRun:true};await Po(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await O__default.pathExists(a),c=i?await Co({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await bo({workspacePath:e,name:`pre-restore-project-${n}-${zt()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),p$1=fc(r),d=p(e,"audit","restores",`${b.basename(r)}.json`);try{await O__default.move(r,a,{overwrite:false}),await O__default.ensureDir(b.dirname(d)),await O__default.move(b.join(a,b.basename(p$1)),d,{overwrite:false});}catch(g){throw await O__default.pathExists(a)&&(await O__default.pathExists(d)&&await O__default.move(d,b.join(a,b.basename(p$1)),{overwrite:false}),await O__default.pathExists(r)||await O__default.move(a,r,{overwrite:false})),i&&await pc(c,e),g}return await Gn(e),await Xe(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:d,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:d,safetySnapshotPath:c.snapshotPath,dryRun:false}}var Zp="rapidkit.infra-stack.v1",kc=d$9.infraPlan.schemaVersion,Xt=".workspai/infra/docker-compose.yml",Qt=e$1.infraPlan,Bn=".workspai/infra/.env.example";function ed(){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 r of e)if(A.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var Hn=null;function Et(t){if(Hn)return Hn;let e=ed(),r=A.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==Zp)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return td(o),(Hn=o),o}function td(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function vc(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function Zt(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Pc(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function od(t){let e=b.join(t,"registry.json");if(!await O__default.pathExists(e))return [];try{let o=(await O__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function nd(t){let e=b.join(t,".env.example");if(!await O__default.pathExists(e))return [];try{let r=await O__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
116
+ `)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&o.push(i[1]);}return o}catch{return []}}async function sd(t){let e=s$1(t,"infra","overrides.json").find(r=>existsSync(r));if(!e)return [];try{let r=await O__default.readJson(e);return Array.isArray(r.services)?[...new Set(r.services.filter(o=>typeof o=="string"&&o.trim().length>0))]:[]}catch{return []}}async function ad(t){let e=await d$8(t,e$1.workspaceContract);if(!e)return [];try{let r=await O__default.readJson(e),o=[];for(let n of r.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&o.push({project:a,env:i.trim().toUpperCase()});}return o}catch{return []}}function So(t,e,r,o){t.add(r),e.push(o);}async function jc(t){let e=b.resolve(t.workspacePath),r=t.contract||Et(),o=new Set,n=[],a=new Set,i=new Set,c=new Set,p=await l$2(e);for(let d of p){let g=b.dirname(b.dirname(d)),m=b.basename(g);for(let k of await od(g)){a.add(k);for(let y of vc(r,k))So(o,n,y,{kind:"module",value:k,project:m});}for(let k of await nd(g)){i.add(k);for(let y of Zt(r,k))So(o,n,y,{kind:"env-var",value:k,project:m});}}for(let d of await ad(e)){i.add(d.env);for(let g of Zt(r,d.env))So(o,n,g,{kind:"contract-env",value:d.env,project:d.project});}for(let d of await sd(e))c.add(d),So(o,n,d,{kind:"override",value:d});return {modules:[...a].sort(),envVars:[...i].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...o].sort()}}function id(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let r=e.indexOf("=");if(r<=0)return null;let o=e.slice(0,r).trim();if(!/^[A-Z0-9_]+$/.test(o))return null;let n=e.slice(r+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let a=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),i=(a?a[1]:n).trim();return i?{key:o,value:i}:null}async function cd(t){if(!await O__default.pathExists(t))return {};try{let e=await O__default.readFile(t,"utf-8"),r={};for(let o of e.split(`
117
+ `)){let n=id(o);n&&(r[n.key]=n.value);}return r}catch{return {}}}async function Cc(t){let e={},r=await l$2(t.workspacePath);for(let o of r){let n=b.dirname(b.dirname(o)),a=await cd(b.join(n,".env.example"));for(let[i,c]of Object.entries(a))Zt(t.contract,i).length>0&&(e[i]=c);}return e}function Sc(t,e){return t.filter(r=>Zt(e,r).length>0).sort()}function xc(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let r=new URL(e),o=r.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(r.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(r.password||"postgres"),POSTGRES_DB:o||"postgres"}}catch{return}}function Ec(t){let e=t.POSTGRES_USER||"postgres",r=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${r}`]}function ld(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
118
+ `)?JSON.stringify(t):t}function Rc(t,e){return Object.entries(t).map(([r,o])=>`${e}${r}: ${ld(o)}`).join(`
119
+ `)}function pd(t,e){let r=t.test.map(o=>JSON.stringify(o)).join(", ");return [`${e}healthcheck:`,`${e} test: [${r}]`,`${e} interval: ${t.interval}`,`${e} timeout: ${t.timeout}`,`${e} retries: ${t.retries}`].join(`
120
+ `)}function Ac(t){let e=["# Generated by Workspai infra plan \u2014 do not edit manually.",`# Workspace: ${t.workspaceName}`,`# Generated at: ${t.plan.generatedAt}`,"name: workspai-infra"],r=new Set;if(t.plan.services.length===0)return e.push("services: {}"),e.push(""),e.join(`
121
+ `);e.push("services:");for(let o of t.plan.services){let n=t.contract.services[o.id];if(n){if(e.push(` ${o.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: workspai-${o.id}`),n.command?.length){let a=n.command.map(i=>JSON.stringify(i)).join(", ");e.push(` command: [${a}]`);}if(n.env&&Object.keys(n.env).length>0){e.push(" environment:");let a={...n.env,...t.plan.serviceEnvOverrides?.[o.id]||{}};e.push(Rc(a," "));}else t.plan.serviceEnvOverrides?.[o.id]&&(e.push(" environment:"),e.push(Rc(t.plan.serviceEnvOverrides[o.id]," ")));if(n.ports.length>0){e.push(" ports:");for(let a of n.ports)e.push(` - "${a.host}:${a.container}"`);}if(n.volumes?.length){e.push(" volumes:");for(let a of n.volumes){e.push(` - ${a}`);let i=a.split(":")[0];i&&!i.startsWith("/")&&r.add(i);}}if(n.healthcheck){let a=t.plan.serviceEnvOverrides?.[o.id];if(o.id==="postgres"&&a){let i=Ec(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(pd(n.healthcheck," "));}e.push(" restart: unless-stopped");}}if(r.size>0){e.push("volumes:");for(let o of [...r].sort())e.push(` ${o}:`),e.push(" driver: local");}return e.push(""),e.join(`
122
+ `)}function ud(t,e,r){return t.kind==="override"?t.value===e:t.kind==="module"?r.moduleMappings[t.value]?.includes(e)??false:r.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function md(t){let e=new Map,r=[];for(let o of t)for(let n of o.ports){let a=e.get(n.host);a&&a!==o.id?r.push(`Port collision on host ${n.host} between services '${a}' and '${o.id}'`):e.set(n.host,o.id);}return r}async function gd(t){let e=s$1(t,"workspace.json").find(r=>existsSync(r));if(e)try{let r=await O__default.readJson(e);return r.workspace_name||r.name}catch{return}}async function zn(t){let e=b.resolve(t.workspacePath),r=Et(),o=await jc({workspacePath:e,contract:r}),n=o.serviceIds.map(k=>{let y=r.services[k];return y?{id:k,displayName:y.displayName,category:y.category,image:y.image,ports:y.ports,sources:o.sources.filter(j=>ud(j,k,r))}:null}).filter(k=>k!==null),a=md(n);n.length===0&&a.push("No infrastructure services detected. Install modules with infra dependencies or add .workspai/infra/overrides.json");for(let k of o.overrides)r.services[k]||a.push(`Override references unknown service '${k}'`);let i=await d$8(e,e$1.workspaceContract)?e$1.workspaceContract:void 0,c=Pc(r,o.serviceIds),p=await Cc({workspacePath:e,contract:r}),d={...c,...p};p.RAPIDKIT_DB_POSTGRES_URL&&(d.DATABASE_URL=p.RAPIDKIT_DB_POSTGRES_URL);let g={},m=xc(d);return m&&o.serviceIds.includes("postgres")&&(g.postgres=m),{schemaVersion:kc,generatedAt:(t.now||(()=>new Date))().toISOString(),workspacePath:e,workspaceName:await gd(e),contractPath:i,strategy:"sidecar",composePath:Xt,envExamplePath:Bn,services:n,connectionEnv:d,serviceEnvOverrides:Object.keys(g).length>0?g:void 0,sources:{modules:o.modules,envVars:o.envVars,overrides:o.overrides},warnings:a}}async function Yn(t){let e=b.resolve(t.workspacePath),r=b.join(e,Xt),o=b.join(e,Qt),n=b.join(e,Bn),a=Et();a$5(t.plan,"contracts/infra-plan.v1.json","Workspai infrastructure plan");let i=Ac({plan:t.plan,contract:a,workspaceName:t.plan.workspaceName||b.basename(e)}),c=["# Generated by: npx workspai infra plan","# Copy values into project .env files as needed.",...Object.entries(t.plan.connectionEnv).map(([p,d])=>`${p}=${d}`),""].join(`
123
123
  `);return t.dryRun?{composePath:r,planPath:o,envExamplePath:n}:(await O__default.ensureDir(b.dirname(r)),await O__default.ensureDir(b.dirname(o)),await O__default.writeFile(r,i,"utf-8"),await O__default.writeFile(o,`${JSON.stringify(t.plan,null,2)}
124
- `,"utf-8"),await O__default.writeFile(n,c,"utf-8"),{composePath:r,planPath:o,envExamplePath:n})}function kd(t){return b.resolve(t).split(b.sep).join("/")}async function $c(){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 vd(){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 $c();}function Nc(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 Tc(t){await vd();let e=await $c(),r=kd(t.composePath),o=await execa(e.command,[...e.prefixArgs,"-f",r,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}function _o(t){let e=t?b.resolve(t):Kn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");return a$8(e)}function Pd(t){return b.join(t,er)}async function es(t){let e=b.join(t,tr);if(!await O__default.pathExists(e))throw new Error(`Infra plan not found at ${tr}. Run: npx workspai infra plan`);let r=await O__default.readJson(e);return a$5(r,"contracts/infra-plan.v1.json",`Infra plan ${e}`),r}async function ts(t){let e=Pd(t.workspacePath);if(!await O__default.pathExists(e))throw new Error(`Compose file not found at ${er}. Run: npx workspai infra plan`);return Tc({composePath:e,workspacePath:t.workspacePath,args:t.args})}function jd(t,e={}){if(console.log(s.bold(`
124
+ `,"utf-8"),await O__default.writeFile(n,c,"utf-8"),{composePath:r,planPath:o,envExamplePath:n})}function fd(t){return b.resolve(t).split(b.sep).join("/")}async function Ic(){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 hd(){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 Ic();}function Oc(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 $c(t){await hd();let e=await Ic(),r=fd(t.composePath),o=await execa(e.command,[...e.prefixArgs,"-f",r,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}function Eo(t){let e=t?b.resolve(t):Fn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");return a$8(e)}function yd(t){return b.join(t,Xt)}async function Xn(t){let e=b.join(t,Qt);if(!await O__default.pathExists(e))throw new Error(`Infra plan not found at ${Qt}. Run: npx workspai infra plan`);let r=await O__default.readJson(e);return a$5(r,"contracts/infra-plan.v1.json",`Infra plan ${e}`),r}async function Qn(t){let e=yd(t.workspacePath);if(!await O__default.pathExists(e))throw new Error(`Compose file not found at ${Xt}. Run: npx workspai infra plan`);return $c({composePath:e,workspacePath:t.workspacePath,args:t.args})}function wd(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: ${tr}`)),console.log(s.gray(`Env example: ${t.envExamplePath}`)),console.log(""),t.services.length===0)console.log(s.yellow("No infrastructure services detected."));else {console.log(s.bold("Services:"));for(let r of t.services){let o=r.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${r.id}`),s.gray(`(${r.displayName})`),o?s.white(`ports ${o}`):"");}}if(t.sources.modules.length>0&&(console.log(""),console.log(s.bold("Detected from modules:")),console.log(s.gray(` ${t.sources.modules.join(", ")}`))),t.sources.envVars.length>0){let r=_t(),o=Ec(t.sources.envVars,r);console.log(s.bold("Detected from env vars (infra-mapped):")),o.length>0?console.log(s.gray(` ${o.join(", ")}`)):console.log(s.gray(" none"));let n=t.sources.envVars.length-o.length;if(n>0&&!e.verbose)console.log(s.gray(` (${n} other project env vars scanned \u2014 use --verbose to list all)`));else if(e.verbose){let a=t.sources.envVars.filter(i=>!o.includes(i));a.length>0&&console.log(s.gray(` Other scanned env vars: ${a.join(", ")}`));}}if(t.sources.overrides.length>0&&(console.log(s.bold("Overrides:")),console.log(s.gray(` ${t.sources.overrides.join(", ")}`))),Object.keys(t.connectionEnv).length>0){console.log(""),console.log(s.bold("Connection env (preview):"));for(let[r,o]of Object.entries(t.connectionEnv))console.log(s.gray(` ${r}=${o}`));}if(t.warnings.length>0){console.log(""),console.log(s.yellow("Warnings:"));for(let r of t.warnings)console.log(s.yellow(` - ${r}`));}console.log("");}function Mc(t){let e=t.command("infra").description("Plan and manage workspace infrastructure (Docker sidecar stack)");e.command("plan").description("Discover infra needs and generate compose plan artifacts").option("--workspace <path>","Workspace root path").option("--json","Print plan as JSON").option("--dry-run","Compute plan without writing artifacts").option("--verbose","Show all scanned project env vars").action(async r=>{try{let o=_o(r.workspace),n=await Qn({workspacePath:o}),a=await Zn({workspacePath:o,plan:n,dryRun:r.dryRun});if(r.json){console.log(JSON.stringify({...n,artifacts:r.dryRun?{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath,dryRun:true}:{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath}},null,2));return}jd(n,{verbose:r.verbose}),r.dryRun?console.log(s.yellow(`Dry run \u2014 no files written.
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: ${Qt}`)),console.log(s.gray(`Env example: ${t.envExamplePath}`)),console.log(""),t.services.length===0)console.log(s.yellow("No infrastructure services detected."));else {console.log(s.bold("Services:"));for(let r of t.services){let o=r.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${r.id}`),s.gray(`(${r.displayName})`),o?s.white(`ports ${o}`):"");}}if(t.sources.modules.length>0&&(console.log(""),console.log(s.bold("Detected from modules:")),console.log(s.gray(` ${t.sources.modules.join(", ")}`))),t.sources.envVars.length>0){let r=Et(),o=Sc(t.sources.envVars,r);console.log(s.bold("Detected from env vars (infra-mapped):")),o.length>0?console.log(s.gray(` ${o.join(", ")}`)):console.log(s.gray(" none"));let n=t.sources.envVars.length-o.length;if(n>0&&!e.verbose)console.log(s.gray(` (${n} other project env vars scanned \u2014 use --verbose to list all)`));else if(e.verbose){let a=t.sources.envVars.filter(i=>!o.includes(i));a.length>0&&console.log(s.gray(` Other scanned env vars: ${a.join(", ")}`));}}if(t.sources.overrides.length>0&&(console.log(s.bold("Overrides:")),console.log(s.gray(` ${t.sources.overrides.join(", ")}`))),Object.keys(t.connectionEnv).length>0){console.log(""),console.log(s.bold("Connection env (preview):"));for(let[r,o]of Object.entries(t.connectionEnv))console.log(s.gray(` ${r}=${o}`));}if(t.warnings.length>0){console.log(""),console.log(s.yellow("Warnings:"));for(let r of t.warnings)console.log(s.yellow(` - ${r}`));}console.log("");}function Nc(t){let e=t.command("infra").description("Plan and manage workspace infrastructure (Docker sidecar stack)");e.command("plan").description("Discover infra needs and generate compose plan artifacts").option("--workspace <path>","Workspace root path").option("--json","Print plan as JSON").option("--dry-run","Compute plan without writing artifacts").option("--verbose","Show all scanned project env vars").action(async r=>{try{let o=Eo(r.workspace),n=await zn({workspacePath:o}),a=await Yn({workspacePath:o,plan:n,dryRun:r.dryRun});if(r.json){console.log(JSON.stringify({...n,artifacts:r.dryRun?{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath,dryRun:true}:{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath}},null,2));return}wd(n,{verbose:r.verbose}),r.dryRun?console.log(s.yellow(`Dry run \u2014 no files written.
127
127
  `)):(console.log(s.green("Artifacts written:")),console.log(s.gray(` ${a.composePath}`)),console.log(s.gray(` ${a.planPath}`)),console.log(s.gray(` ${a.envExamplePath}
128
128
  `)));}catch(o){console.error(s.red(`
129
129
  \u274C ${o instanceof Error?o.message:String(o)}
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 r=>{try{let o=_o(r.workspace);if(r.plan!==false){let c=await Qn({workspacePath:o});await Zn({workspacePath:o,plan:c});}if((await es(o)).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"];r.detach!==false&&a.push("-d"),r.build&&a.push("--build");let i=await ts({workspacePath:o,args:a});if(i.stdout&&process.stdout.write(i.stdout),i.stderr&&process.stderr.write(i.stderr),i.exitCode!==0){let c=Nc(i.stderr);c&&console.error(s.yellow(`
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 r=>{try{let o=Eo(r.workspace);if(r.plan!==false){let c=await zn({workspacePath:o});await Yn({workspacePath:o,plan:c});}if((await Xn(o)).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"];r.detach!==false&&a.push("-d"),r.build&&a.push("--build");let i=await Qn({workspacePath:o,args:a});if(i.stdout&&process.stdout.write(i.stdout),i.stderr&&process.stderr.write(i.stderr),i.exitCode!==0){let c=Oc(i.stderr);c&&console.error(s.yellow(`
131
131
  \u26A0\uFE0F ${c}
132
132
  `)),process.exit(i.exitCode);}r.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(o){console.error(s.red(`
136
136
  \u274C ${o instanceof Error?o.message:String(o)}
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 r=>{try{let o=_o(r.workspace);await es(o);let n=["down"];r.volumes&&n.push("-v");let a=await ts({workspacePath:o,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(`
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 r=>{try{let o=Eo(r.workspace);await Xn(o);let n=["down"];r.volumes&&n.push("-v");let a=await Qn({workspacePath:o,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(o){console.error(s.red(`
140
140
  \u274C ${o instanceof Error?o.message:String(o)}
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 r=>{try{let o=_o(r.workspace),n=await es(o),a=r.json?["ps","--format","json"]:["ps"],i=await ts({workspacePath:o,args:a});if(r.json){i.stdout&&process.stdout.write(i.stdout),i.exitCode!==0&&process.exit(i.exitCode);return}console.log(s.bold(`
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 r=>{try{let o=Eo(r.workspace),n=await Xn(o),a=r.json?["ps","--format","json"]:["ps"],i=await Qn({workspacePath:o,args:a});if(r.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
143
  `)),console.log(s.gray(`Workspace: ${o}`)),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
144
  `))),i.exitCode!==0&&(i.stderr&&process.stderr.write(i.stderr),process.exit(i.exitCode)),r.strict&&/Restarting|Exit|unhealthy/i.test(i.stdout)&&(console.log(""),console.log(s.red("One or more infra containers are not healthy.")),console.log(s.gray(`Inspect logs with: docker logs workspai-postgres (or redis/mailpit)
145
145
  `)),process.exit(1));}catch(o){console.error(s.red(`
146
146
  \u274C ${o instanceof Error?o.message:String(o)}
147
- `)),process.exit(1);}});}function Cd(t){try{let e=b.join(t,"Makefile");return A.existsSync(e)?A.readFileSync(e,"utf8"):""}catch{return ""}}function mt(t,e){let r=Cd(t);return r?new RegExp(`^${e}\\s*:`,"m").test(r):false}var Oo=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}async ensureDotnetInstalled(e){return (await this.run("dotnet",["--version"],e)).exitCode===0?null:{exitCode:1,message:".NET SDK is not installed or not available on PATH. Install .NET 8+ from https://dotnet.microsoft.com/download and retry."}}findFilesBySuffix(e,r,o=3){let n=[],a=[{dir:e,depth:0}],i=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;a.length>0;){let c=a.shift();if(!c||c.depth>o)continue;let p=[];try{p=A.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let d of p){let g=b.join(c.dir,d.name);if(d.isDirectory()){i.has(d.name)||a.push({dir:g,depth:c.depth+1});continue}d.name.toLowerCase().endsWith(r.toLowerCase())&&n.push(g);}}return n.sort()}findProjectFile(e){let r=this.findFilesBySuffix(e,".csproj");return r.find(o=>!o.toLowerCase().includes(".tests.csproj"))||r[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(o=>o.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let r=await this.ensureDotnetInstalled(e);return r||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=await this.run("dotnet",o?["restore",o]:["restore"],e);return n.exitCode===0?n:{exitCode:n.exitCode,message:"dotnet restore failed. Check NuGet connectivity, package references, and .NET SDK workload availability, then retry."}}async runDev(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=o?["watch","--project",o,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",o?["test",o]:["test"],e)}async runBuild(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["build",o,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["run","--project",o]:["run"],e)}async runLint(e){if(!b$4()&&mt(e,"lint"))return this.run("make",["lint"],e);let r=b.join(e,"Directory.Build.props");if(A.existsSync(r)&&A.readFileSync(r,"utf-8").includes("EnforceCodeStyleInBuild")){let o=await this.ensureDotnetInstalled(e);if(o)return o;let n=this.findProjectFile(e);return this.run("dotnet",n?["build",n,"-warnaserror"]:["build","-warnaserror"],e)}return {exitCode:1,message:"No .NET lint tooling detected. Add a Makefile lint target or enable EnforceCodeStyleInBuild in Directory.Build.props."}}async runFormat(e){if(!b$4()&&mt(e,"format"))return this.run("make",["format"],e);let r=await this.ensureDotnetInstalled(e);return r||(A.existsSync(b.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 $o=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}async ensureGoInstalled(e){return (await this.run("go",["version"],e)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findGoRunTarget(e){let r=b.join(e,"main.go");if(A.existsSync(r))return "./main.go";let o=b.join(e,"cmd");try{let n=A.readdirSync(o,{withFileTypes:true}).filter(a=>a.isDirectory()).map(a=>a.name).sort();for(let a of n)if(A.existsSync(b.join(o,a,"main.go")))return `./cmd/${a}`}catch{}return "./."}findWorkspaceRoot(e){let r=e;for(;;){if(A.existsSync(b.join(r,".workspai-workspace"))||A.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>A.existsSync(a));if(!n)return "isolated";try{let c=A.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withGoCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","go"):b.join(e,".workspai","cache","go"),i=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=b.join(a,"mod"),process.env.GOCACHE=b.join(a,"build"),r().finally(()=>{typeof i>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=i,typeof c>"u"?delete process.env.GOCACHE:process.env.GOCACHE=c;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(e){return this.withGoCacheEnv(e,async()=>{try{return process.env.GOMODCACHE&&A.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&A.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let r=await this.ensureGoInstalled(e);if(r)return r;let o=b.join(e,"Makefile");return !b$4()&&A.existsSync(o)?this.run("make",["run"],e):this.run("go",["run",this.findGoRunTarget(e)],e)})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let o=(b$4()?[b.join(e,"server.exe"),b.join(e,"server")]:[b.join(e,"server")]).find(a=>A.existsSync(a));if(o)return this.run(o,[],e);let n=await this.ensureGoInstalled(e);return n||this.run("go",["run",this.findGoRunTarget(e)],e)})}async runLint(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||(!b$4()&&mt(e,"lint")?this.run("make",["lint"],e):A.existsSync(b.join(e,".golangci.yml"))||A.existsSync(b.join(e,".golangci.yaml"))?this.run("golangci-lint",["run","./..."],e):{exitCode:1,message:"No Go lint tooling detected. Add a Makefile lint target or .golangci.yml configuration."})})}async runFormat(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||(!b$4()&&mt(e,"fmt")?this.run("make",["fmt"],e):!b$4()&&mt(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 No=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return (A.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return A.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let r=process.env.JAVA_HOME?.trim();if(!r)return "java";let o=b.join(r,"bin",process.platform==="win32"?"java.exe":"java");return A.existsSync(o)?o:"java"}parseMajorJavaVersion(e){if(!e)return null;let o=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(o,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let r=b.join(e,"pom.xml");if(!A.existsSync(r))return 21;try{let n=A.readFileSync(r,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,r){try{let o=await execa(e,["-version"],{cwd:r,timeout:5e3,reject:false});if(o.exitCode!==0)return null;let n=`${o.stdout||""}
147
+ `)),process.exit(1);}});}function vd(t){try{let e=b.join(t,"Makefile");return A.existsSync(e)?A.readFileSync(e,"utf8"):""}catch{return ""}}function pt(t,e){let r=vd(t);return r?new RegExp(`^${e}\\s*:`,"m").test(r):false}var Ao=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}async ensureDotnetInstalled(e){return (await this.run("dotnet",["--version"],e)).exitCode===0?null:{exitCode:1,message:".NET SDK is not installed or not available on PATH. Install .NET 8+ from https://dotnet.microsoft.com/download and retry."}}findFilesBySuffix(e,r,o=3){let n=[],a=[{dir:e,depth:0}],i=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;a.length>0;){let c=a.shift();if(!c||c.depth>o)continue;let p=[];try{p=A.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let d of p){let g=b.join(c.dir,d.name);if(d.isDirectory()){i.has(d.name)||a.push({dir:g,depth:c.depth+1});continue}d.name.toLowerCase().endsWith(r.toLowerCase())&&n.push(g);}}return n.sort()}findProjectFile(e){let r=this.findFilesBySuffix(e,".csproj");return r.find(o=>!o.toLowerCase().includes(".tests.csproj"))||r[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(o=>o.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let r=await this.ensureDotnetInstalled(e);return r||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=await this.run("dotnet",o?["restore",o]:["restore"],e);return n.exitCode===0?n:{exitCode:n.exitCode,message:"dotnet restore failed. Check NuGet connectivity, package references, and .NET SDK workload availability, then retry."}}async runDev(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=o?["watch","--project",o,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",o?["test",o]:["test"],e)}async runBuild(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["build",o,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["run","--project",o]:["run"],e)}async runLint(e){if(!b$4()&&pt(e,"lint"))return this.run("make",["lint"],e);let r=b.join(e,"Directory.Build.props");if(A.existsSync(r)&&A.readFileSync(r,"utf-8").includes("EnforceCodeStyleInBuild")){let o=await this.ensureDotnetInstalled(e);if(o)return o;let n=this.findProjectFile(e);return this.run("dotnet",n?["build",n,"-warnaserror"]:["build","-warnaserror"],e)}return {exitCode:1,message:"No .NET lint tooling detected. Add a Makefile lint target or enable EnforceCodeStyleInBuild in Directory.Build.props."}}async runFormat(e){if(!b$4()&&pt(e,"format"))return this.run("make",["format"],e);let r=await this.ensureDotnetInstalled(e);return r||(A.existsSync(b.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 _o=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}async ensureGoInstalled(e){return (await this.run("go",["version"],e)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findGoRunTarget(e){let r=b.join(e,"main.go");if(A.existsSync(r))return "./main.go";let o=b.join(e,"cmd");try{let n=A.readdirSync(o,{withFileTypes:true}).filter(a=>a.isDirectory()).map(a=>a.name).sort();for(let a of n)if(A.existsSync(b.join(o,a,"main.go")))return `./cmd/${a}`}catch{}return "./."}findWorkspaceRoot(e){let r=e;for(;;){if(A.existsSync(b.join(r,".workspai-workspace"))||A.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>A.existsSync(a));if(!n)return "isolated";try{let c=A.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withGoCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","go"):b.join(e,".workspai","cache","go"),i=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=b.join(a,"mod"),process.env.GOCACHE=b.join(a,"build"),r().finally(()=>{typeof i>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=i,typeof c>"u"?delete process.env.GOCACHE:process.env.GOCACHE=c;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(e){return this.withGoCacheEnv(e,async()=>{try{return process.env.GOMODCACHE&&A.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&A.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let r=await this.ensureGoInstalled(e);if(r)return r;let o=b.join(e,"Makefile");return !b$4()&&A.existsSync(o)?this.run("make",["run"],e):this.run("go",["run",this.findGoRunTarget(e)],e)})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let o=(b$4()?[b.join(e,"server.exe"),b.join(e,"server")]:[b.join(e,"server")]).find(a=>A.existsSync(a));if(o)return this.run(o,[],e);let n=await this.ensureGoInstalled(e);return n||this.run("go",["run",this.findGoRunTarget(e)],e)})}async runLint(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||(!b$4()&&pt(e,"lint")?this.run("make",["lint"],e):A.existsSync(b.join(e,".golangci.yml"))||A.existsSync(b.join(e,".golangci.yaml"))?this.run("golangci-lint",["run","./..."],e):{exitCode:1,message:"No Go lint tooling detected. Add a Makefile lint target or .golangci.yml configuration."})})}async runFormat(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||(!b$4()&&pt(e,"fmt")?this.run("make",["fmt"],e):!b$4()&&pt(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 Io=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return (A.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return A.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let r=process.env.JAVA_HOME?.trim();if(!r)return "java";let o=b.join(r,"bin",process.platform==="win32"?"java.exe":"java");return A.existsSync(o)?o:"java"}parseMajorJavaVersion(e){if(!e)return null;let o=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(o,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let r=b.join(e,"pom.xml");if(!A.existsSync(r))return 21;try{let n=A.readFileSync(r,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,r){try{let o=await execa(e,["-version"],{cwd:r,timeout:5e3,reject:false});if(o.exitCode!==0)return null;let n=`${o.stdout||""}
148
148
  ${o.stderr||""}`,a=n.match(/version\s+"([^"]+)"/i);if(a?.[1])return this.parseMajorJavaVersion(a[1]);let i=n.match(/(?:openjdk|java)\s+(\d+(?:[._]\d+)?)/i);return i?.[1]?this.parseMajorJavaVersion(i[1]):null}catch{return null}}parseMavenVersion(e){if(!e)return null;let r=e.match(/Apache Maven\s+(\d+)\.(\d+)\.(\d+)/i);return r?[Number.parseInt(r[1],10),Number.parseInt(r[2],10),Number.parseInt(r[3],10)]:null}isMavenVersionAtLeast(e,r){for(let o=0;o<3;o+=1){if(e[o]>r[o])return true;if(e[o]<r[o])return false}return true}async checkSystemMavenVersion(e){try{let r=await execa("mvn",["-version"],{cwd:e,timeout:5e3,reject:false});if(r.exitCode!==0)return {exitCode:r.exitCode||1,message:"Maven is required and must be available on PATH (3.9+)."};let o=this.parseMavenVersion(`${r.stdout||""}
149
- ${r.stderr||""}`);return o?this.isMavenVersionAtLeast(o,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${o.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let r=A.existsSync(b.join(e,"pom.xml")),o=A.existsSync(b.join(e,"mvnw"))||A.existsSync(b.join(e,"mvnw.cmd")),n=A.existsSync(b.join(e,"build.gradle"))||A.existsSync(b.join(e,"build.gradle.kts"))||A.existsSync(b.join(e,"settings.gradle"))||A.existsSync(b.join(e,"settings.gradle.kts")),a=A.existsSync(b.join(e,"gradlew"))||A.existsSync(b.join(e,"gradlew.bat"));return {hasMavenProject:r||o,hasMavenWrapper:o,hasGradleProject:n||a,hasGradleWrapper:a}}findWorkspaceRoot(e){let r=e;for(;;){if(A.existsSync(b.join(r,".workspai-workspace"))||A.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>A.existsSync(a));if(!n)return "isolated";try{let c=A.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let r=b.join(e,"mvnw.cmd");if(process.platform==="win32"&&A.existsSync(r))return {command:r,baseArgs:[]};let o=b.join(e,"mvnw");return A.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let r=b.join(e,"gradlew.bat");if(process.platform==="win32"&&A.existsSync(r))return {command:r,baseArgs:[]};let o=b.join(e,"gradlew");return A.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let r=[],o=new Set,n=[e];for(;n.length>0;){let a=n.shift();if(!a||o.has(a))continue;o.add(a);let i=[];try{i=A.readdirSync(a,{withFileTypes:true});}catch{continue}for(let c of i){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let p=b.join(a,c.name),d=this.inspectJavaProject(p);(d.hasMavenProject||d.hasGradleProject)&&r.push(p),n.push(p);}}return r}withJavaCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","m2"):b.join(e,".workspai","cache","java","m2"),i=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","gradle"):b.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,p=process.env.GRADLE_USER_HOME,d=`-Dmaven.repo.local=${a}`;return process.env.MAVEN_OPTS=c?`${c} ${d}`:d,process.env.GRADLE_USER_HOME=i,r().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof p>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=p;})}async runBuildTool(e,r,o=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:a}=this.buildToolCommand(e),i=await this.runCommand(n,[...a,...r],e);if(i===0||!o)return {exitCode:i};let c=A.existsSync(b.join(e,"pom.xml")),p=A.existsSync(b.join(e,"build.gradle"))||A.existsSync(b.join(e,"build.gradle.kts"));return {exitCode:i,message:c||p?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let r=[b.join(e,"target"),b.join(e,"build","libs")];for(let o of r){if(!A.existsSync(o))continue;let a=A.readdirSync(o).filter(i=>i.toLowerCase().endsWith(".jar")).find(i=>!i.toLowerCase().endsWith("-sources.jar")&&!i.toLowerCase().endsWith("-javadoc.jar")&&!i.toLowerCase().endsWith("-plain.jar"));if(a)return b.join(o,a)}return null}commandArgsFor(e,r){if(e==="gradle"){let o=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return r==="init"?[...o,"dependencies"]:r==="dev"?[...o,"bootRun"]:r==="test"?[...o,"test"]:[...o,"bootJar"]}return r==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:r==="dev"?["spring-boot:run"]:r==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),r=this.resolveJavaCommand(e),o=await this.runCommand(r,["-version"],e);if(o!==0)return {exitCode:o,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),p=await this.detectInstalledJavaMajor(r,e);if(p!==null&&p<c)return {exitCode:1,message:`Detected Java ${p}, but project requires Java ${c}+.`};let d=b.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&A.existsSync(d))try{let m=A.readFileSync(d,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),k=this.parseMajorJavaVersion(m?.[1]);if(k!==null&&k<c)return {exitCode:1,message:`Detected JAVA_HOME version ${k}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),p=c==="gradle"?["--version"]:["-version"],d=await this.runBuildTool(e,p);return d.exitCode!==0?d:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):d}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let p=c.reduce((m,k)=>Math.max(m,this.readRequiredJavaMajor(k)),0);if(p>0){let m=await this.detectInstalledJavaMajor(r,e);if(m!==null&&m<p){let k=c.filter(w=>this.readRequiredJavaMajor(w)>m).map(w=>b.relative(e,w)).join(", ");return {exitCode:1,message:`Detected Java ${m}, but workspace project(s) [${k}] require Java ${p}+.`}}}let d=false,g=false;for(let m of c){let k=this.inspectJavaProject(m);k.hasMavenProject&&!k.hasMavenWrapper&&(d=true),k.hasGradleProject&&!k.hasGradleWrapper&&(g=true);}if(d){let m=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(m!==0)return {exitCode:m,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let k=await this.checkSystemMavenVersion(e);if(k.exitCode!==0)return k}if(g){let m=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(m!==0)return {exitCode:m,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(a===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return i===0?{exitCode:0}:{exitCode:a||i||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let r=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return r&&A.mkdirSync(r,{recursive:true}),process.env.GRADLE_USER_HOME&&A.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let r=this.resolveJarPath(e);if(r)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",r],e)};let o=await this.runBuild(e);if(o.exitCode!==0)return o;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(mt(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let r=b.join(e,"pom.xml");if(A.existsSync(r)){let o=A.readFileSync(r,"utf-8");if(o.includes("spotless-maven-plugin"))return this.runBuildTool(e,["spotless:check"]);if(o.includes("checkstyle"))return this.runBuildTool(e,["checkstyle:check"])}return {exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){if(mt(e,"format"))return {exitCode:await this.runCommand("make",["format"],e)};let r=b.join(e,"pom.xml");return A.existsSync(r)&&A.readFileSync(r,"utf-8").includes("spotless-maven-plugin")?this.runBuildTool(e,["spotless:apply"]):["build.gradle","build.gradle.kts"].map(n=>b.join(e,n)).filter(n=>A.existsSync(n)).some(n=>A.readFileSync(n,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure Spotless in Maven/Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run npx workspai init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var To=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}findWorkspaceRoot(e){let r=e;for(;;){if(A.existsSync(b.join(r,".workspai-workspace"))||A.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>A.existsSync(a));if(!n)return "isolated";try{let c=A.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,r,o){let n=this.resolveDependencyMode(e),a=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=n==="isolated"?b.join(e,".workspai","cache","node"):b.join(a||e,".workspai","cache","node"),c=process.env.npm_config_cache,p=process.env.npm_config_store_dir,d=process.env.RAPIDKIT_DEP_SHARING_MODE,g=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,a&&(process.env.RAPIDKIT_WORKSPACE_PATH=a),r==="pnpm"?(process.env.npm_config_store_dir=b.join(i,"pnpm-store"),process.env.npm_config_cache=b.join(i,"pnpm-cache")):r==="yarn"?process.env.npm_config_cache=b.join(i,"yarn-cache"):process.env.npm_config_cache=b.join(i,"npm-cache"),o().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof p>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=p,typeof d>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=d,typeof g>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=g;})}detectPackageManager(e){if(A.existsSync(b.join(e,"package-lock.json")))return "npm";if(A.existsSync(b.join(e,"pnpm-lock.yaml")))return "pnpm";if(A.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 A.existsSync(b.join(e,"package-lock.json"))||A.existsSync(b.join(e,"pnpm-lock.yaml"))||A.existsSync(b.join(e,"yarn.lock"))}availablePackageManagers(e){let r=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[r]:[r,...["npm","pnpm","yarn"].filter(n=>n!==r&&this.commandAvailable(n))]}commandAvailable(e){let r=e$9(e);return spawnSync(r.command,[...r.prefixArgs,"--version"],{stdio:"ignore",shell:c$c(),env:g$7()}).status===0}scriptArgs(e,r){return e==="npm"?["run-script",r,"--foreground-scripts"]:["run",r]}async runScriptWithFallback(e,r){let o={exitCode:1};for(let n of this.availablePackageManagers(e))if(o=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,r),e)),o.exitCode===0)return o;return o}async runLifecycle(e,r){let o=i$2(e),n=j$3(e,o),a=t$1(e,r,{framework:n.key});return a?this.runScriptWithFallback(e,a.scriptName):{exitCode:1,message:`No npm script available for \`${r}\`. Add a "${r}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let r=this.detectPackageManager(e);return this.withDependencyEnv(e,r,async()=>{try{return process.env.npm_config_cache&&A.mkdirSync(process.env.npm_config_cache,{recursive:true}),r==="pnpm"&&process.env.npm_config_store_dir&&A.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let r=this.detectPackageManager(e),o=this.resolveDependencyMode(e),n=o==="shared-runtime-caches"||o==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,r,()=>this.run(r,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var Wo=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,r){return {exitCode:await this.withPythonCacheEnv(r,()=>this.runCore(e,r))}}findWorkspaceRoot(e){let r=e;for(;;){if(A.existsSync(b.join(r,".workspai-workspace"))||A.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>A.existsSync(a));if(!n)return "isolated";try{let c=A.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","python"):b.join(e,".workspai","cache","python"),i=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=b.join(a,"pip"),process.env.POETRY_CACHE_DIR=b.join(a,"poetry"),r().finally(()=>{typeof i>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=i,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),r=await this.run(["doctor","check"],e);return r.exitCode===0?r:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx workspai doctor workspace" for a full workspace scan.','Use "npx workspai init" after adding or changing modules.',"Use `npx workspai <command>` from the project root to avoid environment drift."]}};var Do=class{constructor(e){this.runCommand=e;}runCommand;runtime="php";async run(e,r,o){let n=await this.runCommand(e,r,o);return n===0?{exitCode:n}:{exitCode:n,message:`PHP lifecycle command failed (${e} ${r.join(" ")}). Ensure ${e} is available on PATH, then review composer.json and the command diagnostics above.`}}hasComposer(e){return A.existsSync(b.join(e,"composer.json"))}hasArtisan(e){return A.existsSync(b.join(e,"artisan"))}hasComposerScript(e,r){try{let o=JSON.parse(A.readFileSync(b.join(e,"composer.json"),"utf8"));return !!o.scripts&&Object.prototype.hasOwnProperty.call(o.scripts,r)}catch{return false}}missingManifest(){return {exitCode:1,message:"composer.json was not found. Run the command from a PHP project root."}}unsupported(e){return {exitCode:1,message:`No deterministic PHP ${e} command was detected. Add a "${e}" Composer script or the expected Laravel tooling.`}}async checkPrereqs(){let e=await this.run("php",["--version"],process.cwd());return e.exitCode!==0?e:this.run("composer",["--version"],process.cwd())}async initProject(e){return this.hasComposer(e)?this.run("composer",["install","--no-interaction"],e):this.missingManifest()}async runDev(e){return this.hasComposerScript(e,"dev")?this.run("composer",["run-script","dev"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("dev")}async runTest(e){return this.hasArtisan(e)?this.run("php",["artisan","test"],e):this.hasComposerScript(e,"test")?this.run("composer",["run-script","test"],e):this.unsupported("test")}async runBuild(e){return this.hasComposerScript(e,"build")?this.run("composer",["run-script","build"],e):this.unsupported("build")}async runStart(e){return this.hasComposerScript(e,"start")?this.run("composer",["run-script","start"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("start")}async runLint(e){for(let r of ["lint","analyse","analyze"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return this.unsupported("lint")}async runFormat(e){for(let r of ["format","fmt"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return A.existsSync(b.join(e,"vendor","bin","pint"))||A.existsSync(b.join(e,"pint.json"))?this.run("php",["vendor/bin/pint"],e):this.unsupported("format")}async doctorHints(e){return ["Install a supported PHP release and Composer, then keep both on PATH.","Commit composer.lock for deterministic application installs.","Expose test, lint, format, and build commands as Composer scripts when the framework does not provide them."]}};var Lo=class{constructor(e){this.runCommand=e;}runCommand;runtime="rust";async run(e,r){let o=await this.runCommand("cargo",e,r);return o===0?{exitCode:o}:{exitCode:o,message:`Cargo command failed (cargo ${e.join(" ")}). Ensure the stable Rust toolchain and cargo are available on PATH, then review Cargo.toml and the command diagnostics above.`}}hasManifest(e){return A.existsSync(b.join(e,"Cargo.toml"))}missingManifest(){return {exitCode:1,message:"Cargo.toml was not found. Run the command from a Rust project root."}}async checkPrereqs(){return this.run(["--version"],process.cwd())}async initProject(e){return this.hasManifest(e)?this.run(["fetch"],e):this.missingManifest()}async runDev(e){return this.hasManifest(e)?this.run(["run"],e):this.missingManifest()}async runTest(e){return this.hasManifest(e)?this.run(["test","--all-targets"],e):this.missingManifest()}async runBuild(e){return this.hasManifest(e)?this.run(["build","--release"],e):this.missingManifest()}async runStart(e){return this.hasManifest(e)?this.run(["run","--release"],e):this.missingManifest()}async runLint(e){return this.hasManifest(e)?this.run(["clippy","--all-targets","--all-features","--","-D","warnings"],e):this.missingManifest()}async runFormat(e){return this.hasManifest(e)?this.run(["fmt","--all"],e):this.missingManifest()}async doctorHints(e){return ["Install the Rust toolchain with rustup and ensure cargo is on PATH.","Use Cargo.lock for deterministic application builds.","Install rustfmt and clippy components for format and lint lifecycle commands."]}};function Rd(){let t={...process.env},e=t.PATH||"";if(e){let r=e.split(b.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter);t.PATH=r;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||i$5(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ke(t,e){return t==="go"?new $o((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="node"?new To((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="java"?new No((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="dotnet"?new Oo((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="rust"?new Lo((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="php"?new Do((r,o,n)=>e.runCommandInCwd(r,o,n)):new Wo((r,o)=>e.runCoreRapidkit(r,{cwd:o,env:Rd()}))}var Fc=b.join($n.homedir(),".workspai","cache"),Jc=1440*60*1e3;function ss(){let t=g$4("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?b.join(Fc,`vitest-${e}`):Fc}var Jo=class t{static instance;memoryCache=new Map;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getCacheKey(e){return createHash("md5").update(e).digest("hex")}getCachePath(e){return b.join(ss(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let r=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${r}.tmp`}async get(e,r="1.0"){let o=this.memoryCache.get(e);if(o&&o.version===r&&Date.now()-o.timestamp<Jc)return f.debug(`Cache hit (memory): ${e}`),o.data;try{let n=this.getCachePath(e),a=await promises.readFile(n,"utf-8"),i=JSON.parse(a);if(i.version===r&&Date.now()-i.timestamp<Jc)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,i),i.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,r,o="1.0"){let n={data:r,timestamp:Date.now(),version:o};this.memoryCache.set(e,n);try{await promises.mkdir(ss(),{recursive:true});let a=this.getCachePath(e),i=this.getTempCachePath(a);await promises.writeFile(i,JSON.stringify(n),"utf-8"),await promises.rename(i,a),f.debug(`Cache set: ${e}`);}catch(a){f.debug(`Cache write failed: ${e}`,a);}}async invalidate(e){this.memoryCache.delete(e);try{let r=this.getCachePath(e);await promises.unlink(r),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=ss(),r=await promises.readdir(e);await Promise.all(r.map(o=>promises.unlink(b.join(e,o)))),f.debug("Cache cleared");}catch{}}};var $r=["list","sync","registry","foundation","intelligence","model","snapshot","diff","impact","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp","policy","contract","share","export","archive","hydrate","import","connect","run","init"],Go=["intelligence","model","snapshot","diff","impact","contract","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp"];function Gc(t){return Go.includes(t)}var Kc="workspai-project-entry-capability-v1";var as="workspai-cli-runtime-command-inventory-v1",Ko=[...h$5,"autopilot","pipeline","import","adopt","snapshot","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands","create","project"],is=["bootstrap","setup","cache","mirror"],Vo="create",Id=[...is,Vo],Od={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."},Uo=[["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","coverage"],["project","workspace"],["project","archives"],["project","archive"],["project","restore"],["project","delete"],["snapshot","create"],["snapshot","inspect"],["snapshot","list"],["snapshot","restore"]];function $d(t,e,r,o){let n=new Set(t),a=new Set(e),i=t.filter(k=>!a.has(k)).sort(),c=e.filter(k=>!n.has(k)).sort(),p=new Set(r),d=new Set(o),g=r.filter(k=>!d.has(k)).sort(),m=o.filter(k=>!p.has(k)).sort();return {ok:i.length===0&&c.length===0&&g.length===0&&m.length===0,registeredButUndeclared:i,declaredButUnregistered:c,registeredScopedButUndeclared:g,declaredScopedButUnregistered:m}}function Vc(t,e=[]){return t.commands.flatMap(r=>{let o=r.name(),n=[...e,o];return [{path:n,command:o,parent:e.length>0?e.join(" "):null,registrationKind:"commander",aliases:r.aliases?.()??[],description:r.description?.()??"",hidden:r._hidden===true,arguments:(r.registeredArguments??[]).map(i=>({name:i.name(),required:i.required,variadic:i.variadic})),options:(r.options??[]).map(i=>({flags:i.flags,attributeName:i.attributeName?.()??null}))},...Vc(r,n)]})}function Uc(t){let e=Vc(t),r=e.filter(c=>c.path.length===1).map(c=>c.command),o=new Set(r),n=Id.filter(c=>!o.has(c)).map(c=>({path:[c],command:c,parent:null,registrationKind:"manual-handler",aliases:[],description:Od[c],hidden:false,arguments:[],options:[]})),a=[...e,...n].sort((c,p)=>c.path.join(" ").localeCompare(p.path.join(" "))),i=[...new Set(a.filter(c=>c.path.length===1).map(c=>c.command))].sort();return {schemaVersion:as,commands:a,topLevelCommands:i,integrity:$d(i,Ko,e.filter(c=>c.path.length>1).map(c=>c.path.join(" ")),Uo.map(c=>c.join(" ")))}}function Hc(t){return `CLI command surface integrity violation (${[t.registeredButUndeclared.length>0?`registered but undeclared: ${t.registeredButUndeclared.join(", ")}`:null,t.declaredButUnregistered.length>0?`declared but unreachable: ${t.declaredButUnregistered.join(", ")}`:null,t.registeredScopedButUndeclared.length>0?`registered scoped but undeclared: ${t.registeredScopedButUndeclared.join(", ")}`:null,t.declaredScopedButUnregistered.length>0?`declared scoped but unreachable: ${t.declaredScopedButUnregistered.join(", ")}`:null].filter(r=>r!==null).join("; ")})`}var Nd={"--workspace":"Use an explicit workspace root instead of the nearest workspace.","--json":"Emit machine-readable JSON.","--strict":"Return a non-zero exit when governed evidence blocks the result.","--for-agent":"Build output for an agent surface (for example codex, copilot, or cursor).","--include-paths":"Include absolute filesystem paths.","--include-evidence":"Read and include referenced evidence metadata.","--scan-depth":"Set the bounded observable-project discovery depth.","--cache":"Reuse the model cache when the structural inputs are unchanged.","--incremental":"Reuse unchanged projects and rebuild affected graph relations.","--write":"Persist the command artifact under .workspai/reports.","--scope":"Limit the operation to a bounded scope such as project:<name>.","--dry-run":"Preview the operation without applying writes.","--preset":"Select the generated agent customization preset.","--refresh-context":"Rebuild agent context before synchronization.","--refresh":"Refresh the underlying registry or context before reading it.","--agent-sync":"Synchronize agent grounding after writing the context artifact.","--no-agent-sync":"Do not synchronize agent grounding after writing context.","--target":"Select one or more agent customization targets.","--experimental-hooks":"Generate advisory VS Code agent hook design files.","--hydrate-prompts":"Add workspace-specific verification steps to supported prompts.","--project-grounding":"Select the project entrypoint policy: managed, local, or off.","--ci":"Produce a CI-oriented command plan.","--from":"Read the specified baseline, report, or graph artifact.","--from-impact":"Read the specified impact report for verification.","--output":"Write the requested export or report to this path.","--limit":"Bound graph query results (1\u2013100).","--once":"Build the initial observed state and exit.","--graph-stream":"Emit graph snapshot/delta events as NDJSON.","--force":"Replace an existing generated target where supported.","--no-doctor":"Exclude Doctor evidence from a share bundle.","--no-blueprint":"Exclude the reproducibility blueprint from a share bundle.","--include-env":"Include private environment files in an export archive.","--archive-compression":"Select the archive compression format.","--max-download-size":"Bound a remote archive download.","--max-expanded-size":"Bound the expanded archive size.","--download-timeout-ms":"Bound remote archive download time.","--allow-private-network":"Allow private-network archive sources explicitly.","--affected":"Run only projects affected by the selected Git change.","--blast-radius":"Include transitive downstream dependents.","--since":"Select the Git baseline used for affected-project discovery.","--parallel":"Run selected projects concurrently.","--max-workers":"Bound concurrent project workers.","--continue-on-error":"Continue remaining projects after a project failure.","--reuse-passed":"Reuse successful project-stage results where safe.","--no-gates":"Skip Doctor and Readiness pre-run gates.","--allow-breaking":"Allow a verified goal to use breaking dependency changes.","--allow-force":"Allow a verified goal to use force-based repair commands.","--card":"Select the dashboard card whose governed remediation actions should be repaired.","--action-id":"Select one exact governed remediation action.","--project":"Limit the repair transaction to one registered project name.","--proposal":"Read a bounded model repair proposal from a JSON file inside the workspace.","--transaction":"Select one durable repair transaction by id.","--approved-by":"Record the local actor approving the immutable repair plan.","--decision":"Submit one of the exact options exposed by a decision-required transaction.","--max-risk":"Set the maximum approved repair risk: safe, guarded, or invasive.","--no-auto-rollback":"Require a decision instead of automatically restoring a failed transaction.","--no-build":"Do not require build validation for the selected verified goal.","--no-tests":"Do not require test validation for the selected verified goal.","--no-run":"Read current goal evidence without executing verification commands.","--reuse-intelligence":"Reuse a just-completed canonical intelligence run while executing goal-specific checks."},Nr={list:{usage:"workspai workspace list [--json]",summary:"List registered Workspai workspaces.",flags:["--json"],examples:["workspai workspace list","workspai workspace list --json"]},intelligence:{usage:"workspai workspace intelligence run [--for-agent <agent>] [--strict] [--json]",summary:"Run the canonical Workspace Intelligence chain in contract order.",flags:["--workspace","--json","--strict","--for-agent"],subactions:["run"],artifact:a$3.intelligenceRun,examples:["workspai workspace intelligence run --strict","workspai workspace intelligence run --for-agent codex --json"]},model:{usage:"workspai workspace model [--cache|--incremental] [--write] [--strict] [--json]",summary:"Build the canonical workspace model from registered and observed sources.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--cache","--incremental","--write","--strict"],artifact:a$3.model,examples:["workspai workspace model --write --json","workspai workspace model --incremental --write --json"]},"agent-sync":{usage:"workspai workspace agent-sync [--for-agent <agent>] [--target <targets>] [--project-grounding <mode>] [--write]",summary:"Synchronize bounded workspace grounding for supported agent surfaces.",flags:["--workspace","--json","--scope","--for-agent","--write","--dry-run","--strict","--preset","--refresh-context","--refresh","--target","--experimental-hooks","--hydrate-prompts","--project-grounding"],artifact:a$3.agentCustomizationPack,examples:["workspai workspace agent-sync --target all --write --strict","workspai workspace agent-sync --for-agent copilot --dry-run --json"]},"remediation-plan":{usage:"workspai workspace remediation-plan [--ci] [--write] [--json]",summary:"Build a governed repair plan from current workspace evidence.",flags:["--workspace","--json","--include-paths","--ci","--write"],artifact:e$1.artifactRemediationPlan,examples:["workspai workspace remediation-plan --write --json","workspai workspace remediation-plan --ci --json"]},repair:{usage:"workspai workspace repair <capabilities|plan|propose|approve|decide|execute|resume|status|list|rollback|cancel> [--transaction <id>] [--json]",summary:"Run a durable, approval-bound repair transaction through checkpoint, validation, canonical verification, and rollback.",flags:["--workspace","--json","--card","--action-id","--project","--proposal","--transaction","--approved-by","--decision","--max-risk","--allow-breaking","--allow-force","--no-auto-rollback"],subactions:["capabilities","plan","propose","approve","decide","execute","resume","status","list","rollback","cancel"],artifact:a$3.repairTransaction,examples:["workspai workspace repair capabilities --json","workspai workspace repair plan --card doctor --project api --json","workspai workspace repair propose --proposal .workspai/repair/inbox/proposal.json --json","workspai workspace repair approve --transaction repair_123 --approved-by local-user --json","workspai workspace repair decide --transaction repair_123 --decision approve-invasive --json","workspai workspace repair execute --transaction repair_123 --json","workspai workspace repair rollback --transaction repair_123 --json"]},context:{usage:"workspai workspace context [--for-agent <agent>] [--scope <scope>] [--write] [--json]",summary:"Build a bounded, evidence-backed context pack for people and agents.",flags:["--workspace","--json","--for-agent","--scope","--include-evidence","--scan-depth","--write","--agent-sync","--no-agent-sync","--preset","--target","--strict","--project-grounding"],artifact:a$3.agentContext,examples:["workspai workspace context --for-agent codex --write --json","workspai workspace context --scope project:api --json"]},snapshot:{usage:"workspai workspace snapshot [--json]",summary:"Persist the current model as the comparison baseline.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth"],artifact:a$3.snapshot,examples:["workspai workspace snapshot --json"]},diff:{usage:"workspai workspace diff --from <snapshot-or-model|git[:ref]> [--strict] [--json]",summary:"Compare the current model with a trusted model baseline.",flags:["--workspace","--json","--from","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:a$3.diff,examples:["workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","workspai workspace diff --from git --json"]},impact:{usage:"workspai workspace impact --from <diff> [--scope <scope>] [--strict] [--json]",summary:"Calculate the evidence-backed blast radius of the current model change.",flags:["--workspace","--json","--from","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:a$3.impact,examples:["workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json","workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --strict --json"]},verify:{usage:"workspai workspace verify [--from-impact <impact-report>] [--scope <scope>] [--strict] [--json]",summary:"Verify the selected change against contracts, gates, and current evidence.",flags:["--workspace","--json","--from-impact","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:a$3.verify,examples:["workspai workspace verify --strict --json","workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json"]},goal:{usage:"workspai workspace goal <plan|status|verify> <kind|goal-id> [--scope <scope>] [--target <percent>] [--json]",summary:"Plan, resume, and evidence-verify a durable engineering goal for people and agents.",flags:["--workspace","--json","--scope","--target","--allow-breaking","--allow-force","--no-build","--no-tests","--no-run","--reuse-intelligence"],flagDescriptions:{"--target":"Set the required test coverage percentage (0\u2013100)."},subactions:["plan","status","verify"],artifact:a$3.verifiedGoalStatus,examples:["workspai workspace goal plan release-readiness --json","workspai workspace goal plan dependency-security --scope project:api --json","workspai workspace goal plan test-coverage --scope project:web --target 75 --json","workspai workspace goal verify <goal-id> --json"]},graph:{usage:"workspai workspace graph [mode] [query|from] [to] [--json]",summary:"Build, query, prove, compare, or export the workspace graph.",flags:["--workspace","--json","--output","--from","--limit","--include-paths","--include-evidence","--scan-depth","--scope"],subactions:["emit","explain","entities","search","evidence","path","overlay","benchmark","dot","mermaid","jsonld","graphml","gexf"],examples:['workspai workspace graph search "authentication endpoint" --limit 12 --json','workspai workspace graph evidence "GET /users" --json',"workspai workspace graph mermaid"]},watch:{usage:"workspai workspace watch [--once] [--graph-stream] [--json]",summary:"Observe model changes and optionally stream graph deltas.",flags:["--workspace","--json","--once","--graph-stream","--scan-depth"],examples:["workspai workspace watch --once --json","workspai workspace watch --graph-stream"]},sync:{usage:"workspai workspace sync [--project-grounding <mode>] [--json]",summary:"Synchronize canonical workspace registration and project metadata.",flags:["--workspace","--json","--project-grounding"],examples:["workspai workspace sync --json"]},registry:{usage:"workspai workspace registry [--refresh] [--json]",summary:"Inspect the canonical workspace registry summary.",flags:["--workspace","--json","--refresh"],examples:["workspai workspace registry --refresh --json"]},foundation:{usage:"workspai workspace foundation [--force] [--json]",summary:"Create or repair the standard workspace foundation files.",flags:["--workspace","--json","--force"],examples:["workspai workspace foundation --json"]},policy:{usage:"workspai workspace policy [show|status|get|set] [key] [value] [--json]",summary:"Inspect or update workspace governance policy.",flags:["--workspace","--json"],subactions:["show","status","get","set"],examples:["workspai workspace policy get --json"]},contract:{usage:"workspai workspace contract [init|inspect|verify|graph] [--strict] [--json]",summary:"Create, inspect, verify, or project the workspace contract.",flags:["--workspace","--json","--output","--force","--strict"],subactions:["init","inspect","verify","graph"],artifact:e$1.workspaceContract,examples:["workspai workspace contract verify --strict --json","workspai workspace contract graph --json"]},share:{usage:"workspai workspace share [--output <file>] [--json]",summary:"Create a bounded, shareable workspace evidence bundle.",flags:["--workspace","--json","--output","--include-paths","--no-doctor","--no-blueprint"],examples:["workspai workspace share --output workspace-share.json --json"]},export:{usage:"workspai workspace export [--output <archive>] [--archive-compression <format>]",summary:"Export a portable workspace archive.",flags:["--workspace","--json","--output","--include-env","--archive-compression"],examples:["workspai workspace export --output workspace.tar.gz"]},archive:{usage:"workspai workspace archive <inspect|verify|doctor> <source> [safety options] [--json]",summary:"Inspect, verify, or diagnose a portable workspace archive without materializing it.",flags:["--json","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],subactions:["inspect","verify","doctor"],examples:["workspai workspace archive inspect ./workspace.tar.gz --json","workspai workspace archive verify ./workspace.tar.gz --strict --json","workspai workspace archive doctor ./workspace.tar.gz --json"]},hydrate:{usage:"workspai workspace hydrate <source> [--output <directory>] [--dry-run] [--json]",summary:"Hydrate a portable workspace into a controlled destination.",flags:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace hydrate workspace.tar.gz --output ./restored --dry-run --json"]},import:{usage:"workspai workspace import <source> [--output <directory>] [--dry-run] [--json]",summary:"Verify, materialize, register, relink, and reconcile a portable workspace archive safely.",flags:["--json","--output","--dry-run","--strict","--project-grounding","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace import workspace.tar.gz --output ./imported --json"]},connect:{usage:"workspai workspace connect [directory] [--project-grounding <mode>] [--dry-run] [--json]",summary:"Register and reconcile an existing Workspai workspace in place without moving its source.",flags:["--json","--dry-run","--project-grounding"],examples:["workspai workspace connect /path/to/existing-workspace --json"]},run:{usage:"workspai workspace run <stage> [selection and concurrency options] [--json]",summary:"Run a lifecycle stage across selected workspace projects.",flags:["--workspace","--json","--scope","--affected","--blast-radius","--since","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],subactions:["init","test","build","start","<custom-from-context>"],artifact:e$1.workspaceRunLast,examples:["workspai workspace run test --affected --blast-radius --strict","workspai workspace run build --parallel --max-workers 4 --json"]},explain:{usage:"workspai workspace explain [target] [--scope <scope>] [--write] [--json]",summary:"Explain current blockers or a selected workspace target from evidence.",flags:["--workspace","--json","--scope","--write"],artifact:a$3.explain,examples:["workspai workspace explain --write --json"]},why:{usage:"workspai workspace why [target] [--scope <scope>] [--write] [--json]",summary:"Alias the evidence-backed workspace explanation flow.",flags:["--workspace","--json","--scope","--write"],artifact:d$4,examples:["workspai workspace why readiness --json"]},trace:{usage:"workspai workspace trace --from <diff-artifact> [--write] [--json]",summary:"Trace a model change through blast radius and decision gates.",flags:["--workspace","--json","--from","--write"],artifact:e$2,examples:["workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --write --json"]},feedback:{usage:"echo '<event-json>' | workspai workspace feedback record --json",summary:"Record a structured outcome event for the workspace intelligence history.",flags:["--workspace","--json"],subactions:["record"],examples:[`echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | workspai workspace feedback record --json`]},eval:{usage:"workspai workspace eval [init|record|status|report|compare] [arguments] [--json]",summary:"Measure agent/model calls, tool use, tokens, latency, and verified outcome.",flags:["--workspace","--json","--from","--output"],subactions:["init","record","status","report","compare"],artifact:a$3.evaluationLastRun,examples:["workspai workspace eval init repair-readiness workspace-intelligence --json","workspai workspace eval report --output ./evaluation.json --json"]},mcp:{usage:"workspai workspace mcp serve",summary:"Serve bounded, read-mostly workspace evidence over stdio MCP.",flags:["--workspace","--json"],subactions:["serve"],examples:["workspai workspace mcp serve"]},init:{usage:"workspai workspace init [selection and concurrency options] [--json]",summary:"Initialize all selected projects through the workspace fleet runner.",flags:["--workspace","--json","--scope","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],artifact:e$1.workspaceRunLast,examples:["workspai workspace init --parallel --strict"]}};function cs(t){if(t)return Nr[t]}function Bc(t){return t[0]==="workspace"&&!!cs(t[1])&&t.slice(2).some(e=>e==="--help"||e==="-h")}function qc(t,e){let r=cs(e)?.flagDescriptions?.[t]??Nd[t];if(!r)throw new Error(`Workspace action flag has no description: ${t}`);return r}function zc(t){let e=cs(t);if(!e)throw new Error(`Unknown workspace action: ${t}`);let r=[`Workspai workspace ${t}`,"",e.summary,"","Usage:",` ${e.usage}`];if(e.subactions&&e.subactions.length>0&&r.push("","Modes:",` ${e.subactions.join(" | ")}`),e.flags.length>0){r.push("","Options:");for(let o of e.flags){let n=qc(o,t);r.push(` ${o.padEnd(24)} ${n}`.trimEnd());}}return e.artifact&&r.push("","Evidence:",` ${e.artifact}`),r.push("","Examples:",...e.examples.map(o=>` ${o}`),""),r.join(`
150
- `)}var Yc="rapidkit-runtime-command-surface-v1";var ls=d$9.doctorRemediationPlan.schemaVersion;var Xc="workspai-workspace-intelligence-architecture-v1";var Qc={autopilotRelease:d$9.autopilotReleaseLastRun.schemaVersion,workspaceList:"rapidkit-workspace-list-v1",workspaceSync:"rapidkit-workspace-sync-v1",compatibilityMatrix:d$9.compatibilityMatrix.schemaVersion,mcpDesign:d$9.workspaiMcpDesign.schemaVersion,agentHooks:d$9.agentHooks.schemaVersion,projectArchive:"rapidkit-project-archive-v1",workspaceSnapshot:"rapidkit-workspace-snapshot-v1",workspaceSnapshotV2:"rapidkit-workspace-snapshot-v2",infraPlan:d$9.infraPlan.schemaVersion,privateProductManifest:"rapidkit.private-product-manifest.v1",productFactoryPlan:"rapidkit.product-factory-plan.v1",workspaceModelCache:d$9.workspaceModelCache.schemaVersion,workspaceWatchEvent:"workspace-watch-event.v1",doctorProjectScan:"doctor-project-scan-v2",doctorWorkspaceCache:d$9.doctorWorkspaceCache.schemaVersion};var Zc="project-workspace-resolution.v1";function el(t){a$5(t,"contracts/project-workspace-resolution.v1.json","Project workspace resolution");}var ps="workspai.ingestion-plan.v1",Ho="workspai.ingestion-result.v1";var tl="contracts/ingestion-result.v1.json";function Ot(t){return {schemaVersion:ps,...t}}var rl="workspai.studio-card-repair-capabilities.v1";var Td="workspai-published-contract-catalog-v1",Md="workspace-graph-stream.v1";function Tr(){return {workspaceContract:1,runtimeCommandSurface:Yc,cliRuntimeCommandInventory:as,cliOperationResult:a$A,publishedContractCatalog:Td,workspaceArchiveCapabilities:a$z,workspaceArchiveManifest:b$j,workspaceArchiveOperationResult:c$2,ingestionPlan:ps,ingestionResult:Ho,projectEntryCapability:Kc,projectWorkspaceLink:d$9.projectWorkspaceLink.schemaVersion,projectWorkspaceResolution:Zc,projectContextAgent:d$9.projectContextAgent.schemaVersion,doctorProjectEvidence:b$i,doctorWorkspaceEvidence:a$y,doctorGraphDiagnosis:d$d,projectTestCoverage:d$9.projectTestCoverage.schemaVersion,verifiedGoal:"workspai.verified-goal.v1",verifiedGoalStatus:b$8.verifiedGoalStatus,workspaceIntelligenceArchitecture:Xc,workspaceIntelligenceChain:a$x,workspaceIntelligenceArtifacts:b$8,cliLogEvent:c$b,freshnessMetadata:e$7,factFreshness:g$5,blockerResolution:a$w,workspaceModel:j$4,workspaceImpact:f$5,workspaceVerify:c$a,workspaceContext:a$v,workspaceDependencyGraph:e$6,workspaceKnowledgeGraph:a$u,workspaceGraphStream:Md,workspaceKnowledgeGraphChangeOverlay:a$t,workspaceKnowledgeSearch:a$s,workspaceGraphTokenEfficiency:a$r,modelUsageEvent:a$q,workspaceIntelligenceEvaluation:b$h,workspaceIntelligenceEvaluationComparison:c$9,workspaceIntelligenceHistory:a$p,agentCustomizationPackCapabilities:c$8,agentCustomizationPackReport:b$8.agentCustomizationPack,agentReportsIndex:b$8.agentIndex,workspaceOperationalSkill:a$o,workspaceSkillsIndex:b$g,workspaceExplain:a$n,agentActionOutcome:a$m,doctorRemediationPlan:ls,doctorDependencyRepairTransaction:"workspai.doctor-dependency-repair-transaction.v1",artifactRemediationPlan:a$l,studioCardRepairCapabilities:rl,workspaceRepairProposal:d$c,workspaceRepairCapabilities:f$4,workspaceRepairTransaction:a$k,doctorFixResult:a$j,backendImportStackParitySnapshot:"backend-import-stack-parity-v1",bootstrapCompliance:d$9.bootstrapCompliance.schemaVersion,commandCapabilities:"rapidkit-command-capabilities-v1",createPlannerCapabilities:"rapidkit-create-planner-capabilities-v1",doctorRemediationPlanLegacy:ls,extensionCliCompatibility:"rapidkit-extension-cli-compatibility.v1",infraStack:"rapidkit.infra-stack.v1",mirrorOps:d$9.mirrorOps.schemaVersion,moduleLayout:"rapidkit.module-layout.v1",moduleSupport:"rapidkit-module-support-v1",pipelineLastRun:d$9.pipelineLastRun.schemaVersion,transparencyEvidence:d$9.transparencyEvidence.schemaVersion,version:"rapidkit-version-v1",studioBlockerHandoff:"rapidkit-studio-blocker-handoff-v1",workspaceRegistry:d$9.workspaceRegistry.schemaVersion,workspaceRunLast:d$9.workspaceRunLast.schemaVersion,workspaceShareBundle:d$9.workspaceShareBundle.schemaVersion,...Qc}}function Bo(){let t=Tr(),e={workspaceContract:"contracts/workspace-contract.v1.json",runtimeCommandSurface:"contracts/runtime-command-surface.v1.json",cliRuntimeCommandInventory:"contracts/cli-runtime-command-inventory.v1.snapshot.json",cliOperationResult:"contracts/cli-operation-result.v1.json",publishedContractCatalog:"contracts/published-contract-catalog.v1.json",workspaceArchiveCapabilities:"contracts/workspace-archive-capabilities.v1.json",workspaceArchiveManifest:"contracts/workspace-archive-manifest.v1.json",workspaceArchiveOperationResult:"contracts/workspace-archive-operation-result.v1.json",ingestionPlan:"contracts/ingestion-plan.v1.json",ingestionResult:"contracts/ingestion-result.v1.json",projectEntryCapability:"contracts/project-entry-capability.v1.json",projectWorkspaceLink:"contracts/project-workspace-link.v1.json",projectWorkspaceResolution:"contracts/project-workspace-resolution.v1.json",projectContextAgent:"contracts/workspace-intelligence/project-context-agent.v1.json",doctorProjectEvidence:"contracts/doctor-project-evidence.v1.json",doctorWorkspaceEvidence:"contracts/doctor-workspace-evidence.v1.json",doctorGraphDiagnosis:"contracts/workspace-intelligence/doctor-graph-diagnosis.v1.json",projectTestCoverage:"contracts/project-test-coverage.v1.json",verifiedGoal:"contracts/workspace-intelligence/verified-goal.v1.json",verifiedGoalStatus:"contracts/workspace-intelligence/verified-goal-status.v1.json",workspaceIntelligenceArchitecture:"contracts/workspace-intelligence-architecture.v1.json",workspaceIntelligenceChain:"contracts/workspace-intelligence-chain.v1.json",workspaceIntelligenceArtifacts:null,cliLogEvent:"contracts/cli-log-event.v1.json",freshnessMetadata:null,factFreshness:"contracts/workspace-intelligence/fact-freshness.v1.json",blockerResolution:"contracts/workspace-intelligence/blocker-resolution.v1.json",workspaceModel:"contracts/workspace-intelligence/workspace-model.v1.json",workspaceImpact:"contracts/workspace-intelligence/workspace-impact.v1.json",workspaceVerify:"contracts/workspace-intelligence/workspace-verify.v1.json",workspaceContext:"contracts/workspace-intelligence/workspace-context.v1.json",workspaceDependencyGraph:"contracts/workspace-intelligence/workspace-dependency-graph.v1.json",workspaceKnowledgeGraph:"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json",workspaceGraphStream:"contracts/workspace-intelligence/workspace-graph-stream.v1.json",workspaceKnowledgeGraphChangeOverlay:"contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json",workspaceKnowledgeSearch:"contracts/workspace-intelligence/workspace-knowledge-search.v1.json",workspaceGraphTokenEfficiency:"contracts/workspace-intelligence/workspace-graph-token-efficiency.v1.json",modelUsageEvent:"contracts/workspace-intelligence/model-usage-event.v1.json",workspaceIntelligenceEvaluation:"contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",workspaceIntelligenceEvaluationComparison:"contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",workspaceIntelligenceHistory:"contracts/workspace-intelligence/workspace-intelligence-history.v1.json",agentCustomizationPackCapabilities:"contracts/agent-customization-pack.v1.json",agentCustomizationPackReport:"contracts/workspace-intelligence/agent-customization-pack-report.v1.json",agentReportsIndex:"contracts/workspace-intelligence/agent-reports-index.v1.json",workspaceOperationalSkill:"contracts/workspace-intelligence/workspace-operational-skill.v1.json",workspaceSkillsIndex:"contracts/workspace-intelligence/workspace-skills-index.v1.json",workspaceExplain:"contracts/workspace-intelligence/workspace-explain.v1.json",agentActionOutcome:"contracts/workspace-intelligence/agent-action-outcome.v1.json",doctorRemediationPlan:"contracts/doctor-remediation-plan.v2.json",doctorDependencyRepairTransaction:"contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json",artifactRemediationPlan:"contracts/artifact-remediation-plan.v1.json",studioCardRepairCapabilities:"contracts/studio-card-repair-capabilities.v1.json",workspaceRepairProposal:"contracts/workspace-intelligence/workspace-repair-proposal.v1.json",workspaceRepairCapabilities:"contracts/workspace-repair-capabilities.v1.json",workspaceRepairTransaction:"contracts/workspace-intelligence/workspace-repair-transaction.v1.json",doctorFixResult:"contracts/workspace-intelligence/doctor-fix-result.v1.json",backendImportStackParitySnapshot:"contracts/backend-import-stack-parity.snapshot.json",bootstrapCompliance:"contracts/bootstrap-compliance.v1.json",commandCapabilities:"contracts/command-capabilities.v1.json",createPlannerCapabilities:"contracts/create-planner-capabilities.v1.json",doctorRemediationPlanLegacy:"contracts/doctor-remediation-plan.v1.json",extensionCliCompatibility:"contracts/extension-cli-compatibility.v1.json",infraStack:"contracts/infra-stack.v1.json",mirrorOps:"contracts/mirror-ops.v1.json",moduleLayout:"contracts/module-layout.v1.json",moduleSupport:"contracts/module-support.v1.json",pipelineLastRun:"contracts/pipeline-last-run.v1.json",transparencyEvidence:"contracts/transparency-evidence.v1.json",version:"contracts/version.v1.json",studioBlockerHandoff:"contracts/workspace-intelligence/studio-blocker-handoff.v1.json",workspaceRegistry:"contracts/workspace-registry.v1.json",workspaceRunLast:"contracts/workspace-run-last.v1.json",workspaceShareBundle:"contracts/workspace-share-bundle.v1.json",autopilotRelease:"contracts/autopilot-release.v1.json",workspaceList:"contracts/workspace-list.v1.json",workspaceSync:"contracts/workspace-sync.v1.json",compatibilityMatrix:"contracts/compatibility-matrix.v1.json",mcpDesign:"contracts/workspace-intelligence/mcp-design.v1.json",agentHooks:"contracts/workspace-intelligence/agent-hooks.v1.json",projectArchive:"contracts/project-archive.v1.json",workspaceSnapshot:"contracts/workspace-snapshot.v1.json",workspaceSnapshotV2:"contracts/workspace-snapshot.v2.json",infraPlan:"contracts/infra-plan.v1.json",privateProductManifest:"contracts/private-product-manifest.v1.json",productFactoryPlan:"contracts/product-factory-plan.v1.json",workspaceModelCache:"contracts/workspace-model-cache.v1.json",workspaceWatchEvent:"contracts/workspace-watch-event.v1.json",doctorProjectScan:"contracts/doctor-project-scan.v2.json",doctorWorkspaceCache:"contracts/doctor-workspace-cache.v2.json"};return Object.fromEntries(Object.entries(t).map(([r,o])=>{let n=e[r];return [r,{schemaVersion:o,contractPath:n,publication:n?r==="runtimeCommandSurface"||r==="cliRuntimeCommandInventory"||r.endsWith("Capabilities")||r.endsWith("Snapshot")||r==="extensionCliCompatibility"||r==="moduleLayout"||r==="moduleSupport"?"capability-contract":"json-schema":"embedded-type",...r==="workspaceIntelligenceArtifacts"?{artifacts:Object.fromEntries(Object.keys(a$3).map(a=>[a,{path:a$3[a],schemaVersion:b$8[a],contractPath:c$7[a]}]))}:{}}]}))}var ds="rapidkit-command-capabilities-v1",nl="rapidkit-version-v1";var Wd=["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"],Dd={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},Ld={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"},Fd={tauri:"desktop",electron:"desktop","vscode-extension":"extension",laravel:"api"};function Jd(t){return t[Math.floor(Math.random()*t.length)]}function us(t){let e=Jd(Wd),r=j$5(t);if(r){let i=Ld[r.id]??"app";return `${e}-${i}`}let o=p$4(t);if(o)return `${e}-${Fd[o.id]??"app"}`;let n=a$4(t),a=n?Dd[n.id]??"service":"app";return `${e}-${a}`}async function Ud(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function Hd(t){if(!await O.pathExists(t))return [];let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(o)for(let n of await promises.readdir(o,{withFileTypes:true})){let a=b.join(o,n.name);n.isFile()?e.push(a):n.isDirectory()&&r.push(a);}}return e}async function al(t,e){await O.outputFile(t,`${JSON.stringify(e,null,2)}
151
- `,"utf-8");}function it(t,e){return b.isAbsolute(e)?e:b.join(t,e)}function Bd(t,e){if(!e.trim()||b.isAbsolute(e)||/^[a-zA-Z]:[\\/]/.test(e))throw new Error(`Mirror artifact target must be a non-empty relative path: ${e}`);let r=b.resolve(t),o=b.resolve(r,e),n=b.relative(r,o);if(!n||n.startsWith("..")||b.isAbsolute(n))throw new Error(`Mirror artifact target escapes the managed artifact directory: ${e}`);return o}async function il(t,e){let r=b.relative(t,e),o=t;for(let a of r.split(b.sep).slice(0,-1)){o=b.join(o,a);let i=await promises.lstat(o).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)break;if(i.isSymbolicLink())throw new Error(`Mirror artifact target traverses a symbolic link: ${o}`);if(!i.isDirectory())throw new Error(`Mirror artifact target parent is not a directory: ${o}`)}let n=await promises.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(n?.isSymbolicLink()||n&&!n.isFile())throw new Error(`Mirror artifact target must be absent or a regular file: ${e}`)}async function qd(t,e){let r=b.resolve(t),o=b.relative(r,b.resolve(e));if(!o||o.startsWith("..")||b.isAbsolute(o))throw new Error("Managed mirror directory escapes the workspace.");let n=r;for(let a of o.split(b.sep)){n=b.join(n,a);let i=await promises.lstat(n);if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Managed mirror path must contain only real directories: ${n}`)}}function zd(t,e){if(t.target)return t.target;if(t.source)return b.basename(t.source);if(t.url)try{let r=new URL(t.url).pathname,o=b.basename(r);if(o&&o!=="/")return o}catch{}return `${e}.artifact`}async function Yd(t){let e=s$1(t,"trusted-sources.lock").find(o=>existsSync(o)),r=new Set(["localhost","127.0.0.1"]);if(!e)return r;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));for(let a of n)r.add(a.toLowerCase());}catch{}return r}async function Xd(t,e,r){await O.ensureDir(b.dirname(e)),await new Promise((o,n)=>{let i=(t.startsWith("https://")?ml:ul).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let p=createWriteStream(e);c.pipe(p),p.on("finish",()=>{p.close(),o();}),p.on("error",d=>{n(d);});});i.setTimeout(r,()=>{i.destroy(new Error(`Request timeout after ${r}ms`));}),i.on("error",c=>{n(c);});});}async function Qd(t,e,r,o,n){let a=new URL(t),i=JSON.stringify(e),c=a.protocol==="https:"?ml:ul;await new Promise((p,d)=>{let g=c.request({method:"POST",hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:`${a.pathname}${a.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...o?{Authorization:`Bearer ${o}`}:{},...n||{}}},m=>{if(!m.statusCode||m.statusCode<200||m.statusCode>=300){d(new Error(`HTTP ${m.statusCode||"unknown"}`)),m.resume();return}m.resume(),p();});g.setTimeout(r,()=>{g.destroy(new Error(`Request timeout after ${r}ms`));}),g.on("error",m=>{d(m);}),g.write(i),g.end();});}function cl(t){return new Promise(e=>setTimeout(e,t))}async function Zd(t,e,r,o){let n=it(t,e||".workspai/reports/evidence-export-dead-letter.ndjson");return await O.ensureDir(b.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:o,payload:r})}
152
- `,"utf-8"),n}function eu(t,e){if(!e?.enabled)return {headers:{}};let r=process.env[e.hmacKeyEnv];if(!r)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let o=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(o,r).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":o}}}async function tu(t,e,r){let o=(r.algorithm||"sha256").toLowerCase(),n=it(t,r.publicKeyPath);if(!await O.pathExists(n))return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(o);c.update(i),c.end();let p=Buffer.from(r.signature,"base64"),d=c.verify(a,p),g=createHash("sha256").update(a).digest("hex");return {verified:d,algorithm:o,publicKeyPath:n,publicKeyFingerprint:g,signature:r.signature,message:d?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Attestation verification error: ${a.message}`}}}async function ru(t,e,r,o){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};let a=r.signaturePath?it(t,r.signaturePath):null;if(!a||!await O.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=r.certificatePath?it(t,r.certificatePath):null;c&&i.push("--certificate",c);let p=r.bundlePath?it(t,r.bundlePath):null;p&&i.push("--bundle",p);let d=r.keyPath?it(t,r.keyPath):null;d&&i.push("--key",d),r.identity&&i.push("--certificate-identity",r.identity),r.issuer&&i.push("--certificate-oidc-issuer",r.issuer),r.rekorUrl&&i.push("--rekor-url",r.rekorUrl),o.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let g=await execa("cosign",i,{reject:false});return g.exitCode===0?{verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${g.stderr||g.stdout||"unknown error"}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}}catch(g){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${g.message}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}}}async function ou(t,e){let r=e.algorithm||"sha256",o=it(t,e.policyPath),n=it(t,e.signaturePath),a=it(t,e.publicKeyPath);if(!await O.pathExists(o))return {verified:false,message:`Governance policy bundle not found: ${o}`,policies:null};if(!await O.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await O.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(o,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),p=await promises.readFile(a,"utf-8"),d=createVerify(r);return d.update(i),d.end(),d.verify(p,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function ms(t,e){let r=[],o={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=s$1(t,"mirror-config.json").find(M=>existsSync(M))??p(t,"mirror-config.json"),a=p(t,"mirror.lock"),i=p(t,"mirror","artifacts"),c=p(t,"reports"),p$1=await Yd(t);if(!await O.pathExists(n))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:r,details:o};let d={};try{d=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return r.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:r,details:o}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||d.mode==="offline-only"))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:r,details:o};await O.ensureDir(i);try{await qd(t,i);}catch(M){return r.push({id:"mirror.root.safety",status:"failed",message:M instanceof Error?M.message:String(M)}),{checks:r,details:o}}let m=Math.max(0,d.prefetch?.retries??2),k=Math.max(0,d.prefetch?.backoffMs??250),w=Math.max(1e3,d.prefetch?.timeoutMs??15e3),j=d.security?.requireAttestation===true,x=d.security?.requireSigstore===true,l=d.security?.requireTransparencyLog===true,P=d.security?.requireSignedGovernance===true,u=d.security?.evidenceExport,h=(process.env.RAPIDKIT_ENV||d.security?.governance?.environment||"dev").toLowerCase(),f=d.security?.governance?.policies||{};if(d.security?.governanceBundle){let M=await ou(t,d.security.governanceBundle);if(r.push({id:"governance.bundle.verify",status:M.verified?"passed":"failed",message:M.message}),M.verified&&M.policies)f=M.policies,o.governanceBundleVerified=true;else if(P)return {checks:r,details:o}}let v=f[h],C=l||v?.requireTransparencyLog===true,R=[],y=Array.isArray(d.artifacts)?d.artifacts:[],E=[];for(let M=0;M<y.length;M+=1){let _=y[M],S=_.id||`artifact-${M+1}`,J=_.source?it(t,_.source):null,F=zd(_,S),W;try{W=Bd(i,F),await il(i,W);}catch(Ee){r.push({id:`mirror.target.${S}`,status:"failed",message:Ee instanceof Error?Ee.message:String(Ee)});continue}let G=false,H=W,Te=false,we=async()=>{Te&&await promises.rm(H,{force:true}).catch(()=>{});},ie={sourceType:"path",source:J||_.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(J&&await O.pathExists(J))await O.ensureDir(b.dirname(W)),H=`${W}.${process.pid}.${randomUUID()}.tmp`,Te=true,await promises.copyFile(J,H),o.syncedArtifacts+=1,G=true,ie={sourceType:"path",source:J,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},r.push({id:`mirror.sync.${S}`,status:"passed",message:`Mirrored artifact ${S} from source path.`});else if(_.url){let Ee="";try{Ee=new URL(_.url).hostname.toLowerCase();}catch{r.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Invalid URL for ${S}: ${_.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||p$1.has(Ee))){r.push({id:`mirror.prefetch.trust.${S}`,status:"failed",message:`Untrusted mirror host for ${S}: ${Ee}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await O.pathExists(W)?(G=true,ie={sourceType:"url",source:_.url,host:Ee,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},r.push({id:`mirror.prefetch.${S}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${S}.`})):r.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${S} without an existing mirrored copy.`}),!G))continue;if(!G){await O.ensureDir(b.dirname(W)),H=`${W}.${process.pid}.${randomUUID()}.tmp`,Te=true;let Re=null,T=0;for(let K=1;K<=m+1;K+=1){T=K;try{await promises.rm(H,{force:true}).catch(()=>{}),await Xd(_.url,H,w),o.syncedArtifacts+=1,G=true,ie={sourceType:"url",source:_.url,host:Ee,fetchedAt:new Date().toISOString(),attempts:T,trusted:true},r.push({id:`mirror.prefetch.${S}`,status:"passed",message:T>1?`Prefetched artifact ${S} from ${Ee} after ${T} attempts.`:`Prefetched artifact ${S} from ${Ee}.`});break}catch(oe){if(Re=oe,K<=m){await cl(k*K);continue}}}if(!G){await we(),r.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S} after ${m+1} attempt(s): ${Re?.message||"unknown error"}`});continue}}if(!G){r.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S}.`});continue}}if(!G){_.required||e.offlineMode?r.push({id:`mirror.sync.${S}`,status:"failed",message:`Mirror source missing for ${S}${J?`: ${J}`:""}`}):r.push({id:`mirror.sync.${S}`,status:"skipped",message:`Mirror source not found for optional artifact ${S}.`});continue}let Me=await Ud(H);if(_.sha256&&_.sha256.toLowerCase()!==Me.toLowerCase()){r.push({id:`mirror.verify.${S}`,status:"failed",message:`Checksum mismatch for ${S}.`}),await we();continue}o.verifiedArtifacts+=1,r.push({id:`mirror.verify.${S}`,status:"passed",message:`Checksum verified for ${S}.`});let Fe=_.attestation?await tu(t,H,_.attestation):null;if(_.attestation){if(r.push({id:`mirror.attest.${S}`,status:Fe?.verified?"passed":"failed",message:Fe?.message||"Attestation verification failed."}),!Fe?.verified){await we();continue}}else if(j){r.push({id:`mirror.attest.${S}`,status:"failed",message:`Attestation is required but missing for ${S}.`}),await we();continue}else r.push({id:`mirror.attest.${S}`,status:"skipped",message:`No attestation provided for ${S}.`});let Ue=_.attestation?.sigstore,ne=Ue?await ru(t,H,Ue,{requireTransparencyLog:C}):null;if(Ue){if(r.push({id:`mirror.sigstore.${S}`,status:ne?.verified?"passed":"failed",message:ne?.message||"Sigstore verification failed."}),R.push({artifactId:S,verified:!!ne?.verified,tlogVerified:!!ne?.tlogVerified,identity:ne?.identity||null,issuer:ne?.issuer||null,rekorUrl:ne?.rekorUrl||null,timestamp:new Date().toISOString(),environment:h}),!ne?.verified){await we();continue}}else if(x){r.push({id:`mirror.sigstore.${S}`,status:"failed",message:`Sigstore attestation is required but missing for ${S}.`}),await we();continue}else r.push({id:`mirror.sigstore.${S}`,status:"skipped",message:`No Sigstore attestation provided for ${S}.`});if(Ue&&ne?.verified&&v){let Ee=v.allowedIdentities||[];if(Ee.length>0){let Re=!!ne.identity&&Ee.includes(ne.identity);if(r.push({id:`mirror.sigstore.policy.identity.${S}`,status:Re?"passed":"failed",message:Re?`Sigstore identity policy passed for ${S} in ${h}.`:`Sigstore identity policy failed for ${S} in ${h}.`}),!Re){await we();continue}}let pr=v.allowedIssuers||[];if(pr.length>0){let Re=!!ne.issuer&&pr.includes(ne.issuer);if(r.push({id:`mirror.sigstore.policy.issuer.${S}`,status:Re?"passed":"failed",message:Re?`Sigstore issuer policy passed for ${S} in ${h}.`:`Sigstore issuer policy failed for ${S} in ${h}.`}),!Re){await we();continue}}let Lt=v.allowedRekorUrls||[];if(Lt.length>0){let Re=!!ne.rekorUrl&&Lt.includes(ne.rekorUrl);if(r.push({id:`mirror.sigstore.policy.rekor.${S}`,status:Re?"passed":"failed",message:Re?`Sigstore Rekor policy passed for ${S} in ${h}.`:`Sigstore Rekor policy failed for ${S} in ${h}.`}),!Re){await we();continue}}}else v&&r.push({id:`mirror.sigstore.policy.${S}`,status:"skipped",message:`Sigstore governance policy configured for ${h} but no verified Sigstore attestation for ${S}.`});Te&&(await il(i,W),await promises.rename(H,W),Te=false);let Bs=await promises.stat(W);E.push({id:S,path:b.relative(t,W),sha256:Me,size:Bs.size,provenance:ie,attestation:{detached:{provided:!!_.attestation,verified:Fe?.verified||false,algorithm:Fe?.algorithm||null,publicKeyPath:Fe?.publicKeyPath||null,publicKeyFingerprint:Fe?.publicKeyFingerprint||null,signature:Fe?.signature||null,verifiedAt:Fe?.verified?new Date().toISOString():null},sigstore:{provided:!!Ue,verified:ne?.verified||false,tlogVerified:ne?.tlogVerified||false,identity:ne?.identity||null,issuer:ne?.issuer||null,rekorUrl:ne?.rekorUrl||null,bundlePath:ne?.bundlePath||null,certificatePath:ne?.certificatePath||null,signaturePath:ne?.signaturePath||null,verifiedAt:ne?.verified?new Date().toISOString():null}}});}let $=d.retention?.keepLast;if(typeof $=="number"&&$>0){let M=new Set(E.map(S=>b.resolve(t,S.path))),_=(await Hd(i)).filter(S=>!M.has(b.resolve(S)));if(_.length>$){let S=await Promise.all(_.map(async F=>({filePath:F,stat:await promises.stat(F)})));S.sort((F,W)=>W.stat.mtimeMs-F.stat.mtimeMs);let J=S.slice($);for(let F of J)await promises.unlink(F.filePath),o.rotatedFiles+=1;}}r.push({id:"mirror.rotate",status:"passed",message:o.rotatedFiles>0?`Mirror retention rotation removed ${o.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let N={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:d.mode||null,environment:h,artifacts:E};if(await promises.writeFile(a,`${JSON.stringify(N,null,2)}
153
- `,"utf-8"),o.lockWritten=true,r.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${b.relative(t,a)}.`}),o.transparencyEvidenceRecords=R.length,R.length>0){let M={schemaVersion:d$9.transparencyEvidence.schemaVersion,generatedAt:new Date().toISOString(),environment:h,records:R},_=new Date().toISOString().replace(/[:.]/g,"-"),S=b.join(c,`transparency-evidence-${_}.json`),J=b.join(c,"transparency-evidence.latest.json");if(b$l(`.workspai/reports/${b.basename(S)}`,M),b$l(e$1.transparencyEvidence,M),await O.ensureDir(c),await al(S,M),await al(J,M),o.transparencyEvidenceWritten=true,r.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${b.relative(t,J)}.`}),u?.enabled){let F=Math.max(1e3,u.timeoutMs??1e4);if(u.target==="file")if(!u.filePath)r.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let W=it(t,u.filePath);await O.ensureDir(b.dirname(W)),await promises.appendFile(W,`${JSON.stringify(M)}
154
- `,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=W,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${W}.`});}catch(W){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${W.message}`});}else if(u.target==="http")if(!u.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let W=Math.max(0,u.retries??0),G=Math.max(0,u.backoffMs??500),H=eu(M,u.signing);H.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:H.error});try{let Te=u.authTokenEnv?process.env[u.authTokenEnv]:void 0,we=false,ie=null;for(let Me=1;Me<=W+1;Me+=1)try{if(H.error)throw new Error(H.error);await Qd(u.endpoint,M,F,Te,H.headers),o.evidenceExported=true,o.evidenceExportTarget=u.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:Me>1?`Transparency evidence exported to HTTP endpoint ${u.endpoint} after ${Me} attempts.`:`Transparency evidence exported to HTTP endpoint ${u.endpoint}.`}),we=true;break}catch(Fe){ie=Fe,Me<=W&&await cl(G*Me);}if(!we)throw ie||new Error("unknown evidence export error")}catch(Te){let we=`Evidence HTTP export failed: ${Te.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:we});try{let ie=await Zd(t,u.deadLetterPath,M,we);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${ie}.`});}catch(ie){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${ie.message}`});}}}if(u.failOnError&&r.some(G=>G.status==="failed"&&(G.id==="sigstore.evidence.export.file"||G.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function qo(t){let e=f$6(t.detection.runtime),r=u$1({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function nu(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function zo(t){if(t.existingProjectJson?.module_support===true){let e=nu(t.existingProjectJson),r=e?a$4(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}function gl(t){return t.replace(/\\/g,"/")}function su(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function au(t,e){let r=gl(b.relative(t,e));return !r||r.startsWith("..")?true:r.split("/").filter(Boolean).some(o=>o==="..")}function Mr(t){let e=gl(b.relative(t.workspacePath,t.projectPath)),r=au(t.workspacePath,t.projectPath),o=su(t.projectName,b.basename(t.projectPath)),n=r?`external/${o}`:e||o;return {relativePath:e||n,contractRelativePath:n,isExternal:r}}var fl=[a$B,b$k];function iu(t,e){let r=b.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!b.isAbsolute(r)}async function rt(t){let e=await O__default.realpath(t);for(let r of fl){let o=b.join(t,r),n=await O__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await O__default.realpath(o);if(!iu(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function hl(t){let e=b.basename(t);return fl.includes(e)?(await O__default.lstat(t)).isSymbolicLink():false}var kl={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},pu={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"},du={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},wl=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function fs(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function hs(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function Wr(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 Qo(t){let e=new Set;for(let r of t)e.add(Wr(r));return [...e].sort((r,o)=>wl.indexOf(r)-wl.indexOf(o))}function uu(t){let e=Qo(t).filter(r=>r!=="unknown");if(e.length!==0)return e.length===1?du[e[0]]:"polyglot"}function yl(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function mu(t,e){return t?"none":e==="strict"?"error":"warning"}function Dr(t){let e=t.ok?void 0:uu(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?yl(e):void 0,ciRecommendedCommand:e?yl(e,{ci:true}):void 0,severity:mu(t.ok,t.mode)}}function $t(t){let e=hs(t.profile),r=Qo(t.runtimes),o=t.mode??"warn",n=kl[e];if(n){let a=r.length===0||r.every(i=>fs(i)===n);return Dr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:r,message:a?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${r.join(", ")}].`,mode:o})}if(e==="minimal"){let a=r.filter(p=>p!=="unknown"),c=new Set(a.map(p=>fs(p))).size<=1;return Dr({ok:c,checkId:"profile.minimal",profile:e,runtimes:r,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${a.join(", ")}].`,mode:o})}return Dr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:r,message:`${e} profile accepts the detected runtime mix.`,mode:o})}function St(t){let e=hs(t.profile),r=Wr(t.runtime),o=t.mode??"warn",n=kl[e];if(!n||r==="unknown")return Dr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[r],message:r==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:o});let a=fs(r)===n;return Dr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:a?[r]:Qo([n,r]),message:a?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${pu[r]}, but workspace profile is "${e}".`,mode:o})}async function ar(t){let e=(await Promise.all(s$1(t,"policies.yml").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "warn";try{return (await O__default.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function ir(t){let e=(await Promise.all(s$1(t,"workspace.json").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "minimal";try{let r=await O__default.readJson(e);return hs(r.profile)}catch{return "minimal"}}async function Nt(t$1,e={}){let r=new Set,o=[],n=new Set,a=[t$1];for(;a.length>0;){let i=a.pop();if(!i||n.has(i))continue;n.add(i);let c=[];try{c=await A.promises.readdir(i,{withFileTypes:true});}catch{continue}for(let p of c){if(!p.isDirectory()||p.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(p.name))continue;let d=b.join(i,p.name);if(d!==t$1&&j$1(d))continue;if((await Promise.all([...t(d,"context.json"),...t(d,"project.json")].map(async m=>O__default.pathExists(m)))).some(Boolean)){o.push(d);continue}a.push(d);}}for(let i of o){let c=i$2(i);r.add(Wr(j$3(i,c).runtime));}for(let i of await a$C(t$1))r.add(Wr(i.runtime));for(let i of e.additionalRuntimes??[])r.add(Wr(i));return Qo(r)}function Zo(t,e={}){let r=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return r?`Recommended: ${r}`:null}function vl(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function fu(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return vl(a)||"imported-project"}function xt(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function hu(t){return xt(t)?"git-url":"local-folder"}async function wu(t,e){let r=vl(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=b.join(t,n);if(!await O__default.pathExists(a))return a;o+=1;}}function yu(t,e){let r=b.resolve(t),o=b.resolve(e),n=b.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!b.isAbsolute(n)}function ku(t,e){if(yu(t,e))throw new Error("Import source must be outside the current workspace root.")}function vu(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function Pu(t){let e=b.basename(t);return !(await hl(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||vu(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function ju(t$1){await rt(t$1);for(let e of t(t$1,"project.json"))if(await O__default.pathExists(e))try{return await O__default.readJson(e)}catch{return null}return null}async function bu(t){await rt(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),o=Mr({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=u(t.projectPath,"project.json"),i=u(t.projectPath,"import.json"),c=u(t.projectPath,"import-readiness.json"),p=zo({existingProjectJson:t.existingProjectJson}),d=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],g=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},m={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:b.basename(t.projectPath),kind:t.projectKind,category:a$e(t.projectKind),project_type:a$e(t.projectKind),runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:p,modules:d,contracts:g,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},k={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:m.name,slug:m.slug,relative_path:n,kind:t.projectKind,category:a$e(t.projectKind),module_support:p},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$e(t.projectKind),confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:p,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},w=qo({projectName:String(m.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:p,projectPath:t.projectPath,generatedAt:new Date(e)});return await O__default.ensureDir(b.dirname(a)),await O__default.writeJson(a,m,{spaces:2}),await O__default.writeJson(i,k,{spaces:2}),await O__default.writeJson(c,w,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:p}}async function Cu(t,e){let r={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,relationship:"imported",importedAt:new Date().toISOString()};await b$e(t,[r]);}async function Su(t){await O__default.pathExists(t)&&(await rt(t),await O__default.remove(t));}async function xu(t,e){await Su(e),await c$3(t,[e]);}async function Pl(t){let e=b.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??hu(r),n=t.name??(o==="git-url"?fu(r):b.basename(r)),a=await wu(e,n),i=false;try{if(o==="local-folder"){let h=b.resolve(r),f=await O__default.stat(h).catch(()=>null);if(!f||!f.isDirectory())throw new Error("Import source is not a directory.");if(await rt(h),j$1(h))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");ku(e,h),i=true,await O__default.copy(h,a,{overwrite:false,errorOnExist:true,filter:Pu});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$d()});await rt(a);let c=await ju(a),p=j$3(a,c),d=await b$d(a,c),[g,m]=await Promise.all([ir(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ar(e)]),k=St({profile:g,runtime:p.runtime,subjectLabel:b.basename(a),mode:m}),w=$t({profile:g,runtimes:await Nt(e,{additionalRuntimes:[p.runtime]}),mode:m}),j=k.ok?w:k;if(!j.ok&&m==="strict")throw new Error(j.message);let x=await bu({workspacePath:e,projectPath:a,sourceType:o,detection:p,existingProjectJson:c,projectKind:d,profileCompatibility:j}),l=Mr({workspacePath:e,projectPath:a,projectName:b.basename(a)}),P={ingestionPlan:Ot({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:b.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:b.basename(a),path:a,relativePath:l.contractRelativePath,stack:p.importStack,runtime:p.runtime,framework:p.key,frameworkDisplayName:p.displayName,supportTier:p.supportTier,moduleSupport:x.moduleSupport,confidence:p.confidence,source:o,projectJsonPath:x.projectJsonPath,importJsonPath:x.importJsonPath,importReadinessPath:x.importReadinessPath,profileCompatibility:j};await Cu(e,P);let{syncWorkspaceContract:u}=await import('./workspace-contract-AYFTZIKM.js');return await u({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:P.path,projectName:P.name,relationship:"imported",mode:t.projectGrounding??"managed"}),P}catch(c){if(i)try{await xu(e,a);let{syncWorkspaceContract:p}=await import('./workspace-contract-AYFTZIKM.js');await p({workspacePath:e,strict:true});}catch(p){let d=c instanceof Error?c.message:String(c),g=p instanceof Error?p.message:String(p);throw new Error(`Import failed: ${d}. Rollback also failed: ${g}`)}throw c}}function Eu(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Ru(t,e){return b.resolve(t)===b.resolve(e)}async function Au(t$1){await rt(t$1);for(let e of t(t$1,"project.json")){if(!await O__default.pathExists(e))continue;let r;try{r=JSON.parse((await O__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}async function ws(t,e){let r=b.resolve(t),o=b.resolve(e);await rt(o);let n=[u(o,"project.json"),u(o,"adopt.json"),u(o,"adopt-readiness.json"),b.join(o,f$2),b.join(o,g$2),b.join(o,h$3),b.join(o,"AGENTS.md"),b.join(o,".gitignore"),p(r,"imported-projects.json")];return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>({path:a,contents:await O__default.pathExists(a)?await O__default.readFile(a):null})))}}function jl(t,e,r){let o=[u(r,"project.json"),u(r,"adopt.json"),u(r,"adopt-readiness.json"),b.join(r,f$2),b.join(r,g$2),b.join(r,h$3),b.join(r,"AGENTS.md"),b.join(r,".gitignore"),p(e,"imported-projects.json")].map(n=>b.resolve(n));if(t.workspacePath!==b.resolve(e)||t.projectPath!==b.resolve(r)||t.files.length!==o.length||t.files.some((n,a)=>b.resolve(n.path)!==o[a]))throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function _u(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,category:a$e(t.projectKind),project_type:a$e(t.projectKind),runtime:t.detection.runtime,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:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function Iu(t,e,r){await rt(e),jl(r,t,e);let o=[];for(let n of r.files)try{n.contents===null?await O__default.remove(n.path):(await O__default.ensureDir(b.dirname(n.path)),await O__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function ys(t){let e=b.resolve(t.workspacePath),r=b.resolve(t.source),o=await O__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await rt(r),Ru(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(j$1(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t.rollbackSnapshot??await ws(e,r);jl(n,e,r);let a=await Au(r),i=j$3(r,a),c=await b$d(r,a),p=Eu(t.name||(typeof a?.name=="string"?a.name:"")||b.basename(r))||"adopted-project",d=Mr({workspacePath:e,projectPath:r,projectName:p}),g=(t.now??new Date).toISOString(),m=u(r,"project.json"),k=u(r,"adopt.json"),w=u(r,"adopt-readiness.json"),j=zo({existingProjectJson:a}),[x,l]=await Promise.all([ir(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ar(e)]),P=St({profile:x,runtime:i.runtime,subjectLabel:p,mode:l}),u$1=$t({profile:x,runtimes:await Nt(e,{additionalRuntimes:[i.runtime]}),mode:l}),h=P.ok?u$1:P;if(!h.ok&&l==="strict")throw new Error(h.message);let f=_u({projectName:p,contractRelativePath:d.contractRelativePath,isExternal:d.isExternal,discoveredRelativePath:d.relativePath,detection:i,existingProjectJson:a,projectKind:c,moduleSupport:j,adoptedAt:g}),v={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:g,managed_by:"workspai",mode:"linked",workspace:{name:b.basename(e),contract:e$1.workspaceContract},project:{name:p,relative_path:d.contractRelativePath,...d.isExternal?{}:{discovered_relative_path:d.relativePath},is_external:d.isExternal,kind:c,category:a$e(c),module_support:j},detection:{framework:i.key,framework_display_name:i.displayName,runtime:i.runtime,kind:c,category:a$e(c),confidence:i.confidence,support_tier:i.supportTier,import_stack:i.importStack,source:i.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:j,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}}},C=qo({projectName:p,relativePath:d.contractRelativePath,projectKind:c,source:"adopted-local",detection:i,moduleSupport:j,projectPath:r,generatedAt:new Date(g)});if(t.dryRun!==true)try{await rt(r),await O__default.ensureDir(b.dirname(m)),await O__default.writeJson(m,f,{spaces:2}),await O__default.writeJson(k,v,{spaces:2}),await O__default.writeJson(w,C,{spaces:2});let R={name:p,path:r,relativePath:d.contractRelativePath,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:j,confidence:i.confidence,source:"adopted-local",importedAt:g};await b$e(e,[R]);let{syncWorkspaceContract:y}=await import('./workspace-contract-AYFTZIKM.js');await y({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:r,projectName:p,relationship:"adopted",mode:t.projectGrounding??"managed",now:new Date(g)});}catch(R){try{await Iu(e,r,n);let{syncWorkspaceContract:y}=await import('./workspace-contract-AYFTZIKM.js');await y({workspacePath:e,strict:true});}catch(y){throw new AggregateError([R,y],`Adopt failed and rollback was incomplete: ${R instanceof Error?R.message:String(R)}`)}throw R}return {ingestionPlan:Ot({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t.projectGrounding??"managed"}),name:p,path:r,relativePath:d.relativePath,contractRelativePath:d.contractRelativePath,isExternal:d.isExternal,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:j,confidence:i.confidence,projectJsonPath:m,adoptJsonPath:k,adoptReadinessPath:w,profileCompatibility:h,wroteFiles:t.dryRun!==true}}async function Ou(t){let e=await O__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=b.join(t,r),n=await O__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function $u(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await O__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=b.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$f(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$5&&(await O__default.remove(i),e.push(b.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function Cl(t,e){if(await b$f(t,b.basename(t)),!(await g$3(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$h(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function ks(t){let e=b.resolve(t.workspacePath);await Ou(e);let r=Ot({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!j$1(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return en(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$4(e);try{let n=await Cl(e,t.projectGrounding??"managed");return en(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$6(e,o).catch(()=>{}),n}}async function vs(t){if(t.dryRun){let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=b.resolve(o.outputPath),a=bl(t,n);return en(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?b.resolve(t.outputPath):void 0;if(e&&await O__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=b.resolve(o.outputPath);let n=bl(t,r);if(!j$1(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await $u(r);o.manifest?.portableContract&&await O__default.outputJson(b.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await Cl(r,t.projectGrounding??"managed");return en(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,p,d)=>d.indexOf(c)===p),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$4(r).catch(()=>{}),await O__default.remove(r).catch(()=>{})),o}}function bl(t,e){return Ot({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function en(t,e){let r={schemaVersion:Ho,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$5(r,tl,"Workspace ingestion result"),r}function Sl(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function xl(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function El(t){let e=t.trim(),r=e.startsWith("~/")?b.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!xt(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:xt(r)?r:b.resolve(r)};if(xt(r))return {kind:"git-project",source:r};let n=b.resolve(r);return j$1(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var Wu=Uo,Du=Ko;function js(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 Lu(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 cr(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function Fu(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Ie(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function Ju(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Is(t){try{return Ju(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function Vs(t$1,e){let r=Ie(t$1,"--port")?.trim(),o=t$1[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Ie(t$1,"--output")||".",i=b.resolve(e,a,o),c=t(i,"project.json").find(d=>A.existsSync(d))??u(i,"project.json");if(!await O__default.pathExists(c))return;let p=await O__default.readJson(c);await O__default.writeJson(c,{...p,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Al(t){let e=Pe(process.cwd()),r=t.trim().toLowerCase();if(!e||!r)return true;try{let[o,n]=await Promise.all([ir(e),ar(e)]),a=a$4(r),i=j$5(r),c=p$4(r),p=i?"node":c?.runtime??a?.runtime??"python",d=St({profile:o,runtime:p,subjectLabel:r,mode:n}),g=$t({profile:o,runtimes:await Nt(e,{additionalRuntimes:[p]}),mode:n}),m=d.ok?g:d;if(m.ok)return true;let k=Zo(m);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${m.message}`)),k&&console.log(s.gray(`\u{1F4A1} ${k}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${m.message}`)),k&&console.log(s.gray(`\u{1F4A1} ${k}`));}catch{}return true}function Us(){return j$6()}function _l(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(b.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$5()),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 Gu(t){return m$3(b.join(t,".venv"))}async function Ku(t,e){return await je(t,["--version"],e)===0}async function Wt(t){let e=b.join(t,"go.mod");if(await O__default.pathExists(e))return "go";let r=b.join(t,"pom.xml"),o=b.join(t,"build.gradle"),n=b.join(t,"build.gradle.kts");if(await O__default.pathExists(r)||await O__default.pathExists(o)||await O__default.pathExists(n))return "java";if((await O__default.pathExists(t)?await A.promises.readdir(t,{withFileTypes:true}):[]).some(w=>w.isFile()&&w.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=b.join(t,"src");if(await O__default.pathExists(i)&&(await A.promises.readdir(i,{withFileTypes:true})).some(j=>j.isFile()&&j.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=b.join(t,"Cargo.toml");if(await O__default.pathExists(c))return "rust";let p=b.join(t,"composer.json");if(await O__default.pathExists(p))return "php";let d=b.join(t,"package.json");if(await O__default.pathExists(d))return "node";let g=b.join(t,"pyproject.toml"),m=b.join(t,"requirements.txt"),k=b.join(t,"poetry.lock");return await O__default.pathExists(g)||await O__default.pathExists(m)||await O__default.pathExists(k)?"python":null}async function Vu(t,e={}){let r=e.runCommand??je;for(let o of e.pythonCandidates??Us())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Hl(t,e={}){let r=e.runCommand??je;for(let o of e.pythonCandidates??Us())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Uu(t,e={}){let r=e.runCommand??je,o=m$3(b.join(t,".venv"));if(!await O__default.pathExists(o)){let c=await Hl(t,e);if(c!==0)return c}if(!(await r("poetry",["--version"],t)===0))return 0;let a=await r("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await r("poetry",["env","use",o],t);return i!==0?i:0}async function Hu(t,e={}){let r=e.runCommand??je,o=m$3(b.join(t,".venv"));if(!await O__default.pathExists(o)){let i=await Hl(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=b.join(t,"requirements.txt");if(await O__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=b.join(t,"pyproject.toml");return await O__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function bs(t,e){return await Uu(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await O__default.pathExists(b.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await Hu(t))}async function Cs(t){let e=await Mt("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await Ku(o,t))continue;if(await je(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function Bu(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Ie([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Ie([...e],"--java-version"),a=Ie([...e],"--spring-boot-version"),i=Ie([...e],"--springdoc-version"),c=Ie([...e],"--group-id"),p=Ie([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(p&&!/^[A-Za-z0-9_.-]+$/.test(p.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Ie([...e],"--target-framework"),a=Ie([...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 Il(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||Ws(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:o}=await import('./create-R6A7EHQZ.js');await o(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b$1()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:r}=await b$2([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},{name:"Create it without workspace management",value:"none"}],default:1}]);if(r==="current"){let{registerWorkspaceAtPath:o}=await import('./create-R6A7EHQZ.js');await o(process.cwd(),{skipGit:e,yes:false,userConfig:await b$1()});}else r==="none"&&t.push("--no-workspace");}async function qu(t){await O__default.ensureDir(t);let e=b.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await A.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
155
- `),async()=>{await o.close().catch(()=>{}),await O__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await O__default.readJson(e).catch(()=>null),a=Number(n?.pid),i=false;if(Number.isInteger(a)&&a>0)try{process.kill(a,0),i=true;}catch(c){i=c.code==="EPERM";}if(!i){await O__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function on(t,e={}){let r$1=b.join(q(),"transactions"),o=await qu(r$1),n;try{await b$b(r$1),n=await a$a({journalDirectory:r$1});}catch(i){throw await o(),i}let a=new Set([b.join(q(),"workspaces.json"),b.join(r(),"workspaces.json"),a$b(t,g$1),b$c(t,g$1),a$b(t,a$c),b$c(t,a$c),...s$1(t,"imported-projects.json")]);e.projectPath&&(a.add(u(e.projectPath,"project.json")),a.add(u(e.projectPath,"context.json")),a.add(u(e.projectPath,"file-hashes.json")),a.add(u(e.projectPath,"adopt.json")),a.add(u(e.projectPath,"adopt-readiness.json")),a.add(b.join(e.projectPath,f$2)),a.add(b.join(e.projectPath,g$2)),a.add(b.join(e.projectPath,h$3)),a.add(b.join(e.projectPath,"AGENTS.md")),a.add(b.join(e.projectPath,".gitignore")));try{for(let c of a)await n.captureFile(c);e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let i=false;return {registerCompensation:c=>n.registerCompensation(c),commit:async()=>{i||(await n.commit(),i=true,await o());},rollback:async()=>{if(!i){i=true;try{await n.rollback();}finally{await o();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await o(),i}}async function lr(t,e){try{await t.rollback();}catch(r){throw new AggregateError([e,r],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function Gr(t,e,r){if(t.includes("--no-workspace")||t.includes("--dry-run"))return;if(!await O__default.pathExists(e)){f.warn(`Created project path was not found for workspace linking: ${e}`);return}let o=Pe(e)||Pe(process.cwd()),n=false,a;if(o)a=await on(o,{projectPath:e});else {o=o$1(),a=await on(o,{projectPath:e,ownedWorkspace:o});try{o=(await Hs()).workspacePath;}catch(c){await lr(a,c);}n=true;}let i="managed";try{await o$2(e);let c=b.relative(o,e);(c.startsWith("..")||b.isAbsolute(c))&&(i=(await ys({source:e,workspacePath:o,name:r})).relationship);let{registerProjectInWorkspaceStrict:d,registerWorkspaceStrict:g}=await import('./workspace-B53XH35L.js'),{syncWorkspaceContract:m}=await import('./workspace-contract-AYFTZIKM.js');await g(o,b.basename(o)),await d(o,r,e),await m({workspacePath:o,strict:true});let{syncProjectIntelligenceLens:k}=await import('./project-intelligence-lens-ZOAWXYC5.js');await k({workspacePath:o,projectPath:e,projectName:r,relationship:i==="adopted"?"adopted":"managed",mode:"managed"}),await a.commit(),await Kr(o);}catch(c){await lr(a,c);}return n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${i$3}" (${i}).`)),console.log(s.gray(` Registry: ${b.join(q(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${o}`))),o}async function Os(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],r=a$4(e),o=t[3];if(!r||r.owner!=="npm")return 1;if(!o)return process.stderr.write(`Usage: ${r.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
149
+ ${r.stderr||""}`);return o?this.isMavenVersionAtLeast(o,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${o.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let r=A.existsSync(b.join(e,"pom.xml")),o=A.existsSync(b.join(e,"mvnw"))||A.existsSync(b.join(e,"mvnw.cmd")),n=A.existsSync(b.join(e,"build.gradle"))||A.existsSync(b.join(e,"build.gradle.kts"))||A.existsSync(b.join(e,"settings.gradle"))||A.existsSync(b.join(e,"settings.gradle.kts")),a=A.existsSync(b.join(e,"gradlew"))||A.existsSync(b.join(e,"gradlew.bat"));return {hasMavenProject:r||o,hasMavenWrapper:o,hasGradleProject:n||a,hasGradleWrapper:a}}findWorkspaceRoot(e){let r=e;for(;;){if(A.existsSync(b.join(r,".workspai-workspace"))||A.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>A.existsSync(a));if(!n)return "isolated";try{let c=A.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let r=b.join(e,"mvnw.cmd");if(process.platform==="win32"&&A.existsSync(r))return {command:r,baseArgs:[]};let o=b.join(e,"mvnw");return A.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let r=b.join(e,"gradlew.bat");if(process.platform==="win32"&&A.existsSync(r))return {command:r,baseArgs:[]};let o=b.join(e,"gradlew");return A.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let r=[],o=new Set,n=[e];for(;n.length>0;){let a=n.shift();if(!a||o.has(a))continue;o.add(a);let i=[];try{i=A.readdirSync(a,{withFileTypes:true});}catch{continue}for(let c of i){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let p=b.join(a,c.name),d=this.inspectJavaProject(p);(d.hasMavenProject||d.hasGradleProject)&&r.push(p),n.push(p);}}return r}withJavaCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","m2"):b.join(e,".workspai","cache","java","m2"),i=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","gradle"):b.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,p=process.env.GRADLE_USER_HOME,d=`-Dmaven.repo.local=${a}`;return process.env.MAVEN_OPTS=c?`${c} ${d}`:d,process.env.GRADLE_USER_HOME=i,r().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof p>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=p;})}async runBuildTool(e,r,o=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:a}=this.buildToolCommand(e),i=await this.runCommand(n,[...a,...r],e);if(i===0||!o)return {exitCode:i};let c=A.existsSync(b.join(e,"pom.xml")),p=A.existsSync(b.join(e,"build.gradle"))||A.existsSync(b.join(e,"build.gradle.kts"));return {exitCode:i,message:c||p?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let r=[b.join(e,"target"),b.join(e,"build","libs")];for(let o of r){if(!A.existsSync(o))continue;let a=A.readdirSync(o).filter(i=>i.toLowerCase().endsWith(".jar")).find(i=>!i.toLowerCase().endsWith("-sources.jar")&&!i.toLowerCase().endsWith("-javadoc.jar")&&!i.toLowerCase().endsWith("-plain.jar"));if(a)return b.join(o,a)}return null}commandArgsFor(e,r){if(e==="gradle"){let o=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return r==="init"?[...o,"dependencies"]:r==="dev"?[...o,"bootRun"]:r==="test"?[...o,"test"]:[...o,"bootJar"]}return r==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:r==="dev"?["spring-boot:run"]:r==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),r=this.resolveJavaCommand(e),o=await this.runCommand(r,["-version"],e);if(o!==0)return {exitCode:o,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),p=await this.detectInstalledJavaMajor(r,e);if(p!==null&&p<c)return {exitCode:1,message:`Detected Java ${p}, but project requires Java ${c}+.`};let d=b.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&A.existsSync(d))try{let m=A.readFileSync(d,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),k=this.parseMajorJavaVersion(m?.[1]);if(k!==null&&k<c)return {exitCode:1,message:`Detected JAVA_HOME version ${k}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),p=c==="gradle"?["--version"]:["-version"],d=await this.runBuildTool(e,p);return d.exitCode!==0?d:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):d}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let p=c.reduce((m,k)=>Math.max(m,this.readRequiredJavaMajor(k)),0);if(p>0){let m=await this.detectInstalledJavaMajor(r,e);if(m!==null&&m<p){let k=c.filter(y=>this.readRequiredJavaMajor(y)>m).map(y=>b.relative(e,y)).join(", ");return {exitCode:1,message:`Detected Java ${m}, but workspace project(s) [${k}] require Java ${p}+.`}}}let d=false,g=false;for(let m of c){let k=this.inspectJavaProject(m);k.hasMavenProject&&!k.hasMavenWrapper&&(d=true),k.hasGradleProject&&!k.hasGradleWrapper&&(g=true);}if(d){let m=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(m!==0)return {exitCode:m,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let k=await this.checkSystemMavenVersion(e);if(k.exitCode!==0)return k}if(g){let m=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(m!==0)return {exitCode:m,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(a===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return i===0?{exitCode:0}:{exitCode:a||i||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let r=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return r&&A.mkdirSync(r,{recursive:true}),process.env.GRADLE_USER_HOME&&A.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let r=this.resolveJarPath(e);if(r)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",r],e)};let o=await this.runBuild(e);if(o.exitCode!==0)return o;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(pt(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let r=b.join(e,"pom.xml");if(A.existsSync(r)){let o=A.readFileSync(r,"utf-8");if(o.includes("spotless-maven-plugin"))return this.runBuildTool(e,["spotless:check"]);if(o.includes("checkstyle"))return this.runBuildTool(e,["checkstyle:check"])}return {exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){if(pt(e,"format"))return {exitCode:await this.runCommand("make",["format"],e)};let r=b.join(e,"pom.xml");return A.existsSync(r)&&A.readFileSync(r,"utf-8").includes("spotless-maven-plugin")?this.runBuildTool(e,["spotless:apply"]):["build.gradle","build.gradle.kts"].map(n=>b.join(e,n)).filter(n=>A.existsSync(n)).some(n=>A.readFileSync(n,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure Spotless in Maven/Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run npx workspai init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var Oo=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}findWorkspaceRoot(e){let r=e;for(;;){if(A.existsSync(b.join(r,".workspai-workspace"))||A.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>A.existsSync(a));if(!n)return "isolated";try{let c=A.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,r,o){let n=this.resolveDependencyMode(e),a=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=n==="isolated"?b.join(e,".workspai","cache","node"):b.join(a||e,".workspai","cache","node"),c=process.env.npm_config_cache,p=process.env.npm_config_store_dir,d=process.env.RAPIDKIT_DEP_SHARING_MODE,g=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,a&&(process.env.RAPIDKIT_WORKSPACE_PATH=a),r==="pnpm"?(process.env.npm_config_store_dir=b.join(i,"pnpm-store"),process.env.npm_config_cache=b.join(i,"pnpm-cache")):r==="yarn"?process.env.npm_config_cache=b.join(i,"yarn-cache"):process.env.npm_config_cache=b.join(i,"npm-cache"),o().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof p>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=p,typeof d>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=d,typeof g>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=g;})}detectPackageManager(e){if(A.existsSync(b.join(e,"package-lock.json")))return "npm";if(A.existsSync(b.join(e,"pnpm-lock.yaml")))return "pnpm";if(A.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 A.existsSync(b.join(e,"package-lock.json"))||A.existsSync(b.join(e,"pnpm-lock.yaml"))||A.existsSync(b.join(e,"yarn.lock"))}availablePackageManagers(e){let r=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[r]:[r,...["npm","pnpm","yarn"].filter(n=>n!==r&&this.commandAvailable(n))]}commandAvailable(e){let r=e$9(e);return spawnSync(r.command,[...r.prefixArgs,"--version"],{stdio:"ignore",shell:c$d(),env:g$7()}).status===0}scriptArgs(e,r){return e==="npm"?["run-script",r,"--foreground-scripts"]:["run",r]}async runScriptWithFallback(e,r){let o={exitCode:1};for(let n of this.availablePackageManagers(e))if(o=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,r),e)),o.exitCode===0)return o;return o}async runLifecycle(e,r){let o=i$2(e),n=j$3(e,o),a=t$1(e,r,{framework:n.key});return a?this.runScriptWithFallback(e,a.scriptName):{exitCode:1,message:`No npm script available for \`${r}\`. Add a "${r}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let r=this.detectPackageManager(e);return this.withDependencyEnv(e,r,async()=>{try{return process.env.npm_config_cache&&A.mkdirSync(process.env.npm_config_cache,{recursive:true}),r==="pnpm"&&process.env.npm_config_store_dir&&A.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let r=this.detectPackageManager(e),o=this.resolveDependencyMode(e),n=o==="shared-runtime-caches"||o==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,r,()=>this.run(r,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var No=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,r){return {exitCode:await this.withPythonCacheEnv(r,()=>this.runCore(e,r))}}findWorkspaceRoot(e){let r=e;for(;;){if(A.existsSync(b.join(r,".workspai-workspace"))||A.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=s$1(o,"policies.yml").find(a=>A.existsSync(a));if(!n)return "isolated";try{let c=A.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","python"):b.join(e,".workspai","cache","python"),i=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=b.join(a,"pip"),process.env.POETRY_CACHE_DIR=b.join(a,"poetry"),r().finally(()=>{typeof i>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=i,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),r=await this.run(["doctor","check"],e);return r.exitCode===0?r:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx workspai doctor workspace" for a full workspace scan.','Use "npx workspai init" after adding or changing modules.',"Use `npx workspai <command>` from the project root to avoid environment drift."]}};var To=class{constructor(e){this.runCommand=e;}runCommand;runtime="php";async run(e,r,o){let n=await this.runCommand(e,r,o);return n===0?{exitCode:n}:{exitCode:n,message:`PHP lifecycle command failed (${e} ${r.join(" ")}). Ensure ${e} is available on PATH, then review composer.json and the command diagnostics above.`}}hasComposer(e){return A.existsSync(b.join(e,"composer.json"))}hasArtisan(e){return A.existsSync(b.join(e,"artisan"))}hasComposerScript(e,r){try{let o=JSON.parse(A.readFileSync(b.join(e,"composer.json"),"utf8"));return !!o.scripts&&Object.prototype.hasOwnProperty.call(o.scripts,r)}catch{return false}}missingManifest(){return {exitCode:1,message:"composer.json was not found. Run the command from a PHP project root."}}unsupported(e){return {exitCode:1,message:`No deterministic PHP ${e} command was detected. Add a "${e}" Composer script or the expected Laravel tooling.`}}async checkPrereqs(){let e=await this.run("php",["--version"],process.cwd());return e.exitCode!==0?e:this.run("composer",["--version"],process.cwd())}async initProject(e){return this.hasComposer(e)?this.run("composer",["install","--no-interaction"],e):this.missingManifest()}async runDev(e){return this.hasComposerScript(e,"dev")?this.run("composer",["run-script","dev"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("dev")}async runTest(e){return this.hasArtisan(e)?this.run("php",["artisan","test"],e):this.hasComposerScript(e,"test")?this.run("composer",["run-script","test"],e):this.unsupported("test")}async runBuild(e){return this.hasComposerScript(e,"build")?this.run("composer",["run-script","build"],e):this.unsupported("build")}async runStart(e){return this.hasComposerScript(e,"start")?this.run("composer",["run-script","start"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("start")}async runLint(e){for(let r of ["lint","analyse","analyze"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return this.unsupported("lint")}async runFormat(e){for(let r of ["format","fmt"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return A.existsSync(b.join(e,"vendor","bin","pint"))||A.existsSync(b.join(e,"pint.json"))?this.run("php",["vendor/bin/pint"],e):this.unsupported("format")}async doctorHints(e){return ["Install a supported PHP release and Composer, then keep both on PATH.","Commit composer.lock for deterministic application installs.","Expose test, lint, format, and build commands as Composer scripts when the framework does not provide them."]}};var Mo=class{constructor(e){this.runCommand=e;}runCommand;runtime="rust";async run(e,r){let o=await this.runCommand("cargo",e,r);return o===0?{exitCode:o}:{exitCode:o,message:`Cargo command failed (cargo ${e.join(" ")}). Ensure the stable Rust toolchain and cargo are available on PATH, then review Cargo.toml and the command diagnostics above.`}}hasManifest(e){return A.existsSync(b.join(e,"Cargo.toml"))}missingManifest(){return {exitCode:1,message:"Cargo.toml was not found. Run the command from a Rust project root."}}async checkPrereqs(){return this.run(["--version"],process.cwd())}async initProject(e){return this.hasManifest(e)?this.run(["fetch"],e):this.missingManifest()}async runDev(e){return this.hasManifest(e)?this.run(["run"],e):this.missingManifest()}async runTest(e){return this.hasManifest(e)?this.run(["test","--all-targets"],e):this.missingManifest()}async runBuild(e){return this.hasManifest(e)?this.run(["build","--release"],e):this.missingManifest()}async runStart(e){return this.hasManifest(e)?this.run(["run","--release"],e):this.missingManifest()}async runLint(e){return this.hasManifest(e)?this.run(["clippy","--all-targets","--all-features","--","-D","warnings"],e):this.missingManifest()}async runFormat(e){return this.hasManifest(e)?this.run(["fmt","--all"],e):this.missingManifest()}async doctorHints(e){return ["Install the Rust toolchain with rustup and ensure cargo is on PATH.","Use Cargo.lock for deterministic application builds.","Install rustfmt and clippy components for format and lint lifecycle commands."]}};function Cd(){let t={...process.env},e=t.PATH||"";if(e){let r=e.split(b.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter);t.PATH=r;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||i$5(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Fe(t,e){return t==="go"?new _o((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="node"?new Oo((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="java"?new Io((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="dotnet"?new Ao((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="rust"?new Mo((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="php"?new To((r,o,n)=>e.runCommandInCwd(r,o,n)):new No((r,o)=>e.runCoreRapidkit(r,{cwd:o,env:Cd()}))}var Dc=b.join(_n.homedir(),".workspai","cache"),Lc=1440*60*1e3;function rs(){let t=g$4("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?b.join(Dc,`vitest-${e}`):Dc}var Do=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(rs(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let r=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${r}.tmp`}async get(e,r="1.0"){let o=this.memoryCache.get(e);if(o&&o.version===r&&Date.now()-o.timestamp<Lc)return f.debug(`Cache hit (memory): ${e}`),o.data;try{let n=this.getCachePath(e),a=await promises.readFile(n,"utf-8"),i=JSON.parse(a);if(i.version===r&&Date.now()-i.timestamp<Lc)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,i),i.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,r,o="1.0"){let n={data:r,timestamp:Date.now(),version:o};this.memoryCache.set(e,n);try{await promises.mkdir(rs(),{recursive:true});let a=this.getCachePath(e),i=this.getTempCachePath(a);await promises.writeFile(i,JSON.stringify(n),"utf-8"),await promises.rename(i,a),f.debug(`Cache set: ${e}`);}catch(a){f.debug(`Cache write failed: ${e}`,a);}}async invalidate(e){this.memoryCache.delete(e);try{let r=this.getCachePath(e);await promises.unlink(r),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=rs(),r=await promises.readdir(e);await Promise.all(r.map(o=>promises.unlink(b.join(e,o)))),f.debug("Cache cleared");}catch{}}};var _r=["list","sync","registry","foundation","intelligence","model","snapshot","diff","impact","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp","policy","contract","share","export","archive","hydrate","import","connect","run","init"],Lo=["intelligence","model","snapshot","diff","impact","contract","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp"];function Fc(t){return Lo.includes(t)}var Jc="workspai-project-entry-capability-v1";var os="workspai-cli-runtime-command-inventory-v1",Fo=[...h$6,"autopilot","pipeline","import","adopt","snapshot","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands","create","project"],ns=["bootstrap","setup","cache","mirror"],Jo="create",Ed=[...ns,Jo],Rd={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."},Go=[["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","coverage"],["project","workspace"],["project","archives"],["project","archive"],["project","restore"],["project","delete"],["snapshot","create"],["snapshot","inspect"],["snapshot","list"],["snapshot","restore"]];function Ad(t,e,r,o){let n=new Set(t),a=new Set(e),i=t.filter(k=>!a.has(k)).sort(),c=e.filter(k=>!n.has(k)).sort(),p=new Set(r),d=new Set(o),g=r.filter(k=>!d.has(k)).sort(),m=o.filter(k=>!p.has(k)).sort();return {ok:i.length===0&&c.length===0&&g.length===0&&m.length===0,registeredButUndeclared:i,declaredButUnregistered:c,registeredScopedButUndeclared:g,declaredScopedButUnregistered:m}}function Gc(t,e=[]){return t.commands.flatMap(r=>{let o=r.name(),n=[...e,o];return [{path:n,command:o,parent:e.length>0?e.join(" "):null,registrationKind:"commander",aliases:r.aliases?.()??[],description:r.description?.()??"",hidden:r._hidden===true,arguments:(r.registeredArguments??[]).map(i=>({name:i.name(),required:i.required,variadic:i.variadic})),options:(r.options??[]).map(i=>({flags:i.flags,attributeName:i.attributeName?.()??null}))},...Gc(r,n)]})}function Kc(t){let e=Gc(t),r=e.filter(c=>c.path.length===1).map(c=>c.command),o=new Set(r),n=Ed.filter(c=>!o.has(c)).map(c=>({path:[c],command:c,parent:null,registrationKind:"manual-handler",aliases:[],description:Rd[c],hidden:false,arguments:[],options:[]})),a=[...e,...n].sort((c,p)=>c.path.join(" ").localeCompare(p.path.join(" "))),i=[...new Set(a.filter(c=>c.path.length===1).map(c=>c.command))].sort();return {schemaVersion:os,commands:a,topLevelCommands:i,integrity:Ad(i,Fo,e.filter(c=>c.path.length>1).map(c=>c.path.join(" ")),Go.map(c=>c.join(" ")))}}function Vc(t){return `CLI command surface integrity violation (${[t.registeredButUndeclared.length>0?`registered but undeclared: ${t.registeredButUndeclared.join(", ")}`:null,t.declaredButUnregistered.length>0?`declared but unreachable: ${t.declaredButUnregistered.join(", ")}`:null,t.registeredScopedButUndeclared.length>0?`registered scoped but undeclared: ${t.registeredScopedButUndeclared.join(", ")}`:null,t.declaredScopedButUnregistered.length>0?`declared scoped but unreachable: ${t.declaredScopedButUnregistered.join(", ")}`:null].filter(r=>r!==null).join("; ")})`}var _d={"--workspace":"Use an explicit workspace root instead of the nearest workspace.","--json":"Emit machine-readable JSON.","--strict":"Return a non-zero exit when governed evidence blocks the result.","--for-agent":"Build output for an agent surface (for example codex, copilot, or cursor).","--include-paths":"Include absolute filesystem paths.","--include-evidence":"Read and include referenced evidence metadata.","--scan-depth":"Set the bounded observable-project discovery depth.","--cache":"Reuse the model cache when the structural inputs are unchanged.","--incremental":"Reuse unchanged projects and rebuild affected graph relations.","--write":"Persist the command artifact under .workspai/reports.","--scope":"Limit the operation to a bounded scope such as project:<name>.","--dry-run":"Preview the operation without applying writes.","--preset":"Select the generated agent customization preset.","--refresh-context":"Rebuild agent context before synchronization.","--refresh":"Refresh the underlying registry or context before reading it.","--agent-sync":"Synchronize agent grounding after writing the context artifact.","--no-agent-sync":"Do not synchronize agent grounding after writing context.","--target":"Select one or more agent customization targets.","--experimental-hooks":"Generate advisory VS Code agent hook design files.","--hydrate-prompts":"Add workspace-specific verification steps to supported prompts.","--project-grounding":"Select the project entrypoint policy: managed, local, or off.","--ci":"Produce a CI-oriented command plan.","--from":"Read the specified baseline, report, or graph artifact.","--from-impact":"Read the specified impact report for verification.","--output":"Write the requested export or report to this path.","--limit":"Bound graph query results (1\u2013100).","--once":"Build the initial observed state and exit.","--graph-stream":"Emit graph snapshot/delta events as NDJSON.","--force":"Replace an existing generated target where supported.","--no-doctor":"Exclude Doctor evidence from a share bundle.","--no-blueprint":"Exclude the reproducibility blueprint from a share bundle.","--include-env":"Include private environment files in an export archive.","--archive-compression":"Select the archive compression format.","--max-download-size":"Bound a remote archive download.","--max-expanded-size":"Bound the expanded archive size.","--download-timeout-ms":"Bound remote archive download time.","--allow-private-network":"Allow private-network archive sources explicitly.","--affected":"Run only projects affected by the selected Git change.","--blast-radius":"Include transitive downstream dependents.","--since":"Select the Git baseline used for affected-project discovery.","--parallel":"Run selected projects concurrently.","--max-workers":"Bound concurrent project workers.","--continue-on-error":"Continue remaining projects after a project failure.","--reuse-passed":"Reuse successful project-stage results where safe.","--no-gates":"Skip Doctor and Readiness pre-run gates.","--allow-breaking":"Allow a verified goal to use breaking dependency changes.","--allow-force":"Allow a verified goal to use force-based repair commands.","--card":"Select the dashboard card whose governed remediation actions should be repaired.","--action-id":"Select one exact governed remediation action.","--project":"Limit the repair transaction to one registered project name.","--proposal":"Read a bounded model repair proposal from a JSON file inside the workspace.","--transaction":"Select one durable repair transaction by id.","--approved-by":"Record the local actor approving the immutable repair plan.","--decision":"Submit one of the exact options exposed by a decision-required transaction.","--max-risk":"Set the maximum approved repair risk: safe, guarded, or invasive.","--no-auto-rollback":"Require a decision instead of automatically restoring a failed transaction.","--no-build":"Do not require build validation for the selected verified goal.","--no-tests":"Do not require test validation for the selected verified goal.","--no-run":"Read current goal evidence without executing verification commands.","--reuse-intelligence":"Reuse a just-completed canonical intelligence run while executing goal-specific checks."},Ir={list:{usage:"workspai workspace list [--json]",summary:"List registered Workspai workspaces.",flags:["--json"],examples:["workspai workspace list","workspai workspace list --json"]},intelligence:{usage:"workspai workspace intelligence run [--for-agent <agent>] [--strict] [--json]",summary:"Run the canonical Workspace Intelligence chain in contract order.",flags:["--workspace","--json","--strict","--for-agent"],subactions:["run"],artifact:a$3.intelligenceRun,examples:["workspai workspace intelligence run --strict","workspai workspace intelligence run --for-agent codex --json"]},model:{usage:"workspai workspace model [--cache|--incremental] [--write] [--strict] [--json]",summary:"Build the canonical workspace model from registered and observed sources.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--cache","--incremental","--write","--strict"],artifact:a$3.model,examples:["workspai workspace model --write --json","workspai workspace model --incremental --write --json"]},"agent-sync":{usage:"workspai workspace agent-sync [--for-agent <agent>] [--target <targets>] [--project-grounding <mode>] [--write]",summary:"Synchronize bounded workspace grounding for supported agent surfaces.",flags:["--workspace","--json","--scope","--for-agent","--write","--dry-run","--strict","--preset","--refresh-context","--refresh","--target","--experimental-hooks","--hydrate-prompts","--project-grounding"],artifact:a$3.agentCustomizationPack,examples:["workspai workspace agent-sync --target all --write --strict","workspai workspace agent-sync --for-agent copilot --dry-run --json"]},"remediation-plan":{usage:"workspai workspace remediation-plan [--ci] [--write] [--json]",summary:"Build a governed repair plan from current workspace evidence.",flags:["--workspace","--json","--include-paths","--ci","--write"],artifact:e$1.artifactRemediationPlan,examples:["workspai workspace remediation-plan --write --json","workspai workspace remediation-plan --ci --json"]},repair:{usage:"workspai workspace repair <capabilities|plan|propose|approve|decide|execute|resume|status|list|rollback|cancel> [--transaction <id>] [--json]",summary:"Run a durable, approval-bound repair transaction through checkpoint, validation, canonical verification, and rollback.",flags:["--workspace","--json","--card","--action-id","--project","--proposal","--transaction","--approved-by","--decision","--max-risk","--allow-breaking","--allow-force","--no-auto-rollback"],subactions:["capabilities","plan","propose","approve","decide","execute","resume","status","list","rollback","cancel"],artifact:a$3.repairTransaction,examples:["workspai workspace repair capabilities --json","workspai workspace repair plan --card doctor --project api --json","workspai workspace repair propose --proposal .workspai/repair/inbox/proposal.json --json","workspai workspace repair approve --transaction repair_123 --approved-by local-user --json","workspai workspace repair decide --transaction repair_123 --decision approve-invasive --json","workspai workspace repair execute --transaction repair_123 --json","workspai workspace repair rollback --transaction repair_123 --json"]},context:{usage:"workspai workspace context [--for-agent <agent>] [--scope <scope>] [--write] [--json]",summary:"Build a bounded, evidence-backed context pack for people and agents.",flags:["--workspace","--json","--for-agent","--scope","--include-evidence","--scan-depth","--write","--agent-sync","--no-agent-sync","--preset","--target","--strict","--project-grounding"],artifact:a$3.agentContext,examples:["workspai workspace context --for-agent codex --write --json","workspai workspace context --scope project:api --json"]},snapshot:{usage:"workspai workspace snapshot [--json]",summary:"Persist the current model as the comparison baseline.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth"],artifact:a$3.snapshot,examples:["workspai workspace snapshot --json"]},diff:{usage:"workspai workspace diff --from <snapshot-or-model|git[:ref]> [--strict] [--json]",summary:"Compare the current model with a trusted model baseline.",flags:["--workspace","--json","--from","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:a$3.diff,examples:["workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","workspai workspace diff --from git --json"]},impact:{usage:"workspai workspace impact --from <diff> [--scope <scope>] [--strict] [--json]",summary:"Calculate the evidence-backed blast radius of the current model change.",flags:["--workspace","--json","--from","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:a$3.impact,examples:["workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json","workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --strict --json"]},verify:{usage:"workspai workspace verify [--from-impact <impact-report>] [--scope <scope>] [--strict] [--json]",summary:"Verify the selected change against contracts, gates, and current evidence.",flags:["--workspace","--json","--from-impact","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:a$3.verify,examples:["workspai workspace verify --strict --json","workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json"]},goal:{usage:"workspai workspace goal <plan|status|verify> <kind|goal-id> [--scope <scope>] [--target <percent>] [--json]",summary:"Plan, resume, and evidence-verify a durable engineering goal for people and agents.",flags:["--workspace","--json","--scope","--target","--allow-breaking","--allow-force","--no-build","--no-tests","--no-run","--reuse-intelligence"],flagDescriptions:{"--target":"Set the required test coverage percentage (0\u2013100)."},subactions:["plan","status","verify"],artifact:a$3.verifiedGoalStatus,examples:["workspai workspace goal plan release-readiness --json","workspai workspace goal plan dependency-security --scope project:api --json","workspai workspace goal plan test-coverage --scope project:web --target 75 --json","workspai workspace goal verify <goal-id> --json"]},graph:{usage:"workspai workspace graph [mode] [query|from] [to] [--json]",summary:"Build, query, prove, compare, or export the workspace graph.",flags:["--workspace","--json","--output","--from","--limit","--include-paths","--include-evidence","--scan-depth","--scope"],subactions:["emit","explain","entities","search","evidence","path","overlay","benchmark","dot","mermaid","jsonld","graphml","gexf"],examples:['workspai workspace graph search "authentication endpoint" --limit 12 --json','workspai workspace graph evidence "GET /users" --json',"workspai workspace graph mermaid"]},watch:{usage:"workspai workspace watch [--once] [--graph-stream] [--json]",summary:"Observe model changes and optionally stream graph deltas.",flags:["--workspace","--json","--once","--graph-stream","--scan-depth"],examples:["workspai workspace watch --once --json","workspai workspace watch --graph-stream"]},sync:{usage:"workspai workspace sync [--project-grounding <mode>] [--json]",summary:"Synchronize canonical workspace registration and project metadata.",flags:["--workspace","--json","--project-grounding"],examples:["workspai workspace sync --json"]},registry:{usage:"workspai workspace registry [--refresh] [--json]",summary:"Inspect the canonical workspace registry summary.",flags:["--workspace","--json","--refresh"],examples:["workspai workspace registry --refresh --json"]},foundation:{usage:"workspai workspace foundation [--force] [--json]",summary:"Create or repair the standard workspace foundation files.",flags:["--workspace","--json","--force"],examples:["workspai workspace foundation --json"]},policy:{usage:"workspai workspace policy [show|status|get|set] [key] [value] [--json]",summary:"Inspect or update workspace governance policy.",flags:["--workspace","--json"],subactions:["show","status","get","set"],examples:["workspai workspace policy get --json"]},contract:{usage:"workspai workspace contract [init|inspect|verify|graph] [--strict] [--json]",summary:"Create, inspect, verify, or project the workspace contract.",flags:["--workspace","--json","--output","--force","--strict"],subactions:["init","inspect","verify","graph"],artifact:e$1.workspaceContract,examples:["workspai workspace contract verify --strict --json","workspai workspace contract graph --json"]},share:{usage:"workspai workspace share [--output <file>] [--json]",summary:"Create a bounded, shareable workspace evidence bundle.",flags:["--workspace","--json","--output","--include-paths","--no-doctor","--no-blueprint"],examples:["workspai workspace share --output workspace-share.json --json"]},export:{usage:"workspai workspace export [--output <archive>] [--archive-compression <format>]",summary:"Export a portable workspace archive.",flags:["--workspace","--json","--output","--include-env","--archive-compression"],examples:["workspai workspace export --output workspace.tar.gz"]},archive:{usage:"workspai workspace archive <inspect|verify|doctor> <source> [safety options] [--json]",summary:"Inspect, verify, or diagnose a portable workspace archive without materializing it.",flags:["--json","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],subactions:["inspect","verify","doctor"],examples:["workspai workspace archive inspect ./workspace.tar.gz --json","workspai workspace archive verify ./workspace.tar.gz --strict --json","workspai workspace archive doctor ./workspace.tar.gz --json"]},hydrate:{usage:"workspai workspace hydrate <source> [--output <directory>] [--dry-run] [--json]",summary:"Hydrate a portable workspace into a controlled destination.",flags:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace hydrate workspace.tar.gz --output ./restored --dry-run --json"]},import:{usage:"workspai workspace import <source> [--output <directory>] [--dry-run] [--json]",summary:"Verify, materialize, register, relink, and reconcile a portable workspace archive safely.",flags:["--json","--output","--dry-run","--strict","--project-grounding","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace import workspace.tar.gz --output ./imported --json"]},connect:{usage:"workspai workspace connect [directory] [--project-grounding <mode>] [--dry-run] [--json]",summary:"Register and reconcile an existing Workspai workspace in place without moving its source.",flags:["--json","--dry-run","--project-grounding"],examples:["workspai workspace connect /path/to/existing-workspace --json"]},run:{usage:"workspai workspace run <stage> [selection and concurrency options] [--json]",summary:"Run a lifecycle stage across selected workspace projects.",flags:["--workspace","--json","--scope","--affected","--blast-radius","--since","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],subactions:["init","test","build","start","<custom-from-context>"],artifact:e$1.workspaceRunLast,examples:["workspai workspace run test --affected --blast-radius --strict","workspai workspace run build --parallel --max-workers 4 --json"]},explain:{usage:"workspai workspace explain [target] [--scope <scope>] [--write] [--json]",summary:"Explain current blockers or a selected workspace target from evidence.",flags:["--workspace","--json","--scope","--write"],artifact:a$3.explain,examples:["workspai workspace explain --write --json"]},why:{usage:"workspai workspace why [target] [--scope <scope>] [--write] [--json]",summary:"Alias the evidence-backed workspace explanation flow.",flags:["--workspace","--json","--scope","--write"],artifact:d$4,examples:["workspai workspace why readiness --json"]},trace:{usage:"workspai workspace trace --from <diff-artifact> [--write] [--json]",summary:"Trace a model change through blast radius and decision gates.",flags:["--workspace","--json","--from","--write"],artifact:e$2,examples:["workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --write --json"]},feedback:{usage:"echo '<event-json>' | workspai workspace feedback record --json",summary:"Record a structured outcome event for the workspace intelligence history.",flags:["--workspace","--json"],subactions:["record"],examples:[`echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | workspai workspace feedback record --json`]},eval:{usage:"workspai workspace eval [init|record|status|report|compare] [arguments] [--json]",summary:"Measure agent/model calls, tool use, tokens, latency, and verified outcome.",flags:["--workspace","--json","--from","--output"],subactions:["init","record","status","report","compare"],artifact:a$3.evaluationLastRun,examples:["workspai workspace eval init repair-readiness workspace-intelligence --json","workspai workspace eval report --output ./evaluation.json --json"]},mcp:{usage:"workspai workspace mcp serve",summary:"Serve bounded, read-mostly workspace evidence over stdio MCP.",flags:["--workspace","--json"],subactions:["serve"],examples:["workspai workspace mcp serve"]},init:{usage:"workspai workspace init [selection and concurrency options] [--json]",summary:"Initialize all selected projects through the workspace fleet runner.",flags:["--workspace","--json","--scope","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],artifact:e$1.workspaceRunLast,examples:["workspai workspace init --parallel --strict"]}};function ss(t){if(t)return Ir[t]}function Uc(t){return t[0]==="workspace"&&!!ss(t[1])&&t.slice(2).some(e=>e==="--help"||e==="-h")}function Hc(t,e){let r=ss(e)?.flagDescriptions?.[t]??_d[t];if(!r)throw new Error(`Workspace action flag has no description: ${t}`);return r}function Bc(t){let e=ss(t);if(!e)throw new Error(`Unknown workspace action: ${t}`);let r=[`Workspai workspace ${t}`,"",e.summary,"","Usage:",` ${e.usage}`];if(e.subactions&&e.subactions.length>0&&r.push("","Modes:",` ${e.subactions.join(" | ")}`),e.flags.length>0){r.push("","Options:");for(let o of e.flags){let n=Hc(o,t);r.push(` ${o.padEnd(24)} ${n}`.trimEnd());}}return e.artifact&&r.push("","Evidence:",` ${e.artifact}`),r.push("","Examples:",...e.examples.map(o=>` ${o}`),""),r.join(`
150
+ `)}var qc="rapidkit-runtime-command-surface-v1";var as=d$9.doctorRemediationPlan.schemaVersion;var zc="workspai-workspace-intelligence-architecture-v1";var Yc={autopilotRelease:d$9.autopilotReleaseLastRun.schemaVersion,workspaceList:"rapidkit-workspace-list-v1",workspaceSync:"rapidkit-workspace-sync-v1",compatibilityMatrix:d$9.compatibilityMatrix.schemaVersion,mcpDesign:d$9.workspaiMcpDesign.schemaVersion,agentHooks:d$9.agentHooks.schemaVersion,projectArchive:"rapidkit-project-archive-v1",workspaceSnapshot:"rapidkit-workspace-snapshot-v1",workspaceSnapshotV2:"rapidkit-workspace-snapshot-v2",infraPlan:d$9.infraPlan.schemaVersion,privateProductManifest:"rapidkit.private-product-manifest.v1",productFactoryPlan:"rapidkit.product-factory-plan.v1",workspaceModelCache:d$9.workspaceModelCache.schemaVersion,workspaceWatchEvent:"workspace-watch-event.v1",doctorProjectScan:"doctor-project-scan-v2",doctorWorkspaceCache:d$9.doctorWorkspaceCache.schemaVersion};var Xc="project-workspace-resolution.v1";function Qc(t){a$5(t,"contracts/project-workspace-resolution.v1.json","Project workspace resolution");}var is="workspai.ingestion-plan.v1",Ko="workspai.ingestion-result.v1";var Zc="contracts/ingestion-result.v1.json";function At(t){return {schemaVersion:is,...t}}var Id="workspai-published-contract-catalog-v1",Od="workspace-graph-stream.v1";function Or(){return {workspaceContract:1,runtimeCommandSurface:qc,cliRuntimeCommandInventory:os,cliOperationResult:a$A,publishedContractCatalog:Id,workspaceArchiveCapabilities:a$z,workspaceArchiveManifest:b$j,workspaceArchiveOperationResult:c$2,ingestionPlan:is,ingestionResult:Ko,projectEntryCapability:Jc,projectWorkspaceLink:d$9.projectWorkspaceLink.schemaVersion,projectWorkspaceResolution:Xc,projectContextAgent:d$9.projectContextAgent.schemaVersion,doctorProjectEvidence:b$i,doctorWorkspaceEvidence:a$y,doctorGraphDiagnosis:d$c,projectTestCoverage:d$9.projectTestCoverage.schemaVersion,verifiedGoal:"workspai.verified-goal.v1",verifiedGoalStatus:b$8.verifiedGoalStatus,workspaceIntelligenceArchitecture:zc,workspaceIntelligenceChain:a$x,workspaceIntelligenceArtifacts:b$8,cliLogEvent:c$c,freshnessMetadata:e$7,factFreshness:g$5,blockerResolution:a$w,workspaceModel:j$4,workspaceImpact:f$5,workspaceVerify:c$b,workspaceContext:a$v,workspaceDependencyGraph:e$6,workspaceKnowledgeGraph:a$u,workspaceGraphStream:Od,workspaceKnowledgeGraphChangeOverlay:a$t,workspaceKnowledgeSearch:a$s,workspaceGraphTokenEfficiency:a$r,modelUsageEvent:a$q,workspaceIntelligenceEvaluation:b$h,workspaceIntelligenceEvaluationComparison:c$a,workspaceIntelligenceHistory:a$p,agentCustomizationPackCapabilities:c$9,agentCustomizationPackReport:b$8.agentCustomizationPack,agentReportsIndex:b$8.agentIndex,workspaceOperationalSkill:a$o,workspaceSkillsIndex:b$g,workspaceExplain:a$n,agentActionOutcome:a$m,doctorRemediationPlan:as,doctorDependencyRepairTransaction:"workspai.doctor-dependency-repair-transaction.v1",artifactRemediationPlan:a$l,studioCardRepairCapabilities:a$k,workspaceRepairProposal:f$4,workspaceRepairCapabilities:h$5,workspaceRepairTransaction:c$8,doctorFixResult:a$j,backendImportStackParitySnapshot:"backend-import-stack-parity-v1",bootstrapCompliance:d$9.bootstrapCompliance.schemaVersion,commandCapabilities:"rapidkit-command-capabilities-v1",createPlannerCapabilities:"rapidkit-create-planner-capabilities-v1",doctorRemediationPlanLegacy:as,extensionCliCompatibility:"rapidkit-extension-cli-compatibility.v1",infraStack:"rapidkit.infra-stack.v1",mirrorOps:d$9.mirrorOps.schemaVersion,moduleLayout:"rapidkit.module-layout.v1",moduleSupport:"rapidkit-module-support-v1",pipelineLastRun:d$9.pipelineLastRun.schemaVersion,transparencyEvidence:d$9.transparencyEvidence.schemaVersion,version:"rapidkit-version-v1",studioBlockerHandoff:"rapidkit-studio-blocker-handoff-v1",workspaceRegistry:d$9.workspaceRegistry.schemaVersion,workspaceRunLast:d$9.workspaceRunLast.schemaVersion,workspaceShareBundle:d$9.workspaceShareBundle.schemaVersion,...Yc}}function Vo(){let t=Or(),e={workspaceContract:"contracts/workspace-contract.v1.json",runtimeCommandSurface:"contracts/runtime-command-surface.v1.json",cliRuntimeCommandInventory:"contracts/cli-runtime-command-inventory.v1.snapshot.json",cliOperationResult:"contracts/cli-operation-result.v1.json",publishedContractCatalog:"contracts/published-contract-catalog.v1.json",workspaceArchiveCapabilities:"contracts/workspace-archive-capabilities.v1.json",workspaceArchiveManifest:"contracts/workspace-archive-manifest.v1.json",workspaceArchiveOperationResult:"contracts/workspace-archive-operation-result.v1.json",ingestionPlan:"contracts/ingestion-plan.v1.json",ingestionResult:"contracts/ingestion-result.v1.json",projectEntryCapability:"contracts/project-entry-capability.v1.json",projectWorkspaceLink:"contracts/project-workspace-link.v1.json",projectWorkspaceResolution:"contracts/project-workspace-resolution.v1.json",projectContextAgent:"contracts/workspace-intelligence/project-context-agent.v1.json",doctorProjectEvidence:"contracts/doctor-project-evidence.v1.json",doctorWorkspaceEvidence:"contracts/doctor-workspace-evidence.v1.json",doctorGraphDiagnosis:"contracts/workspace-intelligence/doctor-graph-diagnosis.v1.json",projectTestCoverage:"contracts/project-test-coverage.v1.json",verifiedGoal:"contracts/workspace-intelligence/verified-goal.v1.json",verifiedGoalStatus:"contracts/workspace-intelligence/verified-goal-status.v1.json",workspaceIntelligenceArchitecture:"contracts/workspace-intelligence-architecture.v1.json",workspaceIntelligenceChain:"contracts/workspace-intelligence-chain.v1.json",workspaceIntelligenceArtifacts:null,cliLogEvent:"contracts/cli-log-event.v1.json",freshnessMetadata:null,factFreshness:"contracts/workspace-intelligence/fact-freshness.v1.json",blockerResolution:"contracts/workspace-intelligence/blocker-resolution.v1.json",workspaceModel:"contracts/workspace-intelligence/workspace-model.v1.json",workspaceImpact:"contracts/workspace-intelligence/workspace-impact.v1.json",workspaceVerify:"contracts/workspace-intelligence/workspace-verify.v1.json",workspaceContext:"contracts/workspace-intelligence/workspace-context.v1.json",workspaceDependencyGraph:"contracts/workspace-intelligence/workspace-dependency-graph.v1.json",workspaceKnowledgeGraph:"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json",workspaceGraphStream:"contracts/workspace-intelligence/workspace-graph-stream.v1.json",workspaceKnowledgeGraphChangeOverlay:"contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json",workspaceKnowledgeSearch:"contracts/workspace-intelligence/workspace-knowledge-search.v1.json",workspaceGraphTokenEfficiency:"contracts/workspace-intelligence/workspace-graph-token-efficiency.v1.json",modelUsageEvent:"contracts/workspace-intelligence/model-usage-event.v1.json",workspaceIntelligenceEvaluation:"contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",workspaceIntelligenceEvaluationComparison:"contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",workspaceIntelligenceHistory:"contracts/workspace-intelligence/workspace-intelligence-history.v1.json",agentCustomizationPackCapabilities:"contracts/agent-customization-pack.v1.json",agentCustomizationPackReport:"contracts/workspace-intelligence/agent-customization-pack-report.v1.json",agentReportsIndex:"contracts/workspace-intelligence/agent-reports-index.v1.json",workspaceOperationalSkill:"contracts/workspace-intelligence/workspace-operational-skill.v1.json",workspaceSkillsIndex:"contracts/workspace-intelligence/workspace-skills-index.v1.json",workspaceExplain:"contracts/workspace-intelligence/workspace-explain.v1.json",agentActionOutcome:"contracts/workspace-intelligence/agent-action-outcome.v1.json",doctorRemediationPlan:"contracts/doctor-remediation-plan.v2.json",doctorDependencyRepairTransaction:"contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json",artifactRemediationPlan:"contracts/artifact-remediation-plan.v1.json",studioCardRepairCapabilities:"contracts/studio-card-repair-capabilities.v1.json",workspaceRepairProposal:"contracts/workspace-intelligence/workspace-repair-proposal.v1.json",workspaceRepairCapabilities:"contracts/workspace-repair-capabilities.v1.json",workspaceRepairTransaction:"contracts/workspace-intelligence/workspace-repair-transaction.v1.json",doctorFixResult:"contracts/workspace-intelligence/doctor-fix-result.v1.json",backendImportStackParitySnapshot:"contracts/backend-import-stack-parity.snapshot.json",bootstrapCompliance:"contracts/bootstrap-compliance.v1.json",commandCapabilities:"contracts/command-capabilities.v1.json",createPlannerCapabilities:"contracts/create-planner-capabilities.v1.json",doctorRemediationPlanLegacy:"contracts/doctor-remediation-plan.v1.json",extensionCliCompatibility:"contracts/extension-cli-compatibility.v1.json",infraStack:"contracts/infra-stack.v1.json",mirrorOps:"contracts/mirror-ops.v1.json",moduleLayout:"contracts/module-layout.v1.json",moduleSupport:"contracts/module-support.v1.json",pipelineLastRun:"contracts/pipeline-last-run.v1.json",transparencyEvidence:"contracts/transparency-evidence.v1.json",version:"contracts/version.v1.json",studioBlockerHandoff:"contracts/workspace-intelligence/studio-blocker-handoff.v1.json",workspaceRegistry:"contracts/workspace-registry.v1.json",workspaceRunLast:"contracts/workspace-run-last.v1.json",workspaceShareBundle:"contracts/workspace-share-bundle.v1.json",autopilotRelease:"contracts/autopilot-release.v1.json",workspaceList:"contracts/workspace-list.v1.json",workspaceSync:"contracts/workspace-sync.v1.json",compatibilityMatrix:"contracts/compatibility-matrix.v1.json",mcpDesign:"contracts/workspace-intelligence/mcp-design.v1.json",agentHooks:"contracts/workspace-intelligence/agent-hooks.v1.json",projectArchive:"contracts/project-archive.v1.json",workspaceSnapshot:"contracts/workspace-snapshot.v1.json",workspaceSnapshotV2:"contracts/workspace-snapshot.v2.json",infraPlan:"contracts/infra-plan.v1.json",privateProductManifest:"contracts/private-product-manifest.v1.json",productFactoryPlan:"contracts/product-factory-plan.v1.json",workspaceModelCache:"contracts/workspace-model-cache.v1.json",workspaceWatchEvent:"contracts/workspace-watch-event.v1.json",doctorProjectScan:"contracts/doctor-project-scan.v2.json",doctorWorkspaceCache:"contracts/doctor-workspace-cache.v2.json"};return Object.fromEntries(Object.entries(t).map(([r,o])=>{let n=e[r];return [r,{schemaVersion:o,contractPath:n,publication:n?r==="runtimeCommandSurface"||r==="cliRuntimeCommandInventory"||r.endsWith("Capabilities")||r.endsWith("Snapshot")||r==="extensionCliCompatibility"||r==="moduleLayout"||r==="moduleSupport"?"capability-contract":"json-schema":"embedded-type",...r==="workspaceIntelligenceArtifacts"?{artifacts:Object.fromEntries(Object.keys(a$3).map(a=>[a,{path:a$3[a],schemaVersion:b$8[a],contractPath:c$7[a]}]))}:{}}]}))}var cs="rapidkit-command-capabilities-v1",el="rapidkit-version-v1";var $d=["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"],Nd={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},Td={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"},Md={tauri:"desktop",electron:"desktop","vscode-extension":"extension",laravel:"api"};function Wd(t){return t[Math.floor(Math.random()*t.length)]}function ls(t){let e=Wd($d),r=j$5(t);if(r){let i=Td[r.id]??"app";return `${e}-${i}`}let o=p$4(t);if(o)return `${e}-${Md[o.id]??"app"}`;let n=a$4(t),a=n?Nd[n.id]??"service":"app";return `${e}-${a}`}async function Jd(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function Gd(t){if(!await O.pathExists(t))return [];let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(o)for(let n of await promises.readdir(o,{withFileTypes:true})){let a=b.join(o,n.name);n.isFile()?e.push(a):n.isDirectory()&&r.push(a);}}return e}async function rl(t,e){await O.outputFile(t,`${JSON.stringify(e,null,2)}
151
+ `,"utf-8");}function nt(t,e){return b.isAbsolute(e)?e:b.join(t,e)}function Kd(t,e){if(!e.trim()||b.isAbsolute(e)||/^[a-zA-Z]:[\\/]/.test(e))throw new Error(`Mirror artifact target must be a non-empty relative path: ${e}`);let r=b.resolve(t),o=b.resolve(r,e),n=b.relative(r,o);if(!n||n.startsWith("..")||b.isAbsolute(n))throw new Error(`Mirror artifact target escapes the managed artifact directory: ${e}`);return o}async function ol(t,e){let r=b.relative(t,e),o=t;for(let a of r.split(b.sep).slice(0,-1)){o=b.join(o,a);let i=await promises.lstat(o).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)break;if(i.isSymbolicLink())throw new Error(`Mirror artifact target traverses a symbolic link: ${o}`);if(!i.isDirectory())throw new Error(`Mirror artifact target parent is not a directory: ${o}`)}let n=await promises.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(n?.isSymbolicLink()||n&&!n.isFile())throw new Error(`Mirror artifact target must be absent or a regular file: ${e}`)}async function Vd(t,e){let r=b.resolve(t),o=b.relative(r,b.resolve(e));if(!o||o.startsWith("..")||b.isAbsolute(o))throw new Error("Managed mirror directory escapes the workspace.");let n=r;for(let a of o.split(b.sep)){n=b.join(n,a);let i=await promises.lstat(n);if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Managed mirror path must contain only real directories: ${n}`)}}function Ud(t,e){if(t.target)return t.target;if(t.source)return b.basename(t.source);if(t.url)try{let r=new URL(t.url).pathname,o=b.basename(r);if(o&&o!=="/")return o}catch{}return `${e}.artifact`}async function Hd(t){let e=s$1(t,"trusted-sources.lock").find(o=>existsSync(o)),r=new Set(["localhost","127.0.0.1"]);if(!e)return r;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));for(let a of n)r.add(a.toLowerCase());}catch{}return r}async function Bd(t,e,r){await O.ensureDir(b.dirname(e)),await new Promise((o,n)=>{let i=(t.startsWith("https://")?ll:cl).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let p=createWriteStream(e);c.pipe(p),p.on("finish",()=>{p.close(),o();}),p.on("error",d=>{n(d);});});i.setTimeout(r,()=>{i.destroy(new Error(`Request timeout after ${r}ms`));}),i.on("error",c=>{n(c);});});}async function qd(t,e,r,o,n){let a=new URL(t),i=JSON.stringify(e),c=a.protocol==="https:"?ll:cl;await new Promise((p,d)=>{let g=c.request({method:"POST",hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:`${a.pathname}${a.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...o?{Authorization:`Bearer ${o}`}:{},...n||{}}},m=>{if(!m.statusCode||m.statusCode<200||m.statusCode>=300){d(new Error(`HTTP ${m.statusCode||"unknown"}`)),m.resume();return}m.resume(),p();});g.setTimeout(r,()=>{g.destroy(new Error(`Request timeout after ${r}ms`));}),g.on("error",m=>{d(m);}),g.write(i),g.end();});}function nl(t){return new Promise(e=>setTimeout(e,t))}async function zd(t,e,r,o){let n=nt(t,e||".workspai/reports/evidence-export-dead-letter.ndjson");return await O.ensureDir(b.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:o,payload:r})}
152
+ `,"utf-8"),n}function Yd(t,e){if(!e?.enabled)return {headers:{}};let r=process.env[e.hmacKeyEnv];if(!r)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let o=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(o,r).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":o}}}async function Xd(t,e,r){let o=(r.algorithm||"sha256").toLowerCase(),n=nt(t,r.publicKeyPath);if(!await O.pathExists(n))return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(o);c.update(i),c.end();let p=Buffer.from(r.signature,"base64"),d=c.verify(a,p),g=createHash("sha256").update(a).digest("hex");return {verified:d,algorithm:o,publicKeyPath:n,publicKeyFingerprint:g,signature:r.signature,message:d?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Attestation verification error: ${a.message}`}}}async function Qd(t,e,r,o){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};let a=r.signaturePath?nt(t,r.signaturePath):null;if(!a||!await O.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=r.certificatePath?nt(t,r.certificatePath):null;c&&i.push("--certificate",c);let p=r.bundlePath?nt(t,r.bundlePath):null;p&&i.push("--bundle",p);let d=r.keyPath?nt(t,r.keyPath):null;d&&i.push("--key",d),r.identity&&i.push("--certificate-identity",r.identity),r.issuer&&i.push("--certificate-oidc-issuer",r.issuer),r.rekorUrl&&i.push("--rekor-url",r.rekorUrl),o.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let g=await execa("cosign",i,{reject:false});return g.exitCode===0?{verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${g.stderr||g.stdout||"unknown error"}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}}catch(g){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${g.message}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}}}async function Zd(t,e){let r=e.algorithm||"sha256",o=nt(t,e.policyPath),n=nt(t,e.signaturePath),a=nt(t,e.publicKeyPath);if(!await O.pathExists(o))return {verified:false,message:`Governance policy bundle not found: ${o}`,policies:null};if(!await O.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await O.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(o,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),p=await promises.readFile(a,"utf-8"),d=createVerify(r);return d.update(i),d.end(),d.verify(p,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function ps(t,e){let r=[],o={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=s$1(t,"mirror-config.json").find(M=>existsSync(M))??p(t,"mirror-config.json"),a=p(t,"mirror.lock"),i=p(t,"mirror","artifacts"),c=p(t,"reports"),p$1=await Hd(t);if(!await O.pathExists(n))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:r,details:o};let d={};try{d=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return r.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:r,details:o}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||d.mode==="offline-only"))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:r,details:o};await O.ensureDir(i);try{await Vd(t,i);}catch(M){return r.push({id:"mirror.root.safety",status:"failed",message:M instanceof Error?M.message:String(M)}),{checks:r,details:o}}let m=Math.max(0,d.prefetch?.retries??2),k=Math.max(0,d.prefetch?.backoffMs??250),y=Math.max(1e3,d.prefetch?.timeoutMs??15e3),j=d.security?.requireAttestation===true,x=d.security?.requireSigstore===true,l=d.security?.requireTransparencyLog===true,P=d.security?.requireSignedGovernance===true,u=d.security?.evidenceExport,h=(process.env.RAPIDKIT_ENV||d.security?.governance?.environment||"dev").toLowerCase(),f=d.security?.governance?.policies||{};if(d.security?.governanceBundle){let M=await Zd(t,d.security.governanceBundle);if(r.push({id:"governance.bundle.verify",status:M.verified?"passed":"failed",message:M.message}),M.verified&&M.policies)f=M.policies,o.governanceBundleVerified=true;else if(P)return {checks:r,details:o}}let v=f[h],C=l||v?.requireTransparencyLog===true,R=[],w=Array.isArray(d.artifacts)?d.artifacts:[],E=[];for(let M=0;M<w.length;M+=1){let _=w[M],S=_.id||`artifact-${M+1}`,J=_.source?nt(t,_.source):null,F=Ud(_,S),W;try{W=Kd(i,F),await ol(i,W);}catch(Se){r.push({id:`mirror.target.${S}`,status:"failed",message:Se instanceof Error?Se.message:String(Se)});continue}let G=false,H=W,Oe=false,fe=async()=>{Oe&&await promises.rm(H,{force:true}).catch(()=>{});},ae={sourceType:"path",source:J||_.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(J&&await O.pathExists(J))await O.ensureDir(b.dirname(W)),H=`${W}.${process.pid}.${randomUUID()}.tmp`,Oe=true,await promises.copyFile(J,H),o.syncedArtifacts+=1,G=true,ae={sourceType:"path",source:J,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},r.push({id:`mirror.sync.${S}`,status:"passed",message:`Mirrored artifact ${S} from source path.`});else if(_.url){let Se="";try{Se=new URL(_.url).hostname.toLowerCase();}catch{r.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Invalid URL for ${S}: ${_.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||p$1.has(Se))){r.push({id:`mirror.prefetch.trust.${S}`,status:"failed",message:`Untrusted mirror host for ${S}: ${Se}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await O.pathExists(W)?(G=true,ae={sourceType:"url",source:_.url,host:Se,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},r.push({id:`mirror.prefetch.${S}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${S}.`})):r.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${S} without an existing mirrored copy.`}),!G))continue;if(!G){await O.ensureDir(b.dirname(W)),H=`${W}.${process.pid}.${randomUUID()}.tmp`,Oe=true;let xe=null,T=0;for(let K=1;K<=m+1;K+=1){T=K;try{await promises.rm(H,{force:true}).catch(()=>{}),await Bd(_.url,H,y),o.syncedArtifacts+=1,G=true,ae={sourceType:"url",source:_.url,host:Se,fetchedAt:new Date().toISOString(),attempts:T,trusted:true},r.push({id:`mirror.prefetch.${S}`,status:"passed",message:T>1?`Prefetched artifact ${S} from ${Se} after ${T} attempts.`:`Prefetched artifact ${S} from ${Se}.`});break}catch(re){if(xe=re,K<=m){await nl(k*K);continue}}}if(!G){await fe(),r.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S} after ${m+1} attempt(s): ${xe?.message||"unknown error"}`});continue}}if(!G){r.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S}.`});continue}}if(!G){_.required||e.offlineMode?r.push({id:`mirror.sync.${S}`,status:"failed",message:`Mirror source missing for ${S}${J?`: ${J}`:""}`}):r.push({id:`mirror.sync.${S}`,status:"skipped",message:`Mirror source not found for optional artifact ${S}.`});continue}let $e=await Jd(H);if(_.sha256&&_.sha256.toLowerCase()!==$e.toLowerCase()){r.push({id:`mirror.verify.${S}`,status:"failed",message:`Checksum mismatch for ${S}.`}),await fe();continue}o.verifiedArtifacts+=1,r.push({id:`mirror.verify.${S}`,status:"passed",message:`Checksum verified for ${S}.`});let We=_.attestation?await Xd(t,H,_.attestation):null;if(_.attestation){if(r.push({id:`mirror.attest.${S}`,status:We?.verified?"passed":"failed",message:We?.message||"Attestation verification failed."}),!We?.verified){await fe();continue}}else if(j){r.push({id:`mirror.attest.${S}`,status:"failed",message:`Attestation is required but missing for ${S}.`}),await fe();continue}else r.push({id:`mirror.attest.${S}`,status:"skipped",message:`No attestation provided for ${S}.`});let Ge=_.attestation?.sigstore,oe=Ge?await Qd(t,H,Ge,{requireTransparencyLog:C}):null;if(Ge){if(r.push({id:`mirror.sigstore.${S}`,status:oe?.verified?"passed":"failed",message:oe?.message||"Sigstore verification failed."}),R.push({artifactId:S,verified:!!oe?.verified,tlogVerified:!!oe?.tlogVerified,identity:oe?.identity||null,issuer:oe?.issuer||null,rekorUrl:oe?.rekorUrl||null,timestamp:new Date().toISOString(),environment:h}),!oe?.verified){await fe();continue}}else if(x){r.push({id:`mirror.sigstore.${S}`,status:"failed",message:`Sigstore attestation is required but missing for ${S}.`}),await fe();continue}else r.push({id:`mirror.sigstore.${S}`,status:"skipped",message:`No Sigstore attestation provided for ${S}.`});if(Ge&&oe?.verified&&v){let Se=v.allowedIdentities||[];if(Se.length>0){let xe=!!oe.identity&&Se.includes(oe.identity);if(r.push({id:`mirror.sigstore.policy.identity.${S}`,status:xe?"passed":"failed",message:xe?`Sigstore identity policy passed for ${S} in ${h}.`:`Sigstore identity policy failed for ${S} in ${h}.`}),!xe){await fe();continue}}let ir=v.allowedIssuers||[];if(ir.length>0){let xe=!!oe.issuer&&ir.includes(oe.issuer);if(r.push({id:`mirror.sigstore.policy.issuer.${S}`,status:xe?"passed":"failed",message:xe?`Sigstore issuer policy passed for ${S} in ${h}.`:`Sigstore issuer policy failed for ${S} in ${h}.`}),!xe){await fe();continue}}let Mt=v.allowedRekorUrls||[];if(Mt.length>0){let xe=!!oe.rekorUrl&&Mt.includes(oe.rekorUrl);if(r.push({id:`mirror.sigstore.policy.rekor.${S}`,status:xe?"passed":"failed",message:xe?`Sigstore Rekor policy passed for ${S} in ${h}.`:`Sigstore Rekor policy failed for ${S} in ${h}.`}),!xe){await fe();continue}}}else v&&r.push({id:`mirror.sigstore.policy.${S}`,status:"skipped",message:`Sigstore governance policy configured for ${h} but no verified Sigstore attestation for ${S}.`});Oe&&(await ol(i,W),await promises.rename(H,W),Oe=false);let Vs=await promises.stat(W);E.push({id:S,path:b.relative(t,W),sha256:$e,size:Vs.size,provenance:ae,attestation:{detached:{provided:!!_.attestation,verified:We?.verified||false,algorithm:We?.algorithm||null,publicKeyPath:We?.publicKeyPath||null,publicKeyFingerprint:We?.publicKeyFingerprint||null,signature:We?.signature||null,verifiedAt:We?.verified?new Date().toISOString():null},sigstore:{provided:!!Ge,verified:oe?.verified||false,tlogVerified:oe?.tlogVerified||false,identity:oe?.identity||null,issuer:oe?.issuer||null,rekorUrl:oe?.rekorUrl||null,bundlePath:oe?.bundlePath||null,certificatePath:oe?.certificatePath||null,signaturePath:oe?.signaturePath||null,verifiedAt:oe?.verified?new Date().toISOString():null}}});}let $=d.retention?.keepLast;if(typeof $=="number"&&$>0){let M=new Set(E.map(S=>b.resolve(t,S.path))),_=(await Gd(i)).filter(S=>!M.has(b.resolve(S)));if(_.length>$){let S=await Promise.all(_.map(async F=>({filePath:F,stat:await promises.stat(F)})));S.sort((F,W)=>W.stat.mtimeMs-F.stat.mtimeMs);let J=S.slice($);for(let F of J)await promises.unlink(F.filePath),o.rotatedFiles+=1;}}r.push({id:"mirror.rotate",status:"passed",message:o.rotatedFiles>0?`Mirror retention rotation removed ${o.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let N={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:d.mode||null,environment:h,artifacts:E};if(await promises.writeFile(a,`${JSON.stringify(N,null,2)}
153
+ `,"utf-8"),o.lockWritten=true,r.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${b.relative(t,a)}.`}),o.transparencyEvidenceRecords=R.length,R.length>0){let M={schemaVersion:d$9.transparencyEvidence.schemaVersion,generatedAt:new Date().toISOString(),environment:h,records:R},_=new Date().toISOString().replace(/[:.]/g,"-"),S=b.join(c,`transparency-evidence-${_}.json`),J=b.join(c,"transparency-evidence.latest.json");if(b$l(`.workspai/reports/${b.basename(S)}`,M),b$l(e$1.transparencyEvidence,M),await O.ensureDir(c),await rl(S,M),await rl(J,M),o.transparencyEvidenceWritten=true,r.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${b.relative(t,J)}.`}),u?.enabled){let F=Math.max(1e3,u.timeoutMs??1e4);if(u.target==="file")if(!u.filePath)r.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let W=nt(t,u.filePath);await O.ensureDir(b.dirname(W)),await promises.appendFile(W,`${JSON.stringify(M)}
154
+ `,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=W,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${W}.`});}catch(W){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${W.message}`});}else if(u.target==="http")if(!u.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let W=Math.max(0,u.retries??0),G=Math.max(0,u.backoffMs??500),H=Yd(M,u.signing);H.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:H.error});try{let Oe=u.authTokenEnv?process.env[u.authTokenEnv]:void 0,fe=false,ae=null;for(let $e=1;$e<=W+1;$e+=1)try{if(H.error)throw new Error(H.error);await qd(u.endpoint,M,F,Oe,H.headers),o.evidenceExported=true,o.evidenceExportTarget=u.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:$e>1?`Transparency evidence exported to HTTP endpoint ${u.endpoint} after ${$e} attempts.`:`Transparency evidence exported to HTTP endpoint ${u.endpoint}.`}),fe=true;break}catch(We){ae=We,$e<=W&&await nl(G*$e);}if(!fe)throw ae||new Error("unknown evidence export error")}catch(Oe){let fe=`Evidence HTTP export failed: ${Oe.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:fe});try{let ae=await zd(t,u.deadLetterPath,M,fe);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${ae}.`});}catch(ae){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${ae.message}`});}}}if(u.failOnError&&r.some(G=>G.status==="failed"&&(G.id==="sigstore.evidence.export.file"||G.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function Uo(t){let e=f$6(t.detection.runtime),r=u$1({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function eu(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function Ho(t){if(t.existingProjectJson?.module_support===true){let e=eu(t.existingProjectJson),r=e?a$4(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}function pl(t){return t.replace(/\\/g,"/")}function tu(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function ru(t,e){let r=pl(b.relative(t,e));return !r||r.startsWith("..")?true:r.split("/").filter(Boolean).some(o=>o==="..")}function $r(t){let e=pl(b.relative(t.workspacePath,t.projectPath)),r=ru(t.workspacePath,t.projectPath),o=tu(t.projectName,b.basename(t.projectPath)),n=r?`external/${o}`:e||o;return {relativePath:e||n,contractRelativePath:n,isExternal:r}}var dl=[a$B,b$k];function ou(t,e){let r=b.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!b.isAbsolute(r)}async function Ze(t){let e=await O__default.realpath(t);for(let r of dl){let o=b.join(t,r),n=await O__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await O__default.realpath(o);if(!ou(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function ul(t){let e=b.basename(t);return dl.includes(e)?(await O__default.lstat(t)).isSymbolicLink():false}var fl={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},au={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"},iu={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},ml=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function us(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function ms(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function Nr(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 zo(t){let e=new Set;for(let r of t)e.add(Nr(r));return [...e].sort((r,o)=>ml.indexOf(r)-ml.indexOf(o))}function cu(t){let e=zo(t).filter(r=>r!=="unknown");if(e.length!==0)return e.length===1?iu[e[0]]:"polyglot"}function gl(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function lu(t,e){return t?"none":e==="strict"?"error":"warning"}function Tr(t){let e=t.ok?void 0:cu(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?gl(e):void 0,ciRecommendedCommand:e?gl(e,{ci:true}):void 0,severity:lu(t.ok,t.mode)}}function _t(t){let e=ms(t.profile),r=zo(t.runtimes),o=t.mode??"warn",n=fl[e];if(n){let a=r.length===0||r.every(i=>us(i)===n);return Tr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:r,message:a?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${r.join(", ")}].`,mode:o})}if(e==="minimal"){let a=r.filter(p=>p!=="unknown"),c=new Set(a.map(p=>us(p))).size<=1;return Tr({ok:c,checkId:"profile.minimal",profile:e,runtimes:r,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${a.join(", ")}].`,mode:o})}return Tr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:r,message:`${e} profile accepts the detected runtime mix.`,mode:o})}function jt(t){let e=ms(t.profile),r=Nr(t.runtime),o=t.mode??"warn",n=fl[e];if(!n||r==="unknown")return Tr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[r],message:r==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:o});let a=us(r)===n;return Tr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:a?[r]:zo([n,r]),message:a?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${au[r]}, but workspace profile is "${e}".`,mode:o})}async function or(t){let e=(await Promise.all(s$1(t,"policies.yml").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "warn";try{return (await O__default.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function nr(t){let e=(await Promise.all(s$1(t,"workspace.json").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "minimal";try{let r=await O__default.readJson(e);return ms(r.profile)}catch{return "minimal"}}async function It(t$1,e={}){let r=new Set,o=[],n=new Set,a=[t$1];for(;a.length>0;){let i=a.pop();if(!i||n.has(i))continue;n.add(i);let c=[];try{c=await A.promises.readdir(i,{withFileTypes:true});}catch{continue}for(let p of c){if(!p.isDirectory()||p.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(p.name))continue;let d=b.join(i,p.name);if(d!==t$1&&j$1(d))continue;if((await Promise.all([...t(d,"context.json"),...t(d,"project.json")].map(async m=>O__default.pathExists(m)))).some(Boolean)){o.push(d);continue}a.push(d);}}for(let i of o){let c=i$2(i);r.add(Nr(j$3(i,c).runtime));}for(let i of await a$C(t$1))r.add(Nr(i.runtime));for(let i of e.additionalRuntimes??[])r.add(Nr(i));return zo(r)}function Yo(t,e={}){let r=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return r?`Recommended: ${r}`:null}function hl(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function du(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return hl(a)||"imported-project"}function bt(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function uu(t){return bt(t)?"git-url":"local-folder"}async function mu(t,e){let r=hl(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=b.join(t,n);if(!await O__default.pathExists(a))return a;o+=1;}}function gu(t,e){let r=b.resolve(t),o=b.resolve(e),n=b.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!b.isAbsolute(n)}function fu(t,e){if(gu(t,e))throw new Error("Import source must be outside the current workspace root.")}function hu(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function yu(t){let e=b.basename(t);return !(await ul(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||hu(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function wu(t$1){await Ze(t$1);for(let e of t(t$1,"project.json"))if(await O__default.pathExists(e))try{return await O__default.readJson(e)}catch{return null}return null}async function ku(t){await Ze(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),o=$r({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=u(t.projectPath,"project.json"),i=u(t.projectPath,"import.json"),c=u(t.projectPath,"import-readiness.json"),p=Ho({existingProjectJson:t.existingProjectJson}),d=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],g=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},m={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:b.basename(t.projectPath),kind:t.projectKind,category:a$e(t.projectKind),project_type:a$e(t.projectKind),runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:p,modules:d,contracts:g,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},k={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:m.name,slug:m.slug,relative_path:n,kind:t.projectKind,category:a$e(t.projectKind),module_support:p},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$e(t.projectKind),confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:p,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},y=Uo({projectName:String(m.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:p,projectPath:t.projectPath,generatedAt:new Date(e)});return await O__default.ensureDir(b.dirname(a)),await O__default.writeJson(a,m,{spaces:2}),await O__default.writeJson(i,k,{spaces:2}),await O__default.writeJson(c,y,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:p}}async function vu(t,e){let r={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,relationship:"imported",importedAt:new Date().toISOString()};await b$e(t,[r]);}async function Pu(t){await O__default.pathExists(t)&&(await Ze(t),await O__default.remove(t));}async function ju(t,e){await Pu(e),await c$3(t,[e]);}async function yl(t){let e=b.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??uu(r),n=t.name??(o==="git-url"?du(r):b.basename(r)),a=await mu(e,n),i=false;try{if(o==="local-folder"){let h=b.resolve(r),f=await O__default.stat(h).catch(()=>null);if(!f||!f.isDirectory())throw new Error("Import source is not a directory.");if(await Ze(h),j$1(h))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");fu(e,h),i=true,await O__default.copy(h,a,{overwrite:false,errorOnExist:true,filter:yu});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$d()});await Ze(a);let c=await wu(a),p=j$3(a,c),d=await b$d(a,c),[g,m]=await Promise.all([nr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):or(e)]),k=jt({profile:g,runtime:p.runtime,subjectLabel:b.basename(a),mode:m}),y=_t({profile:g,runtimes:await It(e,{additionalRuntimes:[p.runtime]}),mode:m}),j=k.ok?y:k;if(!j.ok&&m==="strict")throw new Error(j.message);let x=await ku({workspacePath:e,projectPath:a,sourceType:o,detection:p,existingProjectJson:c,projectKind:d,profileCompatibility:j}),l=$r({workspacePath:e,projectPath:a,projectName:b.basename(a)}),P={ingestionPlan:At({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:b.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:b.basename(a),path:a,relativePath:l.contractRelativePath,stack:p.importStack,runtime:p.runtime,framework:p.key,frameworkDisplayName:p.displayName,supportTier:p.supportTier,moduleSupport:x.moduleSupport,confidence:p.confidence,source:o,projectJsonPath:x.projectJsonPath,importJsonPath:x.importJsonPath,importReadinessPath:x.importReadinessPath,profileCompatibility:j};await vu(e,P);let{syncWorkspaceContract:u}=await import('./workspace-contract-AYFTZIKM.js');return await u({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:P.path,projectName:P.name,relationship:"imported",mode:t.projectGrounding??"managed"}),P}catch(c){if(i)try{await ju(e,a);let{syncWorkspaceContract:p}=await import('./workspace-contract-AYFTZIKM.js');await p({workspacePath:e,strict:true});}catch(p){let d=c instanceof Error?c.message:String(c),g=p instanceof Error?p.message:String(p);throw new Error(`Import failed: ${d}. Rollback also failed: ${g}`)}throw c}}function bu(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Cu(t,e){return b.resolve(t)===b.resolve(e)}async function Su(t$1){await Ze(t$1);for(let e of t(t$1,"project.json")){if(!await O__default.pathExists(e))continue;let r;try{r=JSON.parse((await O__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}async function gs(t,e){let r=b.resolve(t),o=b.resolve(e);await Ze(o);let n=[u(o,"project.json"),u(o,"adopt.json"),u(o,"adopt-readiness.json"),b.join(o,f$2),b.join(o,g$2),b.join(o,h$3),b.join(o,"AGENTS.md"),b.join(o,".gitignore"),p(r,"imported-projects.json")];return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>({path:a,contents:await O__default.pathExists(a)?await O__default.readFile(a):null})))}}function wl(t,e,r){let o=[u(r,"project.json"),u(r,"adopt.json"),u(r,"adopt-readiness.json"),b.join(r,f$2),b.join(r,g$2),b.join(r,h$3),b.join(r,"AGENTS.md"),b.join(r,".gitignore"),p(e,"imported-projects.json")].map(n=>b.resolve(n));if(t.workspacePath!==b.resolve(e)||t.projectPath!==b.resolve(r)||t.files.length!==o.length||t.files.some((n,a)=>b.resolve(n.path)!==o[a]))throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function xu(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,category:a$e(t.projectKind),project_type:a$e(t.projectKind),runtime:t.detection.runtime,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:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function Eu(t,e,r){await Ze(e),wl(r,t,e);let o=[];for(let n of r.files)try{n.contents===null?await O__default.remove(n.path):(await O__default.ensureDir(b.dirname(n.path)),await O__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function fs(t){let e=b.resolve(t.workspacePath),r=b.resolve(t.source),o=await O__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await Ze(r),Cu(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(j$1(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t.rollbackSnapshot??await gs(e,r);wl(n,e,r);let a=await Su(r),i=j$3(r,a),c=await b$d(r,a),p=bu(t.name||(typeof a?.name=="string"?a.name:"")||b.basename(r))||"adopted-project",d=$r({workspacePath:e,projectPath:r,projectName:p}),g=(t.now??new Date).toISOString(),m=u(r,"project.json"),k=u(r,"adopt.json"),y=u(r,"adopt-readiness.json"),j=Ho({existingProjectJson:a}),[x,l]=await Promise.all([nr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):or(e)]),P=jt({profile:x,runtime:i.runtime,subjectLabel:p,mode:l}),u$1=_t({profile:x,runtimes:await It(e,{additionalRuntimes:[i.runtime]}),mode:l}),h=P.ok?u$1:P;if(!h.ok&&l==="strict")throw new Error(h.message);let f=xu({projectName:p,contractRelativePath:d.contractRelativePath,isExternal:d.isExternal,discoveredRelativePath:d.relativePath,detection:i,existingProjectJson:a,projectKind:c,moduleSupport:j,adoptedAt:g}),v={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:g,managed_by:"workspai",mode:"linked",workspace:{name:b.basename(e),contract:e$1.workspaceContract},project:{name:p,relative_path:d.contractRelativePath,...d.isExternal?{}:{discovered_relative_path:d.relativePath},is_external:d.isExternal,kind:c,category:a$e(c),module_support:j},detection:{framework:i.key,framework_display_name:i.displayName,runtime:i.runtime,kind:c,category:a$e(c),confidence:i.confidence,support_tier:i.supportTier,import_stack:i.importStack,source:i.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:j,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}}},C=Uo({projectName:p,relativePath:d.contractRelativePath,projectKind:c,source:"adopted-local",detection:i,moduleSupport:j,projectPath:r,generatedAt:new Date(g)});if(t.dryRun!==true)try{await Ze(r),await O__default.ensureDir(b.dirname(m)),await O__default.writeJson(m,f,{spaces:2}),await O__default.writeJson(k,v,{spaces:2}),await O__default.writeJson(y,C,{spaces:2});let R={name:p,path:r,relativePath:d.contractRelativePath,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:j,confidence:i.confidence,source:"adopted-local",importedAt:g};await b$e(e,[R]);let{syncWorkspaceContract:w}=await import('./workspace-contract-AYFTZIKM.js');await w({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:r,projectName:p,relationship:"adopted",mode:t.projectGrounding??"managed",now:new Date(g)});}catch(R){try{await Eu(e,r,n);let{syncWorkspaceContract:w}=await import('./workspace-contract-AYFTZIKM.js');await w({workspacePath:e,strict:true});}catch(w){throw new AggregateError([R,w],`Adopt failed and rollback was incomplete: ${R instanceof Error?R.message:String(R)}`)}throw R}return {ingestionPlan:At({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t.projectGrounding??"managed"}),name:p,path:r,relativePath:d.relativePath,contractRelativePath:d.contractRelativePath,isExternal:d.isExternal,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:j,confidence:i.confidence,projectJsonPath:m,adoptJsonPath:k,adoptReadinessPath:y,profileCompatibility:h,wroteFiles:t.dryRun!==true}}async function Ru(t){let e=await O__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=b.join(t,r),n=await O__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function Au(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await O__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=b.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$f(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$5&&(await O__default.remove(i),e.push(b.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function vl(t,e){if(await b$f(t,b.basename(t)),!(await g$3(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$h(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function hs(t){let e=b.resolve(t.workspacePath);await Ru(e);let r=At({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!j$1(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return Xo(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$4(e);try{let n=await vl(e,t.projectGrounding??"managed");return Xo(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$6(e,o).catch(()=>{}),n}}async function ys(t){if(t.dryRun){let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=b.resolve(o.outputPath),a=kl(t,n);return Xo(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?b.resolve(t.outputPath):void 0;if(e&&await O__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=b.resolve(o.outputPath);let n=kl(t,r);if(!j$1(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await Au(r);o.manifest?.portableContract&&await O__default.outputJson(b.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await vl(r,t.projectGrounding??"managed");return Xo(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,p,d)=>d.indexOf(c)===p),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$4(r).catch(()=>{}),await O__default.remove(r).catch(()=>{})),o}}function kl(t,e){return At({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function Xo(t,e){let r={schemaVersion:Ko,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$5(r,Zc,"Workspace ingestion result"),r}function Pl(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function jl(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function bl(t){let e=t.trim(),r=e.startsWith("~/")?b.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!bt(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:bt(r)?r:b.resolve(r)};if(bt(r))return {kind:"git-project",source:r};let n=b.resolve(r);return j$1(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var $u=Go,Nu=Fo;function ks(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 Tu(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 sr(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function Mu(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Re(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function Wu(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Rs(t){try{return Wu(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function Js(t$1,e){let r=Re(t$1,"--port")?.trim(),o=t$1[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Re(t$1,"--output")||".",i=b.resolve(e,a,o),c=t(i,"project.json").find(d=>A.existsSync(d))??u(i,"project.json");if(!await O__default.pathExists(c))return;let p=await O__default.readJson(c);await O__default.writeJson(c,{...p,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Sl(t){let e=we(process.cwd()),r=t.trim().toLowerCase();if(!e||!r)return true;try{let[o,n]=await Promise.all([nr(e),or(e)]),a=a$4(r),i=j$5(r),c=p$4(r),p=i?"node":c?.runtime??a?.runtime??"python",d=jt({profile:o,runtime:p,subjectLabel:r,mode:n}),g=_t({profile:o,runtimes:await It(e,{additionalRuntimes:[p]}),mode:n}),m=d.ok?g:d;if(m.ok)return true;let k=Yo(m);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${m.message}`)),k&&console.log(s.gray(`\u{1F4A1} ${k}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${m.message}`)),k&&console.log(s.gray(`\u{1F4A1} ${k}`));}catch{}return true}function Gs(){return j$6()}function xl(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(b.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$5()),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 Du(t){return m$3(b.join(t,".venv"))}async function Lu(t,e){return await ke(t,["--version"],e)===0}async function Nt(t){let e=b.join(t,"go.mod");if(await O__default.pathExists(e))return "go";let r=b.join(t,"pom.xml"),o=b.join(t,"build.gradle"),n=b.join(t,"build.gradle.kts");if(await O__default.pathExists(r)||await O__default.pathExists(o)||await O__default.pathExists(n))return "java";if((await O__default.pathExists(t)?await A.promises.readdir(t,{withFileTypes:true}):[]).some(y=>y.isFile()&&y.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=b.join(t,"src");if(await O__default.pathExists(i)&&(await A.promises.readdir(i,{withFileTypes:true})).some(j=>j.isFile()&&j.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=b.join(t,"Cargo.toml");if(await O__default.pathExists(c))return "rust";let p=b.join(t,"composer.json");if(await O__default.pathExists(p))return "php";let d=b.join(t,"package.json");if(await O__default.pathExists(d))return "node";let g=b.join(t,"pyproject.toml"),m=b.join(t,"requirements.txt"),k=b.join(t,"poetry.lock");return await O__default.pathExists(g)||await O__default.pathExists(m)||await O__default.pathExists(k)?"python":null}async function Fu(t,e={}){let r=e.runCommand??ke;for(let o of e.pythonCandidates??Gs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Gl(t,e={}){let r=e.runCommand??ke;for(let o of e.pythonCandidates??Gs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Ju(t,e={}){let r=e.runCommand??ke,o=m$3(b.join(t,".venv"));if(!await O__default.pathExists(o)){let c=await Gl(t,e);if(c!==0)return c}if(!(await r("poetry",["--version"],t)===0))return 0;let a=await r("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await r("poetry",["env","use",o],t);return i!==0?i:0}async function Gu(t,e={}){let r=e.runCommand??ke,o=m$3(b.join(t,".venv"));if(!await O__default.pathExists(o)){let i=await Gl(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=b.join(t,"requirements.txt");if(await O__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=b.join(t,"pyproject.toml");return await O__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function vs(t,e){return await Ju(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await O__default.pathExists(b.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await Gu(t))}async function Ps(t){let e=await $t("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await Lu(o,t))continue;if(await ke(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function Ku(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Re([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Re([...e],"--java-version"),a=Re([...e],"--spring-boot-version"),i=Re([...e],"--springdoc-version"),c=Re([...e],"--group-id"),p=Re([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(p&&!/^[A-Za-z0-9_.-]+$/.test(p.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Re([...e],"--target-framework"),a=Re([...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 El(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||Ns(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:o}=await import('./create-3NSOY7CA.js');await o(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b$1()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:r}=await b$2([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},{name:"Create it without workspace management",value:"none"}],default:1}]);if(r==="current"){let{registerWorkspaceAtPath:o}=await import('./create-3NSOY7CA.js');await o(process.cwd(),{skipGit:e,yes:false,userConfig:await b$1()});}else r==="none"&&t.push("--no-workspace");}async function Vu(t){await O__default.ensureDir(t);let e=b.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await A.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
155
+ `),async()=>{await o.close().catch(()=>{}),await O__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await O__default.readJson(e).catch(()=>null),a=Number(n?.pid),i=false;if(Number.isInteger(a)&&a>0)try{process.kill(a,0),i=true;}catch(c){i=c.code==="EPERM";}if(!i){await O__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function en(t,e={}){let r$1=b.join(q(),"transactions"),o=await Vu(r$1),n;try{await b$b(r$1),n=await a$a({journalDirectory:r$1});}catch(i){throw await o(),i}let a=new Set([b.join(q(),"workspaces.json"),b.join(r(),"workspaces.json"),a$b(t,g$1),b$c(t,g$1),a$b(t,a$c),b$c(t,a$c),...s$1(t,"imported-projects.json")]);e.projectPath&&(a.add(u(e.projectPath,"project.json")),a.add(u(e.projectPath,"context.json")),a.add(u(e.projectPath,"file-hashes.json")),a.add(u(e.projectPath,"adopt.json")),a.add(u(e.projectPath,"adopt-readiness.json")),a.add(b.join(e.projectPath,f$2)),a.add(b.join(e.projectPath,g$2)),a.add(b.join(e.projectPath,h$3)),a.add(b.join(e.projectPath,"AGENTS.md")),a.add(b.join(e.projectPath,".gitignore")));try{for(let c of a)await n.captureFile(c);e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let i=false;return {registerCompensation:c=>n.registerCompensation(c),commit:async()=>{i||(await n.commit(),i=true,await o());},rollback:async()=>{if(!i){i=true;try{await n.rollback();}finally{await o();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await o(),i}}async function ar(t,e){try{await t.rollback();}catch(r){throw new AggregateError([e,r],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function Lr(t,e,r){if(t.includes("--no-workspace")||t.includes("--dry-run"))return;if(!await O__default.pathExists(e)){f.warn(`Created project path was not found for workspace linking: ${e}`);return}let o=we(e)||we(process.cwd()),n=false,a;if(o)a=await en(o,{projectPath:e});else {o=o$1(),a=await en(o,{projectPath:e,ownedWorkspace:o});try{o=(await Ks()).workspacePath;}catch(c){await ar(a,c);}n=true;}let i="managed";try{await o$2(e);let c=b.relative(o,e);(c.startsWith("..")||b.isAbsolute(c))&&(i=(await fs({source:e,workspacePath:o,name:r})).relationship);let{registerProjectInWorkspaceStrict:d,registerWorkspaceStrict:g}=await import('./workspace-C4UETGY7.js'),{syncWorkspaceContract:m}=await import('./workspace-contract-AYFTZIKM.js');await g(o,b.basename(o)),await d(o,r,e),await m({workspacePath:o,strict:true});let{syncProjectIntelligenceLens:k}=await import('./project-intelligence-lens-ZOAWXYC5.js');await k({workspacePath:o,projectPath:e,projectName:r,relationship:i==="adopted"?"adopted":"managed",mode:"managed"}),await a.commit(),await Fr(o);}catch(c){await ar(a,c);}return n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${i$3}" (${i}).`)),console.log(s.gray(` Registry: ${b.join(q(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${o}`))),o}async function As(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],r=a$4(e),o=t[3];if(!r||r.owner!=="npm")return 1;if(!o)return process.stderr.write(`Usage: ${r.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
156
156
  `),1;try{h$1(o);}catch(m){let k=m instanceof Error?m.message:String(m);return process.stderr.write(`${k}
157
- `),1}let n=Bu(r.id,t);if(n)return process.stderr.write(`${n}
158
- `),1;let a=Ie(t,"--output")||process.cwd(),i=b.resolve(a,o),c=t.includes("--skip-git")||t.includes("--no-git"),p=t.includes("--skip-install"),d=t.includes("--dry-run"),g=false;try{let{default:m}=await import('fs-extra');return await m.pathExists(i)?(process.stderr.write(`\u274C Directory "${i}" already exists
157
+ `),1}let n=Ku(r.id,t);if(n)return process.stderr.write(`${n}
158
+ `),1;let a=Re(t,"--output")||process.cwd(),i=b.resolve(a,o),c=t.includes("--skip-git")||t.includes("--no-git"),p=t.includes("--skip-install"),d=t.includes("--dry-run"),g=false;try{let{default:m}=await import('fs-extra');return await m.pathExists(i)?(process.stderr.write(`\u274C Directory "${i}" already exists
159
159
  `),1):d?(console.log(s.bold(`
160
- ${r.label}`)),console.log(s.gray(` Runtime: ${r.runtime}`)),console.log(s.gray(` Target: ${i}`)),console.log(s.gray(" Dry run: no files or workspace state will be changed.")),0):(await m.ensureDir(b.dirname(i)),await m.ensureDir(i),g=true,await e$3(r,{projectName:o,projectPath:i,args:t,skipGit:c,skipInstall:p}),await Vs(t,process.cwd()),await Gr(t,i,o),0)}catch(m){if(g){let{default:k}=await import('fs-extra');await k.remove(i).catch(()=>{});}return process.stderr.write(`Workspai ${r.id} generator failed: ${m?.message??m}
161
- `),1}}async function Ol(t){let e=j$5(t[2]);if(!e)return 1;let r;try{let o=await n$1({args:t});return o.dryRun||(r=o.projectPath,await Gr(t,o.projectPath,o.projectName)),0}catch(o){return r&&await O__default.remove(r).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${o?.message??o}
160
+ ${r.label}`)),console.log(s.gray(` Runtime: ${r.runtime}`)),console.log(s.gray(` Target: ${i}`)),console.log(s.gray(" Dry run: no files or workspace state will be changed.")),0):(await m.ensureDir(b.dirname(i)),await m.ensureDir(i),g=true,await e$3(r,{projectName:o,projectPath:i,args:t,skipGit:c,skipInstall:p}),await Js(t,process.cwd()),await Lr(t,i,o),0)}catch(m){if(g){let{default:k}=await import('fs-extra');await k.remove(i).catch(()=>{});}return process.stderr.write(`Workspai ${r.id} generator failed: ${m?.message??m}
161
+ `),1}}async function Rl(t){let e=j$5(t[2]);if(!e)return 1;let r;try{let o=await n$1({args:t});return o.dryRun||(r=o.projectPath,await Lr(t,o.projectPath,o.projectName)),0}catch(o){return r&&await O__default.remove(r).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${o?.message??o}
162
162
  `),t[3]||process.stderr.write(`Usage: ${m$2(e.id)}
163
- `),1}}async function $l(t){let e=p$4(t[2]);if(!e)return 1;let r;try{let o=await s$3(t);return o.dryRun||(r=o.projectPath,await Gr(t,o.projectPath,o.projectName)),0}catch(o){return r&&await O__default.remove(r).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${o?.message??o}
163
+ `),1}}async function Al(t){let e=p$4(t[2]);if(!e)return 1;let r;try{let o=await s$3(t);return o.dryRun||(r=o.projectPath,await Lr(t,o.projectPath,o.projectName)),0}catch(o){return r&&await O__default.remove(r).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${o?.message??o}
164
164
  `),t[3]||process.stderr.write(`Usage: ${r$2(e.kitId)}
165
- `),1}}async function tn(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\`.
165
+ `),1}}async function Qo(t,e){if(t.includes("--json"))return process.stderr.write("Workspai CLI offline fallback does not support --json for `create` commands.\nInstall Python 3.10+ and retry the same command.\n"),1;if(t[0]!=="create")return 1;if(t[1]!=="project")return process.stderr.write(`Workspai CLI could not run the Python core engine for \`create\`.
166
166
  Reason: ${e}.
167
167
  Install Python 3.10+ to use the interactive wizard and full kit catalog.
168
168
  `),1;let n=t[2],a=t[3];if(!n||!a)return process.stderr.write(`Usage: npx workspai create project <kit> <name> [--output <dir>]
169
169
  Tip: offline fallback supports only fastapi* and nestjs* kits.
170
- `),1;let i=Fu(n);if(!i)return process.stderr.write(`Workspai CLI could not run the Python core engine to create this kit.
170
+ `),1;let i=Mu(n);if(!i)return process.stderr.write(`Workspai CLI could not run the Python core engine to create this kit.
171
171
  Reason: ${e}.
172
172
  Requested kit: ${n}
173
173
  Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
174
174
  Install Python 3.10+ to access all kits.
175
- `),1;let c=Ie(t,"--output")||process.cwd(),p=b.resolve(c,a),d=false,g=t.includes("--skip-git")||t.includes("--no-git"),m=t.includes("--skip-install");try{if(await O__default.ensureDir(b.dirname(p)),await O__default.pathExists(p))return process.stderr.write(`\u274C Directory "${p}" already exists
176
- `),1;let k="pip",w=Pe(process.cwd());if(w)try{let{readWorkspaceMarker:x}=await import('./workspace-marker-7NHMDIRL.js'),l=await x(w);l?.metadata?.npm?.installMethod&&(k=l.metadata.npm.installMethod,f.debug(`Detected workspace engine: ${k}`));}catch(x){f.debug("Failed to read workspace marker",x);}else f.debug("No workspace found, using default engine: pip");await O__default.ensureDir(p),d=true;let{generateDemoKit:j}=await import('./demo-kit-KHH63TNA.js');return await j(p,{project_name:a,template:i,kit_name:n,skipGit:g,skipInstall:m,engine:k}),await Vs(t,process.cwd()),await Gr(t,p,a),0}catch(k){return d&&await O__default.remove(p).catch(()=>{}),process.stderr.write(`Workspai CLI offline fallback failed: ${k?.message??k}
177
- `),1}}function zu(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("Workspai native create is not available for this request yet.")}
175
+ `),1;let c=Re(t,"--output")||process.cwd(),p=b.resolve(c,a),d=false,g=t.includes("--skip-git")||t.includes("--no-git"),m=t.includes("--skip-install");try{if(await O__default.ensureDir(b.dirname(p)),await O__default.pathExists(p))return process.stderr.write(`\u274C Directory "${p}" already exists
176
+ `),1;let k="pip",y=we(process.cwd());if(y)try{let{readWorkspaceMarker:x}=await import('./workspace-marker-7NHMDIRL.js'),l=await x(y);l?.metadata?.npm?.installMethod&&(k=l.metadata.npm.installMethod,f.debug(`Detected workspace engine: ${k}`));}catch(x){f.debug("Failed to read workspace marker",x);}else f.debug("No workspace found, using default engine: pip");await O__default.ensureDir(p),d=true;let{generateDemoKit:j}=await import('./demo-kit-KHH63TNA.js');return await j(p,{project_name:a,template:i,kit_name:n,skipGit:g,skipInstall:m,engine:k}),await Js(t,process.cwd()),await Lr(t,p,a),0}catch(k){return d&&await O__default.remove(p).catch(()=>{}),process.stderr.write(`Workspai CLI offline fallback failed: ${k?.message??k}
177
+ `),1}}function Uu(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("Workspai native create is not available for this request yet.")}
178
178
  `),process.stderr.write(s.gray(`Requested: ${e}
179
179
  `)),process.stderr.write(s.gray(`Lane: ${t.lane} (${t.status})
180
180
  `)),process.stderr.write(s.gray(`Reason: ${t.reason}
181
181
  `)),t.officialCommands?.length){process.stderr.write(s.gray(`Official generator candidates:
182
182
  `));for(let r of t.officialCommands)process.stderr.write(s.gray(` - ${r}
183
- `));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx workspai adopt <project-path>` to add Workspace Intelligence.\n"));}function Nl(){console.log(`Usage: npx workspai create project <kit> <name> [options]
183
+ `));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx workspai adopt <project-path>` to add Workspace Intelligence.\n"));}function _l(){console.log(`Usage: npx workspai create project <kit> <name> [options]
184
184
 
185
185
  Scaffold a project and register it with Workspace Intelligence.
186
186
 
@@ -223,7 +223,7 @@ Notes:
223
223
  Turning the current folder into a workspace creates only the Workspai foundation;
224
224
  it does not install the optional Python engine.
225
225
  Python-backed kits delegate execution to RapidKit Core when needed, but the
226
- Workspai CLI owns the command UX, workspace registration, and artifacts.`);}function Yu(){console.log(`Usage: npx workspai create workspace [name] [options]
226
+ Workspai CLI owns the command UX, workspace registration, and artifacts.`);}function Hu(){console.log(`Usage: npx workspai create workspace [name] [options]
227
227
 
228
228
  Create a Workspai workspace and initialize Workspace Intelligence files.
229
229
 
@@ -247,7 +247,7 @@ Mental model:
247
247
  \u2193
248
248
  Workspace Intelligence
249
249
  \u2193
250
- Developers \xB7 CI \xB7 IDEs \xB7 AI Agents`);}function Xu(){console.log(`Usage: npx workspai create <workspace|project> [options]
250
+ Developers \xB7 CI \xB7 IDEs \xB7 AI Agents`);}function Bu(){console.log(`Usage: npx workspai create <workspace|project> [options]
251
251
 
252
252
  Create a workspace or scaffold a project into Workspace Intelligence.
253
253
 
@@ -260,75 +260,75 @@ Shortcuts:
260
260
 
261
261
  Run:
262
262
  npx workspai create workspace --help
263
- npx workspai create project --help`);}function Qu(t){let e=t[2]??"<kit>",r=t[3]??"<name>",o=Ie(t,"--output")||process.cwd();console.log("Workspai create project dry run (Dry-run mode)"),console.log(` kit: ${e}`),console.log(` name: ${r}`),console.log(` output: ${b.resolve(o)}`),console.log(" execution: RapidKit Core bridge"),console.log(" writes: none"),console.log(""),console.log("Run without --dry-run to scaffold the project.");}async function $s(t){if(t[0]==="create"&&(t.includes("--help")||t.includes("-h")||t.includes("help")))return t[1]==="project"?Nl():t[1]==="workspace"?Yu():Xu(),0;let e$1=t[0]==="create"&&t[1]==="frontend",r=l$1(t);if(r&&(t=r),e$1&&!k$1(t[2]))return process.stderr.write(`Unknown frontend generator: ${t[2]?.replace(/^frontend\./,"")}
263
+ npx workspai create project --help`);}function qu(t){let e=t[2]??"<kit>",r=t[3]??"<name>",o=Re(t,"--output")||process.cwd();console.log("Workspai create project dry run (Dry-run mode)"),console.log(` kit: ${e}`),console.log(` name: ${r}`),console.log(` output: ${b.resolve(o)}`),console.log(" execution: RapidKit Core bridge"),console.log(" writes: none"),console.log(""),console.log("Run without --dry-run to scaffold the project.");}async function _s(t){if(t[0]==="create"&&(t.includes("--help")||t.includes("-h")||t.includes("help")))return t[1]==="project"?_l():t[1]==="workspace"?Hu():Bu(),0;let e$1=t[0]==="create"&&t[1]==="frontend",r=l$1(t);if(r&&(t=r),e$1&&!k$1(t[2]))return process.stderr.write(`Unknown frontend generator: ${t[2]?.replace(/^frontend\./,"")}
264
264
  `),process.stderr.write(`Usage: ${m$2()}
265
- `),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return tn(t,"PYTHON_NOT_FOUND");let o=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace","--here"]);if(t[0]==="create"&&(!t[1]||t[1].startsWith("-"))){let n=t.includes("--yes")||t.includes("-y"),a$1=t.slice(1),i;if(!process.stdin.isTTY||n)i="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."));else {process.stdin.isTTY&&a("create");let p=Pe(process.cwd()),d=p?b.basename(p):null;i=(await b$2([{type:"rawlist",name:"createTarget",message:d?`What would you like to add to ${d}?`:"What would you like to set up?",choices:Sl(d)}])).createTarget;}if(i==="existing"){let p=Pe(process.cwd()),{source:d}=await b$2([xl()]),g=El(d);if(g.kind==="workspace-archive"){let k=await vs({archivePathOrUrl:g.source,projectGrounding:"managed"});console.log(s.green(`\u2714 Workspace imported and registered: ${k.workspacePath}`));for(let w of k.warnings)console.log(s.yellow(` \u26A0 ${w}`));return 0}if(g.kind==="git-project")return await Ds(g.source,{workspace:p??void 0});if(g.kind==="local-workspace"){let k=await ks({workspacePath:g.source,projectGrounding:"managed"});console.log(s.green(`\u2714 Workspace connected: ${k.workspacePath}`));for(let w of k.warnings)console.log(s.yellow(` \u26A0 ${w}`));return 0}let{existingProjectMode:m}=await b$2([{type:"rawlist",name:"existingProjectMode",message:"How should Workspai add this project?",choices:[{name:"Keep it where it is (recommended)",value:"link"},{name:"Copy it into the workspace",value:"copy"}]}]);return m==="link"?await ep(g.source,{workspace:p??void 0,projectGrounding:"managed"}):await Ds(g.source,{workspace:p??void 0,projectGrounding:"managed"})}let c=["create",i,...a$1];return await $s(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=t.includes("--skip-python-engine")||t.includes("--no-python-engine"),c=t.includes("--dry-run"),p=t[2]&&!t[2].startsWith("-")?t[2]:void 0,d=Ie(t,"--install-method"),g=d==="poetry"||d==="venv"||d==="pipx"?d:void 0,m$1=Ie(t,"--profile"),k=m$1==="minimal"||m$1==="java-only"||m$1==="go-only"||m$1==="dotnet-only"||m$1==="python-only"||m$1==="node-only"||m$1==="polyglot"||m$1==="enterprise"?m$1:void 0,w=p;if(w||(n?w="my-workspace":(process.stdin.isTTY&&a("create workspace"),w=(await b$2([{type:"input",name:"workspaceName",message:"Workspace name:",default:"my-workspace"}])).workspaceName)),!w||!w.trim())return process.stderr.write(`Workspace name is required.
266
- `),1;try{h$1(w);}catch(f){if(f instanceof a$1)return process.stderr.write(`${f.message}
267
- `),1;throw f}let j$1=await j(t,{hasYes:n}),x=h$2(w.trim(),{argv:t,outputParent:j$1});c||await O__default.ensureDir(b.dirname(x));let l=m(w.trim());if(!c&&(i$1(l,x,{outputParent:j$1})&&l&&await O__default.pathExists(l)||await O__default.pathExists(x)))return process.stderr.write(`\u274C Workspace "${w}" already exists
265
+ `),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return Qo(t,"PYTHON_NOT_FOUND");let o=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace","--here"]);if(t[0]==="create"&&(!t[1]||t[1].startsWith("-"))){let n=t.includes("--yes")||t.includes("-y"),a$1=t.slice(1),i;if(!process.stdin.isTTY||n)i="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."));else {process.stdin.isTTY&&a("create");let p=we(process.cwd()),d=p?b.basename(p):null;i=(await b$2([{type:"rawlist",name:"createTarget",message:d?`What would you like to add to ${d}?`:"What would you like to set up?",choices:Pl(d)}])).createTarget;}if(i==="existing"){let p=we(process.cwd()),{source:d}=await b$2([jl()]),g=bl(d);if(g.kind==="workspace-archive"){let k=await ys({archivePathOrUrl:g.source,projectGrounding:"managed"});console.log(s.green(`\u2714 Workspace imported and registered: ${k.workspacePath}`));for(let y of k.warnings)console.log(s.yellow(` \u26A0 ${y}`));return 0}if(g.kind==="git-project")return await Ts(g.source,{workspace:p??void 0});if(g.kind==="local-workspace"){let k=await hs({workspacePath:g.source,projectGrounding:"managed"});console.log(s.green(`\u2714 Workspace connected: ${k.workspacePath}`));for(let y of k.warnings)console.log(s.yellow(` \u26A0 ${y}`));return 0}let{existingProjectMode:m}=await b$2([{type:"rawlist",name:"existingProjectMode",message:"How should Workspai add this project?",choices:[{name:"Keep it where it is (recommended)",value:"link"},{name:"Copy it into the workspace",value:"copy"}]}]);return m==="link"?await Yl(g.source,{workspace:p??void 0,projectGrounding:"managed"}):await Ts(g.source,{workspace:p??void 0,projectGrounding:"managed"})}let c=["create",i,...a$1];return await _s(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=t.includes("--skip-python-engine")||t.includes("--no-python-engine"),c=t.includes("--dry-run"),p=t[2]&&!t[2].startsWith("-")?t[2]:void 0,d=Re(t,"--install-method"),g=d==="poetry"||d==="venv"||d==="pipx"?d:void 0,m$1=Re(t,"--profile"),k=m$1==="minimal"||m$1==="java-only"||m$1==="go-only"||m$1==="dotnet-only"||m$1==="python-only"||m$1==="node-only"||m$1==="polyglot"||m$1==="enterprise"?m$1:void 0,y=p;if(y||(n?y="my-workspace":(process.stdin.isTTY&&a("create workspace"),y=(await b$2([{type:"input",name:"workspaceName",message:"Workspace name:",default:"my-workspace"}])).workspaceName)),!y||!y.trim())return process.stderr.write(`Workspace name is required.
266
+ `),1;try{h$1(y);}catch(f){if(f instanceof a$1)return process.stderr.write(`${f.message}
267
+ `),1;throw f}let j$1=await j(t,{hasYes:n}),x=h$2(y.trim(),{argv:t,outputParent:j$1});c||await O__default.ensureDir(b.dirname(x));let l=m(y.trim());if(!c&&(i$1(l,x,{outputParent:j$1})&&l&&await O__default.pathExists(l)||await O__default.pathExists(x)))return process.stderr.write(`\u274C Workspace "${y}" already exists
268
268
  `),l&&l!==x&&process.stderr.write(` Found at: ${l}
269
- `),1;let P=await b$1(),u=P.author||process.env.USER||"Workspai User";if(!n){let f=await b$2([{type:"input",name:"author",message:"Author name:",default:u}]);f.author?.trim()&&(u=f.author.trim());}let{createProject:h}=await import('./create-R6A7EHQZ.js');return await h(w,{skipGit:a$2,skipPythonEngine:i,yes:n,dryRun:c,userConfig:{...P,author:u},installMethod:g,profile:k,parentDirectory:b.dirname(x)}),0}catch(n){return process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
270
- `),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return Nl(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitChoice:w}=await b$2([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$i()}]);if(d$1(w)||k$1(w)||q$1(w)){let l=us(w),{projectName:P}=await b$2([{type:"input",name:"projectName",message:"Project name:",default:l,validate:v=>v.trim().length>0||"Project name is required"}]),u=t.slice(2).filter(v=>v.startsWith("-")),h=["create","project",w,P.trim(),...u];return await Al(w)?(await Il(h),k$1(w)?await Ol(h):q$1(w)?await $l(h):await Os(h)):1}let j=us(w),{projectName:x}=await b$2([{type:"input",name:"projectName",message:"Project name:",default:j,validate:l=>l.trim().length>0||"Project name is required"}]);t.splice(2,0,w,x.trim());}let a$1=t[2],i=c$6({kitId:a$1,framework:a$1,runtime:a$1});if(d$a(i))return zu(i),1;if(!await Al(t[2]||""))return 1;if(await Il(t),d$1(t[2]))return await Os(t);if(k$1(t[2]))return await Ol(t);if(q$1(t[2]))return await $l(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 Qu(t),0;let p=[...t.filter(w=>{let j=w.split("=")[0];return !o.has(w)&&!o.has(j)})],d=Pe(process.cwd()),k=t.includes("--skip-install")||!!d?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$b();let w=await e(p,{cwd:process.cwd(),env:k});if(w===0&&d&&!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"))),w===0){await Vs(t,process.cwd());let j=t[3],x=Ie(t,"--output")||process.cwd(),l=j?b.resolve(x,j):void 0,P=j&&l?await Gr(t,l,j).catch(async u=>{throw await O__default.remove(l).catch(()=>{}),u}):d;if(P)try{if(j&&l){let u=b.join(P,".python-version"),h=b.join(l,".python-version");if(A.existsSync(u)&&A.existsSync(l)){let f$1=A.readFileSync(u,"utf-8");A.writeFileSync(h,f$1.trim()+`
271
- `),f.debug(`Synced Python version ${f$1.trim()} from workspace to ${j}`);}}}catch(u){f.debug("Could not sync Python version from workspace:",u);}}return w}catch(w){let j=js(w);return j?await tn(t,j):(process.stderr.write(`Workspai failed to run the Python core engine: ${w?.message??w}
272
- `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$b();let n=await e(t,{cwd:process.cwd()});if(n===0){let a=Pe(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-B53XH35L.js');await i(a,true);}}return n}catch(n){let a=js(n);return a?await tn(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
273
- `),1)}return await d$b(),await e(t,{cwd:process.cwd()})}catch(n){let a=js(n);return a?await tn(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
274
- `),1)}}var Tl=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],Zu=[...h$5,"autopilot","pipeline","import","adopt","snapshot","ai","config","product","infra","shell","commands"],em=["init"],tm=q$2,Ml=[...tm,...r$1];function rm(t){return !!t&&Du.includes(t)}function Ns(t){let e=t[0],r=t[1];return e==="project"&&(r==="--help"||r==="-h"||r==="help")?true:Wu.some(([o,n])=>e!==o?false:r?r===n:true)}function Jr(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?Ns(t):rm(t[0])||Ns(t)}function om(t){return !!t&&Zu.includes(t)}function Wl(t){return om(t[0])||Ns(t)}function Dl(t){return !!t&&is.includes(t)}async function Ll(t,e){switch(t){case "bootstrap":return Pm(e);case "setup":return jm(e);case "cache":return Cm(e);case "mirror":return xm(e);default:{let r=t;throw new Error(`Unreachable npm-only manual command: ${String(r)}`)}}}function nm(t=process.env){let e=t.npm_config_user_agent||"",r=t.npm_execpath||"",o=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(r)||o==="exec"||o==="x"}function Bl(t={}){let e=w(process.cwd());if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai project command capabilities")),console.log(s.gray(`Project: ${e.projectRoot??"not detected"}`)),console.log(s.gray(`Runtime: ${e.runtime} (${e.runtimeSupportTier}) | Framework: ${e.frameworkDisplayName} (${e.frameworkSupportTier}) | Module support: ${e.moduleSupport?"yes":"no"}`)),console.log(s.gray(`Doctor support: ${e.runtimeDoctorSupport}`)),console.log(""),console.log(s.green(`Supported: ${e.supportedCommands.join(", ")||"none"}`)),console.log(s.yellow(`Global: ${e.globalCommands.join(", ")||"none"}`)),console.log(s.red(`Unsupported: ${e.unsupportedCommands.join(", ")||"none"}`));}function sm(){return {schemaVersion:nl,cli:"workspai",version:i(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:ds,contracts:Tr(),contractCatalog:Bo()}}function am(){let t=Uc(de),e=[...t.topLevelCommands],r=[...a$9].filter(i=>!e.includes(i)),o=["init","dev","start","build","test","lint","format","help"],n=[...$r],a=[...Go];return {schemaVersion:ds,scope:"global",cli:"workspai",version:i(),cwd:process.cwd(),contracts:Tr(),contractCatalog:Bo(),commands:{npmOwned:e,coreBacked:r,projectScoped:o},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...r.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...o.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function im(t={}){let e=am();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(Hc(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 Ts(t){return y(t)?(Bl({json:t.includes("--json")||t.includes("--ci")}),true):false}function Ms(t){let e=w(process.cwd());if(!e.projectRoot)return false;let r=x(t,process.cwd());if(!r||r.status!=="unsupported")return false;console.error(s.red(z(r,e))),process.exit(1);}function Ye(t){return A.existsSync(b.join(t,".workspai-workspace"))||A.existsSync(b.join(t,".workspai","workspace.json"))||A.existsSync(b.join(t,".rapidkit-workspace"))||A.existsSync(b.join(t,".rapidkit","workspace.json"))}function ql(t$1){let e=t$1;for(;;){let r=t(e,"context.json").find(n=>A.existsSync(n));if(r)return r;let o=b.dirname(e);if(o===e)break;e=o;}return null}function Ws(t){let e=t,r=b.resolve(tmpdir());for(;;){let o=[b.join(e,".workspai-workspace"),b.join(e,".rapidkit-workspace")].find(a=>A.existsSync(a));if(o&&b.resolve(e)!==r)return o;let n=b.dirname(e);if(n===e)break;e=n;}return null}function Pe(t){let e=b$6({startPath:t});return !e||b.resolve(e.workspacePath)===b.resolve(tmpdir())?null:e.workspacePath}function zl(t){try{let r=b$6({startPath:t,strict:true})?.workspacePath??null;return {workspacePath:r&&b.resolve(r)!==b.resolve(tmpdir())?r:null,error:null}}catch(e){if(e instanceof a$2&&e.code==="project.workspace.unlinked")return {workspacePath:null,error:null};if(e instanceof a$2)return {workspacePath:null,error:e};throw e}}async function Kr(t,e){try{let{syncWorkspaceConsumerArtifacts:r}=await import('./workspace-onboarding-2B7CYZ5H.js');await r(t,{silent:e?.silent});}catch(r){e?.silent||(console.log(s.yellow(`\u26A0\uFE0F Workspace consumer sync skipped: ${r.message}`)),console.log(s.gray(" Retry: npx workspai workspace agent-sync --write --refresh-context --preset enterprise")));}}async function cm(t,e=process.cwd(),r=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$4(r))return {detected:false};let n=p$1(e,r);for(let a of n){if(!await O__default.pathExists(a))continue;let i=a.toLowerCase();if(i.endsWith("rapidkit.cmd")||i.endsWith("rapidkit.exe"))return {detected:true,candidatePath:a,reason:"Found workspace-local rapidkit launcher on Windows."}}return {detected:false}}function lm(t){let e=t;for(;;){let r=b.join(e,".rapidkit-workspace"),o=b.join(e,".rapidkit","workspace.json");if(!A.existsSync(r)&&A.existsSync(o))return e;let n=b.dirname(e);if(n===e)break;e=n;}return null}var Yl={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function pm(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Fr(t,e){let r=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return r?r[1]==="true":Yl[e]}function Fl(t){let e=t??"";return {mode:pm(e),dependency_sharing_mode:Xl(e),rules:{enforce_workspace_marker:Fr(e,"enforce_workspace_marker"),enforce_toolchain_lock:Fr(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Fr(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Fr(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Fr(e,"require_mirror_lock_for_offline")}}}function Jl(t,e,r){let o=`${e}: ${r}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${o}
269
+ `),1;let P=await b$1(),u=P.author||process.env.USER||"Workspai User";if(!n){let f=await b$2([{type:"input",name:"author",message:"Author name:",default:u}]);f.author?.trim()&&(u=f.author.trim());}let{createProject:h}=await import('./create-3NSOY7CA.js');return await h(y,{skipGit:a$2,skipPythonEngine:i,yes:n,dryRun:c,userConfig:{...P,author:u},installMethod:g,profile:k,parentDirectory:b.dirname(x)}),0}catch(n){return process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
270
+ `),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return _l(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitChoice:y}=await b$2([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$i()}]);if(d$1(y)||k$1(y)||q$1(y)){let l=ls(y),{projectName:P}=await b$2([{type:"input",name:"projectName",message:"Project name:",default:l,validate:v=>v.trim().length>0||"Project name is required"}]),u=t.slice(2).filter(v=>v.startsWith("-")),h=["create","project",y,P.trim(),...u];return await Sl(y)?(await El(h),k$1(y)?await Rl(h):q$1(y)?await Al(h):await As(h)):1}let j=ls(y),{projectName:x}=await b$2([{type:"input",name:"projectName",message:"Project name:",default:j,validate:l=>l.trim().length>0||"Project name is required"}]);t.splice(2,0,y,x.trim());}let a$1=t[2],i=c$6({kitId:a$1,framework:a$1,runtime:a$1});if(d$a(i))return Uu(i),1;if(!await Sl(t[2]||""))return 1;if(await El(t),d$1(t[2]))return await As(t);if(k$1(t[2]))return await Rl(t);if(q$1(t[2]))return await Al(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 qu(t),0;let p=[...t.filter(y=>{let j=y.split("=")[0];return !o.has(y)&&!o.has(j)})],d=we(process.cwd()),k=t.includes("--skip-install")||!!d?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$b();let y=await e(p,{cwd:process.cwd(),env:k});if(y===0&&d&&!t.includes("--skip-install")&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init"))),y===0){await Js(t,process.cwd());let j=t[3],x=Re(t,"--output")||process.cwd(),l=j?b.resolve(x,j):void 0,P=j&&l?await Lr(t,l,j).catch(async u=>{throw await O__default.remove(l).catch(()=>{}),u}):d;if(P)try{if(j&&l){let u=b.join(P,".python-version"),h=b.join(l,".python-version");if(A.existsSync(u)&&A.existsSync(l)){let f$1=A.readFileSync(u,"utf-8");A.writeFileSync(h,f$1.trim()+`
271
+ `),f.debug(`Synced Python version ${f$1.trim()} from workspace to ${j}`);}}}catch(u){f.debug("Could not sync Python version from workspace:",u);}}return y}catch(y){let j=ks(y);return j?await Qo(t,j):(process.stderr.write(`Workspai failed to run the Python core engine: ${y?.message??y}
272
+ `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$b();let n=await e(t,{cwd:process.cwd()});if(n===0){let a=we(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-C4UETGY7.js');await i(a,true);}}return n}catch(n){let a=ks(n);return a?await Qo(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
273
+ `),1)}return await d$b(),await e(t,{cwd:process.cwd()})}catch(n){let a=ks(n);return a?await Qo(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
274
+ `),1)}}var Il=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],zu=[...h$6,"autopilot","pipeline","import","adopt","snapshot","ai","config","product","infra","shell","commands"],Yu=["init"],Xu=q$2,Ol=[...Xu,...r$1];function Qu(t){return !!t&&Nu.includes(t)}function Is(t){let e=t[0],r=t[1];return e==="project"&&(r==="--help"||r==="-h"||r==="help")?true:$u.some(([o,n])=>e!==o?false:r?r===n:true)}function Dr(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?Is(t):Qu(t[0])||Is(t)}function Zu(t){return !!t&&zu.includes(t)}function $l(t){return Zu(t[0])||Is(t)}function Nl(t){return !!t&&ns.includes(t)}async function Tl(t,e){switch(t){case "bootstrap":return ym(e);case "setup":return wm(e);case "cache":return vm(e);case "mirror":return jm(e);default:{let r=t;throw new Error(`Unreachable npm-only manual command: ${String(r)}`)}}}function em(t=process.env){let e=t.npm_config_user_agent||"",r=t.npm_execpath||"",o=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(r)||o==="exec"||o==="x"}function Kl(t={}){let e=w(process.cwd());if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai project command capabilities")),console.log(s.gray(`Project: ${e.projectRoot??"not detected"}`)),console.log(s.gray(`Runtime: ${e.runtime} (${e.runtimeSupportTier}) | Framework: ${e.frameworkDisplayName} (${e.frameworkSupportTier}) | Module support: ${e.moduleSupport?"yes":"no"}`)),console.log(s.gray(`Doctor support: ${e.runtimeDoctorSupport}`)),console.log(""),console.log(s.green(`Supported: ${e.supportedCommands.join(", ")||"none"}`)),console.log(s.yellow(`Global: ${e.globalCommands.join(", ")||"none"}`)),console.log(s.red(`Unsupported: ${e.unsupportedCommands.join(", ")||"none"}`));}function tm(){return {schemaVersion:el,cli:"workspai",version:i(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:cs,contracts:Or(),contractCatalog:Vo()}}function rm(){let t=Kc(le),e=[...t.topLevelCommands],r=[...a$9].filter(i=>!e.includes(i)),o=["init","dev","start","build","test","lint","format","help"],n=[..._r],a=[...Lo];return {schemaVersion:cs,scope:"global",cli:"workspai",version:i(),cwd:process.cwd(),contracts:Or(),contractCatalog:Vo(),commands:{npmOwned:e,coreBacked:r,projectScoped:o},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...r.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...o.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function om(t={}){let e=rm();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(Vc(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 Os(t){return y(t)?(Kl({json:t.includes("--json")||t.includes("--ci")}),true):false}function $s(t){let e=w(process.cwd());if(!e.projectRoot)return false;let r=x(t,process.cwd());if(!r||r.status!=="unsupported")return false;console.error(s.red(z(r,e))),process.exit(1);}function Be(t){return A.existsSync(b.join(t,".workspai-workspace"))||A.existsSync(b.join(t,".workspai","workspace.json"))||A.existsSync(b.join(t,".rapidkit-workspace"))||A.existsSync(b.join(t,".rapidkit","workspace.json"))}function Vl(t$1){let e=t$1;for(;;){let r=t(e,"context.json").find(n=>A.existsSync(n));if(r)return r;let o=b.dirname(e);if(o===e)break;e=o;}return null}function Ns(t){let e=t,r=b.resolve(tmpdir());for(;;){let o=[b.join(e,".workspai-workspace"),b.join(e,".rapidkit-workspace")].find(a=>A.existsSync(a));if(o&&b.resolve(e)!==r)return o;let n=b.dirname(e);if(n===e)break;e=n;}return null}function we(t){let e=b$6({startPath:t});return !e||b.resolve(e.workspacePath)===b.resolve(tmpdir())?null:e.workspacePath}function Ul(t){try{let r=b$6({startPath:t,strict:true})?.workspacePath??null;return {workspacePath:r&&b.resolve(r)!==b.resolve(tmpdir())?r:null,error:null}}catch(e){if(e instanceof a$2&&e.code==="project.workspace.unlinked")return {workspacePath:null,error:null};if(e instanceof a$2)return {workspacePath:null,error:e};throw e}}async function Fr(t,e){try{let{syncWorkspaceConsumerArtifacts:r}=await import('./workspace-onboarding-5KO7Z7AD.js');await r(t,{silent:e?.silent});}catch(r){e?.silent||(console.log(s.yellow(`\u26A0\uFE0F Workspace consumer sync skipped: ${r.message}`)),console.log(s.gray(" Retry: npx workspai workspace agent-sync --write --refresh-context --preset enterprise")));}}async function nm(t,e=process.cwd(),r=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$4(r))return {detected:false};let n=p$1(e,r);for(let a of n){if(!await O__default.pathExists(a))continue;let i=a.toLowerCase();if(i.endsWith("rapidkit.cmd")||i.endsWith("rapidkit.exe"))return {detected:true,candidatePath:a,reason:"Found workspace-local rapidkit launcher on Windows."}}return {detected:false}}function sm(t){let e=t;for(;;){let r=b.join(e,".rapidkit-workspace"),o=b.join(e,".rapidkit","workspace.json");if(!A.existsSync(r)&&A.existsSync(o))return e;let n=b.dirname(e);if(n===e)break;e=n;}return null}var Hl={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function am(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Wr(t,e){let r=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return r?r[1]==="true":Hl[e]}function Ml(t){let e=t??"";return {mode:am(e),dependency_sharing_mode:Bl(e),rules:{enforce_workspace_marker:Wr(e,"enforce_workspace_marker"),enforce_toolchain_lock:Wr(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Wr(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Wr(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Wr(e,"require_mirror_lock_for_offline")}}}function Wl(t,e,r){let o=`${e}: ${r}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${o}
275
275
  rules:`):`${t.endsWith(`
276
276
  `)?t:`${t}
277
277
  `}${o}
278
- `}function dm(t,e,r){let o=` ${e}: ${r?"true":"false"}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]+${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`rules:
278
+ `}function im(t,e,r){let o=` ${e}: ${r?"true":"false"}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]+${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`rules:
279
279
  ${o}`):`${t.endsWith(`
280
280
  `)?t:`${t}
281
281
  `}rules:
282
282
  ${o}
283
- `}function um(){return ['version: "1.0"','mode: warn # "warn" or "strict"','dependency_sharing_mode: isolated # "isolated" or "shared-runtime-caches" or "shared-node-deps"',"# change profile (recommended): npx workspai bootstrap --profile polyglot","# change mode/dependency manually: edit this file and rerun npx workspai init","rules:"," enforce_workspace_marker: true"," enforce_toolchain_lock: false"," disallow_untrusted_tool_sources: false"," enforce_compatibility_matrix: false"," require_mirror_lock_for_offline: true",""].join(`
284
- `)}async function Gl(t){for(let e of s$1(t,"policies.yml"))if(await O__default.pathExists(e))return A.promises.readFile(e,"utf-8");return um()}async function mm(t,e){let r=p(t,"policies.yml");await O__default.ensureDir(b.dirname(r));let o=e.endsWith(`
283
+ `}function cm(){return ['version: "1.0"','mode: warn # "warn" or "strict"','dependency_sharing_mode: isolated # "isolated" or "shared-runtime-caches" or "shared-node-deps"',"# change profile (recommended): npx workspai bootstrap --profile polyglot","# change mode/dependency manually: edit this file and rerun npx workspai init","rules:"," enforce_workspace_marker: true"," enforce_toolchain_lock: false"," disallow_untrusted_tool_sources: false"," enforce_compatibility_matrix: false"," require_mirror_lock_for_offline: true",""].join(`
284
+ `)}async function Dl(t){for(let e of s$1(t,"policies.yml"))if(await O__default.pathExists(e))return A.promises.readFile(e,"utf-8");return cm()}async function lm(t,e){let r=p(t,"policies.yml");await O__default.ensureDir(b.dirname(r));let o=e.endsWith(`
285
285
  `)?e:`${e}
286
- `;await A.promises.writeFile(r,o,"utf-8");}function gm(t){let e=t.trim().toLowerCase();return e==="true"||e==="1"||e==="on"?true:e==="false"||e==="0"||e==="off"?false:null}function Xl(t){if(!t)return "isolated";let r=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated"?r:"isolated"}function Ql(t){if(!t)return {mode:"isolated",status:"skipped",message:"No policies.yml found; dependency_sharing_mode defaults to isolated."};let e=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m);if(!e)return {mode:"isolated",status:"skipped",message:"dependency_sharing_mode is not set; defaulting to isolated."};let r=e[1].toLowerCase();return r==="isolated"||r==="shared-runtime-caches"||r==="shared-node-deps"?{mode:r,status:"passed",message:`dependency_sharing_mode is valid: ${r}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${r}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function Zl(t,e){let r=Pe(t),o=r?s$1(r,"policies.yml").find(c=>A.existsSync(c)):null,n="isolated";if(o&&await O__default.pathExists(o))try{let c=await A.promises.readFile(o,"utf-8"),p=Ql(c);if(p.status==="failed")return console.log(s.red(`\u274C ${p.message}`)),{ok:false,code:1};n=p.mode;}catch{return console.log(s.red("\u274C Failed to read workspace policy file (.workspai/policies.yml).")),{ok:false,code:1}}let a=process.env.RAPIDKIT_DEP_SHARING_MODE,i=process.env.RAPIDKIT_WORKSPACE_PATH;process.env.RAPIDKIT_DEP_SHARING_MODE=n,r&&(process.env.RAPIDKIT_WORKSPACE_PATH=r);try{return {ok:true,value:await e()}}finally{typeof a>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=a,typeof i>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=i;}}async function je(t,e,r,o={}){let{buildPackageRunnerSubprocessEnv:n,resolvePackageRunnerInvocation:a}=await import('./platform-capabilities-PR6YL4KC.js'),i=fm(t,e,r),c=i?{command:process.execPath,prefixArgs:["-e",i]}:a(t),p=c.command,d=i?c.prefixArgs:[...c.prefixArgs,...e],g=n();if(i){cr()&&process.stderr.write(`[workspai-cli] runCommandInCwd.nodeEval=${JSON.stringify({cwd:r,scriptBytes:i.length})}
287
- `);try{return Mu.runInThisContext(i,{filename:b.join(r,"package.json#script")}),0}catch(l){return process.stderr.write(`${l instanceof Error?l.stack||l.message:String(l)}
288
- `),1}}let k=!(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"),w=()=>{let l=g.npm_config_cache;if(!l)return "";let P=b.join(l,"_logs");try{let h=A.readdirSync(P).filter(v=>v.endsWith(".log")).map(v=>{let C=b.join(P,v);return {filePath:C,mtimeMs:A.statSync(C).mtimeMs}}).sort((v,C)=>C.mtimeMs-v.mtimeMs)[0]?.filePath;return h?A.readFileSync(h,"utf-8").split(/\r?\n/).map(v=>v.trim()).filter(v=>/(?:^|\s)(?:npm\s+)?(?:error|verbose\s+(?:stack|cwd|os|node|npm|exit|code))\b/i.test(v)).slice(0,12).join(`
289
- `):""}catch{return ""}},j=Number.parseInt(process.env.RAPIDKIT_CHILD_COMMAND_TIMEOUT_MS||"",10),x=o.timeoutMs&&o.timeoutMs>0?o.timeoutMs:Number.isFinite(j)&&j>0?j:void 0;return await new Promise(l=>{let P=[],u=[],h=false,f=null,v=null,C=()=>{try{v?.stdout?.destroy();}catch{}try{v?.stderr?.destroy();}catch{}try{v?.stdin?.destroy();}catch{}try{v?.removeAllListeners("close"),v?.removeAllListeners("error"),v?.unref();}catch{}};cr()&&process.stderr.write(`[workspai-cli] runCommandInCwd=${JSON.stringify({executable:p,args:d,cwd:r,directNodeEvalScript:i!==null,npmEnv:Object.fromEntries(Object.entries(g).filter(([y])=>["npm_config_if_present","npm_config_ignore_scripts","npm_config_loglevel","npm_config_silent","npm_config_json","npm_lifecycle_event","npm_lifecycle_script"].includes(y)))})}
286
+ `;await A.promises.writeFile(r,o,"utf-8");}function pm(t){let e=t.trim().toLowerCase();return e==="true"||e==="1"||e==="on"?true:e==="false"||e==="0"||e==="off"?false:null}function Bl(t){if(!t)return "isolated";let r=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated"?r:"isolated"}function ql(t){if(!t)return {mode:"isolated",status:"skipped",message:"No policies.yml found; dependency_sharing_mode defaults to isolated."};let e=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m);if(!e)return {mode:"isolated",status:"skipped",message:"dependency_sharing_mode is not set; defaulting to isolated."};let r=e[1].toLowerCase();return r==="isolated"||r==="shared-runtime-caches"||r==="shared-node-deps"?{mode:r,status:"passed",message:`dependency_sharing_mode is valid: ${r}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${r}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function zl(t,e){let r=we(t),o=r?s$1(r,"policies.yml").find(c=>A.existsSync(c)):null,n="isolated";if(o&&await O__default.pathExists(o))try{let c=await A.promises.readFile(o,"utf-8"),p=ql(c);if(p.status==="failed")return console.log(s.red(`\u274C ${p.message}`)),{ok:false,code:1};n=p.mode;}catch{return console.log(s.red("\u274C Failed to read workspace policy file (.workspai/policies.yml).")),{ok:false,code:1}}let a=process.env.RAPIDKIT_DEP_SHARING_MODE,i=process.env.RAPIDKIT_WORKSPACE_PATH;process.env.RAPIDKIT_DEP_SHARING_MODE=n,r&&(process.env.RAPIDKIT_WORKSPACE_PATH=r);try{return {ok:true,value:await e()}}finally{typeof a>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=a,typeof i>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=i;}}async function ke(t,e,r,o={}){let{buildPackageRunnerSubprocessEnv:n,resolvePackageRunnerInvocation:a}=await import('./platform-capabilities-PR6YL4KC.js'),i=dm(t,e,r),c=i?{command:process.execPath,prefixArgs:["-e",i]}:a(t),p=c.command,d=i?c.prefixArgs:[...c.prefixArgs,...e],g=n();if(i){sr()&&process.stderr.write(`[workspai-cli] runCommandInCwd.nodeEval=${JSON.stringify({cwd:r,scriptBytes:i.length})}
287
+ `);try{return Ou.runInThisContext(i,{filename:b.join(r,"package.json#script")}),0}catch(l){return process.stderr.write(`${l instanceof Error?l.stack||l.message:String(l)}
288
+ `),1}}let k=!(process.argv.includes("--json")||process.env.RAPIDKIT_WORKSPACE_RUN_CHILD==="1"||process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT==="1")&&t==="npm"&&(e[0]==="run"||e[0]==="run-script"||e[0]==="install"),y=()=>{let l=g.npm_config_cache;if(!l)return "";let P=b.join(l,"_logs");try{let h=A.readdirSync(P).filter(v=>v.endsWith(".log")).map(v=>{let C=b.join(P,v);return {filePath:C,mtimeMs:A.statSync(C).mtimeMs}}).sort((v,C)=>C.mtimeMs-v.mtimeMs)[0]?.filePath;return h?A.readFileSync(h,"utf-8").split(/\r?\n/).map(v=>v.trim()).filter(v=>/(?:^|\s)(?:npm\s+)?(?:error|verbose\s+(?:stack|cwd|os|node|npm|exit|code))\b/i.test(v)).slice(0,12).join(`
289
+ `):""}catch{return ""}},j=Number.parseInt(process.env.RAPIDKIT_CHILD_COMMAND_TIMEOUT_MS||"",10),x=o.timeoutMs&&o.timeoutMs>0?o.timeoutMs:Number.isFinite(j)&&j>0?j:void 0;return await new Promise(l=>{let P=[],u=[],h=false,f=null,v=null,C=()=>{try{v?.stdout?.destroy();}catch{}try{v?.stderr?.destroy();}catch{}try{v?.stdin?.destroy();}catch{}try{v?.removeAllListeners("close"),v?.removeAllListeners("error"),v?.unref();}catch{}};sr()&&process.stderr.write(`[workspai-cli] runCommandInCwd=${JSON.stringify({executable:p,args:d,cwd:r,directNodeEvalScript:i!==null,npmEnv:Object.fromEntries(Object.entries(g).filter(([w])=>["npm_config_if_present","npm_config_ignore_scripts","npm_config_loglevel","npm_config_silent","npm_config_json","npm_lifecycle_event","npm_lifecycle_script"].includes(w)))})}
290
290
  `);let R=b$4()&&/\.(?:cmd|bat)$/i.test(p);v=spawn(p,d,{stdio:k?"inherit":["ignore","pipe","pipe"],cwd:r,shell:R,env:g,detached:!b$4()}),x&&x>0&&(f=setTimeout(()=>{if(!h){if(h=true,!b$4()&&v.pid)try{process.kill(-v.pid,"SIGTERM");}catch{v.kill("SIGTERM");}else v.kill("SIGTERM");C(),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`RapidKit command timed out after ${x}ms: ${p} ${d.join(" ")}
291
- `),l(124);}},x)),k||(v.stdout?.on("data",y=>{P.push(y);}),v.stderr?.on("data",y=>{u.push(y);})),v.on("close",y=>{if(h)return;h=true,f&&clearTimeout(f);let E=Buffer.concat(P),$=Buffer.concat(u),N=y&&y!==0&&E.length===0&&$.length===0&&t==="npm"?w():"";cr()&&process.stderr.write(`[workspai-cli] runCommandInCwd.close=${JSON.stringify({code:y,stdoutBytes:E.length,stderrBytes:$.length,npmFailureExcerptBytes:N.length})}
291
+ `),l(124);}},x)),k||(v.stdout?.on("data",w=>{P.push(w);}),v.stderr?.on("data",w=>{u.push(w);})),v.on("close",w=>{if(h)return;h=true,f&&clearTimeout(f);let E=Buffer.concat(P),$=Buffer.concat(u),N=w&&w!==0&&E.length===0&&$.length===0&&t==="npm"?y():"";sr()&&process.stderr.write(`[workspai-cli] runCommandInCwd.close=${JSON.stringify({code:w,stdoutBytes:E.length,stderrBytes:$.length,npmFailureExcerptBytes:N.length})}
292
292
  `),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(E.length>0&&process.stdout.write(E),$.length>0?process.stderr.write($):N&&process.stderr.write(`${N}
293
- `)),l(y??1);}),v.on("error",y=>{h||(h=true,f&&clearTimeout(f),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`Workspai could not execute ${p}: ${y.message}. Install the required runtime or tool and ensure it is available on PATH.
294
- `),l(1));});})}function fm(t,e,r){if(t!=="npm")return null;let o=e[0];if(o!=="run"&&o!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=b.join(r,"package.json");if(!A.existsSync(a))return null;try{let c=JSON.parse(A.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:hm(c)}catch{return null}}function hm(t){let e=t.trim(),r=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(r)return r[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let o=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return o?o[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function nn(t,e){await O__default.outputFile(t,`${JSON.stringify(e,null,2)}
295
- `,"utf-8");}function wm(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function ym(t,e,r){let o=xt(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":b.basename(e),n=wm(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=b.join(t,i);if(!await O__default.pathExists(c))return c;a+=1;}}async function Ds(t,e,r){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?b.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:zl(process.cwd()),i=a.workspacePath,c=false,p=false,d=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!Ye(n)){let k=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:k},null,2)):console.log(s.red(`\u274C ${k}`)),1}}else (!i||!Ye(i))&&(i=o$1(),c=true,d=true);if(!i||!Ye(i)&&!d){let k="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:k},null,2)):(console.log(s.red(`\u274C ${k}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let g="npx workspai project workspace status --json",m;try{let k=await ym(i,t,e.name);if(m=await on(i,{ownedDestination:k,ownedWorkspace:d?i:void 0}),d){let j=await Hs({silent:e.json});i=j.workspacePath,p=j.created;}let w=await Pl({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});w.path!==k&&m.registerCompensation(()=>O__default.remove(w.path));try{if(r?.syncWorkspaceProjects)await r.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:j,registerWorkspaceStrict:x}=await import('./workspace-B53XH35L.js');await x(i,b.basename(i)),await j(i,w.name,w.path);}await m.commit(),await Kr(i,{silent:e.json});}catch(j){try{await lr(m,j);}catch(x){if(x!==j)throw x}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${j instanceof Error?j.message:String(j)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?p:false,projectWorkspaceCommand:g,commandsResolveWorkspaceFromProject:true,plan:w.ingestionPlan,importedProject:w},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${w.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${w.path}`)),console.log(s.gray(` Stack: ${w.stack} (${w.confidence})`)),console.log(s.gray(` Source: ${e.git===true||xt(t)?"git-url":"local-folder"}`)),!w.profileCompatibility.ok){let j=Zo(w.profileCompatibility);console.log(s.yellow(` Profile warning: ${w.profileCompatibility.message}`)),j&&console.log(s.gray(` ${j}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${g}`)),0}catch(k){if(m)try{await lr(m,k);}catch(j){j!==k&&(k=j);}let w=k instanceof Error?k.message:String(k);return e.json?console.log(JSON.stringify({error:w},null,2)):console.log(s.red(`\u274C Import failed: ${w}`)),1}}async function ep(t,e,r){let o=b.resolve(t||process.cwd()),n=e.workspace?b.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:zl(process.cwd()),i=a.workspacePath,c=false,p=false,d=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!Ye(n)){let w=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:w},null,2)):console.log(s.red(`\u274C ${w}`)),1}}else (!i||!Ye(i))&&(i=o$1(),c=true,d=e.dryRun!==true);let g=c&&i!==null&&(e.dryRun===true||d);if(!i||!Ye(i)&&!g){let w="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:w},null,2)):(console.log(s.red(`\u274C ${w}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let m=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),k;try{if(e.dryRun!==true&&(k=await on(i,{projectPath:o,ownedWorkspace:d?i:void 0}),d)){let l=await Hs({silent:e.json});i=l.workspacePath,p=l.created;}let w=await ws(i,o),j=await ys({workspacePath:i,source:o,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:w}),x="npx workspai project workspace status --json";if(e.dryRun!==true)try{if(r?.registerWorkspace||r?.registerProjectInWorkspace||r?.syncWorkspaceProjects)r.registerWorkspace&&await r.registerWorkspace(i,b.basename(i)),r.registerProjectInWorkspace&&await r.registerProjectInWorkspace(i,j.name,j.path),r.syncWorkspaceProjects&&await r.syncWorkspaceProjects(i);else {let{registerProjectInWorkspaceStrict:l,registerWorkspaceStrict:P}=await import('./workspace-B53XH35L.js');if(await P(i,b.basename(i)),await l(i,j.name,j.path),m)throw new Error("forced sync failure for command-level adopt rollback test")}await k?.commit(),await Kr(i,{silent:e.json});}catch(l){if(k)try{await lr(k,l);}catch(P){if(P!==l)throw P}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${l instanceof Error?l.message:String(l)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?p:false,wouldCreateDefaultWorkspace:c&&e.dryRun===true?!Ye(i):false,projectWorkspaceCommand:x,commandsResolveWorkspaceFromProject:e.dryRun!==true,dryRun:e.dryRun===true,plan:j.ingestionPlan,adoptedProject:j},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${i}`)),e.dryRun===true&&console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.green(`\u2714 Adopted project: ${j.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${j.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${j.stack} (${j.confidence})`)),!j.profileCompatibility.ok){let l=Zo(j.profileCompatibility);console.log(s.yellow(` Profile warning: ${j.profileCompatibility.message}`)),l&&console.log(s.gray(` ${l}`));}return console.log(s.gray(` Report: ${j.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Check: ${x}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(w){if(k)try{await lr(k,w);}catch(x){x!==w&&(w=x);}let j=w instanceof Error?w.message:String(w);return e.json?console.log(JSON.stringify({error:j},null,2)):console.log(s.red(`\u274C Adopt failed: ${j}`)),1}}async function Ls(t){let e=new Set(["python-only","polyglot","enterprise"]),r=km(),o="minimal",n$1=false;try{let p$1=s$1(t,"workspace.json").find(g=>A.existsSync(g))??p(t,"workspace.json"),d=JSON.parse(await A.promises.readFile(p$1,"utf-8"));o=d.profile??"minimal",n$1=d.bootstrap_note==="python-engine-skipped"||d.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(!n$1&&e.has(o))return true;let p=await Fs(t);if(p.length===0)return false;for(let d of p){let g=i$2(d),m=g?.module_support,k$1=p$3(d);if(n$1){if(k$1?.moduleSupport===true)return true;continue}if(!(j$2(g,d)||l(g,d)||m$1(g,d))&&m!==false)return n(g,d)||k(g,d),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:p}=await import('./workspace-marker-7NHMDIRL.js'),g=(await p(t))?.metadata?.npm?.installMethod;(g==="poetry"||g==="venv"||g==="pipx"||g==="pip")&&(i=g);}catch{}let c=async()=>{let p=Gu(t);if(!await O__default.pathExists(p)){let k=await Vu(t);if(k!==0)return k}let d=g$4("DEV_PATH"),m=(d?await O__default.pathExists(d):false)&&d?["-m","pip","install",d,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await je(p,m,t,{timeoutMs:r})};if(i==="venv"){let p=await c();if(p!==0)return p}else if(i==="poetry"){let p=b.join(t,"pyproject.toml"),d=false;try{d=(await A.promises.readFile(p,"utf-8")).includes("rapidkit-core");}catch{d=false;}if(d){let g=await c();if(g!==0)return g}else {let g=await je("poetry",["install","--no-root"],t,{timeoutMs:r});if(g!==0)return g;let m=await je("poetry",["add","rapidkit-core"],t,{timeoutMs:r});if(m!==0)return m}}else return 0;try{let{writeWorkspaceLauncher:p}=await import('./create-R6A7EHQZ.js');await p(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:p}=await import('./workspace-python-engine-state-J4QKW55K.js');await p(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function km(){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 Fs(t$1){let e=[],r=new Set,o=[t$1];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await A.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=b.join(n,i.name);if((await Promise.all([...t(c,"context.json"),...t(c,"project.json")].map(d=>O__default.pathExists(d)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function vm(t){return n$2(t)}async function Hs(t={}){let e=o$1(),r=b.basename(e),o=Ye(e);if(!o){let{createProject:n}=await import('./create-R6A7EHQZ.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:b.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b$1()});}finally{t.silent&&(console.log=i,console.warn=c,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function Ss(t){let r=await Ke("go",{runCommandInCwd:je,runCoreRapidkit:e}).initProject(t);return Q(r)}function Q(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Mt(t,e$1){let r=Ke("node",{runCommandInCwd:je,runCoreRapidkit:e});if(t==="init"){let n=await r.initProject(e$1);return Q(n)}if(t==="dev"){let n=await r.runDev(e$1);return Q(n)}if(t==="test"){let n=await r.runTest(e$1);return Q(n)}if(t==="build"){let n=await r.runBuild(e$1);return Q(n)}if(t==="lint"){let n=await r.runLint?.(e$1);return Q(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e$1);return Q(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e$1);return Q(o)}async function ht(t,e$1){let r=Ke("java",{runCommandInCwd:je,runCoreRapidkit:e});if(t==="init"){let n=await r.initProject(e$1);return Q(n)}if(t==="dev"){let n=await r.runDev(e$1);return Q(n)}if(t==="test"){let n=await r.runTest(e$1);return Q(n)}if(t==="build"){let n=await r.runBuild(e$1);return Q(n)}if(t==="lint"){let n=await r.runLint?.(e$1);return Q(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e$1);return Q(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e$1);return Q(o)}function xs(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$7(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$8()})}async function Pm(t,e=Js){if(t.includes("--help")||t.includes("-h")||t.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(T){if(!T)return null;let K=T.trim().toLowerCase();return K==="minimal"||K==="java-only"||K==="go-only"||K==="dotnet-only"||K==="python-only"||K==="node-only"||K==="polyglot"||K==="enterprise"?K:null},i=function(T){let Je=T.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",We=(ye,He)=>{let nt=T.match(new RegExp(`^\\s*${ye}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return nt?nt[1].toLowerCase()==="true":He};return {mode:Je,dependency_sharing_mode:Xl(T),rules:{enforce_workspace_marker:We("enforce_workspace_marker",true),enforce_toolchain_lock:We("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:We("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:We("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:We("require_mirror_lock_for_offline",true)}}};let c=["init"],p$1,d=false,g=false,m=false,k$1=false;for(let T=1;T<t.length;T+=1){let K=t[T];if(K==="--ci"){d=true;continue}if(K==="--offline"){g=true;continue}if(K==="--json"){m=true;continue}if(K==="--compliance-only"){k$1=true;continue}if(K==="--profile"){let oe=t[T+1];if(!oe||oe.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;p$1=oe,T+=1;continue}if(K.startsWith("--profile=")){p$1=K.slice(10);continue}c.push(K);}let w=a(p$1);if(p$1&&!w)return console.log(s.red(`Invalid profile: ${p$1}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let j=process.cwd(),x=c.slice(1).filter(T=>!T.startsWith("-"));if(x.length>0){let T=b.resolve(j,x[0]),K=i$2(T),oe=A.existsSync(T)?await Wt(T):"unknown";if(!Ye(T)&&(j$2(K,T)||l(K,T)||m$1(K,T)||k(K,T)||n(K,T)||oe!=="unknown"))return await e(c)}let l$1=b.join(j,".rapidkit-workspace"),P=b.join(j,".rapidkit","workspace.json"),u;!A.existsSync(l$1)&&A.existsSync(P)?u=j:(u=Pe(j),u||(u=lm(j)));let h=[],f=null,v=null;if(u)try{let T=s$1(u,"workspace.json").find(Je=>A.existsSync(Je))??p(u,"workspace.json"),K=await A.promises.readFile(T,"utf-8"),oe=JSON.parse(K);v=a(oe.profile);}catch{v=null;}let C=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],R={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=w;if(!!u&&!w&&!d&&!m&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let T=v||"minimal",{chosenProfile:K}=await b$2([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${T})`,choices:C.map(oe=>({name:oe===T?`${R[oe]} \u2190 current`:R[oe],value:oe})),default:C.indexOf(T)}]);y=K;}let $=y||v||"minimal";if(u&&!k$1)try{let K=$==="python-only"||$==="polyglot"||$==="enterprise"?"poetry":"venv",oe;try{let He=(await A.promises.readFile(b.join(u,".python-version"),"utf-8")).trim();He&&(oe=He);}catch{}let{syncWorkspaceFoundationFiles:Je}=await import('./create-R6A7EHQZ.js'),We=await Je(u,{workspaceName:b.basename(u),installMethod:K,pythonVersion:oe,profile:$,writeMarker:true,writeGitignore:true,onlyIfMissing:true});h.push({id:"workspace.foundation.sync",status:We.length>0?"passed":"skipped",message:We.length>0?`Workspace foundation synchronized: ${We.join(", ")}`:"Workspace foundation files are already up to date."});}catch(T){h.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${T.message}`});}else u&&h.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(u&&!k$1&&y&&y!==v)try{let T=p(u,"workspace.json"),K=await A.promises.readFile(T,"utf-8"),oe=JSON.parse(K);oe.profile=y,await O__default.ensureDir(b.dirname(T)),await A.promises.writeFile(T,JSON.stringify(oe,null,2)+`
296
- `,"utf-8");let{syncWorkspaceContract:Je}=await import('./workspace-contract-AYFTZIKM.js');await Je({workspacePath:u}),h.push({id:"workspace.profile.sync",status:"passed",message:`Workspace profile synchronized to ${y} across canonical artifacts.`});}catch(T){h.push({id:"workspace.profile.sync",status:"failed",message:`Failed to synchronize workspace profile across canonical artifacts: ${T instanceof Error?T.message:String(T)}`});}let N={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},M=null;if(u)try{let T=s$1(u,"policies.yml").find(oe=>A.existsSync(oe));if(!T)throw new Error("policy file missing");let K=await A.promises.readFile(T,"utf-8");M=K,N=i(K);}catch{h.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else h.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(u){let T=Ql(M);N.dependency_sharing_mode=T.mode,h.push({id:"policy.schema.dependency_sharing_mode",status:T.status,message:T.message}),h.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:N.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":N.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 K=A.existsSync(b.join(u,".workspai-workspace"))||A.existsSync(b.join(u,".rapidkit-workspace"));h.push({id:"policy.enforce_workspace_marker",status:!N.rules.enforce_workspace_marker||K?"passed":"failed",message:!N.rules.enforce_workspace_marker||K?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let oe=s$1(u,"toolchain.lock").some(Ce=>A.existsSync(Ce));h.push({id:"policy.enforce_toolchain_lock",status:!N.rules.enforce_toolchain_lock||oe?"passed":"failed",message:!N.rules.enforce_toolchain_lock||oe?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let Je=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||s$1(u,"trusted-sources.lock").some(Ce=>A.existsSync(Ce));h.push({id:"policy.disallow_untrusted_tool_sources",status:!N.rules.disallow_untrusted_tool_sources||Je?"passed":"failed",message:!N.rules.disallow_untrusted_tool_sources||Je?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let We=s$1(u,"compatibility-matrix.json").find(Ce=>A.existsSync(Ce))??p(u,"compatibility-matrix.json"),ye=A.existsSync(We),He=N.rules.enforce_compatibility_matrix;if(h.push({id:"policy.enforce_compatibility_matrix",status:!He||ye?"passed":"failed",message:!He||ye?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),ye)try{let Ce=await A.promises.readFile(We,"utf-8"),gt=JSON.parse(Ce),zs=!!gt&&typeof gt=="object";h.push({id:"compatibility.matrix.parse",status:zs?"passed":"failed",message:zs?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{h.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let nt=s$1(u,"mirror-config.json").find(Ce=>A.existsSync(Ce))??p(u,"mirror-config.json"),dr=s$1(u,"mirror.lock").find(Ce=>A.existsSync(Ce))??p(u,"mirror.lock"),an=A.existsSync(nt),cn=A.existsSync(dr),qs={};if(an)try{qs=JSON.parse(await A.promises.readFile(nt,"utf-8")),h.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{h.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(k$1)h.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let Ce=await ms(u,{ciMode:d,offlineMode:g});h.push(...Ce.checks.map(gt=>({id:gt.id,status:gt.status,message:gt.message}))),f=Ce.details,Ce.details.lockWritten&&(cn=true);}if(g){let Ce=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||qs.enabled===true;h.push({id:"offline.mirror.enabled",status:Ce?"passed":"failed",message:Ce?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let gt=N.rules.require_mirror_lock_for_offline;h.push({id:"offline.mirror.lock",status:!gt||cn?"passed":"failed",message:!gt||cn?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else h.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Vr=$t({profile:$,runtimes:await Nt(u),mode:N.mode});Vr.profile!=="enterprise"?h.push({id:Vr.checkId,status:Vr.status,message:Vr.message}):(h.push({id:"profile.enterprise.ci",status:d?"passed":k$1?"skipped":"failed",message:d?"enterprise profile running with --ci.":k$1?"Enterprise runtime execution skipped by --compliance-only; --ci is not required.":"enterprise profile expects --ci for deterministic non-interactive mode."}),h.push({id:"profile.enterprise.compatibility-matrix",status:ye?"passed":"failed",message:ye?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),h.push({id:"profile.enterprise.mirror-config",status:an?"passed":"failed",message:an?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}d&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),g&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let S=h.some(T=>T.id.startsWith("policy.schema.")&&T.status==="failed")||N.mode==="strict"&&h.some(T=>T.status==="failed"),F=p(u||j,"reports"),W=new Date().toISOString().replace(/[:.]/g,"-"),G=b.join(F,`bootstrap-compliance-${W}.json`),H=b.join(F,"bootstrap-compliance.latest.json"),Te={schemaVersion:d$9.bootstrapCompliance.schemaVersion,command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:u,profile:$,options:{ci:d,offline:g,strict:N.mode==="strict",complianceOnly:k$1},policyMode:N.mode,policyRules:N.rules,mirrorLifecycle:f,checks:h},we=async T=>{b$l(`.workspai/reports/${b.basename(G)}`,T),b$l(e$1.bootstrapCompliance,T),await O__default.ensureDir(F),await nn(G,T),await nn(H,T);};if(S){let T=xs({...Te,result:"blocked",initExitCode:null},1,h);return await we(T),m?process.stdout.write(`${JSON.stringify(T,null,2)}
297
- `):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${G}`))),1}if(m&&$==="enterprise"&&!d&&!k$1){let T=xs({...Te,result:"blocked",initExitCode:null,complianceOnly:false,bootstrapRuntimeSkipped:{reason:"enterprise JSON bootstrap requires --ci for deterministic non-interactive execution.",nextAction:"npx workspai bootstrap --profile enterprise --ci --json"}},1,h);return await we(T),process.stdout.write(`${JSON.stringify(T,null,2)}
298
- `),1}let Me=async T=>{let K=process.stdout.write.bind(process.stdout),oe=process.stderr.write.bind(process.stderr),Je=[],We=[];process.stdout.write=((ye,He,nt)=>{let dr=typeof He=="function"?He:typeof nt=="function"?nt:void 0;return Je.push(typeof ye=="string"?ye:ye instanceof Uint8Array?Buffer.from(ye).toString("utf8"):String(ye)),dr?.(),true}),process.stderr.write=((ye,He,nt)=>{let dr=typeof He=="function"?He:typeof nt=="function"?nt:void 0;return We.push(typeof ye=="string"?ye:ye instanceof Uint8Array?Buffer.from(ye).toString("utf8"):String(ye)),dr?.(),true});try{return {exitCode:await T(),stdout:Je.join(""),stderr:We.join("")}}finally{process.stdout.write=K,process.stderr.write=oe;}},Fe=T=>{let K=T.split(/\r?\n/).map(oe=>oe.trim()).filter(Boolean);return {bytes:Buffer.byteLength(T),excerpt:K.slice(0,12)}},Ue=0,ne;if(!k$1)if(m){let T=await Me(()=>e(c));Ue=T.exitCode,ne={captured:true,stdout:Fe(T.stdout),stderr:Fe(T.stderr)};}else Ue=await e(c);let Ee=h.filter(T=>T.status==="failed").length,pr=Ue!==0?"failed":Ee>0?"ok_with_warnings":"ok",Lt=Ue!==0?Ue:Ee>0?1:0,Re=xs({...Te,result:pr,initExitCode:Ue,complianceOnly:k$1,...ne?{initOutput:ne}:{}},Lt,h);if(await we(Re),u&&!k$1&&Ue===0)try{let{syncWorkspaceProjects:T}=await import('./workspace-B53XH35L.js');await T(u,m),await Kr(u,{silent:m});}catch{}if(m)process.stdout.write(`${JSON.stringify(Re,null,2)}
299
- `);else {let T=h.filter(K=>K.status==="failed").length;T>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${T} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${G}`));}return Lt}finally{typeof r>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=r;}}async function jm(t,e$1=je){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),0;let r=(t[1]||"").toLowerCase(),o=t.includes("--json"),n=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!r||!["python","node","go","java","dotnet","rust","php"].includes(r))return o?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]"},null,2)}
300
- `):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),1;let a=async(w,j)=>{if(w==="node"){if(!A.existsSync(b.join(j,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let l=A.existsSync(b.join(j,"pnpm-lock.yaml")),P=A.existsSync(b.join(j,"yarn.lock"));return l?{exitCode:await e$1("pnpm",["install","--lockfile-only","--ignore-scripts"],j)}:P?{exitCode:await e$1("yarn",["install","--ignore-scripts"],j)}:{exitCode:await e$1("npm",["install","--package-lock-only","--ignore-scripts"],j)}}if(w==="go")return A.existsSync(b.join(j,"go.mod"))?{exitCode:await e$1("go",["mod","download"],j)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(w==="java"){let x=A.existsSync(b.join(j,"pom.xml")),l=A.existsSync(b.join(j,"build.gradle"))||A.existsSync(b.join(j,"build.gradle.kts")),P=b.join(j,process.platform==="win32"?"gradlew.bat":"gradlew"),u=A.existsSync(P);return !x&&!l?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:x?{exitCode:await e$1("mvn",["-B","-q","-DskipTests","dependency:go-offline"],j)}:{exitCode:await e$1(u?P:"gradle",["--no-daemon","dependencies"],j)}}return w==="dotnet"?(()=>{let l=[{dir:j,depth:0}],P=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;l.length>0;){let u=l.shift();if(!u||u.depth>3)continue;let h=[];try{h=A.readdirSync(u.dir,{withFileTypes:true});}catch{continue}for(let f of h)if(f.isFile()){let v=f.name.toLowerCase();if(v.endsWith(".sln")||v.endsWith(".csproj"))return true}else f.isDirectory()&&!P.has(f.name)&&l.push({dir:b.join(u.dir,f.name),depth:u.depth+1});}return false})()?{exitCode:await e$1("dotnet",["restore"],j)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:w==="rust"?A.existsSync(b.join(j,"Cargo.toml"))?{exitCode:await e$1("cargo",["fetch"],j)}:{exitCode:0,message:"Rust warm-up skipped: Cargo.toml not found in current directory."}:w==="php"?A.existsSync(b.join(j,"composer.json"))?{exitCode:await e$1("composer",["install","--no-interaction","--no-scripts"],j)}:{exitCode:0,message:"PHP warm-up skipped: composer.json not found in current directory."}:{exitCode:0,message:"Dependency warm-up is not available for this runtime."}};if(o){let w=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let x=await Ke(r,{runCommandInCwd:e$1,runCoreRapidkit:async(f,v)=>(await g$6(f,{...v,cwd:void 0})).exitCode}).checkPrereqs(),l$1=Pe(process.cwd()),P=l$1||process.cwd(),u=null;if(r==="node"&&x.exitCode===0&&(u=process.version),l$1&&u){let f=s$1(l$1,"toolchain.lock").find(R=>A.existsSync(R))??p(l$1,"toolchain.lock"),v=p(l$1,"toolchain.lock"),C={};try{C=JSON.parse(await A.promises.readFile(f,"utf-8"));}catch{}(!C.runtime||typeof C.runtime!="object")&&(C.runtime={}),C.runtime[r]={version:u,detectedAt:new Date().toISOString()},await O__default.ensureDir(b.dirname(v)),await A.promises.writeFile(v,JSON.stringify(C,null,2)+`
301
- `,"utf-8");}let h={requested:n,status:"not-requested",exitCode:null,targets:0,messages:[]};if(n&&x.exitCode===0){let f=[P];if(r==="java"&&l$1){let E=(await Fs(l$1)).filter($=>{let N=i$2($);return l(N,$)});E.length>0&&(f=E);}let v=[];for(let y of f)v.push(await a(r,y));let C=v.filter(y=>y.exitCode!==0),R=v.filter(y=>y.exitCode===0&&!/skipped/i.test(y.message||""));h.status=C.length>0?"failed":R.length>0?"passed":"skipped",h.exitCode=C[0]?.exitCode??0,h.targets=f.length,h.messages=v.map(y=>y.message).filter(y=>typeof y=="string");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:r,result:x.exitCode===0?"ok":"failed",exitCode:x.exitCode,workspacePath:l$1,version:u,warmDeps:n,warmDependencies:h},null,2)}
302
- `),x.exitCode}finally{typeof w>"u"?delete process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT:process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT=w;}}let i=Ke(r,{runCommandInCwd:e$1,runCoreRapidkit:(w,j)=>e(w,{...j,cwd:void 0})}),c=await i.checkPrereqs(),p$1=await i.doctorHints(process.cwd()),d=Pe(process.cwd()),g=d||process.cwd(),m=null,k=async()=>r!=="java"||!d?[]:m||(m=(await Fs(d)).filter(j=>{let x=i$2(j);return l(x,j)}),m);if(c.exitCode===0){console.log(s.green(`\u2705 ${r} prerequisites look good.`));let w=["python","node","go","java","dotnet","rust","php"].filter(j=>j!==r).join("/");if(console.log(s.gray(` Scope: validated ${r} runtime only. ${w} checks are optional unless your workspace profile uses them.`)),r==="python"&&console.log(s.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),i.warmSetupCache&&((await i.warmSetupCache(g)).exitCode===0?console.log(s.gray(` ${r} cache warm-up completed.`)):console.log(s.yellow(` ${r} cache warm-up skipped (non-fatal).`))),n)if(r==="java"&&d){let j=await k();if(j.length>0){let x=0,l=0,P=0;for(let u of j){let h=await a("java",u),f=/skipped/i.test(h.message||""),v=b.relative(d,u)||b.basename(u);h.message&&console.log(s.gray(` [${v}] ${h.message}`)),h.exitCode===0&&!f?x+=1:h.exitCode===0&&f?P+=1:l+=1;}x>0&&console.log(s.gray(` java dependency warm-up completed for ${x} project(s) (--warm-deps).`)),l>0&&console.log(s.yellow(` java dependency warm-up failed for ${l} project(s) (non-fatal).`)),x===0&&l===0&&P>0&&console.log(s.gray(" java dependency warm-up skipped for discovered workspace projects."));}else {let x=await a("java",g),l=/skipped/i.test(x.message||"");x.message&&console.log(s.gray(` ${x.message}`)),x.exitCode===0&&!l?console.log(s.gray(` ${r} dependency warm-up completed (--warm-deps).`)):x.exitCode!==0&&console.log(s.yellow(` ${r} dependency warm-up failed (non-fatal).`));}}else {let j=await a(r,g),x=/skipped/i.test(j.message||"");j.message&&console.log(s.gray(` ${j.message}`)),j.exitCode===0&&!x?console.log(s.gray(` ${r} dependency warm-up completed (--warm-deps).`)):j.exitCode!==0&&console.log(s.yellow(` ${r} dependency warm-up failed (non-fatal).`));}if(d)try{let j=s$1(d,"toolchain.lock").find(u=>A.existsSync(u))??p(d,"toolchain.lock"),x=p(d,"toolchain.lock"),l={};try{l=JSON.parse(await A.promises.readFile(j,"utf-8"));}catch{}(!l.runtime||typeof l.runtime!="object")&&(l.runtime={});let P=l.runtime;if(r==="python"){let u=null;try{let{execa:h}=await import('execa');for(let f of Us()){let C=await h(f,f==="py"?["-3","--version"]:["--version"],{cwd:d,stdio:"pipe",reject:false,timeout:3e3});if(C.exitCode===0){let y=(C.stdout||C.stderr||"").match(/Python\s+(\S+)/);if(u=y?y[1]:null,u)break}}}catch{}P.python={...P.python||{},version:u,last_setup:new Date().toISOString()};}else if(r==="node")P.node={...P.node||{},version:process.version,last_setup:new Date().toISOString()};else if(r==="go"){let u=null;try{let{execa:h}=await import('execa'),v=((await h("go",["version"],{cwd:d,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);u=v?v[1]:null;}catch{}P.go={...P.go||{},version:u,last_setup:new Date().toISOString()};}else if(r==="java"){let u=null,h=null,f=null,v=await k(),R=A.existsSync(b.join(g,"pom.xml"))||A.existsSync(b.join(g,"build.gradle"))||A.existsSync(b.join(g,"build.gradle.kts"))?g:v[0]||g;try{let{execa:y}=await import('execa'),E=await y("java",["-version"],{cwd:d,stdio:"pipe",reject:false,timeout:3e3}),N=`${E.stdout||""}
303
- ${E.stderr||""}`.match(/version\s+"([^"]+)"/i);u=N?N[1]:null;let M=A.existsSync(b.join(R,"pom.xml")),_=A.existsSync(b.join(R,"build.gradle"))||A.existsSync(b.join(R,"build.gradle.kts"));if(M){h="maven";let S=(()=>{let G=b.join(R,"mvnw.cmd");if(process.platform==="win32"&&A.existsSync(G))return G;let H=b.join(R,"mvnw");return A.existsSync(H)?H:"mvn"})(),J=await y(S,["-version"],{cwd:R,stdio:"pipe",reject:false,timeout:3e3}),W=`${J.stdout||""}
304
- ${J.stderr||""}`.match(/Apache Maven\s+(\S+)/i);f=W?W[1]:null;}else if(_){h="gradle";let S=(()=>{let G=b.join(R,"gradlew.bat");if(process.platform==="win32"&&A.existsSync(G))return G;let H=b.join(R,"gradlew");return A.existsSync(H)?H:"gradle"})(),J=await y(S,["--version"],{cwd:R,stdio:"pipe",reject:false,timeout:3e3}),W=`${J.stdout||""}
293
+ `)),l(w??1);}),v.on("error",w=>{h||(h=true,f&&clearTimeout(f),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`Workspai could not execute ${p}: ${w.message}. Install the required runtime or tool and ensure it is available on PATH.
294
+ `),l(1));});})}function dm(t,e,r){if(t!=="npm")return null;let o=e[0];if(o!=="run"&&o!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=b.join(r,"package.json");if(!A.existsSync(a))return null;try{let c=JSON.parse(A.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:um(c)}catch{return null}}function um(t){let e=t.trim(),r=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(r)return r[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let o=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return o?o[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function tn(t,e){await O__default.outputFile(t,`${JSON.stringify(e,null,2)}
295
+ `,"utf-8");}function mm(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function gm(t,e,r){let o=bt(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":b.basename(e),n=mm(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=b.join(t,i);if(!await O__default.pathExists(c))return c;a+=1;}}async function Ts(t,e,r){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?b.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:Ul(process.cwd()),i=a.workspacePath,c=false,p=false,d=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!Be(n)){let k=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:k},null,2)):console.log(s.red(`\u274C ${k}`)),1}}else (!i||!Be(i))&&(i=o$1(),c=true,d=true);if(!i||!Be(i)&&!d){let k="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:k},null,2)):(console.log(s.red(`\u274C ${k}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let g="npx workspai project workspace status --json",m;try{let k=await gm(i,t,e.name);if(m=await en(i,{ownedDestination:k,ownedWorkspace:d?i:void 0}),d){let j=await Ks({silent:e.json});i=j.workspacePath,p=j.created;}let y=await yl({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});y.path!==k&&m.registerCompensation(()=>O__default.remove(y.path));try{if(r?.syncWorkspaceProjects)await r.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:j,registerWorkspaceStrict:x}=await import('./workspace-C4UETGY7.js');await x(i,b.basename(i)),await j(i,y.name,y.path);}await m.commit(),await Fr(i,{silent:e.json});}catch(j){try{await ar(m,j);}catch(x){if(x!==j)throw x}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${j instanceof Error?j.message:String(j)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?p:false,projectWorkspaceCommand:g,commandsResolveWorkspaceFromProject:true,plan:y.ingestionPlan,importedProject:y},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${y.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${y.path}`)),console.log(s.gray(` Stack: ${y.stack} (${y.confidence})`)),console.log(s.gray(` Source: ${e.git===true||bt(t)?"git-url":"local-folder"}`)),!y.profileCompatibility.ok){let j=Yo(y.profileCompatibility);console.log(s.yellow(` Profile warning: ${y.profileCompatibility.message}`)),j&&console.log(s.gray(` ${j}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${g}`)),0}catch(k){if(m)try{await ar(m,k);}catch(j){j!==k&&(k=j);}let y=k instanceof Error?k.message:String(k);return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C Import failed: ${y}`)),1}}async function Yl(t,e,r){let o=b.resolve(t||process.cwd()),n=e.workspace?b.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:Ul(process.cwd()),i=a.workspacePath,c=false,p=false,d=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!Be(n)){let y=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C ${y}`)),1}}else (!i||!Be(i))&&(i=o$1(),c=true,d=e.dryRun!==true);let g=c&&i!==null&&(e.dryRun===true||d);if(!i||!Be(i)&&!g){let y="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:y},null,2)):(console.log(s.red(`\u274C ${y}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let m=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),k;try{if(e.dryRun!==true&&(k=await en(i,{projectPath:o,ownedWorkspace:d?i:void 0}),d)){let l=await Ks({silent:e.json});i=l.workspacePath,p=l.created;}let y=await gs(i,o),j=await fs({workspacePath:i,source:o,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:y}),x="npx workspai project workspace status --json";if(e.dryRun!==true)try{if(r?.registerWorkspace||r?.registerProjectInWorkspace||r?.syncWorkspaceProjects)r.registerWorkspace&&await r.registerWorkspace(i,b.basename(i)),r.registerProjectInWorkspace&&await r.registerProjectInWorkspace(i,j.name,j.path),r.syncWorkspaceProjects&&await r.syncWorkspaceProjects(i);else {let{registerProjectInWorkspaceStrict:l,registerWorkspaceStrict:P}=await import('./workspace-C4UETGY7.js');if(await P(i,b.basename(i)),await l(i,j.name,j.path),m)throw new Error("forced sync failure for command-level adopt rollback test")}await k?.commit(),await Fr(i,{silent:e.json});}catch(l){if(k)try{await ar(k,l);}catch(P){if(P!==l)throw P}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${l instanceof Error?l.message:String(l)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?p:false,wouldCreateDefaultWorkspace:c&&e.dryRun===true?!Be(i):false,projectWorkspaceCommand:x,commandsResolveWorkspaceFromProject:e.dryRun!==true,dryRun:e.dryRun===true,plan:j.ingestionPlan,adoptedProject:j},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${i}`)),e.dryRun===true&&console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.green(`\u2714 Adopted project: ${j.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${j.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${j.stack} (${j.confidence})`)),!j.profileCompatibility.ok){let l=Yo(j.profileCompatibility);console.log(s.yellow(` Profile warning: ${j.profileCompatibility.message}`)),l&&console.log(s.gray(` ${l}`));}return console.log(s.gray(` Report: ${j.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Check: ${x}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(y){if(k)try{await ar(k,y);}catch(x){x!==y&&(y=x);}let j=y instanceof Error?y.message:String(y);return e.json?console.log(JSON.stringify({error:j},null,2)):console.log(s.red(`\u274C Adopt failed: ${j}`)),1}}async function Ms(t){let e=new Set(["python-only","polyglot","enterprise"]),r=fm(),o="minimal",n$1=false;try{let p$1=s$1(t,"workspace.json").find(g=>A.existsSync(g))??p(t,"workspace.json"),d=JSON.parse(await A.promises.readFile(p$1,"utf-8"));o=d.profile??"minimal",n$1=d.bootstrap_note==="python-engine-skipped"||d.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(!n$1&&e.has(o))return true;let p=await Ws(t);if(p.length===0)return false;for(let d of p){let g=i$2(d),m=g?.module_support,k$1=p$3(d);if(n$1){if(k$1?.moduleSupport===true)return true;continue}if(!(j$2(g,d)||l(g,d)||m$1(g,d))&&m!==false)return n(g,d)||k(g,d),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:p}=await import('./workspace-marker-7NHMDIRL.js'),g=(await p(t))?.metadata?.npm?.installMethod;(g==="poetry"||g==="venv"||g==="pipx"||g==="pip")&&(i=g);}catch{}let c=async()=>{let p=Du(t);if(!await O__default.pathExists(p)){let k=await Fu(t);if(k!==0)return k}let d=g$4("DEV_PATH"),m=(d?await O__default.pathExists(d):false)&&d?["-m","pip","install",d,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await ke(p,m,t,{timeoutMs:r})};if(i==="venv"){let p=await c();if(p!==0)return p}else if(i==="poetry"){let p=b.join(t,"pyproject.toml"),d=false;try{d=(await A.promises.readFile(p,"utf-8")).includes("rapidkit-core");}catch{d=false;}if(d){let g=await c();if(g!==0)return g}else {let g=await ke("poetry",["install","--no-root"],t,{timeoutMs:r});if(g!==0)return g;let m=await ke("poetry",["add","rapidkit-core"],t,{timeoutMs:r});if(m!==0)return m}}else return 0;try{let{writeWorkspaceLauncher:p}=await import('./create-3NSOY7CA.js');await p(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:p}=await import('./workspace-python-engine-state-J4QKW55K.js');await p(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function fm(){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 Ws(t$1){let e=[],r=new Set,o=[t$1];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await A.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=b.join(n,i.name);if((await Promise.all([...t(c,"context.json"),...t(c,"project.json")].map(d=>O__default.pathExists(d)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function hm(t){return n$2(t)}async function Ks(t={}){let e=o$1(),r=b.basename(e),o=Be(e);if(!o){let{createProject:n}=await import('./create-3NSOY7CA.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:b.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b$1()});}finally{t.silent&&(console.log=i,console.warn=c,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function js(t){let r=await Fe("go",{runCommandInCwd:ke,runCoreRapidkit:e}).initProject(t);return Q(r)}function Q(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function $t(t,e$1){let r=Fe("node",{runCommandInCwd:ke,runCoreRapidkit:e});if(t==="init"){let n=await r.initProject(e$1);return Q(n)}if(t==="dev"){let n=await r.runDev(e$1);return Q(n)}if(t==="test"){let n=await r.runTest(e$1);return Q(n)}if(t==="build"){let n=await r.runBuild(e$1);return Q(n)}if(t==="lint"){let n=await r.runLint?.(e$1);return Q(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e$1);return Q(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e$1);return Q(o)}async function mt(t,e$1){let r=Fe("java",{runCommandInCwd:ke,runCoreRapidkit:e});if(t==="init"){let n=await r.initProject(e$1);return Q(n)}if(t==="dev"){let n=await r.runDev(e$1);return Q(n)}if(t==="test"){let n=await r.runTest(e$1);return Q(n)}if(t==="build"){let n=await r.runBuild(e$1);return Q(n)}if(t==="lint"){let n=await r.runLint?.(e$1);return Q(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e$1);return Q(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e$1);return Q(o)}function bs(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$7(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$8()})}async function ym(t,e=Ds){if(t.includes("--help")||t.includes("-h")||t.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(T){if(!T)return null;let K=T.trim().toLowerCase();return K==="minimal"||K==="java-only"||K==="go-only"||K==="dotnet-only"||K==="python-only"||K==="node-only"||K==="polyglot"||K==="enterprise"?K:null},i=function(T){let De=T.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",Ne=(he,Ke)=>{let tt=T.match(new RegExp(`^\\s*${he}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return tt?tt[1].toLowerCase()==="true":Ke};return {mode:De,dependency_sharing_mode:Bl(T),rules:{enforce_workspace_marker:Ne("enforce_workspace_marker",true),enforce_toolchain_lock:Ne("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:Ne("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:Ne("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:Ne("require_mirror_lock_for_offline",true)}}};let c=["init"],p$1,d=false,g=false,m=false,k$1=false;for(let T=1;T<t.length;T+=1){let K=t[T];if(K==="--ci"){d=true;continue}if(K==="--offline"){g=true;continue}if(K==="--json"){m=true;continue}if(K==="--compliance-only"){k$1=true;continue}if(K==="--profile"){let re=t[T+1];if(!re||re.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;p$1=re,T+=1;continue}if(K.startsWith("--profile=")){p$1=K.slice(10);continue}c.push(K);}let y=a(p$1);if(p$1&&!y)return console.log(s.red(`Invalid profile: ${p$1}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let j=process.cwd(),x=c.slice(1).filter(T=>!T.startsWith("-"));if(x.length>0){let T=b.resolve(j,x[0]),K=i$2(T),re=A.existsSync(T)?await Nt(T):"unknown";if(!Be(T)&&(j$2(K,T)||l(K,T)||m$1(K,T)||k(K,T)||n(K,T)||re!=="unknown"))return await e(c)}let l$1=b.join(j,".rapidkit-workspace"),P=b.join(j,".rapidkit","workspace.json"),u;!A.existsSync(l$1)&&A.existsSync(P)?u=j:(u=we(j),u||(u=sm(j)));let h=[],f=null,v=null;if(u)try{let T=s$1(u,"workspace.json").find(De=>A.existsSync(De))??p(u,"workspace.json"),K=await A.promises.readFile(T,"utf-8"),re=JSON.parse(K);v=a(re.profile);}catch{v=null;}let C=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],R={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"},w=y;if(!!u&&!y&&!d&&!m&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let T=v||"minimal",{chosenProfile:K}=await b$2([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${T})`,choices:C.map(re=>({name:re===T?`${R[re]} \u2190 current`:R[re],value:re})),default:C.indexOf(T)}]);w=K;}let $=w||v||"minimal";if(u&&!k$1)try{let K=$==="python-only"||$==="polyglot"||$==="enterprise"?"poetry":"venv",re;try{let Ke=(await A.promises.readFile(b.join(u,".python-version"),"utf-8")).trim();Ke&&(re=Ke);}catch{}let{syncWorkspaceFoundationFiles:De}=await import('./create-3NSOY7CA.js'),Ne=await De(u,{workspaceName:b.basename(u),installMethod:K,pythonVersion:re,profile:$,writeMarker:true,writeGitignore:true,onlyIfMissing:true});h.push({id:"workspace.foundation.sync",status:Ne.length>0?"passed":"skipped",message:Ne.length>0?`Workspace foundation synchronized: ${Ne.join(", ")}`:"Workspace foundation files are already up to date."});}catch(T){h.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${T.message}`});}else u&&h.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(u&&!k$1&&w&&w!==v)try{let T=p(u,"workspace.json"),K=await A.promises.readFile(T,"utf-8"),re=JSON.parse(K);re.profile=w,await O__default.ensureDir(b.dirname(T)),await A.promises.writeFile(T,JSON.stringify(re,null,2)+`
296
+ `,"utf-8");let{syncWorkspaceContract:De}=await import('./workspace-contract-AYFTZIKM.js');await De({workspacePath:u}),h.push({id:"workspace.profile.sync",status:"passed",message:`Workspace profile synchronized to ${w} across canonical artifacts.`});}catch(T){h.push({id:"workspace.profile.sync",status:"failed",message:`Failed to synchronize workspace profile across canonical artifacts: ${T instanceof Error?T.message:String(T)}`});}let N={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},M=null;if(u)try{let T=s$1(u,"policies.yml").find(re=>A.existsSync(re));if(!T)throw new Error("policy file missing");let K=await A.promises.readFile(T,"utf-8");M=K,N=i(K);}catch{h.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else h.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(u){let T=ql(M);N.dependency_sharing_mode=T.mode,h.push({id:"policy.schema.dependency_sharing_mode",status:T.status,message:T.message}),h.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:N.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":N.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 K=A.existsSync(b.join(u,".workspai-workspace"))||A.existsSync(b.join(u,".rapidkit-workspace"));h.push({id:"policy.enforce_workspace_marker",status:!N.rules.enforce_workspace_marker||K?"passed":"failed",message:!N.rules.enforce_workspace_marker||K?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let re=s$1(u,"toolchain.lock").some(je=>A.existsSync(je));h.push({id:"policy.enforce_toolchain_lock",status:!N.rules.enforce_toolchain_lock||re?"passed":"failed",message:!N.rules.enforce_toolchain_lock||re?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let De=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||s$1(u,"trusted-sources.lock").some(je=>A.existsSync(je));h.push({id:"policy.disallow_untrusted_tool_sources",status:!N.rules.disallow_untrusted_tool_sources||De?"passed":"failed",message:!N.rules.disallow_untrusted_tool_sources||De?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let Ne=s$1(u,"compatibility-matrix.json").find(je=>A.existsSync(je))??p(u,"compatibility-matrix.json"),he=A.existsSync(Ne),Ke=N.rules.enforce_compatibility_matrix;if(h.push({id:"policy.enforce_compatibility_matrix",status:!Ke||he?"passed":"failed",message:!Ke||he?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),he)try{let je=await A.promises.readFile(Ne,"utf-8"),dt=JSON.parse(je),Hs=!!dt&&typeof dt=="object";h.push({id:"compatibility.matrix.parse",status:Hs?"passed":"failed",message:Hs?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{h.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let tt=s$1(u,"mirror-config.json").find(je=>A.existsSync(je))??p(u,"mirror-config.json"),cr=s$1(u,"mirror.lock").find(je=>A.existsSync(je))??p(u,"mirror.lock"),on=A.existsSync(tt),nn=A.existsSync(cr),Us={};if(on)try{Us=JSON.parse(await A.promises.readFile(tt,"utf-8")),h.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{h.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(k$1)h.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let je=await ps(u,{ciMode:d,offlineMode:g});h.push(...je.checks.map(dt=>({id:dt.id,status:dt.status,message:dt.message}))),f=je.details,je.details.lockWritten&&(nn=true);}if(g){let je=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||Us.enabled===true;h.push({id:"offline.mirror.enabled",status:je?"passed":"failed",message:je?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let dt=N.rules.require_mirror_lock_for_offline;h.push({id:"offline.mirror.lock",status:!dt||nn?"passed":"failed",message:!dt||nn?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else h.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Jr=_t({profile:$,runtimes:await It(u),mode:N.mode});Jr.profile!=="enterprise"?h.push({id:Jr.checkId,status:Jr.status,message:Jr.message}):(h.push({id:"profile.enterprise.ci",status:d?"passed":k$1?"skipped":"failed",message:d?"enterprise profile running with --ci.":k$1?"Enterprise runtime execution skipped by --compliance-only; --ci is not required.":"enterprise profile expects --ci for deterministic non-interactive mode."}),h.push({id:"profile.enterprise.compatibility-matrix",status:he?"passed":"failed",message:he?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),h.push({id:"profile.enterprise.mirror-config",status:on?"passed":"failed",message:on?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}d&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),g&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let S=h.some(T=>T.id.startsWith("policy.schema.")&&T.status==="failed")||N.mode==="strict"&&h.some(T=>T.status==="failed"),F=p(u||j,"reports"),W=new Date().toISOString().replace(/[:.]/g,"-"),G=b.join(F,`bootstrap-compliance-${W}.json`),H=b.join(F,"bootstrap-compliance.latest.json"),Oe={schemaVersion:d$9.bootstrapCompliance.schemaVersion,command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:u,profile:$,options:{ci:d,offline:g,strict:N.mode==="strict",complianceOnly:k$1},policyMode:N.mode,policyRules:N.rules,mirrorLifecycle:f,checks:h},fe=async T=>{b$l(`.workspai/reports/${b.basename(G)}`,T),b$l(e$1.bootstrapCompliance,T),await O__default.ensureDir(F),await tn(G,T),await tn(H,T);};if(S){let T=bs({...Oe,result:"blocked",initExitCode:null},1,h);return await fe(T),m?process.stdout.write(`${JSON.stringify(T,null,2)}
297
+ `):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${G}`))),1}if(m&&$==="enterprise"&&!d&&!k$1){let T=bs({...Oe,result:"blocked",initExitCode:null,complianceOnly:false,bootstrapRuntimeSkipped:{reason:"enterprise JSON bootstrap requires --ci for deterministic non-interactive execution.",nextAction:"npx workspai bootstrap --profile enterprise --ci --json"}},1,h);return await fe(T),process.stdout.write(`${JSON.stringify(T,null,2)}
298
+ `),1}let $e=async T=>{let K=process.stdout.write.bind(process.stdout),re=process.stderr.write.bind(process.stderr),De=[],Ne=[];process.stdout.write=((he,Ke,tt)=>{let cr=typeof Ke=="function"?Ke:typeof tt=="function"?tt:void 0;return De.push(typeof he=="string"?he:he instanceof Uint8Array?Buffer.from(he).toString("utf8"):String(he)),cr?.(),true}),process.stderr.write=((he,Ke,tt)=>{let cr=typeof Ke=="function"?Ke:typeof tt=="function"?tt:void 0;return Ne.push(typeof he=="string"?he:he instanceof Uint8Array?Buffer.from(he).toString("utf8"):String(he)),cr?.(),true});try{return {exitCode:await T(),stdout:De.join(""),stderr:Ne.join("")}}finally{process.stdout.write=K,process.stderr.write=re;}},We=T=>{let K=T.split(/\r?\n/).map(re=>re.trim()).filter(Boolean);return {bytes:Buffer.byteLength(T),excerpt:K.slice(0,12)}},Ge=0,oe;if(!k$1)if(m){let T=await $e(()=>e(c));Ge=T.exitCode,oe={captured:true,stdout:We(T.stdout),stderr:We(T.stderr)};}else Ge=await e(c);let Se=h.filter(T=>T.status==="failed").length,ir=Ge!==0?"failed":Se>0?"ok_with_warnings":"ok",Mt=Ge!==0?Ge:Se>0?1:0,xe=bs({...Oe,result:ir,initExitCode:Ge,complianceOnly:k$1,...oe?{initOutput:oe}:{}},Mt,h);if(await fe(xe),u&&!k$1&&Ge===0)try{let{syncWorkspaceProjects:T}=await import('./workspace-C4UETGY7.js');await T(u,m),await Fr(u,{silent:m});}catch{}if(m)process.stdout.write(`${JSON.stringify(xe,null,2)}
299
+ `);else {let T=h.filter(K=>K.status==="failed").length;T>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${T} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${G}`));}return Mt}finally{typeof r>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=r;}}async function wm(t,e$1=ke){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),0;let r=(t[1]||"").toLowerCase(),o=t.includes("--json"),n=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!r||!["python","node","go","java","dotnet","rust","php"].includes(r))return o?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]"},null,2)}
300
+ `):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),1;let a=async(y,j)=>{if(y==="node"){if(!A.existsSync(b.join(j,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let l=A.existsSync(b.join(j,"pnpm-lock.yaml")),P=A.existsSync(b.join(j,"yarn.lock"));return l?{exitCode:await e$1("pnpm",["install","--lockfile-only","--ignore-scripts"],j)}:P?{exitCode:await e$1("yarn",["install","--ignore-scripts"],j)}:{exitCode:await e$1("npm",["install","--package-lock-only","--ignore-scripts"],j)}}if(y==="go")return A.existsSync(b.join(j,"go.mod"))?{exitCode:await e$1("go",["mod","download"],j)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(y==="java"){let x=A.existsSync(b.join(j,"pom.xml")),l=A.existsSync(b.join(j,"build.gradle"))||A.existsSync(b.join(j,"build.gradle.kts")),P=b.join(j,process.platform==="win32"?"gradlew.bat":"gradlew"),u=A.existsSync(P);return !x&&!l?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:x?{exitCode:await e$1("mvn",["-B","-q","-DskipTests","dependency:go-offline"],j)}:{exitCode:await e$1(u?P:"gradle",["--no-daemon","dependencies"],j)}}return y==="dotnet"?(()=>{let l=[{dir:j,depth:0}],P=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;l.length>0;){let u=l.shift();if(!u||u.depth>3)continue;let h=[];try{h=A.readdirSync(u.dir,{withFileTypes:true});}catch{continue}for(let f of h)if(f.isFile()){let v=f.name.toLowerCase();if(v.endsWith(".sln")||v.endsWith(".csproj"))return true}else f.isDirectory()&&!P.has(f.name)&&l.push({dir:b.join(u.dir,f.name),depth:u.depth+1});}return false})()?{exitCode:await e$1("dotnet",["restore"],j)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:y==="rust"?A.existsSync(b.join(j,"Cargo.toml"))?{exitCode:await e$1("cargo",["fetch"],j)}:{exitCode:0,message:"Rust warm-up skipped: Cargo.toml not found in current directory."}:y==="php"?A.existsSync(b.join(j,"composer.json"))?{exitCode:await e$1("composer",["install","--no-interaction","--no-scripts"],j)}:{exitCode:0,message:"PHP warm-up skipped: composer.json not found in current directory."}:{exitCode:0,message:"Dependency warm-up is not available for this runtime."}};if(o){let y=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let x=await Fe(r,{runCommandInCwd:e$1,runCoreRapidkit:async(f,v)=>(await g$6(f,{...v,cwd:void 0})).exitCode}).checkPrereqs(),l$1=we(process.cwd()),P=l$1||process.cwd(),u=null;if(r==="node"&&x.exitCode===0&&(u=process.version),l$1&&u){let f=s$1(l$1,"toolchain.lock").find(R=>A.existsSync(R))??p(l$1,"toolchain.lock"),v=p(l$1,"toolchain.lock"),C={};try{C=JSON.parse(await A.promises.readFile(f,"utf-8"));}catch{}(!C.runtime||typeof C.runtime!="object")&&(C.runtime={}),C.runtime[r]={version:u,detectedAt:new Date().toISOString()},await O__default.ensureDir(b.dirname(v)),await A.promises.writeFile(v,JSON.stringify(C,null,2)+`
301
+ `,"utf-8");}let h={requested:n,status:"not-requested",exitCode:null,targets:0,messages:[]};if(n&&x.exitCode===0){let f=[P];if(r==="java"&&l$1){let E=(await Ws(l$1)).filter($=>{let N=i$2($);return l(N,$)});E.length>0&&(f=E);}let v=[];for(let w of f)v.push(await a(r,w));let C=v.filter(w=>w.exitCode!==0),R=v.filter(w=>w.exitCode===0&&!/skipped/i.test(w.message||""));h.status=C.length>0?"failed":R.length>0?"passed":"skipped",h.exitCode=C[0]?.exitCode??0,h.targets=f.length,h.messages=v.map(w=>w.message).filter(w=>typeof w=="string");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:r,result:x.exitCode===0?"ok":"failed",exitCode:x.exitCode,workspacePath:l$1,version:u,warmDeps:n,warmDependencies:h},null,2)}
302
+ `),x.exitCode}finally{typeof y>"u"?delete process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT:process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT=y;}}let i=Fe(r,{runCommandInCwd:e$1,runCoreRapidkit:(y,j)=>e(y,{...j,cwd:void 0})}),c=await i.checkPrereqs(),p$1=await i.doctorHints(process.cwd()),d=we(process.cwd()),g=d||process.cwd(),m=null,k=async()=>r!=="java"||!d?[]:m||(m=(await Ws(d)).filter(j=>{let x=i$2(j);return l(x,j)}),m);if(c.exitCode===0){console.log(s.green(`\u2705 ${r} prerequisites look good.`));let y=["python","node","go","java","dotnet","rust","php"].filter(j=>j!==r).join("/");if(console.log(s.gray(` Scope: validated ${r} runtime only. ${y} checks are optional unless your workspace profile uses them.`)),r==="python"&&console.log(s.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),i.warmSetupCache&&((await i.warmSetupCache(g)).exitCode===0?console.log(s.gray(` ${r} cache warm-up completed.`)):console.log(s.yellow(` ${r} cache warm-up skipped (non-fatal).`))),n)if(r==="java"&&d){let j=await k();if(j.length>0){let x=0,l=0,P=0;for(let u of j){let h=await a("java",u),f=/skipped/i.test(h.message||""),v=b.relative(d,u)||b.basename(u);h.message&&console.log(s.gray(` [${v}] ${h.message}`)),h.exitCode===0&&!f?x+=1:h.exitCode===0&&f?P+=1:l+=1;}x>0&&console.log(s.gray(` java dependency warm-up completed for ${x} project(s) (--warm-deps).`)),l>0&&console.log(s.yellow(` java dependency warm-up failed for ${l} project(s) (non-fatal).`)),x===0&&l===0&&P>0&&console.log(s.gray(" java dependency warm-up skipped for discovered workspace projects."));}else {let x=await a("java",g),l=/skipped/i.test(x.message||"");x.message&&console.log(s.gray(` ${x.message}`)),x.exitCode===0&&!l?console.log(s.gray(` ${r} dependency warm-up completed (--warm-deps).`)):x.exitCode!==0&&console.log(s.yellow(` ${r} dependency warm-up failed (non-fatal).`));}}else {let j=await a(r,g),x=/skipped/i.test(j.message||"");j.message&&console.log(s.gray(` ${j.message}`)),j.exitCode===0&&!x?console.log(s.gray(` ${r} dependency warm-up completed (--warm-deps).`)):j.exitCode!==0&&console.log(s.yellow(` ${r} dependency warm-up failed (non-fatal).`));}if(d)try{let j=s$1(d,"toolchain.lock").find(u=>A.existsSync(u))??p(d,"toolchain.lock"),x=p(d,"toolchain.lock"),l={};try{l=JSON.parse(await A.promises.readFile(j,"utf-8"));}catch{}(!l.runtime||typeof l.runtime!="object")&&(l.runtime={});let P=l.runtime;if(r==="python"){let u=null;try{let{execa:h}=await import('execa');for(let f of Gs()){let C=await h(f,f==="py"?["-3","--version"]:["--version"],{cwd:d,stdio:"pipe",reject:false,timeout:3e3});if(C.exitCode===0){let w=(C.stdout||C.stderr||"").match(/Python\s+(\S+)/);if(u=w?w[1]:null,u)break}}}catch{}P.python={...P.python||{},version:u,last_setup:new Date().toISOString()};}else if(r==="node")P.node={...P.node||{},version:process.version,last_setup:new Date().toISOString()};else if(r==="go"){let u=null;try{let{execa:h}=await import('execa'),v=((await h("go",["version"],{cwd:d,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);u=v?v[1]:null;}catch{}P.go={...P.go||{},version:u,last_setup:new Date().toISOString()};}else if(r==="java"){let u=null,h=null,f=null,v=await k(),R=A.existsSync(b.join(g,"pom.xml"))||A.existsSync(b.join(g,"build.gradle"))||A.existsSync(b.join(g,"build.gradle.kts"))?g:v[0]||g;try{let{execa:w}=await import('execa'),E=await w("java",["-version"],{cwd:d,stdio:"pipe",reject:false,timeout:3e3}),N=`${E.stdout||""}
303
+ ${E.stderr||""}`.match(/version\s+"([^"]+)"/i);u=N?N[1]:null;let M=A.existsSync(b.join(R,"pom.xml")),_=A.existsSync(b.join(R,"build.gradle"))||A.existsSync(b.join(R,"build.gradle.kts"));if(M){h="maven";let S=(()=>{let G=b.join(R,"mvnw.cmd");if(process.platform==="win32"&&A.existsSync(G))return G;let H=b.join(R,"mvnw");return A.existsSync(H)?H:"mvn"})(),J=await w(S,["-version"],{cwd:R,stdio:"pipe",reject:false,timeout:3e3}),W=`${J.stdout||""}
304
+ ${J.stderr||""}`.match(/Apache Maven\s+(\S+)/i);f=W?W[1]:null;}else if(_){h="gradle";let S=(()=>{let G=b.join(R,"gradlew.bat");if(process.platform==="win32"&&A.existsSync(G))return G;let H=b.join(R,"gradlew");return A.existsSync(H)?H:"gradle"})(),J=await w(S,["--version"],{cwd:R,stdio:"pipe",reject:false,timeout:3e3}),W=`${J.stdout||""}
305
305
  ${J.stderr||""}`.match(/Gradle\s+(\S+)/i);f=W?W[1]:null;}}catch{}P.java={...P.java||{},version:u,build_tool:h,build_tool_version:f,last_setup:new Date().toISOString()};}else if(r==="dotnet"){let u=null;try{let{execa:h}=await import('execa'),v=((await h("dotnet",["--version"],{cwd:d,stdio:"pipe",reject:false,timeout:3e3})).stdout||"").trim();u=v.length>0?v:null;}catch{}P.dotnet={...P.dotnet||{},version:u,sdk:u,last_setup:new Date().toISOString()};}l.updated_at=new Date().toISOString(),await A.promises.writeFile(x,JSON.stringify(l,null,2)+`
306
306
  `,"utf-8"),console.log(s.gray(" toolchain.lock updated (.workspai/toolchain.lock)"));}catch{}}else console.log(s.red(`\u274C ${r} prerequisites check failed.`));if(p$1.length>0){console.log(s.gray(`
307
- Hints:`));for(let w of p$1)console.log(s.gray(`- ${w}`));}return c.exitCode}function bm(t){let e={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let r of t.split(`
308
- `)){let o=r.trim(),n=o.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]/g,""));let a=o.match(/^prune_on_bootstrap:\s*(true|false)/);a&&(e.prune_on_bootstrap=a[1]==="true");let i=o.match(/^self_heal:\s*(true|false)/);i&&(e.self_heal=i[1]==="true");let c=o.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function Cm(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=t.includes("--dry-run"),n=Jo.getInstance(),a=Pe(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(a)try{let c=s$1(a,"cache-config.yml").find(d=>A.existsSync(d));if(!c)throw new Error("cache config missing");let p=await A.promises.readFile(c,"utf-8");i=bm(p);}catch{}if(e==="status"){let c={command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{enabled:true,strategy:i.strategy,selfHeal:i.self_heal,pruneOnBootstrap:i.prune_on_bootstrap,verifyIntegrity:i.verify_integrity,inMemory:true}};return r?(process.stdout.write(`${JSON.stringify(c,null,2)}
307
+ Hints:`));for(let y of p$1)console.log(s.gray(`- ${y}`));}return c.exitCode}function km(t){let e={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let r of t.split(`
308
+ `)){let o=r.trim(),n=o.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]/g,""));let a=o.match(/^prune_on_bootstrap:\s*(true|false)/);a&&(e.prune_on_bootstrap=a[1]==="true");let i=o.match(/^self_heal:\s*(true|false)/);i&&(e.self_heal=i[1]==="true");let c=o.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function vm(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=t.includes("--dry-run"),n=Do.getInstance(),a=we(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(a)try{let c=s$1(a,"cache-config.yml").find(d=>A.existsSync(d));if(!c)throw new Error("cache config missing");let p=await A.promises.readFile(c,"utf-8");i=km(p);}catch{}if(e==="status"){let c={command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{enabled:true,strategy:i.strategy,selfHeal:i.self_heal,pruneOnBootstrap:i.prune_on_bootstrap,verifyIntegrity:i.verify_integrity,inMemory:true}};return r?(process.stdout.write(`${JSON.stringify(c,null,2)}
309
309
  `),0):(console.log(s.cyan("Workspai cache is enabled")),console.log(s.cyan("Workspai cache status")),a?(console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Strategy: ${i.strategy}`)),console.log(s.gray(` Self-heal: ${i.self_heal}`)),console.log(s.gray(` Prune on bootstrap:${i.prune_on_bootstrap}`)),console.log(s.gray(` Verify integrity: ${i.verify_integrity}`))):console.log(s.gray(" (not inside a workspace \u2014 showing in-memory cache only)")),console.log(s.gray(" In-memory cache: enabled")),console.log(s.gray(" Use: workspai cache clear|prune|repair")),0)}return e==="clear"?(await n.clear(),r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{cleared:true,strategy:i.strategy}},null,2)}
310
310
  `),0):(console.log(s.green("Cache clear completed")),console.log(s.green("\u2705 Cache cleared (all entries removed).")),0)):e==="prune"?(o||await n.clear(),r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,dryRun:o,cache:{pruned:!o,strategy:i.strategy,pruneOnBootstrap:i.prune_on_bootstrap},nextActions:i.prune_on_bootstrap?[]:["Set prune_on_bootstrap: true in .workspai/cache-config.yml to auto-prune on bootstrap."]},null,2)}
311
311
  `),0):o?(console.log(s.green("Cache prune dry run completed")),console.log(s.gray(" No cache entries were removed.")),0):(console.log(s.green("\u2705 Cache pruned (stale entries removed).")),i.prune_on_bootstrap||console.log(s.gray(" Tip: set prune_on_bootstrap: true in .workspai/cache-config.yml to auto-prune on every bootstrap.")),0)):e==="repair"?i.self_heal?(await n.clear(),r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{repaired:true,selfHeal:i.self_heal,verifyIntegrity:i.verify_integrity}},null,2)}
312
312
  `),0):(console.log(s.green("\u2705 Cache repaired (self-heal applied, stale entries evicted).")),i.verify_integrity&&console.log(s.gray(" Integrity verification is enabled in cache-config.yml.")),0)):r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"skipped",timestamp:new Date().toISOString(),workspacePath:a,reason:"self_heal is disabled in .workspai/cache-config.yml",cache:{selfHeal:i.self_heal,verifyIntegrity:i.verify_integrity}},null,2)}
313
- `),0):(console.log(s.yellow("\u26A0\uFE0F self_heal is disabled in .workspai/cache-config.yml \u2014 skipping repair.")),0):(console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),1)}async function Sm(t,e,r,o,n=false){let a=(e||"show").toLowerCase(),i=p(t,"policies.yml");if(a==="show"||a==="status"||a==="get"){let m=await Gl(t),k=Fl(m);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,policy:k},null,2)}
313
+ `),0):(console.log(s.yellow("\u26A0\uFE0F self_heal is disabled in .workspai/cache-config.yml \u2014 skipping repair.")),0):(console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),1)}async function Pm(t,e,r,o,n=false){let a=(e||"show").toLowerCase(),i=p(t,"policies.yml");if(a==="show"||a==="status"||a==="get"){let m=await Dl(t),k=Ml(m);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,policy:k},null,2)}
314
314
  `),0):(console.log(s.cyan(`Policy file: ${i}`)),console.log(s.gray(` mode: ${k.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${k.dependency_sharing_mode}`)),console.log(s.gray(" rules:")),console.log(s.gray(` enforce_workspace_marker: ${k.rules.enforce_workspace_marker}`)),console.log(s.gray(` enforce_toolchain_lock: ${k.rules.enforce_toolchain_lock}`)),console.log(s.gray(` disallow_untrusted_tool_sources: ${k.rules.disallow_untrusted_tool_sources}`)),console.log(s.gray(` enforce_compatibility_matrix: ${k.rules.enforce_compatibility_matrix}`)),console.log(s.gray(` require_mirror_lock_for_offline: ${k.rules.require_mirror_lock_for_offline}`)),console.log(s.gray("Examples:")),console.log(s.gray(" npx workspai workspace policy set mode strict")),console.log(s.gray(" npx workspai workspace policy set dependency_sharing_mode shared-runtime-caches")),console.log(s.gray(" npx workspai workspace policy set rules.enforce_toolchain_lock true")),0)}if(a!=="set")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_action",message:`Unknown workspace policy action: ${e||""}`},allowedActions:["show","status","get","set"]},null,2)}
315
315
  `),1):(console.log(s.red(`Unknown workspace policy action: ${e||""}`)),console.log(s.gray("Available: show, set")),1);if(!r||typeof o>"u")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.missing_arguments",message:"Usage: workspai workspace policy set <key> <value>"},allowedKeys:["mode","dependency_sharing_mode","rules.enforce_workspace_marker","rules.enforce_toolchain_lock","rules.disallow_untrusted_tool_sources","rules.enforce_compatibility_matrix","rules.require_mirror_lock_for_offline"]},null,2)}
316
- `),1):(console.log(s.yellow("Usage: workspai workspace policy set <key> <value>")),console.log(s.gray("Allowed keys:")),console.log(s.gray(" mode (warn|strict)")),console.log(s.gray(" dependency_sharing_mode (isolated|shared-runtime-caches|shared-node-deps)")),console.log(s.gray(" rules.enforce_workspace_marker (true|false)")),console.log(s.gray(" rules.enforce_toolchain_lock (true|false)")),console.log(s.gray(" rules.disallow_untrusted_tool_sources (true|false)")),console.log(s.gray(" rules.enforce_compatibility_matrix (true|false)")),console.log(s.gray(" rules.require_mirror_lock_for_offline (true|false)")),1);let c=r.trim(),d=await Gl(t);if(c==="mode"){let m=o.trim().toLowerCase();if(m!=="warn"&&m!=="strict")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_mode",message:"Invalid mode. Use: warn | strict"}},null,2)}
317
- `),1):(console.log(s.red("\u274C Invalid mode. Use: warn | strict")),1);d=Jl(d,"mode",`${m} # "warn" or "strict"`);}else if(c==="dependency_sharing_mode"){let m=o.trim().toLowerCase();if(m!=="isolated"&&m!=="shared-runtime-caches"&&m!=="shared-node-deps")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_dependency_sharing_mode",message:"Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps"}},null,2)}
318
- `),1):(console.log(s.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1);d=Jl(d,"dependency_sharing_mode",`${m} # "isolated" or "shared-runtime-caches" or "shared-node-deps"`);}else if(c.startsWith("rules.")){let m=c.slice(6);if(!(m in Yl))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: ${m}`}},null,2)}
319
- `),1):(console.log(s.red(`\u274C Unknown policy rule: ${m}`)),1);let k=gm(o);if(k===null)return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_boolean",message:"Rule values must be boolean: true | false"}},null,2)}
320
- `),1):(console.log(s.red("\u274C Rule values must be boolean: true | false")),1);d=dm(d,m,k);}else return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_key",message:`Unknown policy key: ${c}`}},null,2)}
321
- `),1):(console.log(s.red(`\u274C Unknown policy key: ${c}`)),1);await mm(t,d);let g=Fl(d);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:g},null,2)}
322
- `),0):(console.log(s.green(`\u2705 Updated ${c} in .workspai/policies.yml`)),console.log(s.gray(` mode: ${g.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${g.dependency_sharing_mode}`)),console.log(s.gray(" Tip: run `npx workspai workspace policy show` to inspect all values.")),0)}async function xm(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=Pe(process.cwd());if(!o)return console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let n=s$1(o,"mirror-config.json").find(m=>A.existsSync(m))??p(o,"mirror-config.json"),a=s$1(o,"mirror.lock").find(m=>A.existsSync(m))??p(o,"mirror.lock"),i=p(o,"mirror","artifacts"),c=p(o,"reports");async function p$1(m){if(!await O__default.pathExists(m))return 0;let k=0,w=[m];for(;w.length>0;){let j=w.shift();if(!j)continue;let x=await A.promises.readdir(j,{withFileTypes:true});for(let l of x)l.isFile()?k+=1:l.isDirectory()&&w.push(b.join(j,l.name));}return k}async function d(m){let k=new Date().toISOString().replace(/[:.]/g,"-"),w=b.join(c,`mirror-ops-${k}.json`),j=b.join(c,"mirror-ops.latest.json"),x={schemaVersion:d$9.mirrorOps.schemaVersion,...m};b$l(`.workspai/reports/${b.basename(w)}`,x),b$l(e$1.mirrorOps,x),await O__default.ensureDir(c),await nn(w,x),await nn(j,x);}async function g(){let m=await O__default.pathExists(n),k=await O__default.pathExists(a),w=await p$1(i);return {configExists:m,lockExists:k,artifactsCount:w}}if(e==="status"){let m=await O__default.pathExists(n),k=await O__default.pathExists(a),w=await p$1(i),j={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:{configExists:m,lockExists:k,artifactsCount:w}};return await d(j),r?(process.stdout.write(`${JSON.stringify(j,null,2)}
323
- `),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Config: ${m?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${k?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${w}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let m=await ms(o,{ciMode:true,offlineMode:e==="verify",forceRun:true}),k=m.checks.filter(x=>x.status==="failed"),w=m.checks.some(x=>x.id.startsWith("mirror.verify.")&&x.status==="failed");if(e==="verify"&&w){let x={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await g(),details:m.details,checks:m.checks};if(await d(x),r)return process.stdout.write(`${JSON.stringify(x,null,2)}
316
+ `),1):(console.log(s.yellow("Usage: workspai workspace policy set <key> <value>")),console.log(s.gray("Allowed keys:")),console.log(s.gray(" mode (warn|strict)")),console.log(s.gray(" dependency_sharing_mode (isolated|shared-runtime-caches|shared-node-deps)")),console.log(s.gray(" rules.enforce_workspace_marker (true|false)")),console.log(s.gray(" rules.enforce_toolchain_lock (true|false)")),console.log(s.gray(" rules.disallow_untrusted_tool_sources (true|false)")),console.log(s.gray(" rules.enforce_compatibility_matrix (true|false)")),console.log(s.gray(" rules.require_mirror_lock_for_offline (true|false)")),1);let c=r.trim(),d=await Dl(t);if(c==="mode"){let m=o.trim().toLowerCase();if(m!=="warn"&&m!=="strict")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_mode",message:"Invalid mode. Use: warn | strict"}},null,2)}
317
+ `),1):(console.log(s.red("\u274C Invalid mode. Use: warn | strict")),1);d=Wl(d,"mode",`${m} # "warn" or "strict"`);}else if(c==="dependency_sharing_mode"){let m=o.trim().toLowerCase();if(m!=="isolated"&&m!=="shared-runtime-caches"&&m!=="shared-node-deps")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_dependency_sharing_mode",message:"Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps"}},null,2)}
318
+ `),1):(console.log(s.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1);d=Wl(d,"dependency_sharing_mode",`${m} # "isolated" or "shared-runtime-caches" or "shared-node-deps"`);}else if(c.startsWith("rules.")){let m=c.slice(6);if(!(m in Hl))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: ${m}`}},null,2)}
319
+ `),1):(console.log(s.red(`\u274C Unknown policy rule: ${m}`)),1);let k=pm(o);if(k===null)return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_boolean",message:"Rule values must be boolean: true | false"}},null,2)}
320
+ `),1):(console.log(s.red("\u274C Rule values must be boolean: true | false")),1);d=im(d,m,k);}else return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_key",message:`Unknown policy key: ${c}`}},null,2)}
321
+ `),1):(console.log(s.red(`\u274C Unknown policy key: ${c}`)),1);await lm(t,d);let g=Ml(d);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:g},null,2)}
322
+ `),0):(console.log(s.green(`\u2705 Updated ${c} in .workspai/policies.yml`)),console.log(s.gray(` mode: ${g.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${g.dependency_sharing_mode}`)),console.log(s.gray(" Tip: run `npx workspai workspace policy show` to inspect all values.")),0)}async function jm(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=we(process.cwd());if(!o)return console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let n=s$1(o,"mirror-config.json").find(m=>A.existsSync(m))??p(o,"mirror-config.json"),a=s$1(o,"mirror.lock").find(m=>A.existsSync(m))??p(o,"mirror.lock"),i=p(o,"mirror","artifacts"),c=p(o,"reports");async function p$1(m){if(!await O__default.pathExists(m))return 0;let k=0,y=[m];for(;y.length>0;){let j=y.shift();if(!j)continue;let x=await A.promises.readdir(j,{withFileTypes:true});for(let l of x)l.isFile()?k+=1:l.isDirectory()&&y.push(b.join(j,l.name));}return k}async function d(m){let k=new Date().toISOString().replace(/[:.]/g,"-"),y=b.join(c,`mirror-ops-${k}.json`),j=b.join(c,"mirror-ops.latest.json"),x={schemaVersion:d$9.mirrorOps.schemaVersion,...m};b$l(`.workspai/reports/${b.basename(y)}`,x),b$l(e$1.mirrorOps,x),await O__default.ensureDir(c),await tn(y,x),await tn(j,x);}async function g(){let m=await O__default.pathExists(n),k=await O__default.pathExists(a),y=await p$1(i);return {configExists:m,lockExists:k,artifactsCount:y}}if(e==="status"){let m=await O__default.pathExists(n),k=await O__default.pathExists(a),y=await p$1(i),j={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:{configExists:m,lockExists:k,artifactsCount:y}};return await d(j),r?(process.stdout.write(`${JSON.stringify(j,null,2)}
323
+ `),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Config: ${m?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${k?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${y}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let m=await ps(o,{ciMode:true,offlineMode:e==="verify",forceRun:true}),k=m.checks.filter(x=>x.status==="failed"),y=m.checks.some(x=>x.id.startsWith("mirror.verify.")&&x.status==="failed");if(e==="verify"&&y){let x={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await g(),details:m.details,checks:m.checks};if(await d(x),r)return process.stdout.write(`${JSON.stringify(x,null,2)}
324
324
  `),1;console.log(s.red("\u274C Mirror verify failed."));for(let l of m.checks.filter(P=>P.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${l.id}: ${l.message}`));return 1}if(k.length>0){let x={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await g(),details:m.details,checks:m.checks};if(await d(x),r)return process.stdout.write(`${JSON.stringify(x,null,2)}
325
325
  `),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${k.length} issue(s).`));for(let l of k)console.log(s.gray(`- ${l.id}: ${l.message}`));return 1}let j={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:await g(),details:m.details,checks:m.checks};return await d(j),r?(process.stdout.write(`${JSON.stringify(j,null,2)}
326
- `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${m.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${m.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${m.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Js(t){let e$1=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$1>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await Zl(r,async()=>{let n$1=Pe(r),a=Ke("python",{runCommandInCwd:je,runCoreRapidkit:e}),i=Ke("dotnet",{runCommandInCwd:je,runCoreRapidkit:e}),c=Ke("rust",{runCommandInCwd:je,runCoreRapidkit:e}),p=Ke("php",{runCommandInCwd:je,runCoreRapidkit:e}),d=t.slice(1).filter(l=>!l.startsWith("-"));if(d.length>0){let l$1=b.resolve(r,d[0]),P=i$2(l$1),u=await Wt(l$1);return j$2(P,l$1)||u==="go"?await Ss(l$1):l(P,l$1)||u==="java"?await ht("init",l$1):m$1(P,l$1)||u==="dotnet"?Q(await i.initProject(l$1)):k(P,l$1)||u==="node"?await Cs(l$1):n(P,l$1)||u==="python"?await bs(l$1,a):u==="rust"?Q(await c.initProject(l$1)):u==="php"?Q(await p.initProject(l$1)):await e(t,{cwd:r})}let g=i$2(r),m=!!Pe(r)&&r===Pe(r);if(!m&&j$2(g,r))return await Ss(r);let k$1=await Wt(r);if(!m&&(l(g,r)||k$1==="java"))return await ht("init",r);if(!m&&(m$1(g,r)||k$1==="dotnet"))return Q(await i.initProject(r));if(!m&&(k(g,r)||k$1==="node"))return await Cs(r);if(!m&&(n(g,r)||k$1==="python"))return await bs(r,a);if(!m&&k$1==="rust")return Q(await c.initProject(r));if(!m&&k$1==="php")return Q(await p.initProject(r));let w=n$1||Pe(r),j=ql(r),x=j?b.dirname(b.dirname(j)):null;if(x&&x!==w){let l$1=i$2(x),P=await Wt(x);return j$2(l$1,x)||P==="go"?await Ss(x):l(l$1,x)||P==="java"?await ht("init",x):m$1(l$1,x)||P==="dotnet"?Q(await i.initProject(x)):k(l$1,x)||P==="node"?await Cs(x):n(l$1,x)||P==="python"?await bs(x,a):P==="rust"?Q(await c.initProject(x)):P==="php"?Q(await p.initProject(x)):await e(["init"],{cwd:x})}if(w&&r===w){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 l=await Ls(w);if(l!==0)return l;let{runWorkspaceStage:P}=await import('./workspace-run-VPXRRHDK.js');return (await P({workspacePath:w,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!w){let l=await b$1(),P=k$2(),{name:u}=vm(P);await O__default.ensureDir(P);let{createProject:h}=await import('./create-R6A7EHQZ.js');return await h(u,{yes:true,userConfig:l,parentDirectory:P}),0}return await e(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e$1>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$1;}}async function Kl(t){let e=Pe(t);if(!e)return [];let r="warn";try{let p=s$1(e,"policies.yml").find(m=>A.existsSync(m));if(!p)return [];let d=await A.promises.readFile(p,"utf-8");(d.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??d.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n$1=s$1(e,"toolchain.lock").find(p=>A.existsSync(p));if(!n$1||!A.existsSync(n$1))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await A.promises.readFile(n$1,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=i$2(t);j$2(c,t)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):k(c,t)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):l(c,t)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):m$1(c,t)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):n(c,t)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let p=s$1(e,"workspace.json").find(w=>A.existsSync(w));if(!p)throw new Error("workspace manifest missing");let g=JSON.parse(await A.promises.readFile(p,"utf-8")).profile??"",m=j$3(t,c),k=St({profile:g,runtime:m.runtime,subjectLabel:b.basename(t),mode:"strict"});k.ok||o.push(`${k.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function Em(){let t$1=async h=>{if(!b$4()||!h.toLowerCase().endsWith(".cmd"))return false;try{let v=(await O__default.readFile(h,"utf8")).replace(/\r\n/g,`
327
- `).toLowerCase(),C=v.includes("\\.rapidkit\\rapidkit"),R=v.includes("\\.rapidkit\\rapidkit.cmd")||v.includes("\\.rapidkit\\rapidkit.exe")||v.includes("\\.venv\\scripts\\rapidkit.exe");return C&&!R}catch{return false}},e$1=process.cwd(),r=process.argv.slice(2),o=r[0],n$1=o==="init",a=new Set(q$2),i=!o||o==="--help"||o==="-h"||o==="help",c=Ye(e$1),p=t(e$1,"project.json").some(h=>A.existsSync(h)),d=i$2(e$1),g=await Wt(e$1),m=j$2(d,e$1)||k(d,e$1)||n(d,e$1)||l(d,e$1)||m$1(d,e$1)||h$4(g??void 0),k$1=!!o&&a.has(o)&&m,w=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Jr(r)||r[0]==="create")return false;if(Ts(r))return true;if(r[0]==="init"&&c&&!p)return false;if(Ms(r))return true;try{let h=o==="shell"&&r[1]==="activate",f=o==="create",v=await Ri(e$1,{cwd:e$1,timeoutMs:1200});if(v.ok&&v.data?.isRapidkitProject&&v.data.engine==="python"){let C=f||Jr(r);if(!i&&!h&&!C&&!n$1&&!k$1&&_n(r)){if(o&&Ml.includes(o)){let y=await Kl(e$1).catch(()=>[]);if(y.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
328
- `);for(let E of y)process.stderr.write(s.red(` \u2022 ${E}`)+`
329
- `);process.exit(1);}}let R=await e(process.argv.slice(2),{cwd:e$1});process.exit(R);}}}catch{}let j=ql(e$1),x=b$4(),l$1=w?[]:p$1(e$1),P=null;for(let h of l$1)if(await O__default.pathExists(h)){if(await t$1(h)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${h}. Falling back to core bridge.`);continue}P=h;break}let u=o==="create";if(o==="init"&&c&&!p)return false;if(o&&Ml.includes(o)){let h=await Kl(e$1);if(h.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
326
+ `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${m.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${m.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${m.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Ds(t){let e$1=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$1>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await zl(r,async()=>{let n$1=we(r),a=Fe("python",{runCommandInCwd:ke,runCoreRapidkit:e}),i=Fe("dotnet",{runCommandInCwd:ke,runCoreRapidkit:e}),c=Fe("rust",{runCommandInCwd:ke,runCoreRapidkit:e}),p=Fe("php",{runCommandInCwd:ke,runCoreRapidkit:e}),d=t.slice(1).filter(l=>!l.startsWith("-"));if(d.length>0){let l$1=b.resolve(r,d[0]),P=i$2(l$1),u=await Nt(l$1);return j$2(P,l$1)||u==="go"?await js(l$1):l(P,l$1)||u==="java"?await mt("init",l$1):m$1(P,l$1)||u==="dotnet"?Q(await i.initProject(l$1)):k(P,l$1)||u==="node"?await Ps(l$1):n(P,l$1)||u==="python"?await vs(l$1,a):u==="rust"?Q(await c.initProject(l$1)):u==="php"?Q(await p.initProject(l$1)):await e(t,{cwd:r})}let g=i$2(r),m=!!we(r)&&r===we(r);if(!m&&j$2(g,r))return await js(r);let k$1=await Nt(r);if(!m&&(l(g,r)||k$1==="java"))return await mt("init",r);if(!m&&(m$1(g,r)||k$1==="dotnet"))return Q(await i.initProject(r));if(!m&&(k(g,r)||k$1==="node"))return await Ps(r);if(!m&&(n(g,r)||k$1==="python"))return await vs(r,a);if(!m&&k$1==="rust")return Q(await c.initProject(r));if(!m&&k$1==="php")return Q(await p.initProject(r));let y=n$1||we(r),j=Vl(r),x=j?b.dirname(b.dirname(j)):null;if(x&&x!==y){let l$1=i$2(x),P=await Nt(x);return j$2(l$1,x)||P==="go"?await js(x):l(l$1,x)||P==="java"?await mt("init",x):m$1(l$1,x)||P==="dotnet"?Q(await i.initProject(x)):k(l$1,x)||P==="node"?await Ps(x):n(l$1,x)||P==="python"?await vs(x,a):P==="rust"?Q(await c.initProject(x)):P==="php"?Q(await p.initProject(x)):await e(["init"],{cwd:x})}if(y&&r===y){console.log(s.yellow("\u26A0\uFE0F Running `npx workspai init` at workspace root.")),console.log(s.gray(" Root `init`, `workspace init`, and `workspace run init` now share the same full-init flow:\n workspace-profile dependencies first, then project dependency initialization.\n"));let l=await Ms(y);if(l!==0)return l;let{runWorkspaceStage:P}=await import('./workspace-run-FJTBX4JQ.js');return (await P({workspacePath:y,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!y){let l=await b$1(),P=k$2(),{name:u}=hm(P);await O__default.ensureDir(P);let{createProject:h}=await import('./create-3NSOY7CA.js');return await h(u,{yes:true,userConfig:l,parentDirectory:P}),0}return await e(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e$1>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$1;}}async function Ll(t){let e=we(t);if(!e)return [];let r="warn";try{let p=s$1(e,"policies.yml").find(m=>A.existsSync(m));if(!p)return [];let d=await A.promises.readFile(p,"utf-8");(d.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??d.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n$1=s$1(e,"toolchain.lock").find(p=>A.existsSync(p));if(!n$1||!A.existsSync(n$1))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await A.promises.readFile(n$1,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=i$2(t);j$2(c,t)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):k(c,t)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):l(c,t)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):m$1(c,t)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):n(c,t)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let p=s$1(e,"workspace.json").find(y=>A.existsSync(y));if(!p)throw new Error("workspace manifest missing");let g=JSON.parse(await A.promises.readFile(p,"utf-8")).profile??"",m=j$3(t,c),k=jt({profile:g,runtime:m.runtime,subjectLabel:b.basename(t),mode:"strict"});k.ok||o.push(`${k.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function bm(){let t$1=async h=>{if(!b$4()||!h.toLowerCase().endsWith(".cmd"))return false;try{let v=(await O__default.readFile(h,"utf8")).replace(/\r\n/g,`
327
+ `).toLowerCase(),C=v.includes("\\.rapidkit\\rapidkit"),R=v.includes("\\.rapidkit\\rapidkit.cmd")||v.includes("\\.rapidkit\\rapidkit.exe")||v.includes("\\.venv\\scripts\\rapidkit.exe");return C&&!R}catch{return false}},e$1=process.cwd(),r=process.argv.slice(2),o=r[0],n$1=o==="init",a=new Set(q$2),i=!o||o==="--help"||o==="-h"||o==="help",c=Be(e$1),p=t(e$1,"project.json").some(h=>A.existsSync(h)),d=i$2(e$1),g=await Nt(e$1),m=j$2(d,e$1)||k(d,e$1)||n(d,e$1)||l(d,e$1)||m$1(d,e$1)||h$4(g??void 0),k$1=!!o&&a.has(o)&&m,y=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Dr(r)||r[0]==="create")return false;if(Os(r))return true;if(r[0]==="init"&&c&&!p)return false;if($s(r))return true;try{let h=o==="shell"&&r[1]==="activate",f=o==="create",v=await xi(e$1,{cwd:e$1,timeoutMs:1200});if(v.ok&&v.data?.isRapidkitProject&&v.data.engine==="python"){let C=f||Dr(r);if(!i&&!h&&!C&&!n$1&&!k$1&&En(r)){if(o&&Ol.includes(o)){let w=await Ll(e$1).catch(()=>[]);if(w.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
328
+ `);for(let E of w)process.stderr.write(s.red(` \u2022 ${E}`)+`
329
+ `);process.exit(1);}}let R=await e(process.argv.slice(2),{cwd:e$1});process.exit(R);}}}catch{}let j=Vl(e$1),x=b$4(),l$1=y?[]:p$1(e$1),P=null;for(let h of l$1)if(await O__default.pathExists(h)){if(await t$1(h)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${h}. Falling back to core bridge.`);continue}P=h;break}let u=o==="create";if(o==="init"&&c&&!p)return false;if(o&&Ol.includes(o)){let h=await Ll(e$1);if(h.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
330
330
  `);for(let f of h)process.stderr.write(s.red(` \u2022 ${f}`)+`
331
- `);process.exit(1);}}if(P&&o&&Tl.includes(o)&&!u&&!n$1&&!k$1){f.debug(`Delegating to local CLI: ${P} ${r.join(" ")}`);let h=o==="init"?_l():process.env,f$1=spawn(P,r,{stdio:"inherit",cwd:e$1,shell:x,env:h});return f$1.on("close",v=>{process.exit(v??0);}),f$1.on("error",v=>{f.error(`Failed to run local rapidkit: ${v.message}`),process.exit(1);}),true}if(j&&await O__default.pathExists(j))try{let h=await O__default.readJson(j);if(_i(h.engine)){let f$1=r[0],v=w?[]:p$1(e$1),C=null;for(let R of v)if(await O__default.pathExists(R)){if(await t$1(R)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${R}. Falling back to core bridge.`);continue}C=R;break}if(C&&f$1&&Tl.includes(f$1)&&f$1!=="init"&&!k$1){f.debug(`Delegating to local CLI (early detection): ${C} ${r.join(" ")}`);let R=f$1==="init"?_l():process.env,y=spawn(C,r,{stdio:"inherit",cwd:e$1,shell:x,env:R});return y.on("close",E=>process.exit(E??0)),y.on("error",E=>{f.error(`Failed to run local rapidkit: ${E.message}`),process.exit(1);}),true}if(f$1==="shell"&&r[1]==="activate"){let R=b$4()?`# RapidKit Core activation snippet (PowerShell)
331
+ `);process.exit(1);}}if(P&&o&&Il.includes(o)&&!u&&!n$1&&!k$1){f.debug(`Delegating to local CLI: ${P} ${r.join(" ")}`);let h=o==="init"?xl():process.env,f$1=spawn(P,r,{stdio:"inherit",cwd:e$1,shell:x,env:h});return f$1.on("close",v=>{process.exit(v??0);}),f$1.on("error",v=>{f.error(`Failed to run local rapidkit: ${v.message}`),process.exit(1);}),true}if(j&&await O__default.pathExists(j))try{let h=await O__default.readJson(j);if(Ri(h.engine)){let f$1=r[0],v=y?[]:p$1(e$1),C=null;for(let R of v)if(await O__default.pathExists(R)){if(await t$1(R)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${R}. Falling back to core bridge.`);continue}C=R;break}if(C&&f$1&&Il.includes(f$1)&&f$1!=="init"&&!k$1){f.debug(`Delegating to local CLI (early detection): ${C} ${r.join(" ")}`);let R=f$1==="init"?xl():process.env,w=spawn(C,r,{stdio:"inherit",cwd:e$1,shell:x,env:R});return w.on("close",E=>process.exit(E??0)),w.on("error",E=>{f.error(`Failed to run local rapidkit: ${E.message}`),process.exit(1);}),true}if(f$1==="shell"&&r[1]==="activate"){let R=b$4()?`# RapidKit Core activation snippet (PowerShell)
332
332
  $venv = ".venv"
333
333
  if (Test-Path "$venv\\Scripts\\Activate.ps1") { . "$venv\\Scripts\\Activate.ps1" }
334
334
  $env:RAPIDKIT_PROJECT_ROOT = (Get-Location).Path
@@ -350,27 +350,27 @@ export PATH="$(pwd)/.workspai:$(pwd)/.rapidkit:$(pwd):$PATH"
350
350
  \u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
351
351
  `)),console.log(R),console.log(s.gray(`
352
352
  \u{1F4A1} After activation you can run: workspai dev
353
- `)),process.exit(0);}if(!i&&!Jr(r)&&f$1!=="init"&&!k$1&&_n(r)){let R=await e(r,{cwd:e$1});process.exit(R);}}}catch{}return false}var Et=null,rn=false,Rm=Lu(),Gs="workspai",Es="npx workspai",de=new Command;de.enablePositionalOptions();var Am=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function _m(t){if(t.length===0)return false;let e=t[0],r=t[1];if(y(t)||em.includes(e))return false;if(r$1.includes(e)){if(e==="lint"||e==="format"){let n$1=i$2(process.cwd()),a=await Wt(process.cwd());if(k(n$1,process.cwd())||a==="node"){let i=j$3(process.cwd(),n$1);if(t$1(process.cwd(),e,{framework:i.key})!==null)return false}if(n(n$1,process.cwd())||a==="python")return true;if(v$1(process.cwd()))return false}return true}if(Jr(t)||e==="shell"&&r==="activate")return false;if(t.includes("--tui"))return true;if(e==="--help"||e==="-h"||e==="help"||e==="--version"||e==="-V"||e==="-v"||t.includes("--template")||t.includes("-t"))return false;let o=await i$4();return An(e,o)?true:t.some(n=>Rn.has(n))?false:o?o.has(e):!!(a$9.has(e)||t.length>1)}de.name(Gs).description("Workspai workspace intelligence CLI").version(i());de.addHelpText("beforeAll",`Workspai CLI
353
+ `)),process.exit(0);}if(!i&&!Dr(r)&&f$1!=="init"&&!k$1&&En(r)){let R=await e(r,{cwd:e$1});process.exit(R);}}}catch{}return false}var Ct=null,Zo=false,Cm=Tu(),Ls="workspai",Cs="npx workspai",le=new Command;le.enablePositionalOptions();var Sm=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function xm(t){if(t.length===0)return false;let e=t[0],r=t[1];if(y(t)||Yu.includes(e))return false;if(r$1.includes(e)){if(e==="lint"||e==="format"){let n$1=i$2(process.cwd()),a=await Nt(process.cwd());if(k(n$1,process.cwd())||a==="node"){let i=j$3(process.cwd(),n$1);if(t$1(process.cwd(),e,{framework:i.key})!==null)return false}if(n(n$1,process.cwd())||a==="python")return true;if(v$1(process.cwd()))return false}return true}if(Dr(t)||e==="shell"&&r==="activate")return false;if(t.includes("--tui"))return true;if(e==="--help"||e==="-h"||e==="help"||e==="--version"||e==="-V"||e==="-v"||t.includes("--template")||t.includes("-t"))return false;let o=await i$4();return xn(e,o)?true:t.some(n=>Sn.has(n))?false:o?o.has(e):!!(a$9.has(e)||t.length>1)}le.name(Ls).description("Workspai workspace intelligence CLI").version(i());le.addHelpText("beforeAll",`Workspai CLI
354
354
 
355
355
  Workspace Intelligence for software systems.
356
- `);de.addHelpText("afterAll",`
356
+ `);le.addHelpText("afterAll",`
357
357
  Discover more:
358
- ${Gs} --help Product overview and first steps
359
- ${Gs} commands --json Complete machine-readable command inventory
358
+ ${Ls} --help Product overview and first steps
359
+ ${Ls} commands --json Complete machine-readable command inventory
360
360
  https://workspai.dev Guides, contracts, and examples
361
- `);de.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-python-engine","Create a Python-aware workspace without installing rapidkit-core now").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, java-only, python-only, node-only, go-only, dotnet-only, polyglot, enterprise").choices(["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not link it to any workspace").hideHelp()).option("--no-update-check","Skip checking for updates").option("--trust-config","Trust and execute workspai.config.js/mjs/cjs discovered in this tree").action(async(t,e$1)=>{try{e$1.debug&&(f.setDebug(true),f.debug("Debug mode enabled"));let r=await b$1();f.debug("User config loaded",{...r,openaiApiKey:r.openaiApiKey?"[REDACTED]":void 0});let o=await c(process.cwd(),{trustExecutableConfig:e$1.trustConfig===true||process.env.WORKSPAI_TRUST_CONFIG==="1"});f.debug("Workspai config loaded",o);let n=d(r,o,{author:e$1.author,pythonVersion:void 0,skipGit:e$1.skipGit});f.debug("Merged config",n),e$1.updateCheck!==false&&await h(),a("workspace"),t||(tp(),process.exit(0));try{h$1(t);}catch(p){throw p instanceof a$1&&(f.error(`
361
+ `);le.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-python-engine","Create a Python-aware workspace without installing rapidkit-core now").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, java-only, python-only, node-only, go-only, dotnet-only, polyglot, enterprise").choices(["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not link it to any workspace").hideHelp()).option("--no-update-check","Skip checking for updates").option("--trust-config","Trust and execute workspai.config.js/mjs/cjs discovered in this tree").action(async(t,e$1)=>{try{e$1.debug&&(f.setDebug(true),f.debug("Debug mode enabled"));let r=await b$1();f.debug("User config loaded",{...r,openaiApiKey:r.openaiApiKey?"[REDACTED]":void 0});let o=await c(process.cwd(),{trustExecutableConfig:e$1.trustConfig===true||process.env.WORKSPAI_TRUST_CONFIG==="1"});f.debug("Workspai config loaded",o);let n=d(r,o,{author:e$1.author,pythonVersion:void 0,skipGit:e$1.skipGit});f.debug("Merged config",n),e$1.updateCheck!==false&&await h(),a("workspace"),t||(Xl(),process.exit(0));try{h$1(t);}catch(p){throw p instanceof a$1&&(f.error(`
362
362
  \u274C ${p.message}`),p.details&&f.warn(`\u{1F4A1} ${p.details}
363
- `),process.exit(1)),p}let a$2=!!e$1.template,i;a$2||(e$1.here?i=process.cwd():e$1.output?i=b.resolve(e$1.output):i=await j([],{hasYes:e$1.yes}));let c$1=a$2?b.resolve(process.cwd(),t):h$2(t,{outputParent:i});if(Et=c$1,!e$1.dryRun){a$2||await O__default.ensureDir(b.dirname(c$1));let p=a$2?void 0:m(t);(!a$2&&i$1(p,c$1,{outputParent:i})&&p&&await O__default.pathExists(p)||await O__default.pathExists(c$1))&&(f.error(`
363
+ `),process.exit(1)),p}let a$2=!!e$1.template,i;a$2||(e$1.here?i=process.cwd():e$1.output?i=b.resolve(e$1.output):i=await j([],{hasYes:e$1.yes}));let c$1=a$2?b.resolve(process.cwd(),t):h$2(t,{outputParent:i});if(Ct=c$1,!e$1.dryRun){a$2||await O__default.ensureDir(b.dirname(c$1));let p=a$2?void 0:m(t);(!a$2&&i$1(p,c$1,{outputParent:i})&&p&&await O__default.pathExists(p)||await O__default.pathExists(c$1))&&(f.error(`
364
364
  \u274C Directory "${t}" already exists`),p&&p!==c$1&&console.log(s.gray(` Found at: ${p}`)),console.log(s.cyan(`
365
365
  \u{1F4A1} Choose a different name or delete the existing directory.
366
366
  `)),process.exit(1));}if(e$1.dryRun){console.log(s.cyan(`
367
367
  \u{1F50D} Dry-run mode - showing what would be created:
368
368
  `)),console.log(s.white("\u{1F4C2} Path:"),c$1),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$2([{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)
369
- `)),a$2){let p=String(e$1.template||"").trim(),d=b$3(p);if(d$1(d)){let u=await Os(["create","project",d,t,...e$1.skipGit?["--skip-git"]:[],...e$1.skipInstall?["--skip-install"]:[]]);u!==0&&process.exit(u);return}if(!!!Ws(process.cwd())){let{registerWorkspaceAtPath:u}=await import('./create-R6A7EHQZ.js');if(e$1.createWorkspace)await u(process.cwd(),{skipGit:e$1.skipGit,yes:e$1.yes,userConfig:r});else if(!e$1.noWorkspace)if(e$1.yes)await u(process.cwd(),{skipGit:e$1.skipGit,yes:true,userConfig:r});else {let{createWs:h}=await b$2([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);h&&await u(process.cwd(),{skipGit:e$1.skipGit,yes:false,userConfig:r});}}let m=["create","project",d,t,"--output",process.cwd()];e$1.yes&&m.push("--yes");let k=Pe(process.cwd()),w=!!e$1.skipInstall,j=w||!!k;w&&m.push("--skip-essentials");let x=j?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,l=await f$1(m,{cwd:process.cwd(),env:x});l!==0&&process.exit(l),k&&!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 P=Ws(process.cwd());if(P){let u=b.dirname(P),h=b.join(u,".python-version"),f$1=b.join(c$1,".python-version");try{if(await O__default.pathExists(h)){let v=A.readFileSync(h,"utf-8");A.writeFileSync(f$1,v.trim()+`
369
+ `)),a$2){let p=String(e$1.template||"").trim(),d=b$3(p);if(d$1(d)){let u=await As(["create","project",d,t,...e$1.skipGit?["--skip-git"]:[],...e$1.skipInstall?["--skip-install"]:[]]);u!==0&&process.exit(u);return}if(!!!Ns(process.cwd())){let{registerWorkspaceAtPath:u}=await import('./create-3NSOY7CA.js');if(e$1.createWorkspace)await u(process.cwd(),{skipGit:e$1.skipGit,yes:e$1.yes,userConfig:r});else if(!e$1.noWorkspace)if(e$1.yes)await u(process.cwd(),{skipGit:e$1.skipGit,yes:true,userConfig:r});else {let{createWs:h}=await b$2([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);h&&await u(process.cwd(),{skipGit:e$1.skipGit,yes:false,userConfig:r});}}let m=["create","project",d,t,"--output",process.cwd()];e$1.yes&&m.push("--yes");let k=we(process.cwd()),y=!!e$1.skipInstall,j=y||!!k;y&&m.push("--skip-essentials");let x=j?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,l=await f$1(m,{cwd:process.cwd(),env:x});l!==0&&process.exit(l),k&&!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 P=Ns(process.cwd());if(P){let u=b.dirname(P),h=b.join(u,".python-version"),f$1=b.join(c$1,".python-version");try{if(await O__default.pathExists(h)){let v=A.readFileSync(h,"utf-8");A.writeFileSync(f$1,v.trim()+`
370
370
  `),f.debug(`Synced Python version ${v.trim()} from workspace to project`);}}catch(v){f.debug("Could not sync Python version from workspace:",v);}}if(!e$1.skipInstall){let u=await e(["init",c$1],{cwd:process.cwd()});if(u!==0&&process.exit(u),P){let h=b.dirname(P),f$1=b.join(h,".python-version"),v=b.join(c$1,".python-version");try{if(await O__default.pathExists(f$1)){let C=A.readFileSync(f$1,"utf-8");A.writeFileSync(v,C.trim()+`
371
- `),f.debug(`Re-synced Python version ${C.trim()} after init`);}}catch(C){f.debug("Could not re-sync Python version after init:",C);}}}}else {let{createProject:p}=await import('./create-R6A7EHQZ.js');await p(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:b.dirname(c$1)});}}catch(r){r instanceof a$1?(f.error(`
371
+ `),f.debug(`Re-synced Python version ${C.trim()} after init`);}}catch(C){f.debug("Could not re-sync Python version after init:",C);}}}}else {let{createProject:p}=await import('./create-3NSOY7CA.js');await p(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:b.dirname(c$1)});}}catch(r){r instanceof a$1?(f.error(`
372
372
  \u274C ${r.message}`),r.details&&f.warn(`\u{1F4A1} ${r.details}`),f.debug("Error code:",r.code)):(f.error(`
373
- \u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Et=null;}});Yi(de);rc(de);Mc(de);de.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{im({json:t.json});});de.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:r}=await import('./analyze-AAZEJ4FC.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});Oi(de);de.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t$1=>{t$1!=="activate"&&(console.log(s.red(`Unknown shell command: ${t$1}`)),process.exit(1));let e=process.cwd();function r(p){let d=p;for(;;){let g=t(d,"context.json").find(k=>A.existsSync(k));if(g)return g;let m=b.dirname(d);if(m===d)break;d=m;}return null}let o$1=r(e);function n(p){let d=p;for(;;){let g=b.join(d,".venv"),m=[b.join(d,".workspai","activate"),b.join(d,".rapidkit","activate")].find(w=>A.existsSync(w))??b.join(d,".workspai","activate");if(A.existsSync(m)||A.existsSync(g))return {venv:g,activateFile:m};let k=b.dirname(d);if(k===d)break;d=k;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&A.existsSync(a.activateFile)?i=a.activateFile:a&&A.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$4();console.log(c?`call "${i}"`:`. "${i}"`);});de.command(g.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$5({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});de.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:r}=await import('./pipeline-TDQK5QYQ.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});de.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Is({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-63XHNGR6.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});de.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ds(t,e);r!==0&&process.exit(r);});de.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await ep(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});var sn=de.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");sn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await xo({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});sn.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 dc({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});sn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await pc({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});sn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await mc({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});var Dt=de.command("project").description("Safe workspace project lifecycle operations");Dt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{Bl({json:t.json});});Dt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$6({startPath:b.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??b.join(o.projectPath,f$2),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json"};if(el(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});Dt.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-44ZPCOPV.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let p of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${p.path}: ${p.percent===null?"unknown":`${p.percent}%`} (${p.uncovered} uncovered)`));}for(let p of o.diagnostics)console.log(s.gray(` ${p}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});Dt.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 Hn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Dt.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Bn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});Dt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await kc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});Dt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await yc({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});de.command(g.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 r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await cm({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-HJ3O7SAO.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);});de.command(g.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
373
+ \u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Ct=null;}});qi(le);ec(le);Nc(le);le.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{om({json:t.json});});le.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:r}=await import('./analyze-AAZEJ4FC.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});_i(le);le.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t$1=>{t$1!=="activate"&&(console.log(s.red(`Unknown shell command: ${t$1}`)),process.exit(1));let e=process.cwd();function r(p){let d=p;for(;;){let g=t(d,"context.json").find(k=>A.existsSync(k));if(g)return g;let m=b.dirname(d);if(m===d)break;d=m;}return null}let o$1=r(e);function n(p){let d=p;for(;;){let g=b.join(d,".venv"),m=[b.join(d,".workspai","activate"),b.join(d,".rapidkit","activate")].find(y=>A.existsSync(y))??b.join(d,".workspai","activate");if(A.existsSync(m)||A.existsSync(g))return {venv:g,activateFile:m};let k=b.dirname(d);if(k===d)break;d=k;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&A.existsSync(a.activateFile)?i=a.activateFile:a&&A.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$4();console.log(c?`call "${i}"`:`. "${i}"`);});le.command(g.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$5({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});le.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:r}=await import('./pipeline-B5S6P36F.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});le.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Rs({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-3H5FTF6H.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});le.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ts(t,e);r!==0&&process.exit(r);});le.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Yl(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});var rn=le.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");rn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await bo({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});rn.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 lc({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});rn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await cc({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});rn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await dc({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});var Tt=le.command("project").description("Safe workspace project lifecycle operations");Tt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{Kl({json:t.json});});Tt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$6({startPath:b.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??b.join(o.projectPath,f$2),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json"};if(Qc(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});Tt.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-44ZPCOPV.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let p of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${p.path}: ${p.percent===null?"unknown":`${p.percent}%`} (${p.uncovered} uncovered)`));}for(let p of o.diagnostics)console.log(s.gray(` ${p}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});Tt.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 Kn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Tt.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Vn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});Tt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await yc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});Tt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await hc({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});le.command(g.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 r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await nm({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-UEFFNAUD.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);});le.command(g.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
374
374
  workspace run <stage> \u2014 fleet stage execution across discovered projects
375
375
  stages: init | test | build | start | <custom-from-context>
376
376
  workspace explain|why \u2014 blocker/project narrative (--write for artifact)
@@ -386,35 +386,35 @@ Workspace Actions:
386
386
  Fleet lifecycle run | init
387
387
 
388
388
  Use "workspai commands --json" for the contract-backed runtime inventory.
389
- See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=l=>{let P=n.workspace?b.resolve(n.workspace):null,u=null,h=null;try{u=b$6({startPath:process.cwd(),explicitWorkspacePath:P,strict:true})?.workspacePath??null;}catch(C){if(C instanceof a$2)h=C;else throw C}if(!u||!Ye(u)){let C=h?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${l}`,code:h?.code??"workspace.root.required",message:C,context:{cwd:b.resolve(process.cwd()),...P?{requestedWorkspace:P}:{},...h?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${C}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let f=b.resolve(process.cwd()),v=b.resolve(u);return f!==v&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${u} for "${l}" (current directory: ${f}).`)),u},i=l=>process.argv.includes(l),c=l=>Ie(process.argv,l),p=()=>n.output||c("--output"),d=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0},g=(l,P)=>{if(!l)return;let u=l.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!u)throw new Error(`${P} must be a byte size such as 500gb or 2tb.`);let h={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},f=Number(u[1])*h[u[2]||"b"];if(!Number.isSafeInteger(Math.floor(f))||f<=0)throw new Error(`${P} is outside the supported numeric range.`);return Math.floor(f)},m=()=>{let l=n.downloadTimeoutMs,P=l===void 0?void 0:Number.parseInt(l,10);if(P!==void 0&&(!Number.isFinite(P)||P<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:g(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:g(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:P,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},k=new Set(Object.values(Nr).flatMap(l=>[...l.flags])),w=new Set(process.argv.slice(2).filter(l=>l.startsWith("--")).map(l=>l.split("=",1)[0]).filter(l=>k.has(l))),j=Nr[t]?.flags,x=j?[...w].filter(l=>!j.includes(l)):[];if(x.length>0){let l=`${x.join(", ")} ${x.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||w.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:l,exitCode:2,context:{action:t,unsupportedFlags:x,allowedFlags:j}}),null,2)):(console.log(s.red(`\u274C ${l}`)),console.log(s.gray(` Allowed flags: ${j.join(", ")||"none"}`))),process.exit(2);}if((Gc(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$5({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:l}=await import('./workspace-B53XH35L.js');await l({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let l=a("intelligence"),{runWorkspaceIntelligenceChain:P}=await import('./workspace-intelligence-runner-EQFLRVRL.js'),u=await P({workspacePath:l,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(u,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${u.status}`));for(let h of u.stages)console.log(s.gray(` ${h.id}: ${h.status} \u2014 ${h.message}`));console.log(s.gray(` Evidence: ${u.artifactPath}`));}u.exitCode!==0&&process.exit(u.exitCode);}else if(t==="model"){let l=a("model"),{buildWorkspaceModelCached:P,buildWorkspaceModelIncremental:u,createWorkspaceModelBuildProvenance:h,writeWorkspaceModel:f}=await import('./workspace-model-MNJOGBPP.js'),v=n.incremental===true||i("--incremental"),C=n.cache===true||i("--cache")||v,R={workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:n.strict===true||i("--strict")},y,E;if(v){let M=await u(R);y=M.model,E=M.mode;}else {let M=await P({...R,cache:C});y=M.model,E=M.cache;}y={...y,build:h({mode:v?"incremental":C?"cache":"full",engineStatus:E})};let $;(n.write===true||i("--write"))&&($=await f(y,l));let N=(n.strict===true||i("--strict"))&&y.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...y,...$?{outputPath:$}:{}},null,2)),N&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${y.workspace.name}`)),v?console.log(s.gray(` Build: ${E} (incremental)`)):C&&console.log(s.gray(` Cache: ${E}`)),console.log(s.gray(` Projects: ${y.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${y.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${y.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${y.identity.workspaceType}`)),console.log(s.gray(` Validation: ${y.validation?.status??"unknown"} (${y.validation?.errors??0} error, ${y.validation?.warnings??0} warning)`)),console.log($?s.gray(` Written: ${$}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),N&&process.exit(1);}else if(t==="agent-sync"){let l=a("agent-sync"),{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:u}=await import('./workspace-agent-sync-446AXPHJ.js'),h=n.strict===true||i("--strict"),f=n.write===true||i("--write"),v=i("--dry-run"),C=await P({workspacePath:l,scope:n.scope,agent:n.forAgent,write:f&&!v,dryRun:v,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:u(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(C,null,2));else {console.log(s.green(`\u2714 Agent grounding ${f&&!v?"synced":"planned"}`)),console.log(s.gray(` Index: ${C.indexPath}`)),C.contextPath&&console.log(s.gray(` Context: ${C.contextPath}`)),C.blockers.length>0&&console.log(s.yellow(` Blockers: ${C.blockers.slice(0,3).join(" \xB7 ")}`));let R=f&&!v?C.writtenFiles:C.skippedFiles;if(R.length>0&&console.log(s.gray(` Files: ${R.join(", ")}`)),C.strictViolations.length>0)for(let y of C.strictViolations)console.log(s.red(`\u274C ${y}`));}h&&C.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let l=e??"status",{approveWorkspaceRepair:P,cancelWorkspaceRepair:u,decideWorkspaceRepair:h,executeWorkspaceRepair:f,inspectWorkspaceRepairCapabilities:v,listWorkspaceRepairTransactions:C,planWorkspaceRepair:R,planWorkspaceRepairProposal:y,readWorkspaceRepairTransaction:E,rollbackWorkspaceRepair:$}=await import('./workspace-repair-engine-OZXOXVVV.js');if(l==="capabilities"){let F;if(n.workspace)F=a("repair capabilities");else try{let G=b$6({startPath:process.cwd(),strict:false})?.workspacePath;G&&Ye(G)&&(F=G);}catch{}let W=await v(F?{workspacePath:F}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(W,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${W.adapters.length}`));for(let G of W.adapters)console.log(s.gray(` ${G.id.padEnd(14)} ${G.support.padEnd(11)} ${G.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let N=a("repair"),M=n.transaction??(["plan","propose","capabilities"].includes(l)?void 0:r),_=()=>{if(!M?.trim())throw new Error(`workspace repair ${l} requires --transaction <id> (or the id as the next positional argument).`);return M.trim()},S;if(l==="plan"){let F=n.card??r;if(!F?.trim())throw new Error("workspace repair plan requires --card <id>.");S=await R({workspacePath:N,cardId:F.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="propose"){let F=n.proposal??r;if(!F?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let W=b.resolve(N,F.trim()),G=b.relative(N,W);if(G.startsWith("..")||b.isAbsolute(G))throw new Error("The repair proposal file must be inside the canonical workspace.");let H=await O__default.lstat(W).catch(()=>{});if(!H?.isFile()||H.isSymbolicLink()||H.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");S=await y({workspacePath:N,proposal:await O__default.readJson(W),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="approve")S=await P({workspacePath:N,transactionId:_(),approvedBy:n.approvedBy});else if(l==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");S=await h({workspacePath:N,transactionId:_(),decision:n.decision});}else if(l==="execute"||l==="resume")S=await f({workspacePath:N,transactionId:_()});else if(l==="status")S=await E({workspacePath:N,transactionId:_()});else if(l==="list")S=await C(N);else if(l==="rollback")S=await $({workspacePath:N,transactionId:_()});else if(l==="cancel")S=await u({workspacePath:N,transactionId:_()});else throw new Error(`Unknown workspace repair action: ${l}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let J=b.join(N,a$3.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$7(`workspace repair ${l}`,S,J),null,2));else if(Array.isArray(S)){console.log(s.green(`\u2714 Workspace repair transactions: ${S.length}`));for(let F of S.slice(0,20))console.log(s.gray(` ${F.transactionId} \xB7 ${F.target.cardId} \xB7 ${F.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${S.state}`)),console.log(s.gray(` Transaction: ${S.transactionId}`)),console.log(s.gray(` Target: ${S.target.cardId}`));for(let F of S.stages)console.log(s.gray(` ${F.status.padEnd(8)} ${F.kind}: ${F.summary}`));S.decision&&console.log(s.yellow(` Decision: ${S.decision.reason}`)),console.log(s.gray(` Evidence: ${a$3.repairTransaction}`));}Array.isArray(S)||(S.state==="decision-required"&&process.exit(2),(S.state==="rolled-back"||S.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let l=a("remediation-plan"),{buildArtifactRemediationPlan:P,writeArtifactRemediationPlan:u}=await import('./artifact-remediation-plan-A2PRCUNA.js'),h=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),f;if((n.write===true||i("--write"))&&(f=await u(h,l)),n.json===true||i("--json")){console.log(JSON.stringify(b$7("workspace remediation-plan",h,f),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${h.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${h.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${h.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${h.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${h.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${h.summary.risk.safe}, guarded=${h.summary.risk.guarded}, invasive=${h.summary.risk.invasive}`));for(let v of h.actions.slice(0,8))console.log(s.gray(` \u2022 ${v.cardId}: ${v.title} (${v.mode}, ${v.risk})`));h.actions.length>8&&console.log(s.gray(` \u2026 ${h.actions.length-8} more action(s)`)),console.log(f?s.gray(` Written: ${f}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let l=a("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:P,writeWorkspaceAgentContext:u}=await import('./workspace-context-XSECHC7O.js'),h=n.strict===true||i("--strict"),f=await P({workspacePath:l,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:false}),v,C;if((n.write===true||i("--write"))&&(v=await u(f,l),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:E,parseAgentGroundingTargets:$}=await import('./workspace-agent-sync-446AXPHJ.js');if(C=await E({workspacePath:l,scope:n.scope,agent:f.agent,write:true,refreshContext:false,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",targets:$(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${C.writtenFiles.length} file(s) updated`)),h&&C.strictViolations.length>0){for(let N of C.strictViolations)console.log(s.red(`\u274C ${N}`));process.exit(1);}}let R=h&&f.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...f,...v?{outputPath:v}:{},...C?{agentGroundingSync:C}:{}},null,2)),R&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${f.workspace.name}`)),console.log(s.gray(` Agent: ${f.agent}`)),console.log(s.gray(` Scope: ${f.scope.activeProject??f.scope.requested}`)),console.log(s.gray(` Projects included: ${f.projects.length}`)),console.log(s.gray(` Safe commands: ${f.safeCommands.length}`)),console.log(s.gray(` Validation: ${f.validation.status} (${f.validation.errors} error, ${f.validation.warnings} warning)`)),console.log(v?s.gray(` Written: ${v}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),R){for(let y of f.validation.issues)console.log(s.red(`\u274C ${y.severity}:${y.code}:${y.target}`));process.exit(1);}}else if(t==="snapshot"){let l=a("snapshot"),{buildWorkspaceModelSnapshot:P,writeWorkspaceModelSnapshot:u}=await import('./workspace-intelligence-FWRB47EJ.js'),h=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),f=await u(h,l);if(n.json){console.log(JSON.stringify(b$7("workspace snapshot",h,f),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${h.model.workspace.name}`)),console.log(s.gray(` Hash: ${h.modelHash}`)),console.log(s.gray(` Projects: ${h.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${h.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${f}`));}else if(t==="diff"){let l=a("diff"),P=n.from||e;P||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:u,writeWorkspaceModelDiff:h}=await import('./workspace-intelligence-FWRB47EJ.js'),f;try{f=await u({workspacePath:l,fromPath:P,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:P},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),R}let v=await h(f,l);if(n.json){console.log(JSON.stringify(b$7("workspace diff",f,v),null,2));return}let C=f.summary.changed?s.yellow:s.green;console.log(C(`\u2714 Workspace model diff: ${f.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${f.fromRef}`)),console.log(s.gray(` Added projects: ${f.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${f.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${f.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${f.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${f.summary.validationChanges}`)),f.git?.available&&console.log(s.gray(` Git: ${f.git.dirty?"dirty":"clean"} (${f.summary.gitChangedFiles} mapped change(s))`));for(let R of f.changes.slice(0,12))console.log(s.gray(` \u2022 ${R.type} ${R.target}: ${R.message}`));f.changes.length>12&&console.log(s.gray(` \u2026 ${f.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="impact"){let l=a("impact"),P=n.from||e;P||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:u,writeWorkspaceImpact:h}=await import('./workspace-intelligence-FWRB47EJ.js'),f;try{f=await u({workspacePath:l,fromPath:P,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:P},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),R}let v=await h(f,l);if(n.json){console.log(JSON.stringify(b$7("workspace impact",f,v),null,2));return}let C=f.summary.risk==="critical"||f.summary.risk==="high"?s.red:f.summary.risk==="medium"?s.yellow:s.green;console.log(C(`\u2714 Workspace impact: ${f.summary.risk}`)),console.log(s.gray(` From: ${f.fromRef}`)),console.log(s.gray(` Affected projects: ${f.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${f.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${f.summary.recommendedCommands}`));for(let R of f.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${R.title}: ${R.summary}`));f.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${f.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="verify"){let l=a("verify"),{buildWorkspaceVerify:P,writeWorkspaceVerify:u,evaluateWorkspaceVerifyGate:h}=await import('./workspace-verify-C6HWHRLJ.js'),f=await P({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),v=await u(f,l),C=h(f,{strict:n.strict===true||i("--strict")}),R=C.exitCode,{recordWorkspaceHistory:y,historyEntryFromVerify:E}=await import('./workspace-history-YY7YRDOH.js');if(await y(l,E(f,C.passed)),n.json){console.log(JSON.stringify(b$7("workspace verify",{...f,gate:C},v),null,2)),R!==0&&process.exit(R);return}let $=f.summary.verdict==="ready"?s.green:f.summary.verdict==="needs-attention"?s.yellow:s.red;console.log($(`\u2714 Workspace verify: ${f.summary.verdict}`)),console.log(s.gray(` Freshness: ${f.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${f.impact.risk}`)),console.log(s.gray(` Steps: ${f.steps.length}`)),console.log(s.gray(` Passed ${f.summary.stepsPassed}, warn ${f.summary.stepsWarn}, failed ${f.summary.stepsFailed}, missing ${f.summary.stepsMissing}`));for(let N of f.steps.slice(0,10))console.log(s.gray(` \u2022 ${N.id}: ${N.status} \u2014 ${N.message}`));if(f.steps.length>10&&console.log(s.gray(` \u2026 ${f.steps.length-10} more step(s)`)),f.policyViolations.length>0){console.log(s.gray(` Policy (${f.policyMode}): ${f.policyViolations.length} violation(s)`));for(let N of f.policyViolations.slice(0,5)){let M=N.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${M} [${N.source}] ${N.code}: ${N.message}`);}}console.log(s.gray(` Gate (${C.mode}): ${C.passed?"passed":"blocked"}`));for(let N of C.reasons.slice(0,5))console.log(s.red(` \u2717 ${N}`));console.log(s.gray(` Written: ${v}`)),R!==0&&process.exit(R);}else if(t==="graph"){let l=a("graph"),{buildWorkspaceModel:P,workspaceModelProjectTopology:u}=await import('./workspace-model-MNJOGBPP.js'),{buildGraphEmit:h,renderGraphDot:f,renderGraphMermaid:v,explainGraphNode:C}=await import('./workspace-graph-2A5THUCI.js'),R=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),y=u(R),E=(e||"emit").toLowerCase();y||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:E,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let $=async()=>{let{buildWorkspaceKnowledgeGraph:_}=await import('./workspace-knowledge-graph-BMMM2FUE.js'),{hashWorkspaceModel:S}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:J}=await import('./workspace-contract-AYFTZIKM.js'),F=null;try{F=(await J({workspacePath:l})).contract;}catch{}return _({workspacePath:l,workspace:{name:R.workspace.name,...R.workspace.profile?{profile:R.workspace.profile}:{}},projects:R.projects.map(W=>({id:W.name,path:W.path,...W.absolutePath?{absolutePath:W.absolutePath}:{},runtime:W.runtime,runtimeCandidates:W.runtimeCandidates,framework:W.framework,...W.kit?{kit:W.kit}:{}})),projectTopology:y,contract:F,now:new Date(R.generatedAt),source:{kind:"workspace-model",artifact:a$3.model,hashAlgorithm:"sha256",hash:S(R)}})};if(E==="dot"||E==="mermaid"){let _=E==="dot"?f(y):v(y),S=p();if(S){let J=b.resolve(l,S);await O__default.outputFile(J,`${_}
390
- `,"utf8"),n.json?console.log(JSON.stringify(b$7(`workspace graph ${E}`,{format:E,nodeCount:y.stats.nodeCount,edgeCount:y.stats.edgeCount},J),null,2)):(console.log(s.green(`\u2714 Workspace dependency graph exported as ${E}`)),console.log(s.gray(` Written: ${J}`)));return}console.log(_);return}if(E==="jsonld"||E==="graphml"||E==="gexf"){let _=await $(),{renderWorkspaceKnowledgeGraphGexf:S,renderWorkspaceKnowledgeGraphGraphMl:J,renderWorkspaceKnowledgeGraphJsonLd:F}=await import('./workspace-knowledge-graph-export-UYAYFTWX.js'),W=E==="jsonld"?F(_):E==="graphml"?J(_):S(_),G=p();if(G){let H=b.resolve(l,G);await O__default.outputFile(H,`${W}
391
- `,"utf8"),n.json?console.log(JSON.stringify(b$7(`workspace graph ${E}`,{format:E,entityCount:_.entities.length,relationCount:_.relations.length,proofCount:_.proofs.length},H),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${E}`)),console.log(s.gray(` Written: ${H}`)));return}console.log(W);return}if(E==="explain"){let _=(n.scope?.replace(/^project:/,"")||r||"").trim();_||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:l,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 S=C(y,_);if(n.json){console.log(JSON.stringify(S,null,2)),S.found||process.exit(1);return}S.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${_}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${S.project}`)),S.centrality&&console.log(s.gray(` Centrality: fanIn ${S.centrality.fanIn}, fanOut ${S.centrality.fanOut}, reach ${S.centrality.reach}, betweenness ${S.centrality.betweenness}${S.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${S.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${S.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${S.transitiveDependents.length}`));for(let J of S.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${J.id} (d${J.distance}, via ${J.via??"\u2014"})`));return}if(E==="entities"){let _=await $(),{queryKnowledgeEntities:S}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),J=S(_,r);if(n.json){console.log(JSON.stringify({schemaVersion:_.schemaVersion,generatedAt:_.generatedAt,kind:r??null,count:J.length,entities:J},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${r?`: ${r}`:""}`)),console.log(s.gray(` Count: ${J.length}`));for(let F of J)console.log(s.gray(` \u2022 ${F.kind}: ${F.label} [${F.id}]`));return}if(E==="search"||E==="benchmark"){let _=(r||"").trim();_||(console.log(s.red(`\u274C workspace graph ${E} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${E} "authentication endpoint" --json`)),process.exit(1));let S=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(S)||S<1||S>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let J=await $();if(E==="benchmark"){let{buildWorkspaceGraphTokenEfficiencyReport:G}=await import('./workspace-graph-token-efficiency-5FNH4JZ5.js'),H=await G({workspacePath:l,graph:J,query:_,limit:S});n.json?console.log(JSON.stringify(H,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${_}`)),console.log(s.gray(` Estimated tokens: ${H.corpus.estimatedTokens} corpus \u2192 ${H.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${H.savings.reductionRatio}\xD7 (${H.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${H.retrieval.matchCount}`)),console.log(s.yellow(` ${H.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:F}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),W=F(J,{query:_,limit:S});if(n.json)console.log(JSON.stringify(W,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${_}`)),console.log(s.gray(` ${W.entities.length}/${W.totalMatches} match(es)${W.truncated?" (bounded)":""}`));for(let G of W.entities)console.log(s.gray(` \u2022 ${G.kind}: ${G.label} [${G.id}]`));}return}if(E==="evidence"){let _=(r||"").trim();_||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let S=await $(),{queryKnowledgeEvidence:J}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),F=J(S,_);if(n.json)console.log(JSON.stringify(F,null,2));else if(F.found){console.log(s.green(`\u2714 Graph evidence: ${_}`));for(let W of F.proofs)console.log(s.gray(` \u2022 ${W.artifact}${W.pointer?`#${W.pointer}`:""} [${W.provider}/${W.trust}/${W.confidence}]`));}else {console.log(s.red(F.candidates.length>0?`\u274C Graph query is ambiguous: ${_}`:`\u274C Graph entity or relation not found: ${_}`));for(let W of F.candidates.slice(0,10))console.log(s.gray(` \u2022 ${W}`));}F.found||process.exit(1);return}if(E==="path"){let _=(r||"").trim(),S=(o||"").trim();(!_||!S)&&(console.log(s.red("\u274C workspace graph path requires <from> and <to>.")),console.log(s.gray(" npx workspai workspace graph path <from> <to> --json")),process.exit(1));let J=await $(),{queryKnowledgePath:F}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),W=F(J,_,S);if(n.json)console.log(JSON.stringify(W,null,2));else if(W.found){console.log(s.green(`\u2714 Graph proof path: ${_} \u2192 ${S}`));for(let G of W.hops)console.log(s.gray(` \u2022 ${G.from} ${G.direction==="forward"?"\u2192":"\u2190"} ${G.to} [${G.kind}]`));console.log(s.gray(` Proofs: ${W.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${_} and ${S}.`));W.found||process.exit(1);return}if(E==="overlay"){let _=(n.from||r||"").trim();_||(console.log(s.red("\u274C workspace graph overlay requires --from <graph.json>.")),console.log(s.gray(" npx workspai workspace graph overlay --from <graph.json> --json")),process.exit(1));let S=b.resolve(l,_),J;try{J=JSON.parse(await O__default.readFile(S,"utf8"));}catch(Me){console.log(s.red(`\u274C Could not read the base knowledge graph: ${Me instanceof Error?Me.message:String(Me)}`)),process.exit(1);}let F=J&&typeof J=="object"?J:{},W=F.graph,G=W&&typeof W=="object"?W:{},H=F.schemaVersion===b$8.knowledgeGraph?F:F.knowledgeGraph??G.knowledgeGraph;(!H||typeof H!="object"||H.schemaVersion!==b$8.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${b$8.knowledgeGraph} document.`)),process.exit(1));let Te=await $(),{buildWorkspaceKnowledgeGraphChangeOverlay:we}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),ie=we(H,Te);if(n.json){console.log(JSON.stringify(ie,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${_}`)),console.log(s.gray(` Risk: ${ie.summary.risk}`)),console.log(s.gray(` Entities: +${ie.summary.entityAdds} -${ie.summary.entityRemovals} ~${ie.summary.entityChanges}`)),console.log(s.gray(` Relations: +${ie.summary.relationAdds} -${ie.summary.relationRemovals} ~${ie.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${ie.summary.proofAdds} -${ie.summary.proofRemovals} ~${ie.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${ie.summary.impactedEntities} entities \xB7 ${ie.summary.changedArtifacts} proof artifacts`));return}let N=h(y),M=await $();if(n.json){console.log(JSON.stringify({...N,knowledgeGraph:M},null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${N.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${N.graph.stats.edgeCount} (inferred ${N.graph.stats.inferredEdges}, contract ${N.graph.stats.contractEdges}, manual ${N.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${N.integrity.ok?"ok":"issues"} (cycles ${N.integrity.stats.cycleCount}, dangling ${N.integrity.stats.danglingCount}, orphans ${N.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${N.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${M.quality.entityCount} entities \xB7 ${M.quality.relationCount} relations \xB7 ${M.quality.proofCount} proofs \xB7 ${M.providers.length} providers`)),console.log(s.gray(" Query: workspace graph search <query> | entities [kind] | path <from> <to> | evidence <entity-or-relation> | overlay --from <graph.json>")),console.log(s.gray(" Render: workspace graph dot | mermaid | jsonld | graphml | gexf [--output <file>]"));}else if(t==="watch"){let l=a("watch"),{runWorkspaceWatch:P}=await import('./workspace-watch-DLPHLF5R.js'),u=n.once===true||i("--once"),h=n.graphStream===true||i("--graph-stream"),f=n.json===true||h,v=h?new(await import('./workspace-graph-stream-AJPS45FD.js')).WorkspaceGraphStreamPublisher({workspacePath:l}):null,C=new AbortController,R=()=>C.abort();process.once("SIGINT",R),process.once("SIGTERM",R),f||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await P({workspacePath:l,once:u,signal:C.signal,buildOptions:{workspacePath:l,observableScanDepth:d()},onProgress:y=>{f||console.error(s.gray(` ${y}`));},onModel:v?async y=>{let E=(await import('./workspace-model-MNJOGBPP.js')).workspaceModelProjectTopology(y);if(!E)return;let{buildWorkspaceKnowledgeGraph:$}=await import('./workspace-knowledge-graph-BMMM2FUE.js'),{readWorkspaceContract:N}=await import('./workspace-contract-AYFTZIKM.js'),M=null;try{M=(await N({workspacePath:l})).contract;}catch{}let _=await $({workspacePath:l,workspace:{name:y.workspace.name,...y.workspace.profile?{profile:y.workspace.profile}:{}},projects:y.projects.map(S=>({id:S.name,path:S.path,...S.absolutePath?{absolutePath:S.absolutePath}:{},runtime:S.runtime,runtimeCandidates:S.runtimeCandidates,framework:S.framework,...S.kit?{kit:S.kit}:{}})),projectTopology:E,contract:M,now:new Date(y.generatedAt),source:{kind:"workspace-model",artifact:a$3.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(y)}});console.log(JSON.stringify(v.publish(y,_)));}:void 0,emit:y=>{if(h)return;if(f){console.log(JSON.stringify(y));return}if(y.kind==="ready"){console.log(s.gray(` Ready: ${y.graph.nodeCount} nodes, ${y.graph.edgeCount} edges (hash ${y.modelHash.slice(0,12)})`));return}if(y.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${y.error??"unknown error"}`));return}if(y.kind==="unchanged"){console.log(s.gray(` No structural change (${y.mode}, ${y.durationMs}ms)`));return}let E=[];y.changedProjects.length>0&&E.push(`changed: ${y.changedProjects.join(", ")}`),y.addedProjects.length>0&&E.push(`added: ${y.addedProjects.join(", ")}`),y.removedProjects.length>0&&E.push(`removed: ${y.removedProjects.join(", ")}`),y.graph.edgesAdded.length>0&&E.push(`+${y.graph.edgesAdded.length} edges`),y.graph.edgesRemoved.length>0&&E.push(`-${y.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${y.mode}, ${y.durationMs}ms): ${E.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R),!f&&!u&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=a("sync"),{syncWorkspaceProjects:P}=await import('./workspace-B53XH35L.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${b.basename(l)}`));let u=await P(l,n.json===true);await Kr(l,{silent:n.json===true});let{syncWorkspaceProjectLenses:h}=await import('./project-intelligence-lens-ZOAWXYC5.js'),f=await h({workspacePath:l,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:v}=await import('./workspace-registry-summary-GPJEL7K7.js'),C=await v(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:u,contractSynced:true,projectLenses:{synced:f.projects.length,skipped:f.skipped},registrySummary:C},null,2));}else if(t==="registry"){let l=a("registry"),P=e||"status";P!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${P}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:u,resolveWorkspaceRegisteredProjects:h}=await import('./workspace-registry-summary-GPJEL7K7.js'),f=await u(l);if(n.json){console.log(JSON.stringify(f,null,2));return}let v=await h(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${f.authority}`)),console.log(s.gray(` Projects: ${f.projectCount}`)),console.log(s.gray(` Summary: ${f.registrySummaryPath}`)),v.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=a("foundation"),P=e||"ensure";P!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${P}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:u}=await import('./workspace-foundation-FFNCK5ZD.js'),h=await u(l,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(h,null,2));return}h.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${h.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=a("policy"),P=await Sm(l,e,r,o,n.json===true||i("--json"));P!==0&&process.exit(P);}else if(t==="contract"){let l=a("contract"),{buildWorkspaceContractGraph:P,readWorkspaceContract:u,verifyWorkspaceContract:h,writeWorkspaceContract:f,WORKSPACE_CONTRACT_PATH:v}=await import('./workspace-contract-AYFTZIKM.js'),C=e||"inspect",R=p();try{if(C==="init"){let y=await f({workspacePath:l,outputPath:R,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${y.contractPath}`)),console.log(s.gray(` Projects: ${y.contract.projects.length}`));return}if(C==="inspect"){let y=await u({workspacePath:l,contractPath:R});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${y.contractPath}`)),console.log(s.gray(` Workspace: ${y.contract.workspace.name}`)),console.log(s.gray(` Projects: ${y.contract.projects.length}`)),console.log(s.gray(` Schema: v${y.contract.schemaVersion}`));return}if(C==="verify"){let y=await h({workspacePath:l,contractPath:R,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:E}=await import('./workspace-contract-AYFTZIKM.js'),$=await E({workspacePath:l,result:y});if(n.json)console.log(JSON.stringify({...y,evidencePath:$},null,2));else {let N=y.status==="passed"?s.green:s.red;console.log(N(`\u2714 Workspace contract verification ${y.status}: ${y.contractPath}`)),console.log(s.gray(` Projects: ${y.projectCount}`));for(let M of y.checks){let _=M.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${_} ${M.id}: ${M.message}`));}for(let M of y.violations)console.log(s.gray(` Violation: ${M}`));}(y.status==="failed"||y.status!=="passed"&&n.strict)&&process.exit(1);return}if(C==="graph"){let y=await P({workspacePath:l,contractPath:R});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${y.contractPath}`)),console.log(s.gray(` Workspace: ${y.graph.workspace.name}`)),console.log(s.gray(` Projects: ${y.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${y.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${y.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${y.graph.summary.relationshipEdges} (${y.graph.summary.inferredEdges} inferred, ${y.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${y.graph.summary.connectedProjects}/${y.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(y.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(y.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${y.graph.summary.orphanProjects} \xB7 Hotspots: ${y.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${y.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${y.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${y.graph.summary.entityCount} entities \xB7 ${y.graph.summary.knowledgeRelations} relations \xB7 ${y.graph.summary.proofCount} proofs \xB7 ${y.graph.summary.providerCount} providers \xB7 ${y.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${y.graph.summary.portCount}`));for(let E of y.graph.nodes){let $=E.ports.map(M=>`${M.name}:${M.port}`).join(", ")||"none",N=E.operationalProfile?` risk=${E.operationalProfile.weight}/${E.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${E.id} (${E.runtime||"unknown"}${E.framework?`/${E.framework}`:""}) ports=${$} manifests=${E.files.manifests.length}${N}`));}for(let E of y.graph.edges){let $=E.type==="event"?`event:${E.label}`:E.label;console.log(s.gray(` ${E.from} -> ${E.to} [${$}]`));}if(y.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let E of y.graph.dependencyGraph.edges)console.log(s.gray(` ${E.from} -> ${E.to} [${E.kind}/${E.source}/${E.confidence}] evidence=${E.evidence.length}`));}for(let E of y.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${E.severity}: ${E.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${C}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${v}]`)),process.exit(1);}catch(y){n.json&&(console.log(JSON.stringify({command:`workspace contract ${C}`,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${C}.failed`,message:y.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${C} failed: ${y.message}`)),process.exit(1);}}else if(t==="share"){let l=a("share"),P=p()||e,{createWorkspaceShareBundle:u}=await import('./workspace-B53XH35L.js'),h=await u(l,{outputPath:P,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:l,bundlePath:h,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${h}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=a("export");try{let{exportWorkspaceArchive:P}=await import('./workspace-archive-VHUPOBAV.js'),u=n.archiveCompression?.trim().toLowerCase()??"store";if(u!=="store"&&u!=="deflate")throw new Error("--archive-compression must be store or deflate.");let h=await P({workspacePath:l,outputPath:p()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:u});if(n.json){console.log(JSON.stringify(h,null,2));return}let f=(h.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.manifest.files.length}`)),console.log(s.gray(` Size: ${f} MB`)),h.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(P){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:P.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${P.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let l=r;l||(n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:P,inspectWorkspaceArchive:u,verifyWorkspaceArchive:h}=await import('./workspace-archive-VHUPOBAV.js');try{if(e==="inspect"){let v=await u({archivePathOrUrl:l,safety:m()});if(n.json){console.log(JSON.stringify(v,null,2));return}let C=(v.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${v.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${v.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${v.fileCount}`)),console.log(s.gray(` Payload: ${C} MB`));return}if(e==="doctor"){let v=await P({archivePathOrUrl:l,strict:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(v,null,2));else {let C=v.status==="passed"?s.green:v.status==="warning"?s.yellow:s.red;console.log(C(`\u2714 Workspace archive doctor ${v.status}: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.workspaceName}`)),console.log(s.gray(` Files: ${v.fileCount}`));for(let R of v.checks){let y=R.status==="passed"?"\u2714":R.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${y} ${R.id}: ${R.message}`));}for(let R of v.recommendedActions)console.log(s.gray(` Next: ${R}`));}(v.status==="failed"||v.status==="warning"&&n.strict)&&process.exit(1);return}let f=await h({archivePathOrUrl:l,requireChecksums:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(f,null,2));else if(f.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${f.archivePath}`)),console.log(s.gray(` Files: ${f.verifiedFiles}/${f.fileCount}`));else {let v=f.status==="failed"?s.red:s.yellow;console.log(v(`\u274C Workspace archive verification ${f.status}: ${f.archivePath}`)),f.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${f.missingArchiveEntries.join(", ")}`)),f.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${f.extraArchiveEntries.join(", ")}`)),f.mismatches.length&&console.log(s.gray(` Mismatches: ${f.mismatches.map(C=>C.path).join(", ")}`)),f.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${f.missingChecksumFiles.join(", ")}`));}(f.status==="failed"||f.status==="warning"&&n.strict)&&process.exit(1);}catch(f){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,error:{code:`workspace.archive.${e}.failed`,message:f.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${f.message}`)),process.exit(1);}}else if(t==="connect"){let l=b.resolve(e||process.cwd());try{let P=await ks({workspacePath:l,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green(P.status==="preview"?`\u2714 Workspace connection preview: ${l}`:`\u2714 Workspace connected: ${l}`));for(let u of P.warnings)console.log(s.yellow(` \u26A0 ${u}`));}catch(P){let u=P instanceof Error?P.message:String(P);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:u}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${u}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let P=await vs({archivePathOrUrl:l,outputPath:p(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:m()});if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green(P.status==="preview"?`\u2714 Workspace import preview: ${P.workspacePath}`:`\u2714 Workspace imported and registered: ${P.workspacePath}`));for(let u of P.warnings)console.log(s.yellow(` \u26A0 ${u}`));}else {let{hydrateWorkspaceArchive:P}=await import('./workspace-archive-VHUPOBAV.js'),u=await P({archivePathOrUrl:l,outputPath:p(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:m()});if(n.json){console.log(JSON.stringify(u,null,2));return}console.log(s.green(u.dryRun?`\u2714 Workspace archive hydrate preview: ${u.outputPath}`:`\u2714 Workspace archive hydrated: ${u.outputPath}`)),console.log(s.gray(` Files: ${u.files.length}`)),u.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${u.manifest.workspaceName}`));}}catch(P){let u=P instanceof Error?P.message:String(P);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:u,context:{archivePathOrUrl:l,...p()?{outputPath:p()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,...p()?{outputPath:p()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:u}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${u}`)),process.exit(1);}}else if(t==="run"){let l=a(`run ${e||""}`.trim()),P=new Set(["init","test","build","start"]),u=e?.trim()??"";u||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .workspai/context.json commands")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2)),P.has(u)||(!/^[a-z][a-z0-9_-]*$/i.test(u)||u==="dev"||u==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${u}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),u==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let h=Is({raw:n.maxWorkers,operation:`workspace run ${u}`,json:n.json===true||i("--json")});if(u==="init"&&n.json!==true){let C=await Ls(l);C!==0&&process.exit(C);}let{runWorkspaceStage:f}=await import('./workspace-run-VPXRRHDK.js'),v=await f({workspacePath:l,stage:u,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:h,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(v,null,2)),v.summary.exitCode!==0&&process.exit(v.summary.exitCode);}else if(t==="explain"||t==="why"){let l=a(t),{parseWorkspaceExplainTarget:P}=await import('./workspace-explain-contract-N2XQHAPM.js'),{buildWorkspaceExplain:u,writeWorkspaceExplainReport:h}=await import('./workspace-explain-SZI2WAAD.js'),f=(e??r??"").trim();!f&&n.scope&&(f=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),f||(f="release-blocked");let v=P(f);v||(console.log(s.red(`\u274C Invalid explain target: ${f}`)),process.exit(1));let C=await u({workspacePath:l,target:v}),R=n.write===true||i("--write"),y;if(R&&(y=await h(C,l,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$7(`workspace ${t}`,C,y),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${C.summary}`));for(let E of C.sections)console.log(s.bold(`
392
- ${E.title}`)),console.log(E.body);y&&console.log(s.gray(`
393
- Written: ${y}`));}else if(t==="trace"){let l=a("trace"),P=n.from||e;P||(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:u}=await import('./workspace-explain-contract-N2XQHAPM.js'),{buildWorkspaceExplain:h,writeWorkspaceExplainReport:f}=await import('./workspace-explain-SZI2WAAD.js'),v=u(P);(!v||v.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${P}`)),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 C=await h({workspacePath:l,target:v}),R=n.write===true||i("--write"),y;if(R&&(y=await f(C,l,"trace")),n.json){console.log(JSON.stringify(b$7("workspace trace",C,y),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${C.summary}`));for(let E of C.sections)console.log(s.bold(`
394
- ${E.title}`)),console.log(E.body);y&&console.log(s.gray(`
395
- Written: ${y}`));}else if(t==="eval"){let l=a("eval"),P=(e||"status").toLowerCase(),{WORKSPACE_EVALUATION_LAST_RUN_PATH:u,WORKSPACE_EVALUATION_LIVE_PATH:h,appendWorkspaceEvaluationEvent:f,compareWorkspaceEvaluations:v,createWorkspaceEvaluation:C,finalizeWorkspaceEvaluation:R,readWorkspaceEvaluation:y,writeWorkspaceEvaluation:E}=await import('./workspace-intelligence-evaluation-UP2K3L35.js');if(P==="init"){let $=(r||"").trim(),N=(o||"workspace-intelligence").trim(),M=["full-corpus","grep","vector","graph","workspace-intelligence","custom"];(!$||!M.includes(N))&&(console.log(s.red("\u274C workspace eval init requires <task> and an optional valid strategy.")),console.log(s.gray(` Strategies: ${M.join(" | ")}
396
- npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:_}=await import('./workspace-marker-7NHMDIRL.js'),S=await _(l),J=C({workspacePath:l,workspaceName:S?.name,taskId:$,strategy:N}),F=await E(l,J);if(n.json){console.log(JSON.stringify(b$7("workspace eval init",J,F),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${$}`)),console.log(s.gray(` Run: ${J.runId}`)),console.log(s.gray(` Strategy: ${J.configuration.strategy}`)),console.log(s.gray(` Live: ${F}`));return}if(P==="record"){!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace eval record requires --json and a stdin event.")),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace eval record requires piped JSON on stdin.")),process.exit(1));let{parseFeedbackStdinPayload:$,readStdinAll:N}=await import('./workspace-feedback-WXE7NVMV.js'),M=$(await N());M||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let _=await f({workspacePath:l,payload:M});console.log(JSON.stringify(_,null,2));}catch(_){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:_ instanceof Error?_.message:String(_),context:{workspacePath:l}}),null,2)),process.exit(1);}return}if(P==="report"){let $=await R({workspacePath:l}),N=p(),M=$.outputPath;if(N){let _=b.resolve(l,N);b.resolve($.outputPath)!==_&&await O__default.copy($.outputPath,_,{overwrite:true}),M=_;}if(n.json){console.log(JSON.stringify(b$7("workspace eval report",$.report,M),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${$.report.runId}`)),console.log(s.gray(` Tokens: ${$.report.summary.tokens.observedTotal} \xB7 model calls ${$.report.summary.modelCalls} \xB7 tool calls ${$.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${$.report.summary.outcome.status}${$.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${M}`));return}if(P==="compare"){let $=(n.from||r||"").trim();$||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let N=await y(l,u),M=await y(l,$),_=v(N,M);if(n.json){console.log(JSON.stringify(_,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${_.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${_.delta.tokens}`)),console.log(s.gray(` Reduction: ${_.delta.reductionPercent===null?"unavailable":`${_.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${_.comparableOutcome?"yes":"no"}`));return}if(P==="status"){let $;try{$=await y(l,h);}catch{$=await y(l,u);}if(n.json){console.log(JSON.stringify($,null,2));return}console.log(s.green(`\u2714 Evaluation ${$.status}: ${$.configuration.taskId}`)),console.log(s.gray(` Run: ${$.runId}`)),console.log(s.gray(` Events: ${$.events.length}`)),console.log(s.gray(` Tokens: ${$.summary.tokens.observedTotal} (${$.summary.tokenSources.providerReported} provider-reported calls, ${$.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${P}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let l=a("feedback"),P=(e||"record").toLowerCase();P!=="record"&&(console.log(s.red(`Unknown feedback action: ${P}`)),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:u,parseFeedbackStdinPayload:h,readStdinAll:f}=await import('./workspace-feedback-WXE7NVMV.js'),v=await f(),C=h(v);C||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let R=await u({workspacePath:l,payload:C});n.json?console.log(JSON.stringify(R,null,2)):R.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${R.historyPath}`))):console.log(s.red(`\u274C ${R.error??"Failed to record feedback"}`)),R.ok||process.exit(1);}else if(t==="goal"){let l=a("goal"),P=(e||"status").toLowerCase(),u=r?.trim(),{planVerifiedGoal:h,readVerifiedGoal:f,verifyVerifiedGoal:v,VERIFIED_GOAL_SCHEMA_VERSION:C}=await import('./verified-goal-S2PEBJUV.js'),R=y=>{if(n.json){console.log(JSON.stringify(y,null,2));return}let E=y.goal;console.log(y.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(y.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),E&&console.log(s.bold(` ${E.summary}`)),console.log(s.gray(` Goal: ${y.status.goalId}`)),console.log(s.gray(` Progress: ${y.status.progress.message}`)),console.log(s.gray(` State: ${y.status.state}`)),y.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${y.status.blockingReasons[0]}`)),y.status.nextActions.length>0&&console.log(s.gray(` Next: ${y.status.nextActions[0]}`)),console.log(s.gray(` Status: ${y.status.artifactPath}`));};if(P==="plan"){if(!u||!["release-readiness","dependency-security","test-coverage"].includes(u)){let N="Goal kind must be release-readiness, dependency-security, or test-coverage.";n.json?console.log(JSON.stringify(c$1({operation:"workspace goal plan",code:"workspace.goal.kind.invalid",message:N}),null,2)):console.log(s.red(`\u274C ${N}`)),process.exit(1);}let E=Number(n.target??80);if(!Number.isFinite(E)||E<0||E>100)throw new Error("--target must be a number from 0 to 100.");let $=await h({workspacePath:l,kind:u,scope:n.scope,target:E,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});R($);}else if(P==="status"){if(!u)throw new Error("workspace goal status requires a goal id.");let y=await f(l,u);R({...y,resumed:y.status.state!=="verified"});}else if(P==="verify"){if(!u)throw new Error("workspace goal verify requires a goal id.");let y=await f(l,u),E=await v({workspacePath:l,goalId:u,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});R({goal:y.goal,status:E}),E.state!=="verified"&&process.exit(2);}else {let y=`Unknown workspace goal action: ${P}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:y,context:{schemaVersion:C,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${y}`)),process.exit(1);}}else if(t==="mcp"){let l=a("mcp"),P=(e||"serve").toLowerCase();P!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:P,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${P}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${P}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:u}=await import('./workspace-mcp-serve-COA4FMCA.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await u({workspacePath:l});}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:
389
+ See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=l=>{let P=n.workspace?b.resolve(n.workspace):null,u=null,h=null;try{u=b$6({startPath:process.cwd(),explicitWorkspacePath:P,strict:true})?.workspacePath??null;}catch(C){if(C instanceof a$2)h=C;else throw C}if(!u||!Be(u)){let C=h?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${l}`,code:h?.code??"workspace.root.required",message:C,context:{cwd:b.resolve(process.cwd()),...P?{requestedWorkspace:P}:{},...h?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${C}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let f=b.resolve(process.cwd()),v=b.resolve(u);return f!==v&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${u} for "${l}" (current directory: ${f}).`)),u},i=l=>process.argv.includes(l),c=l=>Re(process.argv,l),p=()=>n.output||c("--output"),d=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0},g=(l,P)=>{if(!l)return;let u=l.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!u)throw new Error(`${P} must be a byte size such as 500gb or 2tb.`);let h={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},f=Number(u[1])*h[u[2]||"b"];if(!Number.isSafeInteger(Math.floor(f))||f<=0)throw new Error(`${P} is outside the supported numeric range.`);return Math.floor(f)},m=()=>{let l=n.downloadTimeoutMs,P=l===void 0?void 0:Number.parseInt(l,10);if(P!==void 0&&(!Number.isFinite(P)||P<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:g(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:g(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:P,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},k=new Set(Object.values(Ir).flatMap(l=>[...l.flags])),y=new Set(process.argv.slice(2).filter(l=>l.startsWith("--")).map(l=>l.split("=",1)[0]).filter(l=>k.has(l))),j=Ir[t]?.flags,x=j?[...y].filter(l=>!j.includes(l)):[];if(x.length>0){let l=`${x.join(", ")} ${x.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||y.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:l,exitCode:2,context:{action:t,unsupportedFlags:x,allowedFlags:j}}),null,2)):(console.log(s.red(`\u274C ${l}`)),console.log(s.gray(` Allowed flags: ${j.join(", ")||"none"}`))),process.exit(2);}if((Fc(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$5({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:l}=await import('./workspace-C4UETGY7.js');await l({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let l=a("intelligence"),{runWorkspaceIntelligenceChain:P}=await import('./workspace-intelligence-runner-SMEAB4CO.js'),u=await P({workspacePath:l,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(u,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${u.status}`));for(let h of u.stages)console.log(s.gray(` ${h.id}: ${h.status} \u2014 ${h.message}`));console.log(s.gray(` Evidence: ${u.artifactPath}`));}u.exitCode!==0&&process.exit(u.exitCode);}else if(t==="model"){let l=a("model"),{buildWorkspaceModelCached:P,buildWorkspaceModelIncremental:u,createWorkspaceModelBuildProvenance:h,writeWorkspaceModel:f}=await import('./workspace-model-MNJOGBPP.js'),v=n.incremental===true||i("--incremental"),C=n.cache===true||i("--cache")||v,R={workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:n.strict===true||i("--strict")},w,E;if(v){let M=await u(R);w=M.model,E=M.mode;}else {let M=await P({...R,cache:C});w=M.model,E=M.cache;}w={...w,build:h({mode:v?"incremental":C?"cache":"full",engineStatus:E})};let $;(n.write===true||i("--write"))&&($=await f(w,l));let N=(n.strict===true||i("--strict"))&&w.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...w,...$?{outputPath:$}:{}},null,2)),N&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${w.workspace.name}`)),v?console.log(s.gray(` Build: ${E} (incremental)`)):C&&console.log(s.gray(` Cache: ${E}`)),console.log(s.gray(` Projects: ${w.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${w.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${w.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${w.identity.workspaceType}`)),console.log(s.gray(` Validation: ${w.validation?.status??"unknown"} (${w.validation?.errors??0} error, ${w.validation?.warnings??0} warning)`)),console.log($?s.gray(` Written: ${$}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),N&&process.exit(1);}else if(t==="agent-sync"){let l=a("agent-sync"),{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:u}=await import('./workspace-agent-sync-446AXPHJ.js'),h=n.strict===true||i("--strict"),f=n.write===true||i("--write"),v=i("--dry-run"),C=await P({workspacePath:l,scope:n.scope,agent:n.forAgent,write:f&&!v,dryRun:v,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:u(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(C,null,2));else {console.log(s.green(`\u2714 Agent grounding ${f&&!v?"synced":"planned"}`)),console.log(s.gray(` Index: ${C.indexPath}`)),C.contextPath&&console.log(s.gray(` Context: ${C.contextPath}`)),C.blockers.length>0&&console.log(s.yellow(` Blockers: ${C.blockers.slice(0,3).join(" \xB7 ")}`));let R=f&&!v?C.writtenFiles:C.skippedFiles;if(R.length>0&&console.log(s.gray(` Files: ${R.join(", ")}`)),C.strictViolations.length>0)for(let w of C.strictViolations)console.log(s.red(`\u274C ${w}`));}h&&C.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let l=e??"status",{approveWorkspaceRepair:P,cancelWorkspaceRepair:u,decideWorkspaceRepair:h,executeWorkspaceRepair:f,inspectWorkspaceRepairCapabilities:v,listWorkspaceRepairTransactions:C,planWorkspaceRepair:R,planWorkspaceRepairProposal:w,readWorkspaceRepairTransaction:E,rollbackWorkspaceRepair:$}=await import('./workspace-repair-engine-GWTXVVKB.js');if(l==="capabilities"){let F;if(n.workspace)F=a("repair capabilities");else try{let G=b$6({startPath:process.cwd(),strict:false})?.workspacePath;G&&Be(G)&&(F=G);}catch{}let W=await v(F?{workspacePath:F,project:n.project}:n.project?{project:n.project}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(W,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${W.adapters.length}`));for(let G of W.adapters)console.log(s.gray(` ${G.id.padEnd(14)} ${G.support.padEnd(11)} ${G.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let N=a("repair"),M=n.transaction??(["plan","propose","capabilities"].includes(l)?void 0:r),_=()=>{if(!M?.trim())throw new Error(`workspace repair ${l} requires --transaction <id> (or the id as the next positional argument).`);return M.trim()},S;if(l==="plan"){let F=n.card??r;if(!F?.trim())throw new Error("workspace repair plan requires --card <id>.");S=await R({workspacePath:N,cardId:F.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="propose"){let F=n.proposal??r;if(!F?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let W=b.resolve(N,F.trim()),G=b.relative(N,W);if(G.startsWith("..")||b.isAbsolute(G))throw new Error("The repair proposal file must be inside the canonical workspace.");let H=await O__default.lstat(W).catch(()=>{});if(!H?.isFile()||H.isSymbolicLink()||H.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");S=await w({workspacePath:N,proposal:await O__default.readJson(W),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="approve")S=await P({workspacePath:N,transactionId:_(),approvedBy:n.approvedBy});else if(l==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");S=await h({workspacePath:N,transactionId:_(),decision:n.decision});}else if(l==="execute"||l==="resume")S=await f({workspacePath:N,transactionId:_()});else if(l==="status")S=await E({workspacePath:N,transactionId:_()});else if(l==="list")S=await C(N);else if(l==="rollback")S=await $({workspacePath:N,transactionId:_()});else if(l==="cancel")S=await u({workspacePath:N,transactionId:_()});else throw new Error(`Unknown workspace repair action: ${l}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let J=b.join(N,a$3.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$7(`workspace repair ${l}`,S,J),null,2));else if(Array.isArray(S)){console.log(s.green(`\u2714 Workspace repair transactions: ${S.length}`));for(let F of S.slice(0,20))console.log(s.gray(` ${F.transactionId} \xB7 ${F.target.cardId} \xB7 ${F.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${S.state}`)),console.log(s.gray(` Transaction: ${S.transactionId}`)),console.log(s.gray(` Target: ${S.target.cardId}`));for(let F of S.stages)console.log(s.gray(` ${F.status.padEnd(8)} ${F.kind}: ${F.summary}`));S.decision&&console.log(s.yellow(` Decision: ${S.decision.reason}`)),console.log(s.gray(` Evidence: ${a$3.repairTransaction}`));}Array.isArray(S)||(S.state==="decision-required"&&process.exit(2),(S.state==="rolled-back"||S.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let l=a("remediation-plan"),{buildArtifactRemediationPlan:P,writeArtifactRemediationPlan:u}=await import('./artifact-remediation-plan-O3YIULQN.js'),h=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),f;if((n.write===true||i("--write"))&&(f=await u(h,l)),n.json===true||i("--json")){console.log(JSON.stringify(b$7("workspace remediation-plan",h,f),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${h.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${h.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${h.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${h.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${h.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${h.summary.risk.safe}, guarded=${h.summary.risk.guarded}, invasive=${h.summary.risk.invasive}`));for(let v of h.actions.slice(0,8))console.log(s.gray(` \u2022 ${v.cardId}: ${v.title} (${v.mode}, ${v.risk})`));h.actions.length>8&&console.log(s.gray(` \u2026 ${h.actions.length-8} more action(s)`)),console.log(f?s.gray(` Written: ${f}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let l=a("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:P,writeWorkspaceAgentContext:u}=await import('./workspace-context-XSECHC7O.js'),h=n.strict===true||i("--strict"),f=await P({workspacePath:l,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:false}),v,C;if((n.write===true||i("--write"))&&(v=await u(f,l),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:E,parseAgentGroundingTargets:$}=await import('./workspace-agent-sync-446AXPHJ.js');if(C=await E({workspacePath:l,scope:n.scope,agent:f.agent,write:true,refreshContext:false,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",targets:$(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${C.writtenFiles.length} file(s) updated`)),h&&C.strictViolations.length>0){for(let N of C.strictViolations)console.log(s.red(`\u274C ${N}`));process.exit(1);}}let R=h&&f.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...f,...v?{outputPath:v}:{},...C?{agentGroundingSync:C}:{}},null,2)),R&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${f.workspace.name}`)),console.log(s.gray(` Agent: ${f.agent}`)),console.log(s.gray(` Scope: ${f.scope.activeProject??f.scope.requested}`)),console.log(s.gray(` Projects included: ${f.projects.length}`)),console.log(s.gray(` Safe commands: ${f.safeCommands.length}`)),console.log(s.gray(` Validation: ${f.validation.status} (${f.validation.errors} error, ${f.validation.warnings} warning)`)),console.log(v?s.gray(` Written: ${v}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),R){for(let w of f.validation.issues)console.log(s.red(`\u274C ${w.severity}:${w.code}:${w.target}`));process.exit(1);}}else if(t==="snapshot"){let l=a("snapshot"),{buildWorkspaceModelSnapshot:P,writeWorkspaceModelSnapshot:u}=await import('./workspace-intelligence-FWRB47EJ.js'),h=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),f=await u(h,l);if(n.json){console.log(JSON.stringify(b$7("workspace snapshot",h,f),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${h.model.workspace.name}`)),console.log(s.gray(` Hash: ${h.modelHash}`)),console.log(s.gray(` Projects: ${h.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${h.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${f}`));}else if(t==="diff"){let l=a("diff"),P=n.from||e;P||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:u,writeWorkspaceModelDiff:h}=await import('./workspace-intelligence-FWRB47EJ.js'),f;try{f=await u({workspacePath:l,fromPath:P,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:P},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),R}let v=await h(f,l);if(n.json){console.log(JSON.stringify(b$7("workspace diff",f,v),null,2));return}let C=f.summary.changed?s.yellow:s.green;console.log(C(`\u2714 Workspace model diff: ${f.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${f.fromRef}`)),console.log(s.gray(` Added projects: ${f.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${f.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${f.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${f.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${f.summary.validationChanges}`)),f.git?.available&&console.log(s.gray(` Git: ${f.git.dirty?"dirty":"clean"} (${f.summary.gitChangedFiles} mapped change(s))`));for(let R of f.changes.slice(0,12))console.log(s.gray(` \u2022 ${R.type} ${R.target}: ${R.message}`));f.changes.length>12&&console.log(s.gray(` \u2026 ${f.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="impact"){let l=a("impact"),P=n.from||e;P||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:u,writeWorkspaceImpact:h}=await import('./workspace-intelligence-FWRB47EJ.js'),f;try{f=await u({workspacePath:l,fromPath:P,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:P},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),R}let v=await h(f,l);if(n.json){console.log(JSON.stringify(b$7("workspace impact",f,v),null,2));return}let C=f.summary.risk==="critical"||f.summary.risk==="high"?s.red:f.summary.risk==="medium"?s.yellow:s.green;console.log(C(`\u2714 Workspace impact: ${f.summary.risk}`)),console.log(s.gray(` From: ${f.fromRef}`)),console.log(s.gray(` Affected projects: ${f.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${f.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${f.summary.recommendedCommands}`));for(let R of f.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${R.title}: ${R.summary}`));f.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${f.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="verify"){let l=a("verify"),{buildWorkspaceVerify:P,writeWorkspaceVerify:u,evaluateWorkspaceVerifyGate:h}=await import('./workspace-verify-C6HWHRLJ.js'),f=await P({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),v=await u(f,l),C=h(f,{strict:n.strict===true||i("--strict")}),R=C.exitCode,{recordWorkspaceHistory:w,historyEntryFromVerify:E}=await import('./workspace-history-YY7YRDOH.js');if(await w(l,E(f,C.passed)),n.json){console.log(JSON.stringify(b$7("workspace verify",{...f,gate:C},v),null,2)),R!==0&&process.exit(R);return}let $=f.summary.verdict==="ready"?s.green:f.summary.verdict==="needs-attention"?s.yellow:s.red;console.log($(`\u2714 Workspace verify: ${f.summary.verdict}`)),console.log(s.gray(` Freshness: ${f.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${f.impact.risk}`)),console.log(s.gray(` Steps: ${f.steps.length}`)),console.log(s.gray(` Passed ${f.summary.stepsPassed}, warn ${f.summary.stepsWarn}, failed ${f.summary.stepsFailed}, missing ${f.summary.stepsMissing}`));for(let N of f.steps.slice(0,10))console.log(s.gray(` \u2022 ${N.id}: ${N.status} \u2014 ${N.message}`));if(f.steps.length>10&&console.log(s.gray(` \u2026 ${f.steps.length-10} more step(s)`)),f.policyViolations.length>0){console.log(s.gray(` Policy (${f.policyMode}): ${f.policyViolations.length} violation(s)`));for(let N of f.policyViolations.slice(0,5)){let M=N.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${M} [${N.source}] ${N.code}: ${N.message}`);}}console.log(s.gray(` Gate (${C.mode}): ${C.passed?"passed":"blocked"}`));for(let N of C.reasons.slice(0,5))console.log(s.red(` \u2717 ${N}`));console.log(s.gray(` Written: ${v}`)),R!==0&&process.exit(R);}else if(t==="graph"){let l=a("graph"),{buildWorkspaceModel:P,workspaceModelProjectTopology:u}=await import('./workspace-model-MNJOGBPP.js'),{buildGraphEmit:h,renderGraphDot:f,renderGraphMermaid:v,explainGraphNode:C}=await import('./workspace-graph-2A5THUCI.js'),R=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),w=u(R),E=(e||"emit").toLowerCase();w||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:E,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let $=async()=>{let{buildWorkspaceKnowledgeGraph:_}=await import('./workspace-knowledge-graph-BMMM2FUE.js'),{hashWorkspaceModel:S}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:J}=await import('./workspace-contract-AYFTZIKM.js'),F=null;try{F=(await J({workspacePath:l})).contract;}catch{}return _({workspacePath:l,workspace:{name:R.workspace.name,...R.workspace.profile?{profile:R.workspace.profile}:{}},projects:R.projects.map(W=>({id:W.name,path:W.path,...W.absolutePath?{absolutePath:W.absolutePath}:{},runtime:W.runtime,runtimeCandidates:W.runtimeCandidates,framework:W.framework,...W.kit?{kit:W.kit}:{}})),projectTopology:w,contract:F,now:new Date(R.generatedAt),source:{kind:"workspace-model",artifact:a$3.model,hashAlgorithm:"sha256",hash:S(R)}})};if(E==="dot"||E==="mermaid"){let _=E==="dot"?f(w):v(w),S=p();if(S){let J=b.resolve(l,S);await O__default.outputFile(J,`${_}
390
+ `,"utf8"),n.json?console.log(JSON.stringify(b$7(`workspace graph ${E}`,{format:E,nodeCount:w.stats.nodeCount,edgeCount:w.stats.edgeCount},J),null,2)):(console.log(s.green(`\u2714 Workspace dependency graph exported as ${E}`)),console.log(s.gray(` Written: ${J}`)));return}console.log(_);return}if(E==="jsonld"||E==="graphml"||E==="gexf"){let _=await $(),{renderWorkspaceKnowledgeGraphGexf:S,renderWorkspaceKnowledgeGraphGraphMl:J,renderWorkspaceKnowledgeGraphJsonLd:F}=await import('./workspace-knowledge-graph-export-UYAYFTWX.js'),W=E==="jsonld"?F(_):E==="graphml"?J(_):S(_),G=p();if(G){let H=b.resolve(l,G);await O__default.outputFile(H,`${W}
391
+ `,"utf8"),n.json?console.log(JSON.stringify(b$7(`workspace graph ${E}`,{format:E,entityCount:_.entities.length,relationCount:_.relations.length,proofCount:_.proofs.length},H),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${E}`)),console.log(s.gray(` Written: ${H}`)));return}console.log(W);return}if(E==="explain"){let _=(n.scope?.replace(/^project:/,"")||r||"").trim();_||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:l,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 S=C(w,_);if(n.json){console.log(JSON.stringify(S,null,2)),S.found||process.exit(1);return}S.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${_}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${S.project}`)),S.centrality&&console.log(s.gray(` Centrality: fanIn ${S.centrality.fanIn}, fanOut ${S.centrality.fanOut}, reach ${S.centrality.reach}, betweenness ${S.centrality.betweenness}${S.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${S.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${S.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${S.transitiveDependents.length}`));for(let J of S.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${J.id} (d${J.distance}, via ${J.via??"\u2014"})`));return}if(E==="entities"){let _=await $(),{queryKnowledgeEntities:S}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),J=S(_,r);if(n.json){console.log(JSON.stringify({schemaVersion:_.schemaVersion,generatedAt:_.generatedAt,kind:r??null,count:J.length,entities:J},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${r?`: ${r}`:""}`)),console.log(s.gray(` Count: ${J.length}`));for(let F of J)console.log(s.gray(` \u2022 ${F.kind}: ${F.label} [${F.id}]`));return}if(E==="search"||E==="benchmark"){let _=(r||"").trim();_||(console.log(s.red(`\u274C workspace graph ${E} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${E} "authentication endpoint" --json`)),process.exit(1));let S=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(S)||S<1||S>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let J=await $();if(E==="benchmark"){let{buildWorkspaceGraphTokenEfficiencyReport:G}=await import('./workspace-graph-token-efficiency-5FNH4JZ5.js'),H=await G({workspacePath:l,graph:J,query:_,limit:S});n.json?console.log(JSON.stringify(H,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${_}`)),console.log(s.gray(` Estimated tokens: ${H.corpus.estimatedTokens} corpus \u2192 ${H.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${H.savings.reductionRatio}\xD7 (${H.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${H.retrieval.matchCount}`)),console.log(s.yellow(` ${H.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:F}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),W=F(J,{query:_,limit:S});if(n.json)console.log(JSON.stringify(W,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${_}`)),console.log(s.gray(` ${W.entities.length}/${W.totalMatches} match(es)${W.truncated?" (bounded)":""}`));for(let G of W.entities)console.log(s.gray(` \u2022 ${G.kind}: ${G.label} [${G.id}]`));}return}if(E==="evidence"){let _=(r||"").trim();_||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let S=await $(),{queryKnowledgeEvidence:J}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),F=J(S,_);if(n.json)console.log(JSON.stringify(F,null,2));else if(F.found){console.log(s.green(`\u2714 Graph evidence: ${_}`));for(let W of F.proofs)console.log(s.gray(` \u2022 ${W.artifact}${W.pointer?`#${W.pointer}`:""} [${W.provider}/${W.trust}/${W.confidence}]`));}else {console.log(s.red(F.candidates.length>0?`\u274C Graph query is ambiguous: ${_}`:`\u274C Graph entity or relation not found: ${_}`));for(let W of F.candidates.slice(0,10))console.log(s.gray(` \u2022 ${W}`));}F.found||process.exit(1);return}if(E==="path"){let _=(r||"").trim(),S=(o||"").trim();(!_||!S)&&(console.log(s.red("\u274C workspace graph path requires <from> and <to>.")),console.log(s.gray(" npx workspai workspace graph path <from> <to> --json")),process.exit(1));let J=await $(),{queryKnowledgePath:F}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),W=F(J,_,S);if(n.json)console.log(JSON.stringify(W,null,2));else if(W.found){console.log(s.green(`\u2714 Graph proof path: ${_} \u2192 ${S}`));for(let G of W.hops)console.log(s.gray(` \u2022 ${G.from} ${G.direction==="forward"?"\u2192":"\u2190"} ${G.to} [${G.kind}]`));console.log(s.gray(` Proofs: ${W.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${_} and ${S}.`));W.found||process.exit(1);return}if(E==="overlay"){let _=(n.from||r||"").trim();_||(console.log(s.red("\u274C workspace graph overlay requires --from <graph.json>.")),console.log(s.gray(" npx workspai workspace graph overlay --from <graph.json> --json")),process.exit(1));let S=b.resolve(l,_),J;try{J=JSON.parse(await O__default.readFile(S,"utf8"));}catch($e){console.log(s.red(`\u274C Could not read the base knowledge graph: ${$e instanceof Error?$e.message:String($e)}`)),process.exit(1);}let F=J&&typeof J=="object"?J:{},W=F.graph,G=W&&typeof W=="object"?W:{},H=F.schemaVersion===b$8.knowledgeGraph?F:F.knowledgeGraph??G.knowledgeGraph;(!H||typeof H!="object"||H.schemaVersion!==b$8.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${b$8.knowledgeGraph} document.`)),process.exit(1));let Oe=await $(),{buildWorkspaceKnowledgeGraphChangeOverlay:fe}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),ae=fe(H,Oe);if(n.json){console.log(JSON.stringify(ae,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${_}`)),console.log(s.gray(` Risk: ${ae.summary.risk}`)),console.log(s.gray(` Entities: +${ae.summary.entityAdds} -${ae.summary.entityRemovals} ~${ae.summary.entityChanges}`)),console.log(s.gray(` Relations: +${ae.summary.relationAdds} -${ae.summary.relationRemovals} ~${ae.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${ae.summary.proofAdds} -${ae.summary.proofRemovals} ~${ae.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${ae.summary.impactedEntities} entities \xB7 ${ae.summary.changedArtifacts} proof artifacts`));return}let N=h(w),M=await $();if(n.json){console.log(JSON.stringify({...N,knowledgeGraph:M},null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${N.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${N.graph.stats.edgeCount} (inferred ${N.graph.stats.inferredEdges}, contract ${N.graph.stats.contractEdges}, manual ${N.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${N.integrity.ok?"ok":"issues"} (cycles ${N.integrity.stats.cycleCount}, dangling ${N.integrity.stats.danglingCount}, orphans ${N.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${N.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${M.quality.entityCount} entities \xB7 ${M.quality.relationCount} relations \xB7 ${M.quality.proofCount} proofs \xB7 ${M.providers.length} providers`)),console.log(s.gray(" Query: workspace graph search <query> | entities [kind] | path <from> <to> | evidence <entity-or-relation> | overlay --from <graph.json>")),console.log(s.gray(" Render: workspace graph dot | mermaid | jsonld | graphml | gexf [--output <file>]"));}else if(t==="watch"){let l=a("watch"),{runWorkspaceWatch:P}=await import('./workspace-watch-DLPHLF5R.js'),u=n.once===true||i("--once"),h=n.graphStream===true||i("--graph-stream"),f=n.json===true||h,v=h?new(await import('./workspace-graph-stream-AJPS45FD.js')).WorkspaceGraphStreamPublisher({workspacePath:l}):null,C=new AbortController,R=()=>C.abort();process.once("SIGINT",R),process.once("SIGTERM",R),f||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await P({workspacePath:l,once:u,signal:C.signal,buildOptions:{workspacePath:l,observableScanDepth:d()},onProgress:w=>{f||console.error(s.gray(` ${w}`));},onModel:v?async w=>{let E=(await import('./workspace-model-MNJOGBPP.js')).workspaceModelProjectTopology(w);if(!E)return;let{buildWorkspaceKnowledgeGraph:$}=await import('./workspace-knowledge-graph-BMMM2FUE.js'),{readWorkspaceContract:N}=await import('./workspace-contract-AYFTZIKM.js'),M=null;try{M=(await N({workspacePath:l})).contract;}catch{}let _=await $({workspacePath:l,workspace:{name:w.workspace.name,...w.workspace.profile?{profile:w.workspace.profile}:{}},projects:w.projects.map(S=>({id:S.name,path:S.path,...S.absolutePath?{absolutePath:S.absolutePath}:{},runtime:S.runtime,runtimeCandidates:S.runtimeCandidates,framework:S.framework,...S.kit?{kit:S.kit}:{}})),projectTopology:E,contract:M,now:new Date(w.generatedAt),source:{kind:"workspace-model",artifact:a$3.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(w)}});console.log(JSON.stringify(v.publish(w,_)));}:void 0,emit:w=>{if(h)return;if(f){console.log(JSON.stringify(w));return}if(w.kind==="ready"){console.log(s.gray(` Ready: ${w.graph.nodeCount} nodes, ${w.graph.edgeCount} edges (hash ${w.modelHash.slice(0,12)})`));return}if(w.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${w.error??"unknown error"}`));return}if(w.kind==="unchanged"){console.log(s.gray(` No structural change (${w.mode}, ${w.durationMs}ms)`));return}let E=[];w.changedProjects.length>0&&E.push(`changed: ${w.changedProjects.join(", ")}`),w.addedProjects.length>0&&E.push(`added: ${w.addedProjects.join(", ")}`),w.removedProjects.length>0&&E.push(`removed: ${w.removedProjects.join(", ")}`),w.graph.edgesAdded.length>0&&E.push(`+${w.graph.edgesAdded.length} edges`),w.graph.edgesRemoved.length>0&&E.push(`-${w.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${w.mode}, ${w.durationMs}ms): ${E.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R),!f&&!u&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=a("sync"),{syncWorkspaceProjects:P}=await import('./workspace-C4UETGY7.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${b.basename(l)}`));let u=await P(l,n.json===true);await Fr(l,{silent:n.json===true});let{syncWorkspaceProjectLenses:h}=await import('./project-intelligence-lens-ZOAWXYC5.js'),f=await h({workspacePath:l,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:v}=await import('./workspace-registry-summary-GPJEL7K7.js'),C=await v(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:u,contractSynced:true,projectLenses:{synced:f.projects.length,skipped:f.skipped},registrySummary:C},null,2));}else if(t==="registry"){let l=a("registry"),P=e||"status";P!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${P}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:u,resolveWorkspaceRegisteredProjects:h}=await import('./workspace-registry-summary-GPJEL7K7.js'),f=await u(l);if(n.json){console.log(JSON.stringify(f,null,2));return}let v=await h(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${f.authority}`)),console.log(s.gray(` Projects: ${f.projectCount}`)),console.log(s.gray(` Summary: ${f.registrySummaryPath}`)),v.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=a("foundation"),P=e||"ensure";P!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${P}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:u}=await import('./workspace-foundation-3EVAQ5X6.js'),h=await u(l,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(h,null,2));return}h.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${h.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=a("policy"),P=await Pm(l,e,r,o,n.json===true||i("--json"));P!==0&&process.exit(P);}else if(t==="contract"){let l=a("contract"),{buildWorkspaceContractGraph:P,readWorkspaceContract:u,verifyWorkspaceContract:h,writeWorkspaceContract:f,WORKSPACE_CONTRACT_PATH:v}=await import('./workspace-contract-AYFTZIKM.js'),C=e||"inspect",R=p();try{if(C==="init"){let w=await f({workspacePath:l,outputPath:R,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${w.contractPath}`)),console.log(s.gray(` Projects: ${w.contract.projects.length}`));return}if(C==="inspect"){let w=await u({workspacePath:l,contractPath:R});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${w.contractPath}`)),console.log(s.gray(` Workspace: ${w.contract.workspace.name}`)),console.log(s.gray(` Projects: ${w.contract.projects.length}`)),console.log(s.gray(` Schema: v${w.contract.schemaVersion}`));return}if(C==="verify"){let w=await h({workspacePath:l,contractPath:R,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:E}=await import('./workspace-contract-AYFTZIKM.js'),$=await E({workspacePath:l,result:w});if(n.json)console.log(JSON.stringify({...w,evidencePath:$},null,2));else {let N=w.status==="passed"?s.green:s.red;console.log(N(`\u2714 Workspace contract verification ${w.status}: ${w.contractPath}`)),console.log(s.gray(` Projects: ${w.projectCount}`));for(let M of w.checks){let _=M.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${_} ${M.id}: ${M.message}`));}for(let M of w.violations)console.log(s.gray(` Violation: ${M}`));}(w.status==="failed"||w.status!=="passed"&&n.strict)&&process.exit(1);return}if(C==="graph"){let w=await P({workspacePath:l,contractPath:R});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${w.contractPath}`)),console.log(s.gray(` Workspace: ${w.graph.workspace.name}`)),console.log(s.gray(` Projects: ${w.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${w.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${w.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${w.graph.summary.relationshipEdges} (${w.graph.summary.inferredEdges} inferred, ${w.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${w.graph.summary.connectedProjects}/${w.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(w.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(w.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${w.graph.summary.orphanProjects} \xB7 Hotspots: ${w.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${w.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${w.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${w.graph.summary.entityCount} entities \xB7 ${w.graph.summary.knowledgeRelations} relations \xB7 ${w.graph.summary.proofCount} proofs \xB7 ${w.graph.summary.providerCount} providers \xB7 ${w.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${w.graph.summary.portCount}`));for(let E of w.graph.nodes){let $=E.ports.map(M=>`${M.name}:${M.port}`).join(", ")||"none",N=E.operationalProfile?` risk=${E.operationalProfile.weight}/${E.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${E.id} (${E.runtime||"unknown"}${E.framework?`/${E.framework}`:""}) ports=${$} manifests=${E.files.manifests.length}${N}`));}for(let E of w.graph.edges){let $=E.type==="event"?`event:${E.label}`:E.label;console.log(s.gray(` ${E.from} -> ${E.to} [${$}]`));}if(w.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let E of w.graph.dependencyGraph.edges)console.log(s.gray(` ${E.from} -> ${E.to} [${E.kind}/${E.source}/${E.confidence}] evidence=${E.evidence.length}`));}for(let E of w.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${E.severity}: ${E.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${C}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${v}]`)),process.exit(1);}catch(w){n.json&&(console.log(JSON.stringify({command:`workspace contract ${C}`,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${C}.failed`,message:w.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${C} failed: ${w.message}`)),process.exit(1);}}else if(t==="share"){let l=a("share"),P=p()||e,{createWorkspaceShareBundle:u}=await import('./workspace-C4UETGY7.js'),h=await u(l,{outputPath:P,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:l,bundlePath:h,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${h}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=a("export");try{let{exportWorkspaceArchive:P}=await import('./workspace-archive-VHUPOBAV.js'),u=n.archiveCompression?.trim().toLowerCase()??"store";if(u!=="store"&&u!=="deflate")throw new Error("--archive-compression must be store or deflate.");let h=await P({workspacePath:l,outputPath:p()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:u});if(n.json){console.log(JSON.stringify(h,null,2));return}let f=(h.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.manifest.files.length}`)),console.log(s.gray(` Size: ${f} MB`)),h.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(P){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:P.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${P.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let l=r;l||(n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:P,inspectWorkspaceArchive:u,verifyWorkspaceArchive:h}=await import('./workspace-archive-VHUPOBAV.js');try{if(e==="inspect"){let v=await u({archivePathOrUrl:l,safety:m()});if(n.json){console.log(JSON.stringify(v,null,2));return}let C=(v.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${v.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${v.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${v.fileCount}`)),console.log(s.gray(` Payload: ${C} MB`));return}if(e==="doctor"){let v=await P({archivePathOrUrl:l,strict:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(v,null,2));else {let C=v.status==="passed"?s.green:v.status==="warning"?s.yellow:s.red;console.log(C(`\u2714 Workspace archive doctor ${v.status}: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.workspaceName}`)),console.log(s.gray(` Files: ${v.fileCount}`));for(let R of v.checks){let w=R.status==="passed"?"\u2714":R.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${w} ${R.id}: ${R.message}`));}for(let R of v.recommendedActions)console.log(s.gray(` Next: ${R}`));}(v.status==="failed"||v.status==="warning"&&n.strict)&&process.exit(1);return}let f=await h({archivePathOrUrl:l,requireChecksums:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(f,null,2));else if(f.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${f.archivePath}`)),console.log(s.gray(` Files: ${f.verifiedFiles}/${f.fileCount}`));else {let v=f.status==="failed"?s.red:s.yellow;console.log(v(`\u274C Workspace archive verification ${f.status}: ${f.archivePath}`)),f.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${f.missingArchiveEntries.join(", ")}`)),f.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${f.extraArchiveEntries.join(", ")}`)),f.mismatches.length&&console.log(s.gray(` Mismatches: ${f.mismatches.map(C=>C.path).join(", ")}`)),f.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${f.missingChecksumFiles.join(", ")}`));}(f.status==="failed"||f.status==="warning"&&n.strict)&&process.exit(1);}catch(f){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,error:{code:`workspace.archive.${e}.failed`,message:f.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${f.message}`)),process.exit(1);}}else if(t==="connect"){let l=b.resolve(e||process.cwd());try{let P=await hs({workspacePath:l,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green(P.status==="preview"?`\u2714 Workspace connection preview: ${l}`:`\u2714 Workspace connected: ${l}`));for(let u of P.warnings)console.log(s.yellow(` \u26A0 ${u}`));}catch(P){let u=P instanceof Error?P.message:String(P);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:u}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${u}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let P=await ys({archivePathOrUrl:l,outputPath:p(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:m()});if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green(P.status==="preview"?`\u2714 Workspace import preview: ${P.workspacePath}`:`\u2714 Workspace imported and registered: ${P.workspacePath}`));for(let u of P.warnings)console.log(s.yellow(` \u26A0 ${u}`));}else {let{hydrateWorkspaceArchive:P}=await import('./workspace-archive-VHUPOBAV.js'),u=await P({archivePathOrUrl:l,outputPath:p(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:m()});if(n.json){console.log(JSON.stringify(u,null,2));return}console.log(s.green(u.dryRun?`\u2714 Workspace archive hydrate preview: ${u.outputPath}`:`\u2714 Workspace archive hydrated: ${u.outputPath}`)),console.log(s.gray(` Files: ${u.files.length}`)),u.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${u.manifest.workspaceName}`));}}catch(P){let u=P instanceof Error?P.message:String(P);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:u,context:{archivePathOrUrl:l,...p()?{outputPath:p()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,...p()?{outputPath:p()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:u}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${u}`)),process.exit(1);}}else if(t==="run"){let l=a(`run ${e||""}`.trim()),P=new Set(["init","test","build","start"]),u=e?.trim()??"";u||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .workspai/context.json commands")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2)),P.has(u)||(!/^[a-z][a-z0-9_-]*$/i.test(u)||u==="dev"||u==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${u}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),u==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let h=Rs({raw:n.maxWorkers,operation:`workspace run ${u}`,json:n.json===true||i("--json")});if(u==="init"&&n.json!==true){let C=await Ms(l);C!==0&&process.exit(C);}let{runWorkspaceStage:f}=await import('./workspace-run-FJTBX4JQ.js'),v=await f({workspacePath:l,stage:u,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:h,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(v,null,2)),v.summary.exitCode!==0&&process.exit(v.summary.exitCode);}else if(t==="explain"||t==="why"){let l=a(t),{parseWorkspaceExplainTarget:P}=await import('./workspace-explain-contract-6CCC26QT.js'),{buildWorkspaceExplain:u,writeWorkspaceExplainReport:h}=await import('./workspace-explain-ZEWVKDBF.js'),f=(e??r??"").trim();!f&&n.scope&&(f=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),f||(f="release-blocked");let v=P(f);v||(console.log(s.red(`\u274C Invalid explain target: ${f}`)),process.exit(1));let C=await u({workspacePath:l,target:v}),R=n.write===true||i("--write"),w;if(R&&(w=await h(C,l,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$7(`workspace ${t}`,C,w),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${C.summary}`));for(let E of C.sections)console.log(s.bold(`
392
+ ${E.title}`)),console.log(E.body);w&&console.log(s.gray(`
393
+ Written: ${w}`));}else if(t==="trace"){let l=a("trace"),P=n.from||e;P||(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:u}=await import('./workspace-explain-contract-6CCC26QT.js'),{buildWorkspaceExplain:h,writeWorkspaceExplainReport:f}=await import('./workspace-explain-ZEWVKDBF.js'),v=u(P);(!v||v.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${P}`)),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 C=await h({workspacePath:l,target:v}),R=n.write===true||i("--write"),w;if(R&&(w=await f(C,l,"trace")),n.json){console.log(JSON.stringify(b$7("workspace trace",C,w),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${C.summary}`));for(let E of C.sections)console.log(s.bold(`
394
+ ${E.title}`)),console.log(E.body);w&&console.log(s.gray(`
395
+ Written: ${w}`));}else if(t==="eval"){let l=a("eval"),P=(e||"status").toLowerCase(),{WORKSPACE_EVALUATION_LAST_RUN_PATH:u,WORKSPACE_EVALUATION_LIVE_PATH:h,appendWorkspaceEvaluationEvent:f,compareWorkspaceEvaluations:v,createWorkspaceEvaluation:C,finalizeWorkspaceEvaluation:R,readWorkspaceEvaluation:w,writeWorkspaceEvaluation:E}=await import('./workspace-intelligence-evaluation-UP2K3L35.js');if(P==="init"){let $=(r||"").trim(),N=(o||"workspace-intelligence").trim(),M=["full-corpus","grep","vector","graph","workspace-intelligence","custom"];(!$||!M.includes(N))&&(console.log(s.red("\u274C workspace eval init requires <task> and an optional valid strategy.")),console.log(s.gray(` Strategies: ${M.join(" | ")}
396
+ npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:_}=await import('./workspace-marker-7NHMDIRL.js'),S=await _(l),J=C({workspacePath:l,workspaceName:S?.name,taskId:$,strategy:N}),F=await E(l,J);if(n.json){console.log(JSON.stringify(b$7("workspace eval init",J,F),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${$}`)),console.log(s.gray(` Run: ${J.runId}`)),console.log(s.gray(` Strategy: ${J.configuration.strategy}`)),console.log(s.gray(` Live: ${F}`));return}if(P==="record"){!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace eval record requires --json and a stdin event.")),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace eval record requires piped JSON on stdin.")),process.exit(1));let{parseFeedbackStdinPayload:$,readStdinAll:N}=await import('./workspace-feedback-WXE7NVMV.js'),M=$(await N());M||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let _=await f({workspacePath:l,payload:M});console.log(JSON.stringify(_,null,2));}catch(_){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:_ instanceof Error?_.message:String(_),context:{workspacePath:l}}),null,2)),process.exit(1);}return}if(P==="report"){let $=await R({workspacePath:l}),N=p(),M=$.outputPath;if(N){let _=b.resolve(l,N);b.resolve($.outputPath)!==_&&await O__default.copy($.outputPath,_,{overwrite:true}),M=_;}if(n.json){console.log(JSON.stringify(b$7("workspace eval report",$.report,M),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${$.report.runId}`)),console.log(s.gray(` Tokens: ${$.report.summary.tokens.observedTotal} \xB7 model calls ${$.report.summary.modelCalls} \xB7 tool calls ${$.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${$.report.summary.outcome.status}${$.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${M}`));return}if(P==="compare"){let $=(n.from||r||"").trim();$||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let N=await w(l,u),M=await w(l,$),_=v(N,M);if(n.json){console.log(JSON.stringify(_,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${_.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${_.delta.tokens}`)),console.log(s.gray(` Reduction: ${_.delta.reductionPercent===null?"unavailable":`${_.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${_.comparableOutcome?"yes":"no"}`));return}if(P==="status"){let $;try{$=await w(l,h);}catch{$=await w(l,u);}if(n.json){console.log(JSON.stringify($,null,2));return}console.log(s.green(`\u2714 Evaluation ${$.status}: ${$.configuration.taskId}`)),console.log(s.gray(` Run: ${$.runId}`)),console.log(s.gray(` Events: ${$.events.length}`)),console.log(s.gray(` Tokens: ${$.summary.tokens.observedTotal} (${$.summary.tokenSources.providerReported} provider-reported calls, ${$.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${P}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let l=a("feedback"),P=(e||"record").toLowerCase();P!=="record"&&(console.log(s.red(`Unknown feedback action: ${P}`)),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:u,parseFeedbackStdinPayload:h,readStdinAll:f}=await import('./workspace-feedback-WXE7NVMV.js'),v=await f(),C=h(v);C||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let R=await u({workspacePath:l,payload:C});n.json?console.log(JSON.stringify(R,null,2)):R.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${R.historyPath}`))):console.log(s.red(`\u274C ${R.error??"Failed to record feedback"}`)),R.ok||process.exit(1);}else if(t==="goal"){let l=a("goal"),P=(e||"status").toLowerCase(),u=r?.trim(),{planVerifiedGoal:h,readVerifiedGoal:f,verifyVerifiedGoal:v,VERIFIED_GOAL_SCHEMA_VERSION:C}=await import('./verified-goal-KOU3WJYN.js'),R=w=>{if(n.json){console.log(JSON.stringify(w,null,2));return}let E=w.goal;console.log(w.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(w.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),E&&console.log(s.bold(` ${E.summary}`)),console.log(s.gray(` Goal: ${w.status.goalId}`)),console.log(s.gray(` Progress: ${w.status.progress.message}`)),console.log(s.gray(` State: ${w.status.state}`)),w.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${w.status.blockingReasons[0]}`)),w.status.nextActions.length>0&&console.log(s.gray(` Next: ${w.status.nextActions[0]}`)),console.log(s.gray(` Status: ${w.status.artifactPath}`));};if(P==="plan"){if(!u||!["release-readiness","dependency-security","test-coverage"].includes(u)){let N="Goal kind must be release-readiness, dependency-security, or test-coverage.";n.json?console.log(JSON.stringify(c$1({operation:"workspace goal plan",code:"workspace.goal.kind.invalid",message:N}),null,2)):console.log(s.red(`\u274C ${N}`)),process.exit(1);}let E=Number(n.target??80);if(!Number.isFinite(E)||E<0||E>100)throw new Error("--target must be a number from 0 to 100.");let $=await h({workspacePath:l,kind:u,scope:n.scope,target:E,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});R($);}else if(P==="status"){if(!u)throw new Error("workspace goal status requires a goal id.");let w=await f(l,u);R({...w,resumed:w.status.state!=="verified"});}else if(P==="verify"){if(!u)throw new Error("workspace goal verify requires a goal id.");let w=await f(l,u),E=await v({workspacePath:l,goalId:u,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});R({goal:w.goal,status:E}),E.state!=="verified"&&process.exit(2);}else {let w=`Unknown workspace goal action: ${P}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:w,context:{schemaVersion:C,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${w}`)),process.exit(1);}}else if(t==="mcp"){let l=a("mcp"),P=(e||"serve").toLowerCase();P!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:P,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${P}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${P}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:u}=await import('./workspace-mcp-serve-X6C3AWTA.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await u({workspacePath:l});}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:
397
397
  npx workspai init | npx workspai workspace init | npx workspai workspace run init
398
- `)));let l=a("init"),P=Is({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let f=await Ls(l);f!==0&&process.exit(f);}let{runWorkspaceStage:u}=await import('./workspace-run-VPXRRHDK.js'),h=await u({workspacePath:l,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:P,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(h,null,2)),h.summary.exitCode!==0&&process.exit(h.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:$r}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${$r.join(", ")}`)),process.exit(1);});function Rs(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function tp(){let t=r=>r.replace(/\bnpx (?:rapidkit|workspai)\b/g,Es),e=(r,o)=>{console.log(s.cyan(` ${t(r).padEnd(67)} `)+s.gray(o));};console.log(s.white(`Usage:
399
- `)),console.log(s.cyan(` ${Es} <command> [options]
400
- `)),Rm==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${Es}.
398
+ `)));let l=a("init"),P=Rs({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let f=await Ms(l);f!==0&&process.exit(f);}let{runWorkspaceStage:u}=await import('./workspace-run-FJTBX4JQ.js'),h=await u({workspacePath:l,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:P,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(h,null,2)),h.summary.exitCode!==0&&process.exit(h.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:_r}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${_r.join(", ")}`)),process.exit(1);});function Ss(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function Xl(){let t=r=>r.replace(/\bnpx (?:rapidkit|workspai)\b/g,Cs),e=(r,o)=>{console.log(s.cyan(` ${t(r).padEnd(67)} `)+s.gray(o));};console.log(s.white(`Usage:
399
+ `)),console.log(s.cyan(` ${Cs} <command> [options]
400
+ `)),Cm==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${Cs}.
401
401
  `)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems
402
402
  `)),console.log(s.white("Connect projects, contracts, evidence, and checks so developers, CI, IDEs, and AI agents share one current view of the system.")),console.log(s.dim(`One workspace. One truth. Humans and AI aligned.
403
- `)),Rs("Workspace Lifecycle"),console.log(""),e("npx workspai create","Create a workspace/project or bring in existing software"),e("npx workspai adopt .","Link the current project without moving its source"),e("npx workspai import <path|git-url>","Copy or clone software into a workspace"),e("npx workspai workspace intelligence run --for-agent generic --strict --json","Refresh the canonical evidence chain"),Rs("Workspace Intelligence"),console.log(s.gray(`
403
+ `)),Ss("Workspace Lifecycle"),console.log(""),e("npx workspai create","Create a workspace/project or bring in existing software"),e("npx workspai adopt .","Link the current project without moving its source"),e("npx workspai import <path|git-url>","Copy or clone software into a workspace"),e("npx workspai workspace intelligence run --for-agent generic --strict --json","Refresh the canonical evidence chain"),Ss("Workspace Intelligence"),console.log(s.gray(`
404
404
  Code \xB7 APIs \xB7 infrastructure \xB7 docs \xB7 policies \xB7 runtime evidence`)),console.log(s.gray(" \u2193")),console.log(s.gray(" Canonical Workspace Model")),console.log(s.gray(" \u2193")),console.log(s.gray(" Evidence-backed Knowledge Graph")),console.log(s.gray(" \u2193")),console.log(s.gray(` Doctor \xB7 impact \xB7 verify \xB7 context \xB7 explain
405
- `)),e("npx workspai workspace model --write --json","Build the canonical system model"),e("npx workspai workspace graph search <query> --json","Ask a bounded, proven question"),e("npx workspai doctor workspace --json","Diagnose projects and workspace health"),e("npx workspai project coverage --run --target 80 --json","Measure one project"),e("npx workspai workspace explain <target> --write --json","Explain a blocker or project"),Rs("Find the right command"),console.log(""),e("npx workspai create --help","Creation, adoption, import, and supported kits"),e("npx workspai workspace --help","Model, graph, evidence, operations, and governance"),e("npx workspai doctor --help","Project and workspace diagnosis"),e("npx workspai commands --json","Complete machine-readable command inventory"),e("npx workspai mirror [status|sync|verify|rotate]","Registry mirror management"),e("npx workspai cache [status|clear|prune|repair]","Package cache management"),console.log(s.bold(`
405
+ `)),e("npx workspai workspace model --write --json","Build the canonical system model"),e("npx workspai workspace graph search <query> --json","Ask a bounded, proven question"),e("npx workspai doctor workspace --json","Diagnose projects and workspace health"),e("npx workspai project coverage --run --target 80 --json","Measure one project"),e("npx workspai workspace explain <target> --write --json","Explain a blocker or project"),Ss("Find the right command"),console.log(""),e("npx workspai create --help","Creation, adoption, import, and supported kits"),e("npx workspai workspace --help","Model, graph, evidence, operations, and governance"),e("npx workspai doctor --help","Project and workspace diagnosis"),e("npx workspai commands --json","Complete machine-readable command inventory"),e("npx workspai mirror [status|sync|verify|rotate]","Registry mirror management"),e("npx workspai cache [status|clear|prune|repair]","Package cache management"),console.log(s.bold(`
406
406
  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
407
- `)),Am?(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
407
+ `)),Sm?(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
408
408
  `))):console.log(s.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
409
- `));}var Vl="__rapidkit_signal_handlers_registered__",Ul=globalThis;Ul[Vl]||(Ul[Vl]=true,process.on("SIGINT",async()=>{if(!rn){if(rn=true,console.log(s.yellow(`
409
+ `));}var Fl="__rapidkit_signal_handlers_registered__",Jl=globalThis;Jl[Fl]||(Jl[Fl]=true,process.on("SIGINT",async()=>{if(!Zo){if(Zo=true,console.log(s.yellow(`
410
410
 
411
- \u26A0\uFE0F Interrupted by user`)),Et&&await O__default.pathExists(Et)){console.log(s.gray("Cleaning up partial installation..."));try{await O__default.remove(Et),console.log(s.green("\u2713 Cleanup complete"));}catch(t){f.debug("Cleanup failed:",t);}}b$9(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!rn){if(rn=true,f.debug("Received SIGTERM"),Et&&await O__default.pathExists(Et))try{await O__default.remove(Et);}catch(t){f.debug("Cleanup failed:",t);}b$9(143,"Terminated"),process.exit(143);}}));var Im=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Om=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),r=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return A.realpathSync(t)===A.realpathSync(fileURLToPath(import.meta.url))||r}catch{return b.resolve(t)===b.resolve(fileURLToPath(import.meta.url))||r}})(),$m=!Im||Om;function Nm(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}function Tm(){for(let t of [process.stdout,process.stderr]){if(t.isTTY)continue;let e=t;if(e.__rapidkitSyncWriteInstalled)continue;let r=t.fd;if(typeof r!="number")continue;let o=t.write.bind(t);e.write=((n,a,i)=>{let c=typeof a=="string"?a:"utf8",p=typeof a=="function"?a:typeof i=="function"?i:void 0;try{let d=typeof n=="string"?Buffer.from(n,c):n instanceof Uint8Array?Buffer.from(n):Buffer.from(String(n),c);return A.writeSync(r,d),p?.(),true}catch{return o(n,c,p)}}),e.__rapidkitSyncWriteInstalled=true;}}async function _e(t){b$9(t),await new Promise(e=>setImmediate(e)),await new Promise(e=>setTimeout(e,25)),await Promise.all([process.stdout,process.stderr].map(e=>new Promise(r=>{e.write("",()=>r());}))),process.exit(t);}async function As(t,e=0){return A.writeSync(process.stdout.fd??1,t),_e(e)}async function Mm(){Nm(),Tm(),d$7(),a$6({argv:process.argv,cwd:process.cwd(),rapidkitVersion:i()}),c$5(process.argv);let t$1=process.argv.slice(2),e$1=t$1[0],r=process.cwd(),o=Ye(r),n$1=t(r,"project.json").some(g=>A.existsSync(g)),a$1=nm(),i$1=Wl(t$1),c=a$1&&Jr(t$1),p=e$1==="init"&&o&&!n$1,d=t$1.length===0||t$1.length===1&&(e$1==="--help"||e$1==="-h"||e$1==="help");Bc(t$1)&&await As(`${zc(t$1[1])}
412
- `),d&&(a("npm cli"),tp(),await _e(0)),t$1.some(g=>g==="--version"||g==="-V"||g==="-v")&&!t$1.some(g=>g==="--help"||g==="-h"||g==="help")&&(t$1.includes("--json")?await As(`${JSON.stringify(sm(),null,2)}
413
- `):await As(`${i()}
414
- `)),Ts(t$1)&&await _e(0),c&&e$1===Vo?(async()=>{await _e(await $s(t$1));})().catch(g=>{process.stderr.write(`Workspai CLI failed to run create: ${g?.message??g}
415
- `),process.exit(1);}):c&&Dl(e$1)?(async()=>{await _e(await Ll(e$1,t$1));})().catch(g=>{process.stderr.write(`Workspai CLI failed to run ${e$1}: ${g?.message??g}
416
- `),process.exit(1);}):i$1||c?de.parseAsync().then(()=>_e(0)).catch(g=>{let m=cr()&&g instanceof Error&&g.stack?g.stack:g?.message??g;process.stderr.write(`Workspai CLI failed: ${m}
417
- `),process.exit(1);}):p?Js(t$1).then(g=>_e(g)).catch(g=>{process.stderr.write(`Workspai CLI failed to run workspace init: ${g?.message??g}
418
- `),process.exit(1);}):Em().then(async g=>{if(!g){let m=process.argv.slice(2);if(cr()&&process.stderr.write(`[workspai-cli] argv=${JSON.stringify(m)}
419
- `),Wl(m)){await de.parseAsync();return}if(Ts(m)&&await _e(0),m[0]===Vo){let w=await $s(m);await _e(w);}if(m[0]==="init"){let w=await Js(m);await _e(w);}if(Dl(m[0])){let w=await Ll(m[0],m);await _e(w);}if(s$2(m[0])){if(Ms(m))return;let w=m[0],j=i$2(process.cwd()),x=await Wt(process.cwd()),l$1=Pe(process.cwd()),P=false;if(l$1){let v=s$1(l$1,"policies.yml").find(C=>A.existsSync(C));if(v&&await O__default.pathExists(v))try{let C=await A.promises.readFile(v,"utf-8");if(P=((C.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??C.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict",P){let E=s$1(l$1,"toolchain.lock").find(M=>A.existsSync(M)),$=[];if(!E||!await O__default.pathExists(E))$.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain).");else try{let _=JSON.parse(await A.promises.readFile(E,"utf-8")).runtime??{};j$2(j,process.cwd())&&!_.go?.version&&$.push("Go runtime version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."),k(j,process.cwd())&&!_.node?.version&&$.push("Node runtime version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."),l(j,process.cwd())&&!_.java?.version&&$.push("Java runtime version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."),m$1(j,process.cwd())&&!_.dotnet?.version&&$.push(".NET runtime version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."),n(j,process.cwd())&&!_.python?.version&&$.push("Python runtime version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");}catch{$.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode.");}let N=s$1(l$1,"workspace.json").find(M=>A.existsSync(M));if(N&&await O__default.pathExists(N))try{let _=JSON.parse(await A.promises.readFile(N,"utf-8")).profile??"",S=j$3(process.cwd(),j),J=St({profile:_,runtime:S.runtime,subjectLabel:b.basename(process.cwd()),mode:"strict"});J.ok||$.push(`${J.message} Update the workspace profile or use a polyglot workspace.`);}catch{}if($.length>0){console.log(s.red(`\u274C Strict policy violations block \`${w}\`:`));for(let M of $)console.log(s.red(` \u2022 ${M}`));console.log(s.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .workspai/policies.yml")),await _e(1);}}}catch{}}let u=await a$7({startPath:process.cwd(),action:w,writeReport:true}),h=P||process.env.RAPIDKIT_LIFECYCLE_ENFORCE_READINESS==="1"||process.env.RAPIDKIT_ENFORCE_READINESS==="1";if(u.blocking&&h){console.log(s.red(`\u274C Release readiness blocks \`${w}\`:`));for(let v of u.blockingReasons)console.log(s.red(` \u2022 ${v}`));u.evidencePath&&console.log(s.gray(`\u2139\uFE0F Readiness evidence: ${u.evidencePath}`)),await _e(1);}u.overallStatus!=="pass"&&!h&&(console.log(s.yellow(`\u26A0\uFE0F Release readiness is ${u.overallStatus}. Command continues in warn mode.`)),u.evidencePath&&console.log(s.gray(` Evidence: ${u.evidencePath} (set RAPIDKIT_LIFECYCLE_ENFORCE_READINESS=1 to block)`)));let f=await Zl(process.cwd(),async()=>{if(j$2(j,process.cwd())||x==="go"){let v=Ke("go",{runCommandInCwd:je,runCoreRapidkit:e});if(w==="lint")return Q(await v.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(w==="format")return Q(await v.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let C=w==="dev"?await v.runDev(process.cwd()):w==="test"?await v.runTest(process.cwd()):w==="build"?await v.runBuild(process.cwd()):await v.runStart(process.cwd());return C.message&&console.log(s.red(`\u274C ${C.message}`)),C.exitCode}if(l(j,process.cwd())||x==="java")return w==="dev"?await ht("dev",process.cwd()):w==="test"?await ht("test",process.cwd()):w==="build"?await ht("build",process.cwd()):w==="lint"?await ht("lint",process.cwd()):w==="format"?await ht("format",process.cwd()):await ht("start",process.cwd());if(m$1(j,process.cwd())||x==="dotnet"){let v=Ke("dotnet",{runCommandInCwd:je,runCoreRapidkit:e});if(w==="lint")return Q(await v.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(w==="format")return Q(await v.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let C=w==="dev"?await v.runDev(process.cwd()):w==="test"?await v.runTest(process.cwd()):w==="build"?await v.runBuild(process.cwd()):await v.runStart(process.cwd());return C.message&&console.log(s.red(`\u274C ${C.message}`)),C.exitCode}if(k(j,process.cwd())||x==="node")return w==="dev"?await Mt("dev",process.cwd()):w==="test"?await Mt("test",process.cwd()):w==="build"?await Mt("build",process.cwd()):w==="lint"?await Mt("lint",process.cwd()):w==="format"?await Mt("format",process.cwd()):await Mt("start",process.cwd());if(n(j,process.cwd())||x==="python"){if(w==="lint"||w==="format")return await e([w],{cwd:process.cwd()});let v=Ke("python",{runCommandInCwd:je,runCoreRapidkit:e});return Q(w==="dev"?await v.runDev(process.cwd()):w==="test"?await v.runTest(process.cwd()):w==="build"?await v.runBuild(process.cwd()):await v.runStart(process.cwd()))}if(x==="rust"||x==="php"){let v=Ke(x,{runCommandInCwd:je,runCoreRapidkit:e});if(w==="lint")return Q(await v.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(w==="format")return Q(await v.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let C=w==="dev"?await v.runDev(process.cwd()):w==="test"?await v.runTest(process.cwd()):w==="build"?await v.runBuild(process.cwd()):await v.runStart(process.cwd());return Q(C)}return -1});if(!f.ok){await _e(f.code);return}if(f.ok&&f.value>=0){await _e(f.value);return}if(f.ok&&f.value===-1){console.error(s.red(`\u274C Workspai cannot run \`${w}\` for this project runtime.`)),console.error(s.gray("Run `workspai project commands` to inspect supported commands.")),await _e(1);return}}if(Ms(m))return;let k$1=await _m(m);if(cr()&&process.stderr.write(`[workspai-cli] shouldForwardToCore=${k$1}
420
- `),k$1){let w=await e(m,{cwd:process.cwd()});await _e(w);}await de.parseAsync();}});}$m&&await Mm();export{ds as COMMAND_CAPABILITIES_SCHEMA_VERSION,Wu as NPM_ONLY_SCOPED_COMMANDS,Du as NPM_ONLY_TOP_LEVEL_COMMANDS,nl as VERSION_CONTRACT_SCHEMA_VERSION,em as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,Mm as bootstrapCli,js as bridgeFailureCode,_l as buildDelegationEnvForInit,Kl as checkStrictPolicyPreflightForDelegation,Ku as commandAvailable,Hl as createProjectVenv,Vu as createWorkspaceVenv,um as defaultWorkspacePolicyYaml,cm as detectWindowsDoctorWorkspaceShadow,Uu as ensurePythonProjectUsesLocalVenv,ql as findContextFileUp,lm as findLegacyWorkspaceUp,Ws as findWorkspaceMarkerUp,Pe as findWorkspaceUp,am as getGlobalCommandCapabilities,Bo as getPublishedContractCatalog,Tr as getPublishedContractVersions,sm as getVersionContract,ep as handleAdoptCommand,Pm as handleBootstrapCommand,Cm as handleCacheCommand,$s as handleCreateOrFallback,Ss as handleGoInit,Ds as handleImportCommand,Js as handleInitCommand,ht as handleJavaCommand,xm as handleMirrorCommand,Mt as handleNodeCommand,jm as handleSetupCommand,Ye as hasWorkspaceRootMarkers,Us as hostPythonCandidates,Wt as inferRuntimeByFiles,Hu as installPythonDependenciesWithPipFallback,Ls as installWorkspaceDependencies,nm as isNpmExecInvocation,Jr as isNpmOnlyInvocation,Dl as isNpmOnlyManualHandlerCommand,om as isNpmOnlyParseDirectCommand,Wl as isNpmOnlyParseDirectInvocation,Ns as isNpmOnlyScopedCommand,rm as isNpmOnlyTopLevelCommand,Fu as normalizeFallbackTemplate,bm as parseCacheConfig,Ju as parseMaxWorkersOption,hm as parseNodeEvalScript,gm as parsePolicyBooleanLiteral,tp as printHelp,de as program,Ie as readFlagValue,dm as replaceOrInsertRulePolicyLine,Jl as replaceOrInsertTopLevelPolicyLine,Lu as resolveInvokedCliName,je as runCommandInCwd,tn as runCreateFallback,_m as shouldForwardToCore,Bu as validateNpmKitFlags};
411
+ \u26A0\uFE0F Interrupted by user`)),Ct&&await O__default.pathExists(Ct)){console.log(s.gray("Cleaning up partial installation..."));try{await O__default.remove(Ct),console.log(s.green("\u2713 Cleanup complete"));}catch(t){f.debug("Cleanup failed:",t);}}b$9(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!Zo){if(Zo=true,f.debug("Received SIGTERM"),Ct&&await O__default.pathExists(Ct))try{await O__default.remove(Ct);}catch(t){f.debug("Cleanup failed:",t);}b$9(143,"Terminated"),process.exit(143);}}));var Em=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Rm=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),r=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return A.realpathSync(t)===A.realpathSync(fileURLToPath(import.meta.url))||r}catch{return b.resolve(t)===b.resolve(fileURLToPath(import.meta.url))||r}})(),Am=!Em||Rm;function _m(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}function Im(){for(let t of [process.stdout,process.stderr]){if(t.isTTY)continue;let e=t;if(e.__rapidkitSyncWriteInstalled)continue;let r=t.fd;if(typeof r!="number")continue;let o=t.write.bind(t);e.write=((n,a,i)=>{let c=typeof a=="string"?a:"utf8",p=typeof a=="function"?a:typeof i=="function"?i:void 0;try{let d=typeof n=="string"?Buffer.from(n,c):n instanceof Uint8Array?Buffer.from(n):Buffer.from(String(n),c);return A.writeSync(r,d),p?.(),true}catch{return o(n,c,p)}}),e.__rapidkitSyncWriteInstalled=true;}}async function Ee(t){b$9(t),await new Promise(e=>setImmediate(e)),await new Promise(e=>setTimeout(e,25)),await Promise.all([process.stdout,process.stderr].map(e=>new Promise(r=>{e.write("",()=>r());}))),process.exit(t);}async function xs(t,e=0){return A.writeSync(process.stdout.fd??1,t),Ee(e)}async function Om(){_m(),Im(),d$7(),a$6({argv:process.argv,cwd:process.cwd(),rapidkitVersion:i()}),c$5(process.argv);let t$1=process.argv.slice(2),e$1=t$1[0],r=process.cwd(),o=Be(r),n$1=t(r,"project.json").some(g=>A.existsSync(g)),a$1=em(),i$1=$l(t$1),c=a$1&&Dr(t$1),p=e$1==="init"&&o&&!n$1,d=t$1.length===0||t$1.length===1&&(e$1==="--help"||e$1==="-h"||e$1==="help");Uc(t$1)&&await xs(`${Bc(t$1[1])}
412
+ `),d&&(a("npm cli"),Xl(),await Ee(0)),t$1.some(g=>g==="--version"||g==="-V"||g==="-v")&&!t$1.some(g=>g==="--help"||g==="-h"||g==="help")&&(t$1.includes("--json")?await xs(`${JSON.stringify(tm(),null,2)}
413
+ `):await xs(`${i()}
414
+ `)),Os(t$1)&&await Ee(0),c&&e$1===Jo?(async()=>{await Ee(await _s(t$1));})().catch(g=>{process.stderr.write(`Workspai CLI failed to run create: ${g?.message??g}
415
+ `),process.exit(1);}):c&&Nl(e$1)?(async()=>{await Ee(await Tl(e$1,t$1));})().catch(g=>{process.stderr.write(`Workspai CLI failed to run ${e$1}: ${g?.message??g}
416
+ `),process.exit(1);}):i$1||c?le.parseAsync().then(()=>Ee(0)).catch(g=>{let m=sr()&&g instanceof Error&&g.stack?g.stack:g?.message??g;process.stderr.write(`Workspai CLI failed: ${m}
417
+ `),process.exit(1);}):p?Ds(t$1).then(g=>Ee(g)).catch(g=>{process.stderr.write(`Workspai CLI failed to run workspace init: ${g?.message??g}
418
+ `),process.exit(1);}):bm().then(async g=>{if(!g){let m=process.argv.slice(2);if(sr()&&process.stderr.write(`[workspai-cli] argv=${JSON.stringify(m)}
419
+ `),$l(m)){await le.parseAsync();return}if(Os(m)&&await Ee(0),m[0]===Jo){let y=await _s(m);await Ee(y);}if(m[0]==="init"){let y=await Ds(m);await Ee(y);}if(Nl(m[0])){let y=await Tl(m[0],m);await Ee(y);}if(s$2(m[0])){if($s(m))return;let y=m[0],j=i$2(process.cwd()),x=await Nt(process.cwd()),l$1=we(process.cwd()),P=false;if(l$1){let v=s$1(l$1,"policies.yml").find(C=>A.existsSync(C));if(v&&await O__default.pathExists(v))try{let C=await A.promises.readFile(v,"utf-8");if(P=((C.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??C.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict",P){let E=s$1(l$1,"toolchain.lock").find(M=>A.existsSync(M)),$=[];if(!E||!await O__default.pathExists(E))$.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain).");else try{let _=JSON.parse(await A.promises.readFile(E,"utf-8")).runtime??{};j$2(j,process.cwd())&&!_.go?.version&&$.push("Go runtime version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."),k(j,process.cwd())&&!_.node?.version&&$.push("Node runtime version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."),l(j,process.cwd())&&!_.java?.version&&$.push("Java runtime version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."),m$1(j,process.cwd())&&!_.dotnet?.version&&$.push(".NET runtime version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."),n(j,process.cwd())&&!_.python?.version&&$.push("Python runtime version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");}catch{$.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode.");}let N=s$1(l$1,"workspace.json").find(M=>A.existsSync(M));if(N&&await O__default.pathExists(N))try{let _=JSON.parse(await A.promises.readFile(N,"utf-8")).profile??"",S=j$3(process.cwd(),j),J=jt({profile:_,runtime:S.runtime,subjectLabel:b.basename(process.cwd()),mode:"strict"});J.ok||$.push(`${J.message} Update the workspace profile or use a polyglot workspace.`);}catch{}if($.length>0){console.log(s.red(`\u274C Strict policy violations block \`${y}\`:`));for(let M of $)console.log(s.red(` \u2022 ${M}`));console.log(s.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .workspai/policies.yml")),await Ee(1);}}}catch{}}let u=await a$7({startPath:process.cwd(),action:y,writeReport:true}),h=P||process.env.RAPIDKIT_LIFECYCLE_ENFORCE_READINESS==="1"||process.env.RAPIDKIT_ENFORCE_READINESS==="1";if(u.blocking&&h){console.log(s.red(`\u274C Release readiness blocks \`${y}\`:`));for(let v of u.blockingReasons)console.log(s.red(` \u2022 ${v}`));u.evidencePath&&console.log(s.gray(`\u2139\uFE0F Readiness evidence: ${u.evidencePath}`)),await Ee(1);}u.overallStatus!=="pass"&&!h&&(console.log(s.yellow(`\u26A0\uFE0F Release readiness is ${u.overallStatus}. Command continues in warn mode.`)),u.evidencePath&&console.log(s.gray(` Evidence: ${u.evidencePath} (set RAPIDKIT_LIFECYCLE_ENFORCE_READINESS=1 to block)`)));let f=await zl(process.cwd(),async()=>{if(j$2(j,process.cwd())||x==="go"){let v=Fe("go",{runCommandInCwd:ke,runCoreRapidkit:e});if(y==="lint")return Q(await v.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(y==="format")return Q(await v.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let C=y==="dev"?await v.runDev(process.cwd()):y==="test"?await v.runTest(process.cwd()):y==="build"?await v.runBuild(process.cwd()):await v.runStart(process.cwd());return C.message&&console.log(s.red(`\u274C ${C.message}`)),C.exitCode}if(l(j,process.cwd())||x==="java")return y==="dev"?await mt("dev",process.cwd()):y==="test"?await mt("test",process.cwd()):y==="build"?await mt("build",process.cwd()):y==="lint"?await mt("lint",process.cwd()):y==="format"?await mt("format",process.cwd()):await mt("start",process.cwd());if(m$1(j,process.cwd())||x==="dotnet"){let v=Fe("dotnet",{runCommandInCwd:ke,runCoreRapidkit:e});if(y==="lint")return Q(await v.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(y==="format")return Q(await v.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let C=y==="dev"?await v.runDev(process.cwd()):y==="test"?await v.runTest(process.cwd()):y==="build"?await v.runBuild(process.cwd()):await v.runStart(process.cwd());return C.message&&console.log(s.red(`\u274C ${C.message}`)),C.exitCode}if(k(j,process.cwd())||x==="node")return y==="dev"?await $t("dev",process.cwd()):y==="test"?await $t("test",process.cwd()):y==="build"?await $t("build",process.cwd()):y==="lint"?await $t("lint",process.cwd()):y==="format"?await $t("format",process.cwd()):await $t("start",process.cwd());if(n(j,process.cwd())||x==="python"){if(y==="lint"||y==="format")return await e([y],{cwd:process.cwd()});let v=Fe("python",{runCommandInCwd:ke,runCoreRapidkit:e});return Q(y==="dev"?await v.runDev(process.cwd()):y==="test"?await v.runTest(process.cwd()):y==="build"?await v.runBuild(process.cwd()):await v.runStart(process.cwd()))}if(x==="rust"||x==="php"){let v=Fe(x,{runCommandInCwd:ke,runCoreRapidkit:e});if(y==="lint")return Q(await v.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(y==="format")return Q(await v.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let C=y==="dev"?await v.runDev(process.cwd()):y==="test"?await v.runTest(process.cwd()):y==="build"?await v.runBuild(process.cwd()):await v.runStart(process.cwd());return Q(C)}return -1});if(!f.ok){await Ee(f.code);return}if(f.ok&&f.value>=0){await Ee(f.value);return}if(f.ok&&f.value===-1){console.error(s.red(`\u274C Workspai cannot run \`${y}\` for this project runtime.`)),console.error(s.gray("Run `workspai project commands` to inspect supported commands.")),await Ee(1);return}}if($s(m))return;let k$1=await xm(m);if(sr()&&process.stderr.write(`[workspai-cli] shouldForwardToCore=${k$1}
420
+ `),k$1){let y=await e(m,{cwd:process.cwd()});await Ee(y);}await le.parseAsync();}});}Am&&await Om();export{cs as COMMAND_CAPABILITIES_SCHEMA_VERSION,$u as NPM_ONLY_SCOPED_COMMANDS,Nu as NPM_ONLY_TOP_LEVEL_COMMANDS,el as VERSION_CONTRACT_SCHEMA_VERSION,Yu as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,Om as bootstrapCli,ks as bridgeFailureCode,xl as buildDelegationEnvForInit,Ll as checkStrictPolicyPreflightForDelegation,Lu as commandAvailable,Gl as createProjectVenv,Fu as createWorkspaceVenv,cm as defaultWorkspacePolicyYaml,nm as detectWindowsDoctorWorkspaceShadow,Ju as ensurePythonProjectUsesLocalVenv,Vl as findContextFileUp,sm as findLegacyWorkspaceUp,Ns as findWorkspaceMarkerUp,we as findWorkspaceUp,rm as getGlobalCommandCapabilities,Vo as getPublishedContractCatalog,Or as getPublishedContractVersions,tm as getVersionContract,Yl as handleAdoptCommand,ym as handleBootstrapCommand,vm as handleCacheCommand,_s as handleCreateOrFallback,js as handleGoInit,Ts as handleImportCommand,Ds as handleInitCommand,mt as handleJavaCommand,jm as handleMirrorCommand,$t as handleNodeCommand,wm as handleSetupCommand,Be as hasWorkspaceRootMarkers,Gs as hostPythonCandidates,Nt as inferRuntimeByFiles,Gu as installPythonDependenciesWithPipFallback,Ms as installWorkspaceDependencies,em as isNpmExecInvocation,Dr as isNpmOnlyInvocation,Nl as isNpmOnlyManualHandlerCommand,Zu as isNpmOnlyParseDirectCommand,$l as isNpmOnlyParseDirectInvocation,Is as isNpmOnlyScopedCommand,Qu as isNpmOnlyTopLevelCommand,Mu as normalizeFallbackTemplate,km as parseCacheConfig,Wu as parseMaxWorkersOption,um as parseNodeEvalScript,pm as parsePolicyBooleanLiteral,Xl as printHelp,le as program,Re as readFlagValue,im as replaceOrInsertRulePolicyLine,Wl as replaceOrInsertTopLevelPolicyLine,Tu as resolveInvokedCliName,ke as runCommandInCwd,Qo as runCreateFallback,xm as shouldForwardToCore,Ku as validateNpmKitFlags};