workspai 0.60.1 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +90 -33
  2. package/contracts/analyze-last-run.v1.json +7 -1
  3. package/contracts/extension-cli-compatibility.v1.json +1 -1
  4. package/contracts/studio-card-repair-capabilities.v1.json +1 -1
  5. package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +1 -0
  6. package/dist/analyze-K6JDMF5C.js +1 -0
  7. package/dist/autopilot-release-7Q5JT7YN.js +1 -0
  8. package/dist/{chunk-AJ535F22.js → chunk-2FPANIX3.js} +1 -1
  9. package/dist/{chunk-WLFJHRB3.js → chunk-2JVRDBJC.js} +1 -1
  10. package/dist/{chunk-WUB6QGC7.js → chunk-4KNDIFJ5.js} +1 -1
  11. package/dist/{chunk-KTW4EN47.js → chunk-5YNZR74I.js} +1 -1
  12. package/dist/chunk-ASOFWN6J.js +1 -0
  13. package/dist/{chunk-S4CWUZ4K.js → chunk-BQCGULHR.js} +1 -1
  14. package/dist/{chunk-MDF2FBLS.js → chunk-GWMC6SSY.js} +1 -1
  15. package/dist/{chunk-VV55EAWO.js → chunk-JEGG4EEZ.js} +1 -1
  16. package/dist/chunk-JRIEP4BY.js +2 -0
  17. package/dist/{chunk-TYQMO36U.js → chunk-NJ6WJ7VU.js} +1 -1
  18. package/dist/chunk-RALI2ESF.js +49 -0
  19. package/dist/chunk-VRQLHCE2.js +8 -0
  20. package/dist/{chunk-KNTPDRZB.js → chunk-YGONW6VG.js} +1 -1
  21. package/dist/{chunk-I2O6AC2Z.js → chunk-ZJ62F4U3.js} +1 -1
  22. package/dist/{create-ZLDOBXG4.js → create-TPUFKW6B.js} +1 -1
  23. package/dist/{goal-lifecycle-OV6NZDD6.js → goal-lifecycle-BNLXDHED.js} +1 -1
  24. package/dist/{goal-pack-Q3O2Z7R5.js → goal-pack-2PF775AU.js} +1 -1
  25. package/dist/index.js +19 -19
  26. package/dist/{pipeline-NICVJLZF.js → pipeline-BY2YL7C6.js} +1 -1
  27. package/dist/{project-agent-entry-DVPKQST7.js → project-agent-entry-VXCOXRJB.js} +1 -1
  28. package/dist/{project-intelligence-lens-RLYSPJB2.js → project-intelligence-lens-BA6JLXQH.js} +1 -1
  29. package/dist/{verified-goal-2BRQZQBL.js → verified-goal-5OV4BALK.js} +1 -1
  30. package/dist/{workspace-LQ77WAHC.js → workspace-J4OGSSNO.js} +1 -1
  31. package/dist/workspace-agent-sync-MU7W3C4S.js +1 -0
  32. package/dist/{workspace-context-YAK5XX27.js → workspace-context-MDACPLHD.js} +1 -1
  33. package/dist/workspace-explain-NWP3JTFR.js +1 -0
  34. package/dist/{workspace-explain-contract-ZL4NMLZI.js → workspace-explain-contract-JWFM22L4.js} +1 -1
  35. package/dist/{workspace-foundation-G4KPT5CN.js → workspace-foundation-3X5OBEMM.js} +1 -1
  36. package/dist/{workspace-intelligence-runner-T6CVJIQQ.js → workspace-intelligence-runner-DEW3CZKA.js} +1 -1
  37. package/dist/{workspace-mcp-serve-ALIZV72K.js → workspace-mcp-serve-S5IXSJJL.js} +1 -1
  38. package/dist/{workspace-onboarding-46BE3EQD.js → workspace-onboarding-LK5IK6LE.js} +1 -1
  39. package/dist/workspace-repair-engine-3OLRNXD6.js +3 -0
  40. package/dist/workspace-run-JTEIX4WA.js +1 -0
  41. package/docs/README.md +16 -14
  42. package/docs/ci-workflows.md +1 -1
  43. package/docs/workspace-repair-engine.md +48 -2
  44. package/package.json +1 -1
  45. package/dist/analyze-FYNMI5KT.js +0 -1
  46. package/dist/autopilot-release-IRXB2VOH.js +0 -1
  47. package/dist/chunk-7ITSLGPZ.js +0 -8
  48. package/dist/chunk-KBR4Y4RW.js +0 -1
  49. package/dist/chunk-NRVSDL4J.js +0 -39
  50. package/dist/chunk-OU7DF6MP.js +0 -2
  51. package/dist/workspace-agent-sync-YLP75OWF.js +0 -1
  52. package/dist/workspace-explain-QH4FXQW5.js +0 -1
  53. package/dist/workspace-repair-engine-SZZKV3JF.js +0 -3
  54. package/dist/workspace-run-JTEFCQYQ.js +0 -1
  55. /package/dist/{chunk-HQWDW2BV.js → chunk-JMFCMPWI.js} +0 -0
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {c as c$8,b as b$f,a as a$p}from'./chunk-QCKWQFCD.js';import {a as a$l}from'./chunk-ICGWHIMK.js';import {a as a$s}from'./chunk-FB7SCXAZ.js';import {b,c,d,j as j$1,h as h$2,i,a as a$F}from'./chunk-NVQUBUTY.js';import {a as a$h}from'./chunk-VV55EAWO.js';import {a as a$q}from'./chunk-5SFCBZOH.js';import {d as d$3,c as c$3,p as p$2,b as b$j,a as a$D}from'./chunk-KTN2ARZJ.js';import {a as a$j,f as f$5,d as d$9,i as i$5}from'./chunk-S4CWUZ4K.js';import {c as c$1,b as b$6,a as a$E}from'./chunk-LPCWROQ3.js';import {b as b$4,a as a$7}from'./chunk-GPGEJVVO.js';import {c as c$5,d as d$5,e as e$5,b as b$d,g as g$3}from'./chunk-WUB6QGC7.js';import {b as b$e,a as a$n,c as c$7}from'./chunk-NRVSDL4J.js';import {b as b$8,a as a$a}from'./chunk-THIOE2PB.js';import {f as f$3}from'./chunk-AJ535F22.js';import {b as b$b,g as g$2,c as c$c,a as a$C}from'./chunk-I2O6AC2Z.js';import {g as g$6,e as e$8,c as c$a,b as b$h,a as a$y}from'./chunk-KNTPDRZB.js';import {a as a$i,e as e$9,d as d$a}from'./chunk-J3X56S7L.js';import {a,b as b$1}from'./chunk-B6FJ6RG6.js';import {a as a$r}from'./chunk-4PUJVYRM.js';import {b as b$7,d as d$6,a as a$6,c as c$6,f as f$8,e as e$a}from'./chunk-ILIBOMYL.js';import {b as b$5,a as a$2,d as d$2}from'./chunk-GPOZILMY.js';import {a as a$m}from'./chunk-PXWKMPPI.js';import {e as e$3,d as d$4}from'./chunk-KBR4Y4RW.js';import {a as a$u}from'./chunk-OU7DF6MP.js';import {a as a$x}from'./chunk-WQX3JYEP.js';import {c as c$9,a as a$v}from'./chunk-O6R7SE6Y.js';import {a as a$B,b as b$i}from'./chunk-HCFWT42C.js';import {a as a$A}from'./chunk-NS53IPAC.js';import {f as f$6}from'./chunk-NBJ6AP7K.js';import {a as a$k}from'./chunk-PVXSIYLP.js';import {a as a$o}from'./chunk-N4QQADXX.js';import {a as a$c}from'./chunk-KCJ3VS6R.js';import {a as a$9}from'./chunk-A5FBGRJA.js';import {a as a$t}from'./chunk-TFOOSYGO.js';import {b as b$a,a as a$e,j as j$5,g as g$5,e as e$7,c as c$d,d as d$b}from'./chunk-NA2NXX5P.js';import {h as h$1,a as a$1,l as l$1,k as k$2,m as m$2,q as q$1,j as j$6,p as p$4,n as n$1,s as s$3,r as r$2}from'./chunk-PTNLVI62.js';import {a as a$g}from'./chunk-27UR373Z.js';import {d as d$8,b as b$g,i as i$7}from'./chunk-KG3TUTXU.js';import {b as b$2,d as d$1,a as a$3,e as e$4,w,i as i$2,p as p$3,j as j$3,l,m as m$1,n,k as k$1,s as s$2,o as o$2,y,q as q$2,h as h$5,r as r$1,x,z,t as t$1,v as v$1,f as f$7,u as u$1}from'./chunk-SCP5LJNO.js';export{r as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-SCP5LJNO.js';import {c as c$4,b as b$c,a as a$H}from'./chunk-T5YRFRJV.js';import {j as j$4,i as i$4}from'./chunk-ZCPT6KC3.js';import {a as a$f}from'./chunk-GR6442P7.js';import {d as d$7,a as a$b,b as b$9}from'./chunk-CCDGHPEJ.js';import {b as b$l}from'./chunk-D65FCQIO.js';import {a as a$4}from'./chunk-AFIFZTOY.js';import {k,i as i$1,e as e$2,f as f$2,h as h$3,g as g$4,c as c$b,a as a$z,l as l$2}from'./chunk-NZ3WZYD5.js';import {h,e,g,c as c$2,a as a$8,f as f$4}from'./chunk-X6TNBARH.js';import {a as a$d}from'./chunk-TQEMLBAG.js';import {a as a$w}from'./chunk-VR6XMUF3.js';import {f,e as e$1,a as a$5,d as d$c,i as i$6,g as g$7}from'./chunk-W3HXTCSY.js';import {m,f as f$1,t,o as o$1,v,p,j as j$2,s as s$1,u,i as i$3,g as g$1,h as h$4,e as e$6,a as a$G,b as b$k,k as k$3,n as n$2}from'./chunk-MOSXTVPU.js';import {o,b as b$3,p as p$1,q,r,m as m$3,i as i$8,j as j$7,e as e$b,g as g$8,c as c$e}from'./chunk-RJIYCDVC.js';import {c as c$f}from'./chunk-2FIX2MDC.js';import {Command,Option}from'commander';import s from'chalk';import j from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Zu from'vm';import*as O from'fs-extra';import O__default from'fs-extra';import _,{existsSync,promises,createWriteStream}from'fs';import Tn,{tmpdir,homedir}from'os';import {execa}from'execa';import Pt,{randomUUID,createVerify,createHash,createHmac}from'crypto';import bl from'http';import Cl from'https';function yp(){return j$7()}function wp(t,e){return t==="py"?["-3",...e]:e}function kp(t){return typeof t=="object"&&t!==null}async function vp(t,e,r,o=c$f()){try{let n=await execa(t,e,{cwd:r,timeout:o,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function Pp(t,e){let r=["-m","rapidkit",...t],o=yp();for(let n of o){let a=await vp(n,wp(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return kp(c)?{ok:true,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr,data:c}:{ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}catch{return {ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}}return {ok:false}}async function Gi(t,e){let r=await Pp(["project","detect","--path",t,"--json"],e);return !r.ok||!r.data||r.data.schema_version!==1?{ok:false,command:r.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:r}var Ji=new Set(["create"]),_n=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),jp=new Set(["pip","poetry","venv","pipx","python"]);function Vi(t){return typeof t=="string"&&jp.has(t)}function In(t,e){return !t||Ji.has(t)?false:a$5.has(t)?true:e?.has(t)??false}function On(t,e=null){let r=t[0];return !r||r.startsWith("-")||Ji.has(r)||r==="init"?false:In(r,e)?true:t.filter(n=>!n.startsWith("-")&&!_n.has(n)).length<=1?false:t.length>1}var Ht=j.join(Tn.homedir(),".workspairc.json"),bp=j.join(Tn.homedir(),".rapidkitrc.json"),Cp=j.join(Tn.homedir(),".rapidkit","config.json");function $n(t){try{if(!_.existsSync(t))return {};let e=_.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Ki(t){if(process.platform!=="win32")try{_.chmodSync(t,384);}catch{}}function Bt(){let t=$n(Ht),e=$n(bp),r=$n(Cp);return _.existsSync(Ht)&&Ki(Ht),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function ho(t){let r={...Bt(),...t};_.writeFileSync(Ht,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Ki(Ht);}function jr(){return process.env.OPENAI_API_KEY||Bt().openaiApiKey||null}function Mn(){return Bt().aiEnabled!==false}function Wn(){return Ht}function Ui(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async r=>{let o=r.key;o?o.startsWith("sk-")||(console.log(s.red(`
2
+ import {c as c$8,b as b$f,a as a$p}from'./chunk-QCKWQFCD.js';import {a as a$l}from'./chunk-ICGWHIMK.js';import {a as a$s}from'./chunk-FB7SCXAZ.js';import {b,c,d,j as j$1,h as h$2,i,a as a$F}from'./chunk-NVQUBUTY.js';import {a as a$h}from'./chunk-JEGG4EEZ.js';import {a as a$q}from'./chunk-5SFCBZOH.js';import {d as d$3,c as c$3,p as p$2,b as b$j,a as a$D}from'./chunk-KTN2ARZJ.js';import {a as a$j,f as f$5,d as d$9,i as i$5}from'./chunk-BQCGULHR.js';import {c as c$1,b as b$6,a as a$E}from'./chunk-LPCWROQ3.js';import {b as b$4,a as a$7}from'./chunk-GPGEJVVO.js';import {c as c$5,d as d$5,e as e$5,b as b$d,g as g$3}from'./chunk-4KNDIFJ5.js';import {b as b$e,a as a$n,c as c$7}from'./chunk-RALI2ESF.js';import {b as b$8,a as a$a}from'./chunk-THIOE2PB.js';import {f as f$3}from'./chunk-2FPANIX3.js';import {b as b$b,g as g$2,c as c$c,a as a$C}from'./chunk-ZJ62F4U3.js';import {g as g$6,e as e$8,c as c$a,b as b$h,a as a$y}from'./chunk-YGONW6VG.js';import {a as a$i,e as e$9,d as d$a}from'./chunk-J3X56S7L.js';import {a,b as b$1}from'./chunk-B6FJ6RG6.js';import {a as a$r}from'./chunk-4PUJVYRM.js';import {b as b$7,d as d$6,a as a$6,c as c$6,f as f$8,e as e$a}from'./chunk-ILIBOMYL.js';import {b as b$5,a as a$2,d as d$2}from'./chunk-GPOZILMY.js';import {a as a$m}from'./chunk-PXWKMPPI.js';import {e as e$3,d as d$4}from'./chunk-ASOFWN6J.js';import {a as a$u}from'./chunk-JRIEP4BY.js';import {a as a$x}from'./chunk-WQX3JYEP.js';import {c as c$9,a as a$v}from'./chunk-O6R7SE6Y.js';import {a as a$B,b as b$i}from'./chunk-HCFWT42C.js';import {a as a$A}from'./chunk-NS53IPAC.js';import {f as f$6}from'./chunk-NBJ6AP7K.js';import {a as a$k}from'./chunk-PVXSIYLP.js';import {a as a$o}from'./chunk-N4QQADXX.js';import {a as a$c}from'./chunk-KCJ3VS6R.js';import {a as a$9}from'./chunk-A5FBGRJA.js';import {a as a$t}from'./chunk-TFOOSYGO.js';import {b as b$a,a as a$e,j as j$5,g as g$5,e as e$7,c as c$d,d as d$b}from'./chunk-NA2NXX5P.js';import {h as h$1,a as a$1,l as l$1,k as k$2,m as m$2,q as q$1,j as j$6,p as p$4,n as n$1,s as s$3,r as r$2}from'./chunk-PTNLVI62.js';import {a as a$g}from'./chunk-27UR373Z.js';import {d as d$8,b as b$g,i as i$7}from'./chunk-KG3TUTXU.js';import {b as b$2,d as d$1,a as a$3,e as e$4,w,i as i$2,p as p$3,j as j$3,l,m as m$1,n,k as k$1,s as s$2,o as o$2,y,q as q$2,h as h$5,r as r$1,x,z,t as t$1,v as v$1,f as f$7,u as u$1}from'./chunk-SCP5LJNO.js';export{r as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-SCP5LJNO.js';import {c as c$4,b as b$c,a as a$H}from'./chunk-T5YRFRJV.js';import {j as j$4,i as i$4}from'./chunk-ZCPT6KC3.js';import {a as a$f}from'./chunk-GR6442P7.js';import {d as d$7,a as a$b,b as b$9}from'./chunk-CCDGHPEJ.js';import {b as b$l}from'./chunk-D65FCQIO.js';import {a as a$4}from'./chunk-AFIFZTOY.js';import {k,i as i$1,e as e$2,f as f$2,h as h$3,g as g$4,c as c$b,a as a$z,l as l$2}from'./chunk-NZ3WZYD5.js';import {h,e,g,c as c$2,a as a$8,f as f$4}from'./chunk-X6TNBARH.js';import {a as a$d}from'./chunk-TQEMLBAG.js';import {a as a$w}from'./chunk-VR6XMUF3.js';import {f,e as e$1,a as a$5,d as d$c,i as i$6,g as g$7}from'./chunk-W3HXTCSY.js';import {m,f as f$1,t,o as o$1,v,p,j as j$2,s as s$1,u,i as i$3,g as g$1,h as h$4,e as e$6,a as a$G,b as b$k,k as k$3,n as n$2}from'./chunk-MOSXTVPU.js';import {o,b as b$3,p as p$1,q,r,m as m$3,i as i$8,j as j$7,e as e$b,g as g$8,c as c$e}from'./chunk-RJIYCDVC.js';import {c as c$f}from'./chunk-2FIX2MDC.js';import {Command,Option}from'commander';import s from'chalk';import j from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Zu from'vm';import*as O from'fs-extra';import O__default from'fs-extra';import _,{existsSync,promises,createWriteStream}from'fs';import Tn,{tmpdir,homedir}from'os';import {execa}from'execa';import Pt,{randomUUID,createVerify,createHash,createHmac}from'crypto';import bl from'http';import Cl from'https';function yp(){return j$7()}function wp(t,e){return t==="py"?["-3",...e]:e}function kp(t){return typeof t=="object"&&t!==null}async function vp(t,e,r,o=c$f()){try{let n=await execa(t,e,{cwd:r,timeout:o,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function Pp(t,e){let r=["-m","rapidkit",...t],o=yp();for(let n of o){let a=await vp(n,wp(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return kp(c)?{ok:true,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr,data:c}:{ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}catch{return {ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}}return {ok:false}}async function Gi(t,e){let r=await Pp(["project","detect","--path",t,"--json"],e);return !r.ok||!r.data||r.data.schema_version!==1?{ok:false,command:r.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:r}var Ji=new Set(["create"]),_n=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),jp=new Set(["pip","poetry","venv","pipx","python"]);function Vi(t){return typeof t=="string"&&jp.has(t)}function In(t,e){return !t||Ji.has(t)?false:a$5.has(t)?true:e?.has(t)??false}function On(t,e=null){let r=t[0];return !r||r.startsWith("-")||Ji.has(r)||r==="init"?false:In(r,e)?true:t.filter(n=>!n.startsWith("-")&&!_n.has(n)).length<=1?false:t.length>1}var Ht=j.join(Tn.homedir(),".workspairc.json"),bp=j.join(Tn.homedir(),".rapidkitrc.json"),Cp=j.join(Tn.homedir(),".rapidkit","config.json");function $n(t){try{if(!_.existsSync(t))return {};let e=_.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Ki(t){if(process.platform!=="win32")try{_.chmodSync(t,384);}catch{}}function Bt(){let t=$n(Ht),e=$n(bp),r=$n(Cp);return _.existsSync(Ht)&&Ki(Ht),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function ho(t){let r={...Bt(),...t};_.writeFileSync(Ht,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Ki(Ht);}function jr(){return process.env.OPENAI_API_KEY||Bt().openaiApiKey||null}function Mn(){return Bt().aiEnabled!==false}function Wn(){return Ht}function Ui(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async r=>{let o=r.key;o?o.startsWith("sk-")||(console.log(s.red(`
3
3
  \u274C Invalid API key format (should start with sk-)
4
4
  `)),process.exit(1)):o=(await b$1([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:a=>a?a.startsWith("sk-")?a.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,ho({openaiApiKey:o}),console.log(s.green(`
5
5
  \u2705 OpenAI API key saved successfully!
@@ -112,7 +112,7 @@ Workspai Private Product Manifest
112
112
  `)),console.log(s.cyan("Product:"),s.white(t.product.slug)),console.log(s.cyan("Kit:"),s.white(t.projects[0].kit)),console.log(s.cyan("Modules:"),s.white(String(t.projects[0].modules.length))),console.log(s.cyan("Module gaps:"),s.yellow(String(t.projects[0].moduleGaps.length))),console.log(s.cyan("Checksum:"),s.white(t.factory.manifestChecksum)),console.log(s.gray(`
113
113
  Wrote manifest: ${j.resolve(process.cwd(),e)}
114
114
  `));}function fc(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(r,o)=>{try{let n=o.output||pc("--output"),a=await gc({backlogPath:r,kit:o.kit,tier:o.tier,category:o.category,limit:o.limit});a$4(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await uc(n,a,true),o.json?console.log(Xt(a)):Qp(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Xt({ok:false,error:{message:a}})):console.error(s.red(`Product plan failed: ${a}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(r,o)=>{try{let n=o.output||pc("--output");mc(r);let a=await Yp({backlogPath:o.fromBacklog,slug:r,kit:o.kit,outputRoot:o.workspaceOutput});a$4(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=Xp(n,r);await uc(i,a,o.force===true),o.json?console.log(Xt(a)):Zp(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Xt({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var wc="rapidkit-workspace-snapshot-v1",Er="rapidkit-workspace-snapshot-v2",ed=wc,kc="rapidkit-project-archive-v1",pt="workspai-archive.json",bo="rapidkit-archive.json",td=[".workspai/workspace.json",".workspai-workspace","workspai.config.json","workspai.config.js","workspai.config.cjs","workspai.config.mjs",".rapidkit/workspace.json",".rapidkit-workspace","rapidkit.config.json","rapidkit.config.js","rapidkit.config.cjs","rapidkit.config.mjs","package.json"],rd=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),xr={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function Zt(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function Co(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!e)throw new Error("Snapshot name must contain at least one letter or number.");return e.slice(0,120)}async function od(t){try{let e=await O__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function nd(t,e){if(!t)return e;let r=t.trim().toLowerCase();return ["true","yes","1","on"].includes(r)?true:["false","no","0","off"].includes(r)?false:e}async function sd(t){let e=s$1(t,"policies.yml").find(r=>existsSync(r))??p(t,"policies.yml");if(!await O__default.pathExists(e))return {...xr};try{let r=await O__default.readFile(e,"utf-8"),o=(n,a)=>{let i=r.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return nd(i?.[1],a)};return {requireReasonForDestructiveOps:o("require_reason_for_destructive_ops",xr.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:o("require_safety_snapshot_for_destructive_ops",xr.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:o("allow_permanent_delete",xr.allowPermanentDelete)}}catch{return {...xr}}}function ad(t){return p(t,"audit","events.jsonl")}async function Ze(t,e){let r={schema:"rapidkit-workspace-audit-event-v1",id:Pt.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},o=ad(t);return await O__default.ensureDir(j.dirname(o)),await O__default.appendFile(o,`${JSON.stringify(r)}
115
- `,"utf-8"),r}async function So(t,e,r){let o=await sd(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function Un(t=process.cwd()){let e=j.resolve(t),r=j.resolve(Tn.tmpdir());for(;;){if(e!==r&&j$2(e))return e;let o=j.dirname(e);if(o===e)return null;e=o;}}function jt(t){let e=t?j.resolve(t):Un(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!j$2(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function vc(t){let e=await od(s$1(t,"workspace.json").find(o=>existsSync(o))??p(t,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():j.basename(t)}function er(t){return p(t,"snapshots")}function Rr(t){return p(t,"archive","projects")}function Qt(t){return j.join(t,"files")}function id(t){return j.join(Tn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${Pt.randomBytes(4).toString("hex")}`)}function cd(t,e){return j.join(er(t),`.tmp-${process.pid}-${e}-${Pt.randomBytes(4).toString("hex")}`)}function xo(t,e){let r=j.relative(t,e);if(!r)return true;let o=r.split(j.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>rd.has(n)||a$f(n))}async function ld(t){return (await a$g(t,{descendIntoMatchedProjects:false})).map(r=>({name:j.basename(r),relativePath:j.relative(t,r)}))}async function pd(t,e){let r=[],o=new Set;for(let n of td){let a=j.join(t,n);if(!await O__default.pathExists(a))continue;let i=v(n);if(o.has(i))continue;let c=j.join(e,i);await O__default.copy(a,c,{filter:d=>xo(t,d)}),r.push(i),o.add(i);}return r}async function Pc(t){let e=[];async function r(o){let n=[];try{n=await O__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=j.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=j.join(j.dirname(o),j.basename(v(j.basename(o))));await O__default.copy(o,n,{overwrite:false,errorOnExist:false}),await O__default.remove(o);}}async function jc(t,e){let r=e.schema===Er?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,r,"Workspace snapshot manifest"),await O__default.writeJson(j.join(t,"snapshot.json"),e,{spaces:2});}async function Hn(t){let e=j.join(t,"snapshot.json"),r=await O__default.readJson(e);if(!r||typeof r!="object"||![wc,Er].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===Er?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==Er||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function dd(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await O__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=j.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let d=await O__default.stat(c);e+=1,r+=d.size;}catch{}}}return {files:e,bytes:r}}async function Eo(t={}){let e=jt(t.workspacePath),r=t.name?t.name:`snapshot-${Zt()}`,o=Co(r),n=j.join(er(e),o),a=id(o);if(await O__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=Qt(a);try{await O__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",d=c==="full"?["."]:await pd(e,i);c==="full"&&(await O__default.copy(e,i,{filter:f=>xo(e,f)}),await Pc(i));let l={schema:ed,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await vc(e),workspacePath:e,copiedPaths:d,projects:await ld(e)};return await jc(a,l),await O__default.ensureDir(j.dirname(n)),await O__default.move(a,n,{overwrite:false}),await Ze(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:d,snapshotPath:n,projectCount:l.projects.length}}),{manifest:l,snapshotPath:n}}catch(c){throw await O__default.remove(a),await Ze(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function Ro(t){let e=j.resolve(t.workspacePath),r=j.resolve(t.projectPath),o=j.relative(e,r);if(!o||o.startsWith("..")||j.isAbsolute(o)||o.split(j.sep).some(f=>f===".workspai"||f===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=j.basename(r),a=Co(`${t.namePrefix}-${n}-${Zt()}-${Pt.randomBytes(3).toString("hex")}`),i=j.join(er(e),a),c=cd(e,a),d=j.join(Qt(c),o),l=false;try{await O__default.ensureDir(j.dirname(d)),t.moveSource?(await O__default.move(r,d,{overwrite:false}),l=true):await O__default.copy(r,d,{overwrite:false,errorOnExist:true,filter:u=>xo(r,u)});let f={schema:Er,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await vc(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await jc(c,f),await O__default.move(c,i,{overwrite:false}),await Ze(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:f,snapshotPath:i}}catch(f){if(l&&!await O__default.pathExists(r)){let u=await O__default.pathExists(d)?d:j.join(Qt(i),o);await O__default.pathExists(u)&&(await O__default.ensureDir(j.dirname(r)),await O__default.move(u,r,{overwrite:false}));}throw await O__default.remove(c),await O__default.remove(i),await Ze(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:f instanceof Error?f.message:String(f)}}),f}}async function bc(t){let e=jt(t.workspacePath),r=j.join(er(e),Co(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Hn(r),n=Qt(r),a=await dd(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function Cc(t={}){let e=jt(t.workspacePath),r=er(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=j.join(r,a.name);try{n.push({...await Hn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var ud=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function md(t){let e=j.dirname(t.workspacePath),r=j.basename(t.workspacePath),o=`${Zt()}-${Pt.randomBytes(4).toString("hex")}`,n=j.join(e,`.${r}.restore-staging-${o}`),a=j.join(e,`.${r}.pre-restore-${o}`),i=j.join(e,`.${r}.restore-failed-${o}`),c=[],d=false,l=false;try{await O__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:f=>xo(t.filesRoot,f)}),await Pc(n),await O__default.rename(t.workspacePath,a),d=true,await O__default.rename(n,t.workspacePath),l=true;for(let f of ud){let u=j.join(a,f);if(!await O__default.pathExists(u))continue;let w=j.join(t.workspacePath,f);if(await O__default.pathExists(w))throw new Error(`Full restore operational path collision: ${f}`);await O__default.ensureDir(j.dirname(w)),await O__default.rename(u,w),c.push(f);}return a}catch(f){for(let u of [...c].reverse()){let w=j.join(t.workspacePath,u),y=j.join(a,u);await O__default.pathExists(w)&&(await O__default.ensureDir(j.dirname(y)),await O__default.rename(w,y));}throw l&&await O__default.pathExists(t.workspacePath)&&await O__default.rename(t.workspacePath,i),d&&await O__default.pathExists(a)&&await O__default.rename(a,t.workspacePath),await O__default.remove(i),await O__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${f instanceof Error?f.message:String(f)}`)}}async function Sc(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=j.join(Qt(t.snapshotPath),r),n=j.join(e,r);await O__default.pathExists(o)&&!await O__default.pathExists(n)&&(await O__default.ensureDir(j.dirname(n)),await O__default.move(o,n,{overwrite:false})),await O__default.remove(t.snapshotPath);}async function xc(t){let e=jt(t.workspacePath),r=j.join(er(e),Co(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Hn(r),n=Qt(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(d=>{let l=v(d);return l.startsWith(".workspai/")?".workspai":l})));if(t.dryRun)return await Ze(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await So(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await md({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let d=o.recoveryScope?.relativePath;if(!d)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let l=j.join(n,d),f=j.join(e,d),u=await O__default.pathExists(f),w,y=j.join(j.dirname(f),`.${j.basename(f)}.pre-restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`),P=false;u&&t.safetySnapshot!==false?(w=await Ro({workspacePath:e,projectPath:f,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=w.snapshotPath):u&&(await O__default.rename(f,y),P=true);let S=j.join(j.dirname(f),`.${j.basename(f)}.restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`);try{await O__default.copy(l,S,{overwrite:false,errorOnExist:true}),await O__default.rename(S,f),P&&await O__default.remove(y);}catch(p){throw await O__default.remove(S),P&&await O__default.pathExists(y)&&(await O__default.remove(f),await O__default.rename(y,f)),w&&await Sc(w,e),p}}else t.safetySnapshot!==false&&(i=(await Eo({workspacePath:e,name:`pre-restore-${o.name}-${Zt()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let d=new Set;for(let l of o.copiedPaths){let f=v(l);d.has(f)||(await O__default.copy(j.join(n,l),j.join(e,f),{overwrite:true,errorOnExist:false}),d.add(f));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await Ze(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function Ec(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function Rc(t,e){let r=Ec(e),o=j.isAbsolute(r)?j.resolve(r):j.resolve(t,r);if(o.startsWith(`${j.resolve(t)}${j.sep}`)&&await O__default.pathExists(o))return o;let a=(await a$g(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=j.relative(t,i);return j.basename(i)===r||c===r});if(a.length===0)throw new Error(`Project not found in workspace: ${e}`);if(a.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return a[0]}async function Bn(t){let{syncWorkspaceProjects:e}=await import('./workspace-LQ77WAHC.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-3BWIRSVQ.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-RLYSPJB2.js');await o({workspacePath:t,mode:"managed"});}function gd(t,e){let r=Pt.randomBytes(4).toString("hex");return j.join(Rr(t),`${e}-${Zt()}-${r}`)}async function Ac(t){let e=_c(t),r=await O__default.readJson(e);if(!r||typeof r!="object"||r.schema!==kc)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function _c(t){return [pt,bo].map(e=>j.join(t,e)).find(e=>O__default.existsSync(e))??j.join(t,pt)}async function qn(t={}){let e=jt(t.workspacePath),r=Rr(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=j.join(r,a.name),c=[pt,bo].map(d=>j.join(i,d)).find(d=>O__default.existsSync(d))??j.join(i,pt);try{n.push({...await Ac(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function fd(t,e){let r=Ec(e),o=j.isAbsolute(r)?j.resolve(r):j.resolve(Rr(t),r);if(o.startsWith(`${j.resolve(Rr(t))}${j.sep}`)&&(await O__default.pathExists(j.join(o,pt))||await O__default.pathExists(j.join(o,bo))))return o;let a=(await qn({workspacePath:t})).filter(i=>j.basename(i.archivePath)===r||i.projectName===r||j.relative(Rr(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function zn(t){let e=jt(t.workspacePath),r=await Rc(e,t.project),o=j.basename(r),n=gd(e,o),a=j.join(n,pt),i=`${n}.tmp-${process.pid}`,c=j.join(i,pt);for(let u of [pt,bo])if(await O__default.pathExists(j.join(r,u)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${u}`);if(t.dryRun)return await Ze(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await So(e,"project.archive",{reason:t.reason,safetySnapshot:true});let d=await Ro({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),l={schema:kc,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:d.snapshotPath};a$4(l,"contracts/project-archive.v1.json","Project archive manifest");let f=false;try{await O__default.ensureDir(j.dirname(n)),await O__default.move(r,i,{overwrite:false}),f=true,await O__default.writeJson(c,l,{spaces:2}),await O__default.rename(i,n);}catch(u){if(f&&!await O__default.pathExists(r)){let w=await O__default.pathExists(i)?i:n;await O__default.pathExists(w)&&(await O__default.remove(j.join(w,pt)),await O__default.move(w,r,{overwrite:false}));}throw await O__default.remove(i),u}return await c$4(e,[r]),await Bn(e),await Ze(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:d.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:d.snapshotPath,dryRun:false}}async function Ic(t){if(!t.permanent)return zn(t);let e=jt(t.workspacePath),r=await Rc(e,t.project),o=j.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await Ze(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await So(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Ro({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$4(e,[r]),await Bn(e),await Ze(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function Oc(t){let e=jt(t.workspacePath),r=await fd(e,t.archive),o=await Ac(r),n=t.targetName?.trim()||o.projectName,a=j.join(e,n);if(!a.startsWith(`${j.resolve(e)}${j.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await O__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await Ze(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:j.join(r,pt),dryRun:true};await So(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await O__default.pathExists(a),c=i?await Ro({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await Eo({workspacePath:e,name:`pre-restore-project-${n}-${Zt()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),d=_c(r),l=p(e,"audit","restores",`${j.basename(r)}.json`);try{await O__default.move(r,a,{overwrite:false}),await O__default.ensureDir(j.dirname(l)),await O__default.move(j.join(a,j.basename(d)),l,{overwrite:false});}catch(f){throw await O__default.pathExists(a)&&(await O__default.pathExists(l)&&await O__default.move(l,j.join(a,j.basename(d)),{overwrite:false}),await O__default.pathExists(r)||await O__default.move(a,r,{overwrite:false})),i&&await Sc(c,e),f}return await Bn(e),await Ze(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:l,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:l,safetySnapshotPath:c.snapshotPath,dryRun:false}}var yd="rapidkit.infra-stack.v1",Nc=h$3.infraPlan.schemaVersion,tr=".workspai/infra/docker-compose.yml",rr=i$1.infraPlan,Qn=".workspai/infra/.env.example";function wd(){let t=j.dirname(fileURLToPath(import.meta.url)),e=[j.join(t,"../../contracts/infra-stack.v1.json"),j.join(t,"../contracts/infra-stack.v1.json")];for(let r of e)if(_.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var Xn=null;function Ot(t){if(Xn)return Xn;let e=wd(),r=_.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==yd)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return kd(o),(Xn=o),o}function kd(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function Tc(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function or(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Mc(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function Pd(t){let e=j.join(t,"registry.json");if(!await O__default.pathExists(e))return [];try{let o=(await O__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function jd(t){let e=j.join(t,".env.example");if(!await O__default.pathExists(e))return [];try{let r=await O__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
115
+ `,"utf-8"),r}async function So(t,e,r){let o=await sd(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function Un(t=process.cwd()){let e=j.resolve(t),r=j.resolve(Tn.tmpdir());for(;;){if(e!==r&&j$2(e))return e;let o=j.dirname(e);if(o===e)return null;e=o;}}function jt(t){let e=t?j.resolve(t):Un(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!j$2(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function vc(t){let e=await od(s$1(t,"workspace.json").find(o=>existsSync(o))??p(t,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():j.basename(t)}function er(t){return p(t,"snapshots")}function Rr(t){return p(t,"archive","projects")}function Qt(t){return j.join(t,"files")}function id(t){return j.join(Tn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${Pt.randomBytes(4).toString("hex")}`)}function cd(t,e){return j.join(er(t),`.tmp-${process.pid}-${e}-${Pt.randomBytes(4).toString("hex")}`)}function xo(t,e){let r=j.relative(t,e);if(!r)return true;let o=r.split(j.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>rd.has(n)||a$f(n))}async function ld(t){return (await a$g(t,{descendIntoMatchedProjects:false})).map(r=>({name:j.basename(r),relativePath:j.relative(t,r)}))}async function pd(t,e){let r=[],o=new Set;for(let n of td){let a=j.join(t,n);if(!await O__default.pathExists(a))continue;let i=v(n);if(o.has(i))continue;let c=j.join(e,i);await O__default.copy(a,c,{filter:d=>xo(t,d)}),r.push(i),o.add(i);}return r}async function Pc(t){let e=[];async function r(o){let n=[];try{n=await O__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=j.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=j.join(j.dirname(o),j.basename(v(j.basename(o))));await O__default.copy(o,n,{overwrite:false,errorOnExist:false}),await O__default.remove(o);}}async function jc(t,e){let r=e.schema===Er?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,r,"Workspace snapshot manifest"),await O__default.writeJson(j.join(t,"snapshot.json"),e,{spaces:2});}async function Hn(t){let e=j.join(t,"snapshot.json"),r=await O__default.readJson(e);if(!r||typeof r!="object"||![wc,Er].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===Er?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==Er||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function dd(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await O__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=j.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let d=await O__default.stat(c);e+=1,r+=d.size;}catch{}}}return {files:e,bytes:r}}async function Eo(t={}){let e=jt(t.workspacePath),r=t.name?t.name:`snapshot-${Zt()}`,o=Co(r),n=j.join(er(e),o),a=id(o);if(await O__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=Qt(a);try{await O__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",d=c==="full"?["."]:await pd(e,i);c==="full"&&(await O__default.copy(e,i,{filter:f=>xo(e,f)}),await Pc(i));let l={schema:ed,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await vc(e),workspacePath:e,copiedPaths:d,projects:await ld(e)};return await jc(a,l),await O__default.ensureDir(j.dirname(n)),await O__default.move(a,n,{overwrite:false}),await Ze(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:d,snapshotPath:n,projectCount:l.projects.length}}),{manifest:l,snapshotPath:n}}catch(c){throw await O__default.remove(a),await Ze(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function Ro(t){let e=j.resolve(t.workspacePath),r=j.resolve(t.projectPath),o=j.relative(e,r);if(!o||o.startsWith("..")||j.isAbsolute(o)||o.split(j.sep).some(f=>f===".workspai"||f===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=j.basename(r),a=Co(`${t.namePrefix}-${n}-${Zt()}-${Pt.randomBytes(3).toString("hex")}`),i=j.join(er(e),a),c=cd(e,a),d=j.join(Qt(c),o),l=false;try{await O__default.ensureDir(j.dirname(d)),t.moveSource?(await O__default.move(r,d,{overwrite:false}),l=true):await O__default.copy(r,d,{overwrite:false,errorOnExist:true,filter:u=>xo(r,u)});let f={schema:Er,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await vc(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await jc(c,f),await O__default.move(c,i,{overwrite:false}),await Ze(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:f,snapshotPath:i}}catch(f){if(l&&!await O__default.pathExists(r)){let u=await O__default.pathExists(d)?d:j.join(Qt(i),o);await O__default.pathExists(u)&&(await O__default.ensureDir(j.dirname(r)),await O__default.move(u,r,{overwrite:false}));}throw await O__default.remove(c),await O__default.remove(i),await Ze(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:f instanceof Error?f.message:String(f)}}),f}}async function bc(t){let e=jt(t.workspacePath),r=j.join(er(e),Co(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Hn(r),n=Qt(r),a=await dd(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function Cc(t={}){let e=jt(t.workspacePath),r=er(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=j.join(r,a.name);try{n.push({...await Hn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var ud=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function md(t){let e=j.dirname(t.workspacePath),r=j.basename(t.workspacePath),o=`${Zt()}-${Pt.randomBytes(4).toString("hex")}`,n=j.join(e,`.${r}.restore-staging-${o}`),a=j.join(e,`.${r}.pre-restore-${o}`),i=j.join(e,`.${r}.restore-failed-${o}`),c=[],d=false,l=false;try{await O__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:f=>xo(t.filesRoot,f)}),await Pc(n),await O__default.rename(t.workspacePath,a),d=true,await O__default.rename(n,t.workspacePath),l=true;for(let f of ud){let u=j.join(a,f);if(!await O__default.pathExists(u))continue;let w=j.join(t.workspacePath,f);if(await O__default.pathExists(w))throw new Error(`Full restore operational path collision: ${f}`);await O__default.ensureDir(j.dirname(w)),await O__default.rename(u,w),c.push(f);}return a}catch(f){for(let u of [...c].reverse()){let w=j.join(t.workspacePath,u),y=j.join(a,u);await O__default.pathExists(w)&&(await O__default.ensureDir(j.dirname(y)),await O__default.rename(w,y));}throw l&&await O__default.pathExists(t.workspacePath)&&await O__default.rename(t.workspacePath,i),d&&await O__default.pathExists(a)&&await O__default.rename(a,t.workspacePath),await O__default.remove(i),await O__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${f instanceof Error?f.message:String(f)}`)}}async function Sc(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=j.join(Qt(t.snapshotPath),r),n=j.join(e,r);await O__default.pathExists(o)&&!await O__default.pathExists(n)&&(await O__default.ensureDir(j.dirname(n)),await O__default.move(o,n,{overwrite:false})),await O__default.remove(t.snapshotPath);}async function xc(t){let e=jt(t.workspacePath),r=j.join(er(e),Co(t.name));if(!await O__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Hn(r),n=Qt(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(d=>{let l=v(d);return l.startsWith(".workspai/")?".workspai":l})));if(t.dryRun)return await Ze(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await So(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await md({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let d=o.recoveryScope?.relativePath;if(!d)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let l=j.join(n,d),f=j.join(e,d),u=await O__default.pathExists(f),w,y=j.join(j.dirname(f),`.${j.basename(f)}.pre-restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`),P=false;u&&t.safetySnapshot!==false?(w=await Ro({workspacePath:e,projectPath:f,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=w.snapshotPath):u&&(await O__default.rename(f,y),P=true);let S=j.join(j.dirname(f),`.${j.basename(f)}.restore-${process.pid}-${Pt.randomBytes(4).toString("hex")}`);try{await O__default.copy(l,S,{overwrite:false,errorOnExist:true}),await O__default.rename(S,f),P&&await O__default.remove(y);}catch(p){throw await O__default.remove(S),P&&await O__default.pathExists(y)&&(await O__default.remove(f),await O__default.rename(y,f)),w&&await Sc(w,e),p}}else t.safetySnapshot!==false&&(i=(await Eo({workspacePath:e,name:`pre-restore-${o.name}-${Zt()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let d=new Set;for(let l of o.copiedPaths){let f=v(l);d.has(f)||(await O__default.copy(j.join(n,l),j.join(e,f),{overwrite:true,errorOnExist:false}),d.add(f));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await Ze(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function Ec(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function Rc(t,e){let r=Ec(e),o=j.isAbsolute(r)?j.resolve(r):j.resolve(t,r);if(o.startsWith(`${j.resolve(t)}${j.sep}`)&&await O__default.pathExists(o))return o;let a=(await a$g(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=j.relative(t,i);return j.basename(i)===r||c===r});if(a.length===0)throw new Error(`Project not found in workspace: ${e}`);if(a.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return a[0]}async function Bn(t){let{syncWorkspaceProjects:e}=await import('./workspace-J4OGSSNO.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-3BWIRSVQ.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-BA6JLXQH.js');await o({workspacePath:t,mode:"managed"});}function gd(t,e){let r=Pt.randomBytes(4).toString("hex");return j.join(Rr(t),`${e}-${Zt()}-${r}`)}async function Ac(t){let e=_c(t),r=await O__default.readJson(e);if(!r||typeof r!="object"||r.schema!==kc)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function _c(t){return [pt,bo].map(e=>j.join(t,e)).find(e=>O__default.existsSync(e))??j.join(t,pt)}async function qn(t={}){let e=jt(t.workspacePath),r=Rr(e);if(!await O__default.pathExists(r))return [];let o=await O__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=j.join(r,a.name),c=[pt,bo].map(d=>j.join(i,d)).find(d=>O__default.existsSync(d))??j.join(i,pt);try{n.push({...await Ac(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function fd(t,e){let r=Ec(e),o=j.isAbsolute(r)?j.resolve(r):j.resolve(Rr(t),r);if(o.startsWith(`${j.resolve(Rr(t))}${j.sep}`)&&(await O__default.pathExists(j.join(o,pt))||await O__default.pathExists(j.join(o,bo))))return o;let a=(await qn({workspacePath:t})).filter(i=>j.basename(i.archivePath)===r||i.projectName===r||j.relative(Rr(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function zn(t){let e=jt(t.workspacePath),r=await Rc(e,t.project),o=j.basename(r),n=gd(e,o),a=j.join(n,pt),i=`${n}.tmp-${process.pid}`,c=j.join(i,pt);for(let u of [pt,bo])if(await O__default.pathExists(j.join(r,u)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${u}`);if(t.dryRun)return await Ze(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await So(e,"project.archive",{reason:t.reason,safetySnapshot:true});let d=await Ro({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),l={schema:kc,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:d.snapshotPath};a$4(l,"contracts/project-archive.v1.json","Project archive manifest");let f=false;try{await O__default.ensureDir(j.dirname(n)),await O__default.move(r,i,{overwrite:false}),f=true,await O__default.writeJson(c,l,{spaces:2}),await O__default.rename(i,n);}catch(u){if(f&&!await O__default.pathExists(r)){let w=await O__default.pathExists(i)?i:n;await O__default.pathExists(w)&&(await O__default.remove(j.join(w,pt)),await O__default.move(w,r,{overwrite:false}));}throw await O__default.remove(i),u}return await c$4(e,[r]),await Bn(e),await Ze(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:d.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:d.snapshotPath,dryRun:false}}async function Ic(t){if(!t.permanent)return zn(t);let e=jt(t.workspacePath),r=await Rc(e,t.project),o=j.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await Ze(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await So(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Ro({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$4(e,[r]),await Bn(e),await Ze(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function Oc(t){let e=jt(t.workspacePath),r=await fd(e,t.archive),o=await Ac(r),n=t.targetName?.trim()||o.projectName,a=j.join(e,n);if(!a.startsWith(`${j.resolve(e)}${j.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await O__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await Ze(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:j.join(r,pt),dryRun:true};await So(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await O__default.pathExists(a),c=i?await Ro({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await Eo({workspacePath:e,name:`pre-restore-project-${n}-${Zt()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),d=_c(r),l=p(e,"audit","restores",`${j.basename(r)}.json`);try{await O__default.move(r,a,{overwrite:false}),await O__default.ensureDir(j.dirname(l)),await O__default.move(j.join(a,j.basename(d)),l,{overwrite:false});}catch(f){throw await O__default.pathExists(a)&&(await O__default.pathExists(l)&&await O__default.move(l,j.join(a,j.basename(d)),{overwrite:false}),await O__default.pathExists(r)||await O__default.move(a,r,{overwrite:false})),i&&await Sc(c,e),f}return await Bn(e),await Ze(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:l,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:l,safetySnapshotPath:c.snapshotPath,dryRun:false}}var yd="rapidkit.infra-stack.v1",Nc=h$3.infraPlan.schemaVersion,tr=".workspai/infra/docker-compose.yml",rr=i$1.infraPlan,Qn=".workspai/infra/.env.example";function wd(){let t=j.dirname(fileURLToPath(import.meta.url)),e=[j.join(t,"../../contracts/infra-stack.v1.json"),j.join(t,"../contracts/infra-stack.v1.json")];for(let r of e)if(_.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var Xn=null;function Ot(t){if(Xn)return Xn;let e=wd(),r=_.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==yd)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return kd(o),(Xn=o),o}function kd(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function Tc(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function or(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Mc(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function Pd(t){let e=j.join(t,"registry.json");if(!await O__default.pathExists(e))return [];try{let o=(await O__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function jd(t){let e=j.join(t,".env.example");if(!await O__default.pathExists(e))return [];try{let r=await O__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
116
116
  `)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&o.push(i[1]);}return o}catch{return []}}async function bd(t){let e=s$1(t,"infra","overrides.json").find(r=>existsSync(r));if(!e)return [];try{let r=await O__default.readJson(e);return Array.isArray(r.services)?[...new Set(r.services.filter(o=>typeof o=="string"&&o.trim().length>0))]:[]}catch{return []}}async function Cd(t){let e=await d$7(t,i$1.workspaceContract);if(!e)return [];try{let r=await O__default.readJson(e),o=[];for(let n of r.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&o.push({project:a,env:i.trim().toUpperCase()});}return o}catch{return []}}function Ao(t,e,r,o){t.add(r),e.push(o);}async function Wc(t){let e=j.resolve(t.workspacePath),r=t.contract||Ot(),o=new Set,n=[],a=new Set,i=new Set,c=new Set,d=await i$7(e);for(let l of d){let f=j.dirname(j.dirname(l)),u=j.basename(f);for(let w of await Pd(f)){a.add(w);for(let y of Tc(r,w))Ao(o,n,y,{kind:"module",value:w,project:u});}for(let w of await jd(f)){i.add(w);for(let y of or(r,w))Ao(o,n,y,{kind:"env-var",value:w,project:u});}}for(let l of await Cd(e)){i.add(l.env);for(let f of or(r,l.env))Ao(o,n,f,{kind:"contract-env",value:l.env,project:l.project});}for(let l of await bd(e))c.add(l),Ao(o,n,l,{kind:"override",value:l});return {modules:[...a].sort(),envVars:[...i].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...o].sort()}}function Sd(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let r=e.indexOf("=");if(r<=0)return null;let o=e.slice(0,r).trim();if(!/^[A-Z0-9_]+$/.test(o))return null;let n=e.slice(r+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let a=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),i=(a?a[1]:n).trim();return i?{key:o,value:i}:null}async function xd(t){if(!await O__default.pathExists(t))return {};try{let e=await O__default.readFile(t,"utf-8"),r={};for(let o of e.split(`
117
117
  `)){let n=Sd(o);n&&(r[n.key]=n.value);}return r}catch{return {}}}async function Lc(t){let e={},r=await i$7(t.workspacePath);for(let o of r){let n=j.dirname(j.dirname(o)),a=await xd(j.join(n,".env.example"));for(let[i,c]of Object.entries(a))or(t.contract,i).length>0&&(e[i]=c);}return e}function Fc(t,e){return t.filter(r=>or(e,r).length>0).sort()}function Gc(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let r=new URL(e),o=r.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(r.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(r.password||"postgres"),POSTGRES_DB:o||"postgres"}}catch{return}}function Jc(t){let e=t.POSTGRES_USER||"postgres",r=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${r}`]}function Ed(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
118
118
  `)?JSON.stringify(t):t}function Vc(t,e){return Object.entries(t).map(([r,o])=>`${e}${r}: ${Ed(o)}`).join(`
@@ -151,8 +151,8 @@ ${r.stderr||""}`);return o?this.isMavenVersionAtLeast(o,[3,9,0])?{exitCode:0}:{e
151
151
  `,"utf-8");}function st(t,e){return j.isAbsolute(e)?e:j.join(t,e)}function iu(t,e){if(!e.trim()||j.isAbsolute(e)||/^[a-zA-Z]:[\\/]/.test(e))throw new Error(`Mirror artifact target must be a non-empty relative path: ${e}`);let r=j.resolve(t),o=j.resolve(r,e),n=j.relative(r,o);if(!n||n.startsWith("..")||j.isAbsolute(n))throw new Error(`Mirror artifact target escapes the managed artifact directory: ${e}`);return o}async function wl(t,e){let r=j.relative(t,e),o=t;for(let a of r.split(j.sep).slice(0,-1)){o=j.join(o,a);let i=await promises.lstat(o).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)break;if(i.isSymbolicLink())throw new Error(`Mirror artifact target traverses a symbolic link: ${o}`);if(!i.isDirectory())throw new Error(`Mirror artifact target parent is not a directory: ${o}`)}let n=await promises.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(n?.isSymbolicLink()||n&&!n.isFile())throw new Error(`Mirror artifact target must be absent or a regular file: ${e}`)}async function cu(t,e){let r=j.resolve(t),o=j.relative(r,j.resolve(e));if(!o||o.startsWith("..")||j.isAbsolute(o))throw new Error("Managed mirror directory escapes the workspace.");let n=r;for(let a of o.split(j.sep)){n=j.join(n,a);let i=await promises.lstat(n);if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Managed mirror path must contain only real directories: ${n}`)}}function lu(t,e){if(t.target)return t.target;if(t.source)return j.basename(t.source);if(t.url)try{let r=new URL(t.url).pathname,o=j.basename(r);if(o&&o!=="/")return o}catch{}return `${e}.artifact`}async function pu(t){let e=s$1(t,"trusted-sources.lock").find(o=>existsSync(o)),r=new Set(["localhost","127.0.0.1"]);if(!e)return r;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));for(let a of n)r.add(a.toLowerCase());}catch{}return r}async function du(t,e,r){await O.ensureDir(j.dirname(e)),await new Promise((o,n)=>{let i=(t.startsWith("https://")?Cl:bl).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let d=createWriteStream(e);c.pipe(d),d.on("finish",()=>{d.close(),o();}),d.on("error",l=>{n(l);});});i.setTimeout(r,()=>{i.destroy(new Error(`Request timeout after ${r}ms`));}),i.on("error",c=>{n(c);});});}async function uu(t,e,r,o,n){let a=new URL(t),i=JSON.stringify(e),c=a.protocol==="https:"?Cl:bl;await new Promise((d,l)=>{let f=c.request({method:"POST",hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:`${a.pathname}${a.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...o?{Authorization:`Bearer ${o}`}:{},...n||{}}},u=>{if(!u.statusCode||u.statusCode<200||u.statusCode>=300){l(new Error(`HTTP ${u.statusCode||"unknown"}`)),u.resume();return}u.resume(),d();});f.setTimeout(r,()=>{f.destroy(new Error(`Request timeout after ${r}ms`));}),f.on("error",u=>{l(u);}),f.write(i),f.end();});}function kl(t){return new Promise(e=>setTimeout(e,t))}async function mu(t,e,r,o){let n=st(t,e||".workspai/reports/evidence-export-dead-letter.ndjson");return await O.ensureDir(j.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:o,payload:r})}
152
152
  `,"utf-8"),n}function gu(t,e){if(!e?.enabled)return {headers:{}};let r=process.env[e.hmacKeyEnv];if(!r)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let o=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(o,r).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":o}}}async function fu(t,e,r){let o=(r.algorithm||"sha256").toLowerCase(),n=st(t,r.publicKeyPath);if(!await O.pathExists(n))return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(o);c.update(i),c.end();let d=Buffer.from(r.signature,"base64"),l=c.verify(a,d),f=createHash("sha256").update(a).digest("hex");return {verified:l,algorithm:o,publicKeyPath:n,publicKeyFingerprint:f,signature:r.signature,message:l?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Attestation verification error: ${a.message}`}}}async function hu(t,e,r,o){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};let a=r.signaturePath?st(t,r.signaturePath):null;if(!a||!await O.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=r.certificatePath?st(t,r.certificatePath):null;c&&i.push("--certificate",c);let d=r.bundlePath?st(t,r.bundlePath):null;d&&i.push("--bundle",d);let l=r.keyPath?st(t,r.keyPath):null;l&&i.push("--key",l),r.identity&&i.push("--certificate-identity",r.identity),r.issuer&&i.push("--certificate-oidc-issuer",r.issuer),r.rekorUrl&&i.push("--rekor-url",r.rekorUrl),o.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let f=await execa("cosign",i,{reject:false});return f.exitCode===0?{verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:d,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${f.stderr||f.stdout||"unknown error"}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:d,certificatePath:c,signaturePath:a}}catch(f){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${f.message}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:d,certificatePath:c,signaturePath:a}}}async function yu(t,e){let r=e.algorithm||"sha256",o=st(t,e.policyPath),n=st(t,e.signaturePath),a=st(t,e.publicKeyPath);if(!await O.pathExists(o))return {verified:false,message:`Governance policy bundle not found: ${o}`,policies:null};if(!await O.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await O.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(o,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),d=await promises.readFile(a,"utf-8"),l=createVerify(r);return l.update(i),l.end(),l.verify(d,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function fs(t,e){let r=[],o={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=s$1(t,"mirror-config.json").find(M=>existsSync(M))??p(t,"mirror-config.json"),a=p(t,"mirror.lock"),i=p(t,"mirror","artifacts"),c=p(t,"reports"),d=await pu(t);if(!await O.pathExists(n))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:r,details:o};let l={};try{l=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return r.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:r,details:o}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||l.mode==="offline-only"))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:r,details:o};await O.ensureDir(i);try{await cu(t,i);}catch(M){return r.push({id:"mirror.root.safety",status:"failed",message:M instanceof Error?M.message:String(M)}),{checks:r,details:o}}let u=Math.max(0,l.prefetch?.retries??2),w=Math.max(0,l.prefetch?.backoffMs??250),y=Math.max(1e3,l.prefetch?.timeoutMs??15e3),P=l.security?.requireAttestation===true,S=l.security?.requireSigstore===true,p$1=l.security?.requireTransparencyLog===true,v=l.security?.requireSignedGovernance===true,m=l.security?.evidenceExport,h=(process.env.RAPIDKIT_ENV||l.security?.governance?.environment||"dev").toLowerCase(),g=l.security?.governance?.policies||{};if(l.security?.governanceBundle){let M=await yu(t,l.security.governanceBundle);if(r.push({id:"governance.bundle.verify",status:M.verified?"passed":"failed",message:M.message}),M.verified&&M.policies)g=M.policies,o.governanceBundleVerified=true;else if(v)return {checks:r,details:o}}let k=g[h],b=p$1||k?.requireTransparencyLog===true,x=[],C=Array.isArray(l.artifacts)?l.artifacts:[],R=[];for(let M=0;M<C.length;M+=1){let N=C[M],A=N.id||`artifact-${M+1}`,X=N.source?st(t,N.source):null,U=lu(N,A),q;try{q=iu(i,U),await wl(i,q);}catch(le){r.push({id:`mirror.target.${A}`,status:"failed",message:le instanceof Error?le.message:String(le)});continue}let Q=false,L=q,F=false,K=async()=>{F&&await promises.rm(L,{force:true}).catch(()=>{});},te={sourceType:"path",source:X||N.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(X&&await O.pathExists(X))await O.ensureDir(j.dirname(q)),L=`${q}.${process.pid}.${randomUUID()}.tmp`,F=true,await promises.copyFile(X,L),o.syncedArtifacts+=1,Q=true,te={sourceType:"path",source:X,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},r.push({id:`mirror.sync.${A}`,status:"passed",message:`Mirrored artifact ${A} from source path.`});else if(N.url){let le="";try{le=new URL(N.url).hostname.toLowerCase();}catch{r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Invalid URL for ${A}: ${N.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||d.has(le))){r.push({id:`mirror.prefetch.trust.${A}`,status:"failed",message:`Untrusted mirror host for ${A}: ${le}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await O.pathExists(q)?(Q=true,te={sourceType:"url",source:N.url,host:le,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},r.push({id:`mirror.prefetch.${A}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${A}.`})):r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${A} without an existing mirrored copy.`}),!Q))continue;if(!Q){await O.ensureDir(j.dirname(q)),L=`${q}.${process.pid}.${randomUUID()}.tmp`,F=true;let _e=null,T=0;for(let G=1;G<=u+1;G+=1){T=G;try{await promises.rm(L,{force:true}).catch(()=>{}),await du(N.url,L,y),o.syncedArtifacts+=1,Q=true,te={sourceType:"url",source:N.url,host:le,fetchedAt:new Date().toISOString(),attempts:T,trusted:true},r.push({id:`mirror.prefetch.${A}`,status:"passed",message:T>1?`Prefetched artifact ${A} from ${le} after ${T} attempts.`:`Prefetched artifact ${A} from ${le}.`});break}catch(de){if(_e=de,G<=u){await kl(w*G);continue}}}if(!Q){await K(),r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Failed to prefetch ${A} after ${u+1} attempt(s): ${_e?.message||"unknown error"}`});continue}}if(!Q){r.push({id:`mirror.prefetch.${A}`,status:"failed",message:`Failed to prefetch ${A}.`});continue}}if(!Q){N.required||e.offlineMode?r.push({id:`mirror.sync.${A}`,status:"failed",message:`Mirror source missing for ${A}${X?`: ${X}`:""}`}):r.push({id:`mirror.sync.${A}`,status:"skipped",message:`Mirror source not found for optional artifact ${A}.`});continue}let H=await su(L);if(N.sha256&&N.sha256.toLowerCase()!==H.toLowerCase()){r.push({id:`mirror.verify.${A}`,status:"failed",message:`Checksum mismatch for ${A}.`}),await K();continue}o.verifiedArtifacts+=1,r.push({id:`mirror.verify.${A}`,status:"passed",message:`Checksum verified for ${A}.`});let pe=N.attestation?await fu(t,L,N.attestation):null;if(N.attestation){if(r.push({id:`mirror.attest.${A}`,status:pe?.verified?"passed":"failed",message:pe?.message||"Attestation verification failed."}),!pe?.verified){await K();continue}}else if(P){r.push({id:`mirror.attest.${A}`,status:"failed",message:`Attestation is required but missing for ${A}.`}),await K();continue}else r.push({id:`mirror.attest.${A}`,status:"skipped",message:`No attestation provided for ${A}.`});let ue=N.attestation?.sigstore,ae=ue?await hu(t,L,ue,{requireTransparencyLog:b}):null;if(ue){if(r.push({id:`mirror.sigstore.${A}`,status:ae?.verified?"passed":"failed",message:ae?.message||"Sigstore verification failed."}),x.push({artifactId:A,verified:!!ae?.verified,tlogVerified:!!ae?.tlogVerified,identity:ae?.identity||null,issuer:ae?.issuer||null,rekorUrl:ae?.rekorUrl||null,timestamp:new Date().toISOString(),environment:h}),!ae?.verified){await K();continue}}else if(S){r.push({id:`mirror.sigstore.${A}`,status:"failed",message:`Sigstore attestation is required but missing for ${A}.`}),await K();continue}else r.push({id:`mirror.sigstore.${A}`,status:"skipped",message:`No Sigstore attestation provided for ${A}.`});if(ue&&ae?.verified&&k){let le=k.allowedIdentities||[];if(le.length>0){let _e=!!ae.identity&&le.includes(ae.identity);if(r.push({id:`mirror.sigstore.policy.identity.${A}`,status:_e?"passed":"failed",message:_e?`Sigstore identity policy passed for ${A} in ${h}.`:`Sigstore identity policy failed for ${A} in ${h}.`}),!_e){await K();continue}}let ut=k.allowedIssuers||[];if(ut.length>0){let _e=!!ae.issuer&&ut.includes(ae.issuer);if(r.push({id:`mirror.sigstore.policy.issuer.${A}`,status:_e?"passed":"failed",message:_e?`Sigstore issuer policy passed for ${A} in ${h}.`:`Sigstore issuer policy failed for ${A} in ${h}.`}),!_e){await K();continue}}let Ft=k.allowedRekorUrls||[];if(Ft.length>0){let _e=!!ae.rekorUrl&&Ft.includes(ae.rekorUrl);if(r.push({id:`mirror.sigstore.policy.rekor.${A}`,status:_e?"passed":"failed",message:_e?`Sigstore Rekor policy passed for ${A} in ${h}.`:`Sigstore Rekor policy failed for ${A} in ${h}.`}),!_e){await K();continue}}}else k&&r.push({id:`mirror.sigstore.policy.${A}`,status:"skipped",message:`Sigstore governance policy configured for ${h} but no verified Sigstore attestation for ${A}.`});F&&(await wl(i,q),await promises.rename(L,q),F=false);let ze=await promises.stat(q);R.push({id:A,path:j.relative(t,q),sha256:H,size:ze.size,provenance:te,attestation:{detached:{provided:!!N.attestation,verified:pe?.verified||false,algorithm:pe?.algorithm||null,publicKeyPath:pe?.publicKeyPath||null,publicKeyFingerprint:pe?.publicKeyFingerprint||null,signature:pe?.signature||null,verifiedAt:pe?.verified?new Date().toISOString():null},sigstore:{provided:!!ue,verified:ae?.verified||false,tlogVerified:ae?.tlogVerified||false,identity:ae?.identity||null,issuer:ae?.issuer||null,rekorUrl:ae?.rekorUrl||null,bundlePath:ae?.bundlePath||null,certificatePath:ae?.certificatePath||null,signaturePath:ae?.signaturePath||null,verifiedAt:ae?.verified?new Date().toISOString():null}}});}let E=l.retention?.keepLast;if(typeof E=="number"&&E>0){let M=new Set(R.map(A=>j.resolve(t,A.path))),N=(await au(i)).filter(A=>!M.has(j.resolve(A)));if(N.length>E){let A=await Promise.all(N.map(async U=>({filePath:U,stat:await promises.stat(U)})));A.sort((U,q)=>q.stat.mtimeMs-U.stat.mtimeMs);let X=A.slice(E);for(let U of X)await promises.unlink(U.filePath),o.rotatedFiles+=1;}}r.push({id:"mirror.rotate",status:"passed",message:o.rotatedFiles>0?`Mirror retention rotation removed ${o.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let $={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:l.mode||null,environment:h,artifacts:R};if(await promises.writeFile(a,`${JSON.stringify($,null,2)}
153
153
  `,"utf-8"),o.lockWritten=true,r.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${j.relative(t,a)}.`}),o.transparencyEvidenceRecords=x.length,x.length>0){let M={schemaVersion:h$3.transparencyEvidence.schemaVersion,generatedAt:new Date().toISOString(),environment:h,records:x},N=new Date().toISOString().replace(/[:.]/g,"-"),A=j.join(c,`transparency-evidence-${N}.json`),X=j.join(c,"transparency-evidence.latest.json");if(b$l(`.workspai/reports/${j.basename(A)}`,M),b$l(i$1.transparencyEvidence,M),await O.ensureDir(c),await yl(A,M),await yl(X,M),o.transparencyEvidenceWritten=true,r.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${j.relative(t,X)}.`}),m?.enabled){let U=Math.max(1e3,m.timeoutMs??1e4);if(m.target==="file")if(!m.filePath)r.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let q=st(t,m.filePath);await O.ensureDir(j.dirname(q)),await promises.appendFile(q,`${JSON.stringify(M)}
154
- `,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=q,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${q}.`});}catch(q){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${q.message}`});}else if(m.target==="http")if(!m.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let q=Math.max(0,m.retries??0),Q=Math.max(0,m.backoffMs??500),L=gu(M,m.signing);L.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:L.error});try{let F=m.authTokenEnv?process.env[m.authTokenEnv]:void 0,K=false,te=null;for(let H=1;H<=q+1;H+=1)try{if(L.error)throw new Error(L.error);await uu(m.endpoint,M,U,F,L.headers),o.evidenceExported=true,o.evidenceExportTarget=m.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:H>1?`Transparency evidence exported to HTTP endpoint ${m.endpoint} after ${H} attempts.`:`Transparency evidence exported to HTTP endpoint ${m.endpoint}.`}),K=true;break}catch(pe){te=pe,H<=q&&await kl(Q*H);}if(!K)throw te||new Error("unknown evidence export error")}catch(F){let K=`Evidence HTTP export failed: ${F.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:K});try{let te=await mu(t,m.deadLetterPath,M,K);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${te}.`});}catch(te){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${te.message}`});}}}if(m.failOnError&&r.some(Q=>Q.status==="failed"&&(Q.id==="sigstore.evidence.export.file"||Q.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function Yo(t){let e=f$7(t.detection.runtime),r=u$1({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function wu(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function Xo(t){if(t.existingProjectJson?.module_support===true){let e=wu(t.existingProjectJson),r=e?a$3(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}function Sl(t){return t.replace(/\\/g,"/")}function ku(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function vu(t,e){let r=Sl(j.relative(t,e));return !r||r.startsWith("..")?true:r.split("/").filter(Boolean).some(o=>o==="..")}function Nr(t){let e=Sl(j.relative(t.workspacePath,t.projectPath)),r=vu(t.workspacePath,t.projectPath),o=ku(t.projectName,j.basename(t.projectPath)),n=r?`external/${o}`:e||o;return {relativePath:e||n,contractRelativePath:n,isExternal:r}}var xl=[a$G,b$k];function Pu(t,e){let r=j.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!j.isAbsolute(r)}async function tt(t){let e=await O__default.realpath(t);for(let r of xl){let o=j.join(t,r),n=await O__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await O__default.realpath(o);if(!Pu(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function El(t){let e=j.basename(t);return xl.includes(e)?(await O__default.lstat(t)).isSymbolicLink():false}var _l={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},Cu={python:"Python",node:"Node",go:"Go",java:"Java",dotnet:".NET",php:"PHP",ruby:"Ruby",rust:"Rust",elixir:"Elixir",clojure:"Clojure",scala:"Scala",kotlin:"Kotlin",deno:"Deno",bun:"Bun",c:"C",cpp:"C++",unknown:"Unknown"},Su={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},Rl=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function ys(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function ws(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function Tr(t){if(typeof t!="string")return "unknown";let e=t.trim().toLowerCase();return e==="python"||e==="node"||e==="go"||e==="java"||e==="dotnet"||e==="php"||e==="ruby"||e==="rust"||e==="elixir"||e==="clojure"||e==="scala"||e==="kotlin"||e==="deno"||e==="bun"||e==="c"||e==="cpp"?e:e==="c++"||e==="cplusplus"||e==="cc"||e==="clang++"||e==="g++"?"cpp":e==="clang"||e==="gcc"?"c":"unknown"}function en(t){let e=new Set;for(let r of t)e.add(Tr(r));return [...e].sort((r,o)=>Rl.indexOf(r)-Rl.indexOf(o))}function xu(t){let e=en(t).filter(r=>r!=="unknown");if(e.length!==0)return e.length===1?Su[e[0]]:"polyglot"}function Al(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function Eu(t,e){return t?"none":e==="strict"?"error":"warning"}function Mr(t){let e=t.ok?void 0:xu(t.runtimes)??"polyglot";return {ok:t.ok,checkId:t.checkId,status:t.ok?"passed":"failed",profile:t.profile,runtimes:t.runtimes,message:t.message,recommendedProfile:e,recommendedCommand:e?Al(e):void 0,ciRecommendedCommand:e?Al(e,{ci:true}):void 0,severity:Eu(t.ok,t.mode)}}function Tt(t){let e=ws(t.profile),r=en(t.runtimes),o=t.mode??"warn",n=_l[e];if(n){let a=r.length===0||r.every(i=>ys(i)===n);return Mr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:r,message:a?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${r.join(", ")}].`,mode:o})}if(e==="minimal"){let a=r.filter(d=>d!=="unknown"),c=new Set(a.map(d=>ys(d))).size<=1;return Mr({ok:c,checkId:"profile.minimal",profile:e,runtimes:r,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${a.join(", ")}].`,mode:o})}return Mr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:r,message:`${e} profile accepts the detected runtime mix.`,mode:o})}function St(t){let e=ws(t.profile),r=Tr(t.runtime),o=t.mode??"warn",n=_l[e];if(!n||r==="unknown")return Mr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[r],message:r==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:o});let a=ys(r)===n;return Mr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:a?[r]:en([n,r]),message:a?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${Cu[r]}, but workspace profile is "${e}".`,mode:o})}async function ir(t){let e=(await Promise.all(s$1(t,"policies.yml").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "warn";try{return (await O__default.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function cr(t){let e=(await Promise.all(s$1(t,"workspace.json").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "minimal";try{let r=await O__default.readJson(e);return ws(r.profile)}catch{return "minimal"}}async function Mt(t$1,e={}){let r=new Set,o=[],n=new Set,a=[t$1];for(;a.length>0;){let i=a.pop();if(!i||n.has(i))continue;n.add(i);let c=[];try{c=await _.promises.readdir(i,{withFileTypes:true});}catch{continue}for(let d of c){if(!d.isDirectory()||d.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(d.name))continue;let l=j.join(i,d.name);if(l!==t$1&&j$2(l))continue;if((await Promise.all([...t(l,"context.json"),...t(l,"project.json")].map(async u=>O__default.pathExists(u)))).some(Boolean)){o.push(l);continue}a.push(l);}}for(let i of o){let c=i$2(i);r.add(Tr(j$4(i,c).runtime));}for(let i of await a$H(t$1))r.add(Tr(i.runtime));for(let i of e.additionalRuntimes??[])r.add(Tr(i));return en(r)}function tn(t,e={}){let r=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return r?`Recommended: ${r}`:null}function Il(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Au(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return Il(a)||"imported-project"}function xt(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function _u(t){return xt(t)?"git-url":"local-folder"}async function Iu(t,e){let r=Il(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=j.join(t,n);if(!await O__default.pathExists(a))return a;o+=1;}}function Ou(t,e){let r=j.resolve(t),o=j.resolve(e),n=j.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!j.isAbsolute(n)}function $u(t,e){if(Ou(t,e))throw new Error("Import source must be outside the current workspace root.")}function Nu(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function Tu(t){let e=j.basename(t);return !(await El(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||Nu(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Mu(t$1){await tt(t$1);for(let e of t(t$1,"project.json"))if(await O__default.pathExists(e))try{return await O__default.readJson(e)}catch{return null}return null}async function Wu(t){await tt(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:j.basename(t.projectPath),o=Nr({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=u(t.projectPath,"project.json"),i=u(t.projectPath,"import.json"),c=u(t.projectPath,"import-readiness.json"),d=Xo({existingProjectJson:t.existingProjectJson}),l=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],f=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},u$1={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:j.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:j.basename(t.projectPath),kind:t.projectKind,category:a$e(t.projectKind),project_type:a$e(t.projectKind),runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:d,modules:l,contracts:f,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},w={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:j.basename(t.projectPath)},project:{name:u$1.name,slug:u$1.slug,relative_path:n,kind:t.projectKind,category:a$e(t.projectKind),module_support:d},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$e(t.projectKind),confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:d,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},y=Yo({projectName:String(u$1.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:d,projectPath:t.projectPath,generatedAt:new Date(e)});return await O__default.ensureDir(j.dirname(a)),await O__default.writeJson(a,u$1,{spaces:2}),await O__default.writeJson(i,w,{spaces:2}),await O__default.writeJson(c,y,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:d}}async function Du(t,e){let r={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,relationship:"imported",importedAt:new Date().toISOString()};await b$c(t,[r]);}async function Lu(t){await O__default.pathExists(t)&&(await tt(t),await O__default.remove(t));}async function Fu(t,e){await Lu(e),await c$4(t,[e]);}async function Ol(t){let e=j.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??_u(r),n=t.name??(o==="git-url"?Au(r):j.basename(r)),a=await Iu(e,n),i=false;try{if(o==="local-folder"){let h=j.resolve(r),g=await O__default.stat(h).catch(()=>null);if(!g||!g.isDirectory())throw new Error("Import source is not a directory.");if(await tt(h),j$2(h))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");$u(e,h),i=true,await O__default.copy(h,a,{overwrite:false,errorOnExist:true,filter:Tu});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$d()});await tt(a);let c=await Mu(a),d=j$4(a,c),l=await b$a(a,c),[f,u]=await Promise.all([cr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ir(e)]),w=St({profile:f,runtime:d.runtime,subjectLabel:j.basename(a),mode:u}),y=Tt({profile:f,runtimes:await Mt(e,{additionalRuntimes:[d.runtime]}),mode:u}),P=w.ok?y:w;if(!P.ok&&u==="strict")throw new Error(P.message);let S=await Wu({workspacePath:e,projectPath:a,sourceType:o,detection:d,existingProjectJson:c,projectKind:l,profileCompatibility:P}),p=Nr({workspacePath:e,projectPath:a,projectName:j.basename(a)}),v={ingestionPlan:Nt({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:j.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:j.basename(a),path:a,relativePath:p.contractRelativePath,stack:d.importStack,runtime:d.runtime,framework:d.key,frameworkDisplayName:d.displayName,supportTier:d.supportTier,moduleSupport:S.moduleSupport,confidence:d.confidence,source:o,projectJsonPath:S.projectJsonPath,importJsonPath:S.importJsonPath,importReadinessPath:S.importReadinessPath,profileCompatibility:P};await Du(e,v);let{syncWorkspaceContract:m}=await import('./workspace-contract-3BWIRSVQ.js');return await m({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:v.path,projectName:v.name,relationship:"imported",mode:t.projectGrounding??"managed"}),v}catch(c){if(i)try{await Fu(e,a);let{syncWorkspaceContract:d}=await import('./workspace-contract-3BWIRSVQ.js');await d({workspacePath:e,strict:true});}catch(d){let l=c instanceof Error?c.message:String(c),f=d instanceof Error?d.message:String(d);throw new Error(`Import failed: ${l}. Rollback also failed: ${f}`)}throw c}}function Gu(t){return {schemaVersion:qo,sourceMode:"linked",sourceCodeModified:false,projectMetadataFiles:[".workspai/project.json",".workspai/adopt.json",".workspai/adopt-readiness.json",f$1,...t==="off"?[]:[h$4,g$1,b$b]],repositoryControlFiles:[{path:".gitignore",action:"reconcile",condition:"machine-local workspace binding and project-grounding portability rules"},...t==="managed"?[{path:"AGENTS.md",action:"reconcile",condition:"managed grounding is enabled and the path is a regular file; authored deletions and symbolic links are preserved"},...g$2.map(e=>({path:e,action:"reconcile",condition:"managed provider adapter is enabled; authored content, deletions, symbolic links, and unsafe parent paths are preserved"}))]:[]],workspaceOperations:["register-project","sync-contract","rebuild-model","rebuild-graph","sync-agent-grounding"]}}function Ju(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Vu(t,e){return j.resolve(t)===j.resolve(e)}async function Ku(t$1){await tt(t$1);for(let e of t(t$1,"project.json")){if(!await O__default.pathExists(e))continue;let r;try{r=JSON.parse((await O__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}function Uu(t){if(!t?.adoption||typeof t.adoption!="object")return false;let e=t.adoption;return e.managed_by==="workspai"&&e.mode==="linked"}async function $l(t,e){let r=j.relative(t,e);if(r.startsWith("..")||j.isAbsolute(r))return true;let o=r.split(j.sep).slice(0,-1),n=t;for(let a of o){n=j.join(n,a);let i=await O__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)return false;if(i.isSymbolicLink()||!i.isDirectory())return true}return false}async function Hu(t){let e=j.join(t,".amazonq"),r=await O__default.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!r)return [e,j.join(e,"rules")];if(r.isSymbolicLink()||!r.isDirectory())return [];let o=j.join(e,"rules");return await O__default.lstat(o).catch(a=>{if(a.code==="ENOENT")return null;throw a})?[]:[o]}async function ks(t,e){let r=j.resolve(t),o=j.resolve(e);await tt(o);let n=[u(o,"project.json"),u(o,"adopt.json"),u(o,"adopt-readiness.json"),j.join(o,f$1),j.join(o,g$1),j.join(o,h$4),j.join(o,b$b),j.join(o,"AGENTS.md"),...g$2.map(a=>j.join(o,a)),j.join(o,".gitignore"),p(r,"imported-projects.json")];return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>{if(a.startsWith(`${o}${j.sep}`)&&await $l(o,a))return {path:a,contents:null,preserve:"unsafe-parent"};let i=await O__default.lstat(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});return i?.isSymbolicLink()?{path:a,contents:null,preserve:"symbolic-link"}:{path:a,contents:i?.isFile()?await O__default.readFile(a):null}})),createdAdapterDirectories:await Hu(o)}}function Nl(t,e,r){let o=[u(r,"project.json"),u(r,"adopt.json"),u(r,"adopt-readiness.json"),j.join(r,f$1),j.join(r,g$1),j.join(r,h$4),j.join(r,b$b),j.join(r,"AGENTS.md"),...g$2.map(a=>j.join(r,a)),j.join(r,".gitignore"),p(e,"imported-projects.json")].map(a=>j.resolve(a)),n=new Set([".amazonq",".amazonq/rules"].map(a=>j.resolve(r,a)));if(t.workspacePath!==j.resolve(e)||t.projectPath!==j.resolve(r)||t.files.length!==o.length||t.files.some((a,i)=>j.resolve(a.path)!==o[i])||t.createdAdapterDirectories.some(a=>!n.has(j.resolve(a)))||new Set(t.createdAdapterDirectories.map(a=>j.resolve(a))).size!==t.createdAdapterDirectories.length)throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function Bu(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,category:a$e(t.projectKind),project_type:a$e(t.projectKind),runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,framework:t.detection.key,kit:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function qu(t,e,r){await tt(e),Nl(r,t,e);let o=[];for(let n of r.files)try{if(n.preserve==="symbolic-link")continue;n.contents===null?await O__default.remove(n.path):(await O__default.ensureDir(j.dirname(n.path)),await O__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}for(let n of [...r.createdAdapterDirectories].reverse())try{if(await $l(e,n))continue;await O__default.rmdir(n);}catch(a){let i=a.code;i!=="ENOENT"&&i!=="ENOTEMPTY"&&o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function vs(t){let e=j.resolve(t.workspacePath),r=j.resolve(t.source),o=await O__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await tt(r),Vu(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(j$2(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t.rollbackSnapshot??await ks(e,r);Nl(n,e,r);let a=await Ku(r),i=Uu(a),c=j$4(r,i?null:a),d=i$4(r),l=[c.runtime,...d.filter(E=>E!==c.runtime)].filter((E,$,M)=>E!=="unknown"&&M.indexOf(E)===$);l.length===0&&l.push("unknown");let f=await b$a(r,a),u$1=Ju(t.name||(typeof a?.name=="string"?a.name:"")||j.basename(r))||"adopted-project",w=Nr({workspacePath:e,projectPath:r,projectName:u$1}),y=(t.now??new Date).toISOString(),P=u(r,"project.json"),S=u(r,"adopt.json"),p=u(r,"adopt-readiness.json"),v=Xo({existingProjectJson:a}),[m,h]=await Promise.all([cr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ir(e)]),g=St({profile:m,runtime:c.runtime,subjectLabel:u$1,mode:h}),k=Tt({profile:m,runtimes:await Mt(e,{additionalRuntimes:l}),mode:h}),b=g.ok?k:g;if(!b.ok&&h==="strict")throw new Error(b.message);let x=Bu({projectName:u$1,contractRelativePath:w.contractRelativePath,isExternal:w.isExternal,discoveredRelativePath:w.relativePath,detection:c,runtimeCandidates:l,existingProjectJson:a,refreshManagedDetection:i,projectKind:f,moduleSupport:v,adoptedAt:y}),C={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:y,managed_by:"workspai",mode:"linked",workspace:{name:j.basename(e),contract:i$1.workspaceContract},project:{name:u$1,relative_path:w.contractRelativePath,...w.isExternal?{}:{discovered_relative_path:w.relativePath},is_external:w.isExternal,kind:f,category:a$e(f),module_support:v},detection:{framework:c.key,framework_display_name:c.displayName,runtime:c.runtime,runtime_candidates:l,kind:f,category:a$e(f),confidence:c.confidence,support_tier:c.supportTier,import_stack:c.importStack,source:c.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:v,workspace_contract:"linked-project",profile_compatibility:{ok:b.ok,profile:b.profile,runtimes:b.runtimes,message:b.message,recommended_profile:b.recommendedProfile,recommended_command:b.recommendedCommand}}},R=Yo({projectName:u$1,relativePath:w.contractRelativePath,projectKind:f,source:"adopted-local",detection:c,moduleSupport:v,projectPath:r,generatedAt:new Date(y)});if(t.dryRun!==true)try{await tt(r),await O__default.ensureDir(j.dirname(P)),await O__default.writeJson(P,x,{spaces:2}),await O__default.writeJson(S,C,{spaces:2}),await O__default.writeJson(p,R,{spaces:2});let E={name:u$1,path:r,relativePath:w.contractRelativePath,relationship:"adopted",stack:c.importStack,runtime:c.runtime,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:v,confidence:c.confidence,source:"adopted-local",importedAt:y};await b$c(e,[E]);let{syncWorkspaceContract:$}=await import('./workspace-contract-3BWIRSVQ.js');await $({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:r,projectName:u$1,relationship:"adopted",mode:t.projectGrounding??"managed",now:new Date(y)});}catch(E){try{await qu(e,r,n);let{syncWorkspaceContract:$}=await import('./workspace-contract-3BWIRSVQ.js');await $({workspacePath:e,strict:true});}catch($){throw new AggregateError([E,$],`Adopt failed and rollback was incomplete: ${E instanceof Error?E.message:String(E)}`)}throw E}return {ingestionPlan:Nt({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t.projectGrounding??"managed"}),name:u$1,path:r,relativePath:w.relativePath,contractRelativePath:w.contractRelativePath,isExternal:w.isExternal,relationship:"adopted",stack:c.importStack,runtime:c.runtime,runtimeCandidates:l,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:v,confidence:c.confidence,projectJsonPath:P,adoptJsonPath:S,adoptReadinessPath:p,profileCompatibility:b,effects:Gu(t.projectGrounding??"managed"),wroteFiles:t.dryRun!==true}}async function zu(t){let e=await O__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=j.join(t,r),n=await O__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function Yu(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await O__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=j.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$f(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$6&&(await O__default.remove(i),e.push(j.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function Ml(t,e){if(await b$d(t,j.basename(t)),!(await g$3(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$h(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function Ps(t){let e=j.resolve(t.workspacePath);await zu(e);let r=Nt({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!j$2(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return rn(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$5(e);try{let n=await Ml(e,t.projectGrounding??"managed");return rn(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$5(e,o).catch(()=>{}),n}}async function js(t){if(t.dryRun){let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=j.resolve(o.outputPath),a=Tl(t,n);return rn(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?j.resolve(t.outputPath):void 0;if(e&&await O__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=j.resolve(o.outputPath);let n=Tl(t,r);if(!j$2(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await Yu(r);o.manifest?.portableContract&&await O__default.outputJson(j.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await Ml(r,t.projectGrounding??"managed");return rn(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,d,l)=>l.indexOf(c)===d),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$5(r).catch(()=>{}),await O__default.remove(r).catch(()=>{})),o}}function Tl(t,e){return Nt({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function rn(t,e){let r={schemaVersion:Bo,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$4(r,gl,"Workspace ingestion result"),r}function Wl(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function Dl(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function Ll(t){let e=t.trim(),r=e.startsWith("~/")?j.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!xt(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:xt(r)?r:j.resolve(r)};if(xt(r))return {kind:"git-project",source:r};let n=j.resolve(r);return j$2(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var em=Ho,tm=Ko;function Cs(t){if(!t||typeof t!="object")return null;let e=t.code;return e==="PYTHON_NOT_FOUND"||e==="BRIDGE_VENV_BOOTSTRAP_FAILED"||e==="BRIDGE_VENV_CREATE_FAILED"||e==="BRIDGE_PIP_BOOTSTRAP_FAILED"?e:null}function rm(t=process.argv){let e=j.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function lr(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function om(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Oe(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function nm(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Os(t){try{return nm(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function Us(t$1,e){let r=Oe(t$1,"--port")?.trim(),o=t$1[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Oe(t$1,"--output")||".",i=j.resolve(e,a,o),c=t(i,"project.json").find(l=>_.existsSync(l))??u(i,"project.json");if(!await O__default.pathExists(c))return;let d=await O__default.readJson(c);await O__default.writeJson(c,{...d,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Gl(t){let e=be(process.cwd()),r=t.trim().toLowerCase();if(!e||!r)return true;try{let[o,n]=await Promise.all([cr(e),ir(e)]),a=a$3(r),i=j$6(r),c=p$4(r),d=i?"node":c?.runtime??a?.runtime??"python",l=St({profile:o,runtime:d,subjectLabel:r,mode:n}),f=Tt({profile:o,runtimes:await Mt(e,{additionalRuntimes:[d]}),mode:n}),u=l.ok?f:l;if(u.ok)return true;let w=tn(u);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${u.message}`)),w&&console.log(s.gray(`\u{1F4A1} ${w}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${u.message}`)),w&&console.log(s.gray(`\u{1F4A1} ${w}`));}catch{}return true}function Hs(){return j$7()}function Jl(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(j.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(j.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$8()),t.RAPIDKIT_SKIP_LOCK_SYNC||(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t.POETRY_KEYRING_ENABLED||(t.POETRY_KEYRING_ENABLED="false"),t.PYTHON_KEYRING_BACKEND||(t.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),t.POETRY_NO_INTERACTION||(t.POETRY_NO_INTERACTION="1"),t}function sm(t){return m$3(j.join(t,".venv"))}async function am(t,e){return await Ce(t,["--version"],e)===0}async function Lt(t){let e=j.join(t,"go.mod");if(await O__default.pathExists(e))return "go";let r=j.join(t,"pom.xml"),o=j.join(t,"build.gradle"),n=j.join(t,"build.gradle.kts");if(await O__default.pathExists(r)||await O__default.pathExists(o)||await O__default.pathExists(n))return "java";if((await O__default.pathExists(t)?await _.promises.readdir(t,{withFileTypes:true}):[]).some(y=>y.isFile()&&y.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=j.join(t,"src");if(await O__default.pathExists(i)&&(await _.promises.readdir(i,{withFileTypes:true})).some(P=>P.isFile()&&P.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=j.join(t,"Cargo.toml");if(await O__default.pathExists(c))return "rust";let d=j.join(t,"composer.json");if(await O__default.pathExists(d))return "php";let l=j.join(t,"package.json");if(await O__default.pathExists(l))return "node";let f=j.join(t,"pyproject.toml"),u=j.join(t,"requirements.txt"),w=j.join(t,"poetry.lock");return await O__default.pathExists(f)||await O__default.pathExists(u)||await O__default.pathExists(w)?"python":null}async function im(t,e={}){let r=e.runCommand??Ce;for(let o of e.pythonCandidates??Hs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function np(t,e={}){let r=e.runCommand??Ce;for(let o of e.pythonCandidates??Hs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function cm(t,e={}){let r=e.runCommand??Ce,o=m$3(j.join(t,".venv"));if(!await O__default.pathExists(o)){let c=await np(t,e);if(c!==0)return c}if(!(await r("poetry",["--version"],t)===0))return 0;let a=await r("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await r("poetry",["env","use",o],t);return i!==0?i:0}async function lm(t,e={}){let r=e.runCommand??Ce,o=m$3(j.join(t,".venv"));if(!await O__default.pathExists(o)){let i=await np(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=j.join(t,"requirements.txt");if(await O__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=j.join(t,"pyproject.toml");return await O__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function Ss(t,e){return await cm(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await O__default.pathExists(j.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await lm(t))}async function xs(t){let e=await Dt("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await am(o,t))continue;if(await Ce(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function pm(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Oe([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Oe([...e],"--java-version"),a=Oe([...e],"--spring-boot-version"),i=Oe([...e],"--springdoc-version"),c=Oe([...e],"--group-id"),d=Oe([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(d&&!/^[A-Za-z0-9_.-]+$/.test(d.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Oe([...e],"--target-framework"),a=Oe([...e],"--root-namespace");if(n&&!/^net\d+\.\d+$/.test(n.trim()))return "Invalid --target-framework. Expected .NET target framework, e.g. net8.0";if(a&&!/^[A-Za-z0-9_.]+$/.test(a.trim()))return "Invalid --root-namespace. Use dot-separated .NET namespace identifiers only."}return null}async function Vl(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||Ds(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:o}=await import('./create-ZLDOBXG4.js');await o(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:r}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},{name:"Create it without workspace management",value:"none"}],default:1}]);if(r==="current"){let{registerWorkspaceAtPath:o}=await import('./create-ZLDOBXG4.js');await o(process.cwd(),{skipGit:e,yes:false,userConfig:await b()});}else r==="none"&&t.push("--no-workspace");}async function dm(t){await O__default.ensureDir(t);let e=j.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await _.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
155
- `),async()=>{await o.close().catch(()=>{}),await O__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await O__default.readJson(e).catch(()=>null),a=Number(n?.pid),i=false;if(Number.isInteger(a)&&a>0)try{process.kill(a,0),i=true;}catch(c){i=c.code==="EPERM";}if(!i){await O__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function sn(t,e={}){let r$1=j.join(q(),"transactions"),o=await dm(r$1),n;try{await b$8(r$1),n=await a$a({journalDirectory:r$1});}catch(i){throw await o(),i}let a=new Set([j.join(q(),"workspaces.json"),j.join(r(),"workspaces.json"),a$b(t,d$8),b$9(t,d$8),a$b(t,a$c),b$9(t,a$c),...s$1(t,"imported-projects.json")]);e.projectPath&&(a.add(u(e.projectPath,"project.json")),a.add(u(e.projectPath,"context.json")),a.add(u(e.projectPath,"file-hashes.json")),a.add(u(e.projectPath,"adopt.json")),a.add(u(e.projectPath,"adopt-readiness.json")),a.add(j.join(e.projectPath,f$1)),a.add(j.join(e.projectPath,g$1)),a.add(j.join(e.projectPath,h$4)),a.add(j.join(e.projectPath,"AGENTS.md")),a.add(j.join(e.projectPath,".gitignore")));try{for(let c of a)(e.projectPath&&c===j.join(e.projectPath,"AGENTS.md")?await O__default.lstat(c).catch(f=>{if(f.code==="ENOENT")return null;throw f}):null)?.isSymbolicLink()||await n.captureFile(c);e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let i=false;return {registerCompensation:c=>n.registerCompensation(c),commit:async()=>{i||(await n.commit(),i=true,await o());},rollback:async()=>{if(!i){i=true;try{await n.rollback();}finally{await o();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await o(),i}}async function pr(t,e){try{await t.rollback();}catch(r){throw new AggregateError([e,r],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function Gr(t,e$1,r){if(t.includes("--no-workspace")||t.includes("--dry-run"))return;if(!await O__default.pathExists(e$1)){e.warn(`Created project path was not found for workspace linking: ${e$1}`);return}let o=be(e$1)||be(process.cwd()),n=false,a;if(o)a=await sn(o,{projectPath:e$1});else {o=o$1(),a=await sn(o,{projectPath:e$1,ownedWorkspace:o});try{o=(await Bs()).workspacePath;}catch(c){await pr(a,c);}n=true;}let i="managed";try{await o$2(e$1);let c=j.relative(o,e$1);(c.startsWith("..")||j.isAbsolute(c))&&(i=(await vs({source:e$1,workspacePath:o,name:r})).relationship);let{registerProjectInWorkspaceStrict:l,registerWorkspaceStrict:f}=await import('./workspace-LQ77WAHC.js'),{syncWorkspaceContract:u}=await import('./workspace-contract-3BWIRSVQ.js');await f(o,j.basename(o)),await l(o,r,e$1),await u({workspacePath:o,strict:true});let{syncProjectIntelligenceLens:w}=await import('./project-intelligence-lens-RLYSPJB2.js');await w({workspacePath:o,projectPath:e$1,projectName:r,relationship:i==="adopted"?"adopted":"managed",mode:"managed"}),await a.commit(),await Jr(o);}catch(c){await pr(a,c);}return n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${i$3}" (${i}).`)),console.log(s.gray(` Registry: ${j.join(q(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${o}`))),o}async function $s(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],r=a$3(e),o=t[3];if(!r||r.owner!=="npm")return 1;if(!o)return process.stderr.write(`Usage: ${r.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
154
+ `,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=q,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${q}.`});}catch(q){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${q.message}`});}else if(m.target==="http")if(!m.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let q=Math.max(0,m.retries??0),Q=Math.max(0,m.backoffMs??500),L=gu(M,m.signing);L.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:L.error});try{let F=m.authTokenEnv?process.env[m.authTokenEnv]:void 0,K=false,te=null;for(let H=1;H<=q+1;H+=1)try{if(L.error)throw new Error(L.error);await uu(m.endpoint,M,U,F,L.headers),o.evidenceExported=true,o.evidenceExportTarget=m.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:H>1?`Transparency evidence exported to HTTP endpoint ${m.endpoint} after ${H} attempts.`:`Transparency evidence exported to HTTP endpoint ${m.endpoint}.`}),K=true;break}catch(pe){te=pe,H<=q&&await kl(Q*H);}if(!K)throw te||new Error("unknown evidence export error")}catch(F){let K=`Evidence HTTP export failed: ${F.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:K});try{let te=await mu(t,m.deadLetterPath,M,K);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${te}.`});}catch(te){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${te.message}`});}}}if(m.failOnError&&r.some(Q=>Q.status==="failed"&&(Q.id==="sigstore.evidence.export.file"||Q.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function Yo(t){let e=f$7(t.detection.runtime),r=u$1({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function wu(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function Xo(t){if(t.existingProjectJson?.module_support===true){let e=wu(t.existingProjectJson),r=e?a$3(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}function Sl(t){return t.replace(/\\/g,"/")}function ku(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function vu(t,e){let r=Sl(j.relative(t,e));return !r||r.startsWith("..")?true:r.split("/").filter(Boolean).some(o=>o==="..")}function Nr(t){let e=Sl(j.relative(t.workspacePath,t.projectPath)),r=vu(t.workspacePath,t.projectPath),o=ku(t.projectName,j.basename(t.projectPath)),n=r?`external/${o}`:e||o;return {relativePath:e||n,contractRelativePath:n,isExternal:r}}var xl=[a$G,b$k];function Pu(t,e){let r=j.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!j.isAbsolute(r)}async function tt(t){let e=await O__default.realpath(t);for(let r of xl){let o=j.join(t,r),n=await O__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await O__default.realpath(o);if(!Pu(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function El(t){let e=j.basename(t);return xl.includes(e)?(await O__default.lstat(t)).isSymbolicLink():false}var _l={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},Cu={python:"Python",node:"Node",go:"Go",java:"Java",dotnet:".NET",php:"PHP",ruby:"Ruby",rust:"Rust",elixir:"Elixir",clojure:"Clojure",scala:"Scala",kotlin:"Kotlin",deno:"Deno",bun:"Bun",c:"C",cpp:"C++",unknown:"Unknown"},Su={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},Rl=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function ys(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function ws(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function Tr(t){if(typeof t!="string")return "unknown";let e=t.trim().toLowerCase();return e==="python"||e==="node"||e==="go"||e==="java"||e==="dotnet"||e==="php"||e==="ruby"||e==="rust"||e==="elixir"||e==="clojure"||e==="scala"||e==="kotlin"||e==="deno"||e==="bun"||e==="c"||e==="cpp"?e:e==="c++"||e==="cplusplus"||e==="cc"||e==="clang++"||e==="g++"?"cpp":e==="clang"||e==="gcc"?"c":"unknown"}function en(t){let e=new Set;for(let r of t)e.add(Tr(r));return [...e].sort((r,o)=>Rl.indexOf(r)-Rl.indexOf(o))}function xu(t){let e=en(t).filter(r=>r!=="unknown");if(e.length!==0)return e.length===1?Su[e[0]]:"polyglot"}function Al(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function Eu(t,e){return t?"none":e==="strict"?"error":"warning"}function Mr(t){let e=t.ok?void 0:xu(t.runtimes)??"polyglot";return {ok:t.ok,checkId:t.checkId,status:t.ok?"passed":"failed",profile:t.profile,runtimes:t.runtimes,message:t.message,recommendedProfile:e,recommendedCommand:e?Al(e):void 0,ciRecommendedCommand:e?Al(e,{ci:true}):void 0,severity:Eu(t.ok,t.mode)}}function Tt(t){let e=ws(t.profile),r=en(t.runtimes),o=t.mode??"warn",n=_l[e];if(n){let a=r.length===0||r.every(i=>ys(i)===n);return Mr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:r,message:a?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${r.join(", ")}].`,mode:o})}if(e==="minimal"){let a=r.filter(d=>d!=="unknown"),c=new Set(a.map(d=>ys(d))).size<=1;return Mr({ok:c,checkId:"profile.minimal",profile:e,runtimes:r,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${a.join(", ")}].`,mode:o})}return Mr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:r,message:`${e} profile accepts the detected runtime mix.`,mode:o})}function St(t){let e=ws(t.profile),r=Tr(t.runtime),o=t.mode??"warn",n=_l[e];if(!n||r==="unknown")return Mr({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[r],message:r==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:o});let a=ys(r)===n;return Mr({ok:a,checkId:`profile.${e}`,profile:e,runtimes:a?[r]:en([n,r]),message:a?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${Cu[r]}, but workspace profile is "${e}".`,mode:o})}async function ir(t){let e=(await Promise.all(s$1(t,"policies.yml").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "warn";try{return (await O__default.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function cr(t){let e=(await Promise.all(s$1(t,"workspace.json").map(async r=>await O__default.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!e)return "minimal";try{let r=await O__default.readJson(e);return ws(r.profile)}catch{return "minimal"}}async function Mt(t$1,e={}){let r=new Set,o=[],n=new Set,a=[t$1];for(;a.length>0;){let i=a.pop();if(!i||n.has(i))continue;n.add(i);let c=[];try{c=await _.promises.readdir(i,{withFileTypes:true});}catch{continue}for(let d of c){if(!d.isDirectory()||d.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(d.name))continue;let l=j.join(i,d.name);if(l!==t$1&&j$2(l))continue;if((await Promise.all([...t(l,"context.json"),...t(l,"project.json")].map(async u=>O__default.pathExists(u)))).some(Boolean)){o.push(l);continue}a.push(l);}}for(let i of o){let c=i$2(i);r.add(Tr(j$4(i,c).runtime));}for(let i of await a$H(t$1))r.add(Tr(i.runtime));for(let i of e.additionalRuntimes??[])r.add(Tr(i));return en(r)}function tn(t,e={}){let r=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return r?`Recommended: ${r}`:null}function Il(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Au(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return Il(a)||"imported-project"}function xt(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function _u(t){return xt(t)?"git-url":"local-folder"}async function Iu(t,e){let r=Il(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=j.join(t,n);if(!await O__default.pathExists(a))return a;o+=1;}}function Ou(t,e){let r=j.resolve(t),o=j.resolve(e),n=j.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!j.isAbsolute(n)}function $u(t,e){if(Ou(t,e))throw new Error("Import source must be outside the current workspace root.")}function Nu(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function Tu(t){let e=j.basename(t);return !(await El(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||Nu(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Mu(t$1){await tt(t$1);for(let e of t(t$1,"project.json"))if(await O__default.pathExists(e))try{return await O__default.readJson(e)}catch{return null}return null}async function Wu(t){await tt(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:j.basename(t.projectPath),o=Nr({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=u(t.projectPath,"project.json"),i=u(t.projectPath,"import.json"),c=u(t.projectPath,"import-readiness.json"),d=Xo({existingProjectJson:t.existingProjectJson}),l=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],f=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},u$1={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:j.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:j.basename(t.projectPath),kind:t.projectKind,category:a$e(t.projectKind),project_type:a$e(t.projectKind),runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:d,modules:l,contracts:f,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},w={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:j.basename(t.projectPath)},project:{name:u$1.name,slug:u$1.slug,relative_path:n,kind:t.projectKind,category:a$e(t.projectKind),module_support:d},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$e(t.projectKind),confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:d,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},y=Yo({projectName:String(u$1.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:d,projectPath:t.projectPath,generatedAt:new Date(e)});return await O__default.ensureDir(j.dirname(a)),await O__default.writeJson(a,u$1,{spaces:2}),await O__default.writeJson(i,w,{spaces:2}),await O__default.writeJson(c,y,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:d}}async function Du(t,e){let r={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,relationship:"imported",importedAt:new Date().toISOString()};await b$c(t,[r]);}async function Lu(t){await O__default.pathExists(t)&&(await tt(t),await O__default.remove(t));}async function Fu(t,e){await Lu(e),await c$4(t,[e]);}async function Ol(t){let e=j.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??_u(r),n=t.name??(o==="git-url"?Au(r):j.basename(r)),a=await Iu(e,n),i=false;try{if(o==="local-folder"){let h=j.resolve(r),g=await O__default.stat(h).catch(()=>null);if(!g||!g.isDirectory())throw new Error("Import source is not a directory.");if(await tt(h),j$2(h))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");$u(e,h),i=true,await O__default.copy(h,a,{overwrite:false,errorOnExist:true,filter:Tu});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$d()});await tt(a);let c=await Mu(a),d=j$4(a,c),l=await b$a(a,c),[f,u]=await Promise.all([cr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ir(e)]),w=St({profile:f,runtime:d.runtime,subjectLabel:j.basename(a),mode:u}),y=Tt({profile:f,runtimes:await Mt(e,{additionalRuntimes:[d.runtime]}),mode:u}),P=w.ok?y:w;if(!P.ok&&u==="strict")throw new Error(P.message);let S=await Wu({workspacePath:e,projectPath:a,sourceType:o,detection:d,existingProjectJson:c,projectKind:l,profileCompatibility:P}),p=Nr({workspacePath:e,projectPath:a,projectName:j.basename(a)}),v={ingestionPlan:Nt({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:j.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:j.basename(a),path:a,relativePath:p.contractRelativePath,stack:d.importStack,runtime:d.runtime,framework:d.key,frameworkDisplayName:d.displayName,supportTier:d.supportTier,moduleSupport:S.moduleSupport,confidence:d.confidence,source:o,projectJsonPath:S.projectJsonPath,importJsonPath:S.importJsonPath,importReadinessPath:S.importReadinessPath,profileCompatibility:P};await Du(e,v);let{syncWorkspaceContract:m}=await import('./workspace-contract-3BWIRSVQ.js');return await m({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:v.path,projectName:v.name,relationship:"imported",mode:t.projectGrounding??"managed"}),v}catch(c){if(i)try{await Fu(e,a);let{syncWorkspaceContract:d}=await import('./workspace-contract-3BWIRSVQ.js');await d({workspacePath:e,strict:true});}catch(d){let l=c instanceof Error?c.message:String(c),f=d instanceof Error?d.message:String(d);throw new Error(`Import failed: ${l}. Rollback also failed: ${f}`)}throw c}}function Gu(t){return {schemaVersion:qo,sourceMode:"linked",sourceCodeModified:false,projectMetadataFiles:[".workspai/project.json",".workspai/adopt.json",".workspai/adopt-readiness.json",f$1,...t==="off"?[]:[h$4,g$1,b$b]],repositoryControlFiles:[{path:".gitignore",action:"reconcile",condition:"machine-local workspace binding and project-grounding portability rules"},...t==="managed"?[{path:"AGENTS.md",action:"reconcile",condition:"managed grounding is enabled and the path is a regular file; authored deletions and symbolic links are preserved"},...g$2.map(e=>({path:e,action:"reconcile",condition:"managed provider adapter is enabled; authored content, deletions, symbolic links, and unsafe parent paths are preserved"}))]:[]],workspaceOperations:["register-project","sync-contract","rebuild-model","rebuild-graph","sync-agent-grounding"]}}function Ju(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Vu(t,e){return j.resolve(t)===j.resolve(e)}async function Ku(t$1){await tt(t$1);for(let e of t(t$1,"project.json")){if(!await O__default.pathExists(e))continue;let r;try{r=JSON.parse((await O__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}function Uu(t){if(!t?.adoption||typeof t.adoption!="object")return false;let e=t.adoption;return e.managed_by==="workspai"&&e.mode==="linked"}async function $l(t,e){let r=j.relative(t,e);if(r.startsWith("..")||j.isAbsolute(r))return true;let o=r.split(j.sep).slice(0,-1),n=t;for(let a of o){n=j.join(n,a);let i=await O__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)return false;if(i.isSymbolicLink()||!i.isDirectory())return true}return false}async function Hu(t){let e=j.join(t,".amazonq"),r=await O__default.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!r)return [e,j.join(e,"rules")];if(r.isSymbolicLink()||!r.isDirectory())return [];let o=j.join(e,"rules");return await O__default.lstat(o).catch(a=>{if(a.code==="ENOENT")return null;throw a})?[]:[o]}async function ks(t,e){let r=j.resolve(t),o=j.resolve(e);await tt(o);let n=[u(o,"project.json"),u(o,"adopt.json"),u(o,"adopt-readiness.json"),j.join(o,f$1),j.join(o,g$1),j.join(o,h$4),j.join(o,b$b),j.join(o,"AGENTS.md"),...g$2.map(a=>j.join(o,a)),j.join(o,".gitignore"),p(r,"imported-projects.json")];return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>{if(a.startsWith(`${o}${j.sep}`)&&await $l(o,a))return {path:a,contents:null,preserve:"unsafe-parent"};let i=await O__default.lstat(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});return i?.isSymbolicLink()?{path:a,contents:null,preserve:"symbolic-link"}:{path:a,contents:i?.isFile()?await O__default.readFile(a):null}})),createdAdapterDirectories:await Hu(o)}}function Nl(t,e,r){let o=[u(r,"project.json"),u(r,"adopt.json"),u(r,"adopt-readiness.json"),j.join(r,f$1),j.join(r,g$1),j.join(r,h$4),j.join(r,b$b),j.join(r,"AGENTS.md"),...g$2.map(a=>j.join(r,a)),j.join(r,".gitignore"),p(e,"imported-projects.json")].map(a=>j.resolve(a)),n=new Set([".amazonq",".amazonq/rules"].map(a=>j.resolve(r,a)));if(t.workspacePath!==j.resolve(e)||t.projectPath!==j.resolve(r)||t.files.length!==o.length||t.files.some((a,i)=>j.resolve(a.path)!==o[i])||t.createdAdapterDirectories.some(a=>!n.has(j.resolve(a)))||new Set(t.createdAdapterDirectories.map(a=>j.resolve(a))).size!==t.createdAdapterDirectories.length)throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function Bu(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,category:a$e(t.projectKind),project_type:a$e(t.projectKind),runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,framework:t.detection.key,kit:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function qu(t,e,r){await tt(e),Nl(r,t,e);let o=[];for(let n of r.files)try{if(n.preserve==="symbolic-link")continue;n.contents===null?await O__default.remove(n.path):(await O__default.ensureDir(j.dirname(n.path)),await O__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}for(let n of [...r.createdAdapterDirectories].reverse())try{if(await $l(e,n))continue;await O__default.rmdir(n);}catch(a){let i=a.code;i!=="ENOENT"&&i!=="ENOTEMPTY"&&o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function vs(t){let e=j.resolve(t.workspacePath),r=j.resolve(t.source),o=await O__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await tt(r),Vu(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(j$2(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t.rollbackSnapshot??await ks(e,r);Nl(n,e,r);let a=await Ku(r),i=Uu(a),c=j$4(r,i?null:a),d=i$4(r),l=[c.runtime,...d.filter(E=>E!==c.runtime)].filter((E,$,M)=>E!=="unknown"&&M.indexOf(E)===$);l.length===0&&l.push("unknown");let f=await b$a(r,a),u$1=Ju(t.name||(typeof a?.name=="string"?a.name:"")||j.basename(r))||"adopted-project",w=Nr({workspacePath:e,projectPath:r,projectName:u$1}),y=(t.now??new Date).toISOString(),P=u(r,"project.json"),S=u(r,"adopt.json"),p=u(r,"adopt-readiness.json"),v=Xo({existingProjectJson:a}),[m,h]=await Promise.all([cr(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):ir(e)]),g=St({profile:m,runtime:c.runtime,subjectLabel:u$1,mode:h}),k=Tt({profile:m,runtimes:await Mt(e,{additionalRuntimes:l}),mode:h}),b=g.ok?k:g;if(!b.ok&&h==="strict")throw new Error(b.message);let x=Bu({projectName:u$1,contractRelativePath:w.contractRelativePath,isExternal:w.isExternal,discoveredRelativePath:w.relativePath,detection:c,runtimeCandidates:l,existingProjectJson:a,refreshManagedDetection:i,projectKind:f,moduleSupport:v,adoptedAt:y}),C={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:y,managed_by:"workspai",mode:"linked",workspace:{name:j.basename(e),contract:i$1.workspaceContract},project:{name:u$1,relative_path:w.contractRelativePath,...w.isExternal?{}:{discovered_relative_path:w.relativePath},is_external:w.isExternal,kind:f,category:a$e(f),module_support:v},detection:{framework:c.key,framework_display_name:c.displayName,runtime:c.runtime,runtime_candidates:l,kind:f,category:a$e(f),confidence:c.confidence,support_tier:c.supportTier,import_stack:c.importStack,source:c.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:v,workspace_contract:"linked-project",profile_compatibility:{ok:b.ok,profile:b.profile,runtimes:b.runtimes,message:b.message,recommended_profile:b.recommendedProfile,recommended_command:b.recommendedCommand}}},R=Yo({projectName:u$1,relativePath:w.contractRelativePath,projectKind:f,source:"adopted-local",detection:c,moduleSupport:v,projectPath:r,generatedAt:new Date(y)});if(t.dryRun!==true)try{await tt(r),await O__default.ensureDir(j.dirname(P)),await O__default.writeJson(P,x,{spaces:2}),await O__default.writeJson(S,C,{spaces:2}),await O__default.writeJson(p,R,{spaces:2});let E={name:u$1,path:r,relativePath:w.contractRelativePath,relationship:"adopted",stack:c.importStack,runtime:c.runtime,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:v,confidence:c.confidence,source:"adopted-local",importedAt:y};await b$c(e,[E]);let{syncWorkspaceContract:$}=await import('./workspace-contract-3BWIRSVQ.js');await $({workspacePath:e,strict:true}),await f$3({workspacePath:e,projectPath:r,projectName:u$1,relationship:"adopted",mode:t.projectGrounding??"managed",now:new Date(y)});}catch(E){try{await qu(e,r,n);let{syncWorkspaceContract:$}=await import('./workspace-contract-3BWIRSVQ.js');await $({workspacePath:e,strict:true});}catch($){throw new AggregateError([E,$],`Adopt failed and rollback was incomplete: ${E instanceof Error?E.message:String(E)}`)}throw E}return {ingestionPlan:Nt({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t.projectGrounding??"managed"}),name:u$1,path:r,relativePath:w.relativePath,contractRelativePath:w.contractRelativePath,isExternal:w.isExternal,relationship:"adopted",stack:c.importStack,runtime:c.runtime,runtimeCandidates:l,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:v,confidence:c.confidence,projectJsonPath:P,adoptJsonPath:S,adoptReadinessPath:p,profileCompatibility:b,effects:Gu(t.projectGrounding??"managed"),wroteFiles:t.dryRun!==true}}async function zu(t){let e=await O__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=j.join(t,r),n=await O__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function Yu(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await O__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=j.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$f(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$6&&(await O__default.remove(i),e.push(j.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function Ml(t,e){if(await b$d(t,j.basename(t)),!(await g$3(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$h(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function Ps(t){let e=j.resolve(t.workspacePath);await zu(e);let r=Nt({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!j$2(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return rn(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$5(e);try{let n=await Ml(e,t.projectGrounding??"managed");return rn(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$5(e,o).catch(()=>{}),n}}async function js(t){if(t.dryRun){let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=j.resolve(o.outputPath),a=Tl(t,n);return rn(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?j.resolve(t.outputPath):void 0;if(e&&await O__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=j.resolve(o.outputPath);let n=Tl(t,r);if(!j$2(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await Yu(r);o.manifest?.portableContract&&await O__default.outputJson(j.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await Ml(r,t.projectGrounding??"managed");return rn(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,d,l)=>l.indexOf(c)===d),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$5(r).catch(()=>{}),await O__default.remove(r).catch(()=>{})),o}}function Tl(t,e){return Nt({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function rn(t,e){let r={schemaVersion:Bo,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$4(r,gl,"Workspace ingestion result"),r}function Wl(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function Dl(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function Ll(t){let e=t.trim(),r=e.startsWith("~/")?j.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!xt(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:xt(r)?r:j.resolve(r)};if(xt(r))return {kind:"git-project",source:r};let n=j.resolve(r);return j$2(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var em=Ho,tm=Ko;function Cs(t){if(!t||typeof t!="object")return null;let e=t.code;return e==="PYTHON_NOT_FOUND"||e==="BRIDGE_VENV_BOOTSTRAP_FAILED"||e==="BRIDGE_VENV_CREATE_FAILED"||e==="BRIDGE_PIP_BOOTSTRAP_FAILED"?e:null}function rm(t=process.argv){let e=j.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function lr(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function om(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Oe(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function nm(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Os(t){try{return nm(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function Us(t$1,e){let r=Oe(t$1,"--port")?.trim(),o=t$1[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Oe(t$1,"--output")||".",i=j.resolve(e,a,o),c=t(i,"project.json").find(l=>_.existsSync(l))??u(i,"project.json");if(!await O__default.pathExists(c))return;let d=await O__default.readJson(c);await O__default.writeJson(c,{...d,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Gl(t){let e=be(process.cwd()),r=t.trim().toLowerCase();if(!e||!r)return true;try{let[o,n]=await Promise.all([cr(e),ir(e)]),a=a$3(r),i=j$6(r),c=p$4(r),d=i?"node":c?.runtime??a?.runtime??"python",l=St({profile:o,runtime:d,subjectLabel:r,mode:n}),f=Tt({profile:o,runtimes:await Mt(e,{additionalRuntimes:[d]}),mode:n}),u=l.ok?f:l;if(u.ok)return true;let w=tn(u);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${u.message}`)),w&&console.log(s.gray(`\u{1F4A1} ${w}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${u.message}`)),w&&console.log(s.gray(`\u{1F4A1} ${w}`));}catch{}return true}function Hs(){return j$7()}function Jl(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(j.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(j.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$8()),t.RAPIDKIT_SKIP_LOCK_SYNC||(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t.POETRY_KEYRING_ENABLED||(t.POETRY_KEYRING_ENABLED="false"),t.PYTHON_KEYRING_BACKEND||(t.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),t.POETRY_NO_INTERACTION||(t.POETRY_NO_INTERACTION="1"),t}function sm(t){return m$3(j.join(t,".venv"))}async function am(t,e){return await Ce(t,["--version"],e)===0}async function Lt(t){let e=j.join(t,"go.mod");if(await O__default.pathExists(e))return "go";let r=j.join(t,"pom.xml"),o=j.join(t,"build.gradle"),n=j.join(t,"build.gradle.kts");if(await O__default.pathExists(r)||await O__default.pathExists(o)||await O__default.pathExists(n))return "java";if((await O__default.pathExists(t)?await _.promises.readdir(t,{withFileTypes:true}):[]).some(y=>y.isFile()&&y.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=j.join(t,"src");if(await O__default.pathExists(i)&&(await _.promises.readdir(i,{withFileTypes:true})).some(P=>P.isFile()&&P.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=j.join(t,"Cargo.toml");if(await O__default.pathExists(c))return "rust";let d=j.join(t,"composer.json");if(await O__default.pathExists(d))return "php";let l=j.join(t,"package.json");if(await O__default.pathExists(l))return "node";let f=j.join(t,"pyproject.toml"),u=j.join(t,"requirements.txt"),w=j.join(t,"poetry.lock");return await O__default.pathExists(f)||await O__default.pathExists(u)||await O__default.pathExists(w)?"python":null}async function im(t,e={}){let r=e.runCommand??Ce;for(let o of e.pythonCandidates??Hs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function np(t,e={}){let r=e.runCommand??Ce;for(let o of e.pythonCandidates??Hs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function cm(t,e={}){let r=e.runCommand??Ce,o=m$3(j.join(t,".venv"));if(!await O__default.pathExists(o)){let c=await np(t,e);if(c!==0)return c}if(!(await r("poetry",["--version"],t)===0))return 0;let a=await r("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await r("poetry",["env","use",o],t);return i!==0?i:0}async function lm(t,e={}){let r=e.runCommand??Ce,o=m$3(j.join(t,".venv"));if(!await O__default.pathExists(o)){let i=await np(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=j.join(t,"requirements.txt");if(await O__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=j.join(t,"pyproject.toml");return await O__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function Ss(t,e){return await cm(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await O__default.pathExists(j.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await lm(t))}async function xs(t){let e=await Dt("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await am(o,t))continue;if(await Ce(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function pm(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Oe([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Oe([...e],"--java-version"),a=Oe([...e],"--spring-boot-version"),i=Oe([...e],"--springdoc-version"),c=Oe([...e],"--group-id"),d=Oe([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(d&&!/^[A-Za-z0-9_.-]+$/.test(d.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Oe([...e],"--target-framework"),a=Oe([...e],"--root-namespace");if(n&&!/^net\d+\.\d+$/.test(n.trim()))return "Invalid --target-framework. Expected .NET target framework, e.g. net8.0";if(a&&!/^[A-Za-z0-9_.]+$/.test(a.trim()))return "Invalid --root-namespace. Use dot-separated .NET namespace identifiers only."}return null}async function Vl(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||Ds(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:o}=await import('./create-TPUFKW6B.js');await o(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:r}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},{name:"Create it without workspace management",value:"none"}],default:1}]);if(r==="current"){let{registerWorkspaceAtPath:o}=await import('./create-TPUFKW6B.js');await o(process.cwd(),{skipGit:e,yes:false,userConfig:await b()});}else r==="none"&&t.push("--no-workspace");}async function dm(t){await O__default.ensureDir(t);let e=j.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await _.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
155
+ `),async()=>{await o.close().catch(()=>{}),await O__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await O__default.readJson(e).catch(()=>null),a=Number(n?.pid),i=false;if(Number.isInteger(a)&&a>0)try{process.kill(a,0),i=true;}catch(c){i=c.code==="EPERM";}if(!i){await O__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function sn(t,e={}){let r$1=j.join(q(),"transactions"),o=await dm(r$1),n;try{await b$8(r$1),n=await a$a({journalDirectory:r$1});}catch(i){throw await o(),i}let a=new Set([j.join(q(),"workspaces.json"),j.join(r(),"workspaces.json"),a$b(t,d$8),b$9(t,d$8),a$b(t,a$c),b$9(t,a$c),...s$1(t,"imported-projects.json")]);e.projectPath&&(a.add(u(e.projectPath,"project.json")),a.add(u(e.projectPath,"context.json")),a.add(u(e.projectPath,"file-hashes.json")),a.add(u(e.projectPath,"adopt.json")),a.add(u(e.projectPath,"adopt-readiness.json")),a.add(j.join(e.projectPath,f$1)),a.add(j.join(e.projectPath,g$1)),a.add(j.join(e.projectPath,h$4)),a.add(j.join(e.projectPath,"AGENTS.md")),a.add(j.join(e.projectPath,".gitignore")));try{for(let c of a)(e.projectPath&&c===j.join(e.projectPath,"AGENTS.md")?await O__default.lstat(c).catch(f=>{if(f.code==="ENOENT")return null;throw f}):null)?.isSymbolicLink()||await n.captureFile(c);e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let i=false;return {registerCompensation:c=>n.registerCompensation(c),commit:async()=>{i||(await n.commit(),i=true,await o());},rollback:async()=>{if(!i){i=true;try{await n.rollback();}finally{await o();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await o(),i}}async function pr(t,e){try{await t.rollback();}catch(r){throw new AggregateError([e,r],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function Gr(t,e$1,r){if(t.includes("--no-workspace")||t.includes("--dry-run"))return;if(!await O__default.pathExists(e$1)){e.warn(`Created project path was not found for workspace linking: ${e$1}`);return}let o=be(e$1)||be(process.cwd()),n=false,a;if(o)a=await sn(o,{projectPath:e$1});else {o=o$1(),a=await sn(o,{projectPath:e$1,ownedWorkspace:o});try{o=(await Bs()).workspacePath;}catch(c){await pr(a,c);}n=true;}let i="managed";try{await o$2(e$1);let c=j.relative(o,e$1);(c.startsWith("..")||j.isAbsolute(c))&&(i=(await vs({source:e$1,workspacePath:o,name:r})).relationship);let{registerProjectInWorkspaceStrict:l,registerWorkspaceStrict:f}=await import('./workspace-J4OGSSNO.js'),{syncWorkspaceContract:u}=await import('./workspace-contract-3BWIRSVQ.js');await f(o,j.basename(o)),await l(o,r,e$1),await u({workspacePath:o,strict:true});let{syncProjectIntelligenceLens:w}=await import('./project-intelligence-lens-BA6JLXQH.js');await w({workspacePath:o,projectPath:e$1,projectName:r,relationship:i==="adopted"?"adopted":"managed",mode:"managed"}),await a.commit(),await Jr(o);}catch(c){await pr(a,c);}return n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${i$3}" (${i}).`)),console.log(s.gray(` Registry: ${j.join(q(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${o}`))),o}async function $s(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],r=a$3(e),o=t[3];if(!r||r.owner!=="npm")return 1;if(!o)return process.stderr.write(`Usage: ${r.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
156
156
  `),1;try{h$1(o);}catch(u){let w=u instanceof Error?u.message:String(u);return process.stderr.write(`${w}
157
157
  `),1}let n=pm(r.id,t);if(n)return process.stderr.write(`${n}
158
158
  `),1;let a=Oe(t,"--output")||process.cwd(),i=j.resolve(a,o),c=t.includes("--skip-git")||t.includes("--no-git"),d=t.includes("--skip-install"),l=t.includes("--dry-run"),f=false;try{let{default:u}=await import('fs-extra');return await u.pathExists(i)?(process.stderr.write(`\u274C Directory "${i}" already exists
@@ -266,12 +266,12 @@ Run:
266
266
  `),1;try{h$1(y);}catch(g){if(g instanceof a$1)return process.stderr.write(`${g.message}
267
267
  `),1;throw g}let P=await j$1(t,{hasYes:n}),S=h$2(y.trim(),{argv:t,outputParent:P});c||await O__default.ensureDir(j.dirname(S));let p=m(y.trim());if(!c&&(i(p,S,{outputParent:P})&&p&&await O__default.pathExists(p)||await O__default.pathExists(S)))return process.stderr.write(`\u274C Workspace "${y}" already exists
268
268
  `),p&&p!==S&&process.stderr.write(` Found at: ${p}
269
- `),1;let v=await b(),m$1=v.author||process.env.USER||"Workspai User";if(!n){let g=await b$1([{type:"input",name:"author",message:"Author name:",default:m$1}]);g.author?.trim()&&(m$1=g.author.trim());}let{createProject:h}=await import('./create-ZLDOBXG4.js');return await h(y,{skipGit:a$2,skipPythonEngine:i$1,yes:n,dryRun:c,userConfig:{...v,author:m$1},installMethod:f,profile:w,parentDirectory:j.dirname(S)}),0}catch(n){return process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
269
+ `),1;let v=await b(),m$1=v.author||process.env.USER||"Workspai User";if(!n){let g=await b$1([{type:"input",name:"author",message:"Author name:",default:m$1}]);g.author?.trim()&&(m$1=g.author.trim());}let{createProject:h}=await import('./create-TPUFKW6B.js');return await h(y,{skipGit:a$2,skipPythonEngine:i$1,yes:n,dryRun:c,userConfig:{...v,author:m$1},installMethod:f,profile:w,parentDirectory:j.dirname(S)}),0}catch(n){return process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
270
270
  `),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return Hl(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitChoice:y}=await b$1([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$F()}]);if(d$1(y)||k$2(y)||q$1(y)){let p=gs(y),{projectName:v}=await b$1([{type:"input",name:"projectName",message:"Project name:",default:p,validate:k=>k.trim().length>0||"Project name is required"}]),m=t.slice(2).filter(k=>k.startsWith("-")),h=["create","project",y,v.trim(),...m];return await Gl(y)?(await Vl(h),k$2(y)?await Kl(h):q$1(y)?await Ul(h):await $s(h)):1}let P=gs(y),{projectName:S}=await b$1([{type:"input",name:"projectName",message:"Project name:",default:P,validate:p=>p.trim().length>0||"Project name is required"}]);t.splice(2,0,y,S.trim());}let a$1=t[2],i=c$d({kitId:a$1,framework:a$1,runtime:a$1});if(d$b(i))return um(i),1;if(!await Gl(t[2]||""))return 1;if(await Vl(t),d$1(t[2]))return await $s(t);if(k$2(t[2]))return await Kl(t);if(q$1(t[2]))return await Ul(t);if(t.includes("--skip-python-engine")||t.includes("--no-python-engine"))return process.stderr.write("`--skip-python-engine` is a workspace creation option. For projects, use `--skip-install` to scaffold first, then run `npx workspai init` when ready.\n"),1;if(t.includes("--dry-run"))return fm(t),0;let d=[...t.filter(y=>{let P=y.split("=")[0];return !o.has(y)&&!o.has(P)})],l=be(process.cwd()),w=t.includes("--skip-install")||!!l?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$c();let y=await e$1(d,{cwd:process.cwd(),env:w});if(y===0&&l&&!t.includes("--skip-install")&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init"))),y===0){await Us(t,process.cwd());let P=t[3],S=Oe(t,"--output")||process.cwd(),p=P?j.resolve(S,P):void 0,v=P&&p?await Gr(t,p,P).catch(async m=>{throw await O__default.remove(p).catch(()=>{}),m}):l;if(v)try{if(P&&p){let m=j.join(v,".python-version"),h=j.join(p,".python-version");if(_.existsSync(m)&&_.existsSync(p)){let g=_.readFileSync(m,"utf-8");_.writeFileSync(h,g.trim()+`
271
271
  `),e.debug(`Synced Python version ${g.trim()} from workspace to ${P}`);}}}catch(m){e.debug("Could not sync Python version from workspace:",m);}}return y}catch(y){let P=Cs(y);return P?await on(t,P):(process.stderr.write(`Workspai failed to run the Python core engine: ${y?.message??y}
272
- `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$c();let n=await e$1(t,{cwd:process.cwd()});if(n===0){let a=be(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-LQ77WAHC.js');await i(a,true);}}return n}catch(n){let a=Cs(n);return a?await on(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
272
+ `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$c();let n=await e$1(t,{cwd:process.cwd()});if(n===0){let a=be(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-J4OGSSNO.js');await i(a,true);}}return n}catch(n){let a=Cs(n);return a?await on(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
273
273
  `),1)}return await d$c(),await e$1(t,{cwd:process.cwd()})}catch(n){let a=Cs(n);return a?await on(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
274
- `),1)}}var Bl=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],hm=[...l$2,"autopilot","pipeline","import","adopt","snapshot","ai","config","product","infra","shell","commands"],ym=["init"],wm=q$2,ql=[...wm,...r$1];function km(t){return !!t&&tm.includes(t)}function Ts(t){let e=t[0],r=t[1];return e==="project"&&(r==="--help"||r==="-h"||r==="help")?true:em.some(([o,n])=>e!==o?false:r?r===n:true)}function Fr(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?Ts(t):km(t[0])||Ts(t)}function vm(t){return !!t&&hm.includes(t)}function zl(t){return vm(t[0])||Ts(t)}function Yl(t){return !!t&&ls.includes(t)}async function Xl(t,e){switch(t){case "bootstrap":return Wm(e);case "setup":return Dm(e);case "cache":return Fm(e);case "mirror":return Jm(e);default:{let r=t;throw new Error(`Unreachable npm-only manual command: ${String(r)}`)}}}function Pm(t=process.env){let e=t.npm_config_user_agent||"",r=t.npm_execpath||"",o=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(r)||o==="exec"||o==="x"}function sp(t={}){let e=w(process.cwd());if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai project command capabilities")),console.log(s.gray(`Project: ${e.projectRoot??"not detected"}`)),console.log(s.gray(`Runtime: ${e.runtime} (${e.runtimeSupportTier}) | Framework: ${e.frameworkDisplayName} (${e.frameworkSupportTier}) | Module support: ${e.moduleSupport?"yes":"no"}`)),console.log(s.gray(`Doctor support: ${e.runtimeDoctorSupport}`)),console.log(""),console.log(s.green(`Supported: ${e.supportedCommands.join(", ")||"none"}`)),console.log(s.yellow(`Global: ${e.globalCommands.join(", ")||"none"}`)),console.log(s.red(`Unsupported: ${e.unsupportedCommands.join(", ")||"none"}`));}function jm(){return {schemaVersion:fl,cli:"workspai",version:h(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:ms,contracts:$r(),contractCatalog:zo()}}function ap(){let t=nl(fe),e=[...t.topLevelCommands],r=[...a$5].filter(i=>!e.includes(i)),o=["init","dev","start","build","test","lint","format","help"],n=[...Ir],a=[...Vo];return {schemaVersion:ms,scope:"global",cli:"workspai",version:h(),cwd:process.cwd(),contracts:$r(),contractCatalog:zo(),commands:{npmOwned:e,coreBacked:r,projectScoped:o},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...r.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...o.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function bm(t={}){let e=ap();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(sl(e.runtimeInventory.integrity));console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai command capabilities")),console.log(s.gray(`CLI: ${e.cli} v${e.version}`)),console.log(""),console.log(s.green(`npm wrapper: ${e.commands.npmOwned.join(", ")}`)),console.log(s.cyan(`Python core: ${e.commands.coreBacked.join(", ")}`)),console.log(s.yellow(`Project runtime: ${e.commands.projectScoped.join(", ")}`)),console.log(s.magenta(`Workspace intelligence: ${e.workspace.intelligenceSubcommands.join(", ")}`)),console.log(""),console.log(s.gray("Tip: run `workspai project commands --json` inside a project."));}function Ms(t){return y(t)?(sp({json:t.includes("--json")||t.includes("--ci")}),true):false}function Ws(t){let e=w(process.cwd());if(!e.projectRoot)return false;let r=x(t,process.cwd());if(!r||r.status!=="unsupported")return false;console.error(s.red(z(r,e))),process.exit(1);}function qe(t){return _.existsSync(j.join(t,".workspai-workspace"))||_.existsSync(j.join(t,".workspai","workspace.json"))||_.existsSync(j.join(t,".rapidkit-workspace"))||_.existsSync(j.join(t,".rapidkit","workspace.json"))}function ip(t$1){let e=t$1;for(;;){let r=t(e,"context.json").find(n=>_.existsSync(n));if(r)return r;let o=j.dirname(e);if(o===e)break;e=o;}return null}function Ds(t){let e=t,r=j.resolve(tmpdir());for(;;){let o=[j.join(e,".workspai-workspace"),j.join(e,".rapidkit-workspace")].find(a=>_.existsSync(a));if(o&&j.resolve(e)!==r)return o;let n=j.dirname(e);if(n===e)break;e=n;}return null}function be(t){let e=b$5({startPath:t});return !e||j.resolve(e.workspacePath)===j.resolve(tmpdir())?null:e.workspacePath}function cp(t){try{let r=b$5({startPath:t,strict:true})?.workspacePath??null;return {workspacePath:r&&j.resolve(r)!==j.resolve(tmpdir())?r:null,error:null}}catch(e){if(e instanceof a$2&&e.code==="project.workspace.unlinked")return {workspacePath:null,error:null};if(e instanceof a$2)return {workspacePath:null,error:e};throw e}}async function Jr(t,e){try{let{syncWorkspaceConsumerArtifacts:r}=await import('./workspace-onboarding-46BE3EQD.js');await r(t,{silent:e?.silent});}catch(r){e?.silent||(console.log(s.yellow(`\u26A0\uFE0F Workspace consumer sync skipped: ${r.message}`)),console.log(s.gray(" Retry: npx workspai workspace agent-sync --write --refresh-context --preset enterprise")));}}async function Cm(t,e=process.cwd(),r=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$3(r))return {detected:false};let n=p$1(e,r);for(let a of n){if(!await O__default.pathExists(a))continue;let i=a.toLowerCase();if(i.endsWith("rapidkit.cmd")||i.endsWith("rapidkit.exe"))return {detected:true,candidatePath:a,reason:"Found workspace-local rapidkit launcher on Windows."}}return {detected:false}}function Sm(t){let e=t;for(;;){let r=j.join(e,".rapidkit-workspace"),o=j.join(e,".rapidkit","workspace.json");if(!_.existsSync(r)&&_.existsSync(o))return e;let n=j.dirname(e);if(n===e)break;e=n;}return null}var lp={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function xm(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Dr(t,e){let r=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return r?r[1]==="true":lp[e]}function Ql(t){let e=t??"";return {mode:xm(e),dependency_sharing_mode:pp(e),rules:{enforce_workspace_marker:Dr(e,"enforce_workspace_marker"),enforce_toolchain_lock:Dr(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Dr(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Dr(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Dr(e,"require_mirror_lock_for_offline")}}}function Zl(t,e,r){let o=`${e}: ${r}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${o}
274
+ `),1)}}var Bl=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],hm=[...l$2,"autopilot","pipeline","import","adopt","snapshot","ai","config","product","infra","shell","commands"],ym=["init"],wm=q$2,ql=[...wm,...r$1];function km(t){return !!t&&tm.includes(t)}function Ts(t){let e=t[0],r=t[1];return e==="project"&&(r==="--help"||r==="-h"||r==="help")?true:em.some(([o,n])=>e!==o?false:r?r===n:true)}function Fr(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?Ts(t):km(t[0])||Ts(t)}function vm(t){return !!t&&hm.includes(t)}function zl(t){return vm(t[0])||Ts(t)}function Yl(t){return !!t&&ls.includes(t)}async function Xl(t,e){switch(t){case "bootstrap":return Wm(e);case "setup":return Dm(e);case "cache":return Fm(e);case "mirror":return Jm(e);default:{let r=t;throw new Error(`Unreachable npm-only manual command: ${String(r)}`)}}}function Pm(t=process.env){let e=t.npm_config_user_agent||"",r=t.npm_execpath||"",o=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(r)||o==="exec"||o==="x"}function sp(t={}){let e=w(process.cwd());if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai project command capabilities")),console.log(s.gray(`Project: ${e.projectRoot??"not detected"}`)),console.log(s.gray(`Runtime: ${e.runtime} (${e.runtimeSupportTier}) | Framework: ${e.frameworkDisplayName} (${e.frameworkSupportTier}) | Module support: ${e.moduleSupport?"yes":"no"}`)),console.log(s.gray(`Doctor support: ${e.runtimeDoctorSupport}`)),console.log(""),console.log(s.green(`Supported: ${e.supportedCommands.join(", ")||"none"}`)),console.log(s.yellow(`Global: ${e.globalCommands.join(", ")||"none"}`)),console.log(s.red(`Unsupported: ${e.unsupportedCommands.join(", ")||"none"}`));}function jm(){return {schemaVersion:fl,cli:"workspai",version:h(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:ms,contracts:$r(),contractCatalog:zo()}}function ap(){let t=nl(fe),e=[...t.topLevelCommands],r=[...a$5].filter(i=>!e.includes(i)),o=["init","dev","start","build","test","lint","format","help"],n=[...Ir],a=[...Vo];return {schemaVersion:ms,scope:"global",cli:"workspai",version:h(),cwd:process.cwd(),contracts:$r(),contractCatalog:zo(),commands:{npmOwned:e,coreBacked:r,projectScoped:o},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...r.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...o.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function bm(t={}){let e=ap();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(sl(e.runtimeInventory.integrity));console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai command capabilities")),console.log(s.gray(`CLI: ${e.cli} v${e.version}`)),console.log(""),console.log(s.green(`npm wrapper: ${e.commands.npmOwned.join(", ")}`)),console.log(s.cyan(`Python core: ${e.commands.coreBacked.join(", ")}`)),console.log(s.yellow(`Project runtime: ${e.commands.projectScoped.join(", ")}`)),console.log(s.magenta(`Workspace intelligence: ${e.workspace.intelligenceSubcommands.join(", ")}`)),console.log(""),console.log(s.gray("Tip: run `workspai project commands --json` inside a project."));}function Ms(t){return y(t)?(sp({json:t.includes("--json")||t.includes("--ci")}),true):false}function Ws(t){let e=w(process.cwd());if(!e.projectRoot)return false;let r=x(t,process.cwd());if(!r||r.status!=="unsupported")return false;console.error(s.red(z(r,e))),process.exit(1);}function qe(t){return _.existsSync(j.join(t,".workspai-workspace"))||_.existsSync(j.join(t,".workspai","workspace.json"))||_.existsSync(j.join(t,".rapidkit-workspace"))||_.existsSync(j.join(t,".rapidkit","workspace.json"))}function ip(t$1){let e=t$1;for(;;){let r=t(e,"context.json").find(n=>_.existsSync(n));if(r)return r;let o=j.dirname(e);if(o===e)break;e=o;}return null}function Ds(t){let e=t,r=j.resolve(tmpdir());for(;;){let o=[j.join(e,".workspai-workspace"),j.join(e,".rapidkit-workspace")].find(a=>_.existsSync(a));if(o&&j.resolve(e)!==r)return o;let n=j.dirname(e);if(n===e)break;e=n;}return null}function be(t){let e=b$5({startPath:t});return !e||j.resolve(e.workspacePath)===j.resolve(tmpdir())?null:e.workspacePath}function cp(t){try{let r=b$5({startPath:t,strict:true})?.workspacePath??null;return {workspacePath:r&&j.resolve(r)!==j.resolve(tmpdir())?r:null,error:null}}catch(e){if(e instanceof a$2&&e.code==="project.workspace.unlinked")return {workspacePath:null,error:null};if(e instanceof a$2)return {workspacePath:null,error:e};throw e}}async function Jr(t,e){try{let{syncWorkspaceConsumerArtifacts:r}=await import('./workspace-onboarding-LK5IK6LE.js');await r(t,{silent:e?.silent});}catch(r){e?.silent||(console.log(s.yellow(`\u26A0\uFE0F Workspace consumer sync skipped: ${r.message}`)),console.log(s.gray(" Retry: npx workspai workspace agent-sync --write --refresh-context --preset enterprise")));}}async function Cm(t,e=process.cwd(),r=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$3(r))return {detected:false};let n=p$1(e,r);for(let a of n){if(!await O__default.pathExists(a))continue;let i=a.toLowerCase();if(i.endsWith("rapidkit.cmd")||i.endsWith("rapidkit.exe"))return {detected:true,candidatePath:a,reason:"Found workspace-local rapidkit launcher on Windows."}}return {detected:false}}function Sm(t){let e=t;for(;;){let r=j.join(e,".rapidkit-workspace"),o=j.join(e,".rapidkit","workspace.json");if(!_.existsSync(r)&&_.existsSync(o))return e;let n=j.dirname(e);if(n===e)break;e=n;}return null}var lp={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function xm(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Dr(t,e){let r=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return r?r[1]==="true":lp[e]}function Ql(t){let e=t??"";return {mode:xm(e),dependency_sharing_mode:pp(e),rules:{enforce_workspace_marker:Dr(e,"enforce_workspace_marker"),enforce_toolchain_lock:Dr(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Dr(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Dr(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Dr(e,"require_mirror_lock_for_offline")}}}function Zl(t,e,r){let o=`${e}: ${r}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${o}
275
275
  rules:`):`${t.endsWith(`
276
276
  `)?t:`${t}
277
277
  `}${o}
@@ -292,10 +292,10 @@ ${o}
292
292
  `),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(R.length>0&&process.stdout.write(R),E.length>0?process.stderr.write(E):$&&process.stderr.write(`${$}
293
293
  `)),p(C??1);}),k.on("error",C=>{h||(h=true,g&&clearTimeout(g),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`Workspai could not execute ${d}: ${C.message}. Install the required runtime or tool and ensure it is available on PATH.
294
294
  `),p(1));});})}function Im(t,e,r){if(t!=="npm")return null;let o=e[0];if(o!=="run"&&o!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=j.join(r,"package.json");if(!_.existsSync(a))return null;try{let c=JSON.parse(_.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:Om(c)}catch{return null}}function Om(t){let e=t.trim(),r=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(r)return r[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let o=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return o?o[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function an(t,e){await O__default.outputFile(t,`${JSON.stringify(e,null,2)}
295
- `,"utf-8");}function $m(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function Nm(t,e,r){let o=xt(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":j.basename(e),n=$m(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=j.join(t,i);if(!await O__default.pathExists(c))return c;a+=1;}}async function Ls(t,e,r){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?j.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:cp(process.cwd()),i=a.workspacePath,c=false,d=false,l=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!qe(n)){let w=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:w},null,2)):console.log(s.red(`\u274C ${w}`)),1}}else (!i||!qe(i))&&(i=o$1(),c=true,l=true);if(!i||!qe(i)&&!l){let w="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:w},null,2)):(console.log(s.red(`\u274C ${w}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let f="npx workspai project workspace status --json",u;try{let w=await Nm(i,t,e.name);if(u=await sn(i,{ownedDestination:w,ownedWorkspace:l?i:void 0}),l){let P=await Bs({silent:e.json});i=P.workspacePath,d=P.created;}let y=await Ol({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});y.path!==w&&u.registerCompensation(()=>O__default.remove(y.path));try{if(r?.syncWorkspaceProjects)await r.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:P,registerWorkspaceStrict:S}=await import('./workspace-LQ77WAHC.js');await S(i,j.basename(i)),await P(i,y.name,y.path);}await u.commit(),await Jr(i,{silent:e.json});}catch(P){try{await pr(u,P);}catch(S){if(S!==P)throw S}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${P instanceof Error?P.message:String(P)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?d:false,projectWorkspaceCommand:f,commandsResolveWorkspaceFromProject:true,plan:y.ingestionPlan,importedProject:y},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${y.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${y.path}`)),console.log(s.gray(` Stack: ${y.stack} (${y.confidence})`)),console.log(s.gray(` Source: ${e.git===true||xt(t)?"git-url":"local-folder"}`)),!y.profileCompatibility.ok){let P=tn(y.profileCompatibility);console.log(s.yellow(` Profile warning: ${y.profileCompatibility.message}`)),P&&console.log(s.gray(` ${P}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${f}`)),0}catch(w){if(u)try{await pr(u,w);}catch(P){P!==w&&(w=P);}let y=w instanceof Error?w.message:String(w);return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C Import failed: ${y}`)),1}}async function mp(t,e,r){let o=j.resolve(t||process.cwd()),n=e.workspace?j.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:cp(process.cwd()),i=a.workspacePath,c=false,d=false,l=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!qe(n)){let y=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C ${y}`)),1}}else (!i||!qe(i))&&(i=o$1(),c=true,l=e.dryRun!==true);let f=c&&i!==null&&(e.dryRun===true||l);if(!i||!qe(i)&&!f){let y="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:y},null,2)):(console.log(s.red(`\u274C ${y}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let u=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),w;try{if(e.dryRun!==true&&(w=await sn(i,{projectPath:o,ownedWorkspace:l?i:void 0}),l)){let h=await Bs({silent:e.json});i=h.workspacePath,d=h.created;}let y=await ks(i,o),P=await vs({workspacePath:i,source:o,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:y}),S="npx workspai project workspace status --json",p=e.dryRun===true?b$5({startPath:o}):null,v=e.dryRun!==true||p!==null&&j.resolve(p.workspacePath)===j.resolve(i)&&(!p.projectPath||j.resolve(p.projectPath)===o);if(e.dryRun!==true)try{if(r?.registerWorkspace||r?.registerProjectInWorkspace||r?.syncWorkspaceProjects)r.registerWorkspace&&await r.registerWorkspace(i,j.basename(i)),r.registerProjectInWorkspace&&await r.registerProjectInWorkspace(i,P.name,P.path),r.syncWorkspaceProjects&&await r.syncWorkspaceProjects(i);else {let{registerProjectInWorkspaceStrict:h,registerWorkspaceStrict:g}=await import('./workspace-LQ77WAHC.js');if(await g(i,j.basename(i)),await h(i,P.name,P.path),u)throw new Error("forced sync failure for command-level adopt rollback test")}await w?.commit(),await Jr(i,{silent:e.json});}catch(h){if(w)try{await pr(w,h);}catch(g){if(g!==h)throw g}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${h instanceof Error?h.message:String(h)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?d:false,wouldCreateDefaultWorkspace:c&&e.dryRun===true?!qe(i):false,projectWorkspaceCommand:S,commandsResolveWorkspaceFromProject:v,dryRun:e.dryRun===true,plan:P.ingestionPlan,adoptedProject:P},null,2)),0;c&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${i}`)),e.dryRun===true&&(console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.gray(" Planned effects: project metadata + workspace registration + model, graph, and agent-grounding sync.")),P.effects.repositoryControlFiles.length>0&&console.log(s.gray(` Repository controls may be reconciled: ${P.effects.repositoryControlFiles.map(h=>h.path).join(", ")}.`))),console.log(s.green(`\u2714 Adopted project: ${P.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${P.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)"));let m=P.stack==="unknown"?P.frameworkDisplayName||P.runtime:P.stack;if(console.log(s.gray(` Stack: ${m} (${P.confidence})`)),!P.profileCompatibility.ok){let h=tn(P.profileCompatibility);console.log(s.yellow(` Profile warning: ${P.profileCompatibility.message}`)),h&&console.log(s.gray(` ${h}`));}return console.log(s.gray(` Report: ${P.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Check: ${S}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(y){if(w)try{await pr(w,y);}catch(S){S!==y&&(y=S);}let P=y instanceof Error?y.message:String(y);return e.json?console.log(JSON.stringify({error:P},null,2)):console.log(s.red(`\u274C Adopt failed: ${P}`)),1}}async function Fs(t){let e=new Set(["python-only","polyglot","enterprise"]),r=Tm(),o="minimal",n$1=false;try{let d=s$1(t,"workspace.json").find(f=>_.existsSync(f))??p(t,"workspace.json"),l=JSON.parse(await _.promises.readFile(d,"utf-8"));o=l.profile??"minimal",n$1=l.bootstrap_note==="python-engine-skipped"||l.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(!n$1&&e.has(o))return true;let d=await Gs(t);if(d.length===0)return false;for(let l$1 of d){let f=i$2(l$1),u=f?.module_support,w=p$3(l$1);if(n$1){if(w?.moduleSupport===true)return true;continue}if(!(j$3(f,l$1)||l(f,l$1)||m$1(f,l$1))&&u!==false)return n(f,l$1)||k$1(f,l$1),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:d}=await import('./workspace-marker-7NHMDIRL.js'),f=(await d(t))?.metadata?.npm?.installMethod;(f==="poetry"||f==="venv"||f==="pipx"||f==="pip")&&(i=f);}catch{}let c=async()=>{let d=sm(t);if(!await O__default.pathExists(d)){let w=await im(t);if(w!==0)return w}let l=f$4("DEV_PATH"),u=(l?await O__default.pathExists(l):false)&&l?["-m","pip","install",l,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await Ce(d,u,t,{timeoutMs:r})};if(i==="venv"){let d=await c();if(d!==0)return d}else if(i==="poetry"){let d=j.join(t,"pyproject.toml"),l=false;try{l=(await _.promises.readFile(d,"utf-8")).includes("rapidkit-core");}catch{l=false;}if(l){let f=await c();if(f!==0)return f}else {let f=await Ce("poetry",["install","--no-root"],t,{timeoutMs:r});if(f!==0)return f;let u=await Ce("poetry",["add","rapidkit-core"],t,{timeoutMs:r});if(u!==0)return u}}else return 0;try{let{writeWorkspaceLauncher:d}=await import('./create-ZLDOBXG4.js');await d(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:d}=await import('./workspace-python-engine-state-J4QKW55K.js');await d(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function Tm(){let t=process.env.RAPIDKIT_WORKSPACE_DEPS_TIMEOUT_MS;if(t){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 12e4}async function Gs(t$1){let e=[],r=new Set,o=[t$1];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await _.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){if(!i.isDirectory()||i.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(i.name))continue;let c=j.join(n,i.name);if((await Promise.all([...t(c,"context.json"),...t(c,"project.json")].map(l=>O__default.pathExists(l)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function Mm(t){return n$2(t)}async function Bs(t={}){let e=o$1(),r=j.basename(e),o=qe(e);if(!o){let{createProject:n}=await import('./create-ZLDOBXG4.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:j.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b()});}finally{t.silent&&(console.log=i,console.warn=c,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function Es(t){let r=await Ke("go",{runCommandInCwd:Ce,runCoreRapidkit:e$1}).initProject(t);return oe(r)}function oe(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Dt(t,e){let r=Ke("node",{runCommandInCwd:Ce,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return oe(n)}if(t==="dev"){let n=await r.runDev(e);return oe(n)}if(t==="test"){let n=await r.runTest(e);return oe(n)}if(t==="build"){let n=await r.runBuild(e);return oe(n)}if(t==="lint"){let n=await r.runLint?.(e);return oe(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return oe(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return oe(o)}async function ft(t,e){let r=Ke("java",{runCommandInCwd:Ce,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return oe(n)}if(t==="dev"){let n=await r.runDev(e);return oe(n)}if(t==="test"){let n=await r.runTest(e);return oe(n)}if(t==="build"){let n=await r.runBuild(e);return oe(n)}if(t==="lint"){let n=await r.runLint?.(e);return oe(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return oe(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return oe(o)}function Rs(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$8(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$a()})}async function Wm(t,e=Js){if(t.includes("--help")||t.includes("-h")||t.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(T){if(!T)return null;let G=T.trim().toLowerCase();return G==="minimal"||G==="java-only"||G==="go-only"||G==="dotnet-only"||G==="python-only"||G==="node-only"||G==="polyglot"||G==="enterprise"?G:null},i=function(T){let Je=T.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",De=(Pe,Ue)=>{let rt=T.match(new RegExp(`^\\s*${Pe}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return rt?rt[1].toLowerCase()==="true":Ue};return {mode:Je,dependency_sharing_mode:pp(T),rules:{enforce_workspace_marker:De("enforce_workspace_marker",true),enforce_toolchain_lock:De("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:De("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:De("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:De("require_mirror_lock_for_offline",true)}}};let c=["init"],d,l$1=false,f=false,u=false,w=false;for(let T=1;T<t.length;T+=1){let G=t[T];if(G==="--ci"){l$1=true;continue}if(G==="--offline"){f=true;continue}if(G==="--json"){u=true;continue}if(G==="--compliance-only"){w=true;continue}if(G==="--profile"){let de=t[T+1];if(!de||de.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;d=de,T+=1;continue}if(G.startsWith("--profile=")){d=G.slice(10);continue}c.push(G);}let y=a(d);if(d&&!y)return console.log(s.red(`Invalid profile: ${d}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let P=process.cwd(),S=c.slice(1).filter(T=>!T.startsWith("-"));if(S.length>0){let T=j.resolve(P,S[0]),G=i$2(T),de=_.existsSync(T)?await Lt(T):"unknown";if(!qe(T)&&(j$3(G,T)||l(G,T)||m$1(G,T)||k$1(G,T)||n(G,T)||de!=="unknown"))return await e(c)}let p$1=j.join(P,".rapidkit-workspace"),v=j.join(P,".rapidkit","workspace.json"),m;!_.existsSync(p$1)&&_.existsSync(v)?m=P:(m=be(P),m||(m=Sm(P)));let h=[],g=null,k=null;if(m)try{let T=s$1(m,"workspace.json").find(Je=>_.existsSync(Je))??p(m,"workspace.json"),G=await _.promises.readFile(T,"utf-8"),de=JSON.parse(G);k=a(de.profile);}catch{k=null;}let b=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],x={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},C=y;if(!!m&&!y&&!l$1&&!u&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let T=k||"minimal",{chosenProfile:G}=await b$1([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${T})`,choices:b.map(de=>({name:de===T?`${x[de]} \u2190 current`:x[de],value:de})),default:b.indexOf(T)}]);C=G;}let E=C||k||"minimal";if(m&&!w)try{let G=E==="python-only"||E==="polyglot"||E==="enterprise"?"poetry":"venv",de;try{let Ue=(await _.promises.readFile(j.join(m,".python-version"),"utf-8")).trim();Ue&&(de=Ue);}catch{}let{syncWorkspaceFoundationFiles:Je}=await import('./create-ZLDOBXG4.js'),De=await Je(m,{workspaceName:j.basename(m),installMethod:G,pythonVersion:de,profile:E,writeMarker:true,writeGitignore:true,onlyIfMissing:true});h.push({id:"workspace.foundation.sync",status:De.length>0?"passed":"skipped",message:De.length>0?`Workspace foundation synchronized: ${De.join(", ")}`:"Workspace foundation files are already up to date."});}catch(T){h.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${T.message}`});}else m&&h.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(m&&!w&&C&&C!==k)try{let T=p(m,"workspace.json"),G=await _.promises.readFile(T,"utf-8"),de=JSON.parse(G);de.profile=C,await O__default.ensureDir(j.dirname(T)),await _.promises.writeFile(T,JSON.stringify(de,null,2)+`
295
+ `,"utf-8");}function $m(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function Nm(t,e,r){let o=xt(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":j.basename(e),n=$m(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=j.join(t,i);if(!await O__default.pathExists(c))return c;a+=1;}}async function Ls(t,e,r){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?j.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:cp(process.cwd()),i=a.workspacePath,c=false,d=false,l=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!qe(n)){let w=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:w},null,2)):console.log(s.red(`\u274C ${w}`)),1}}else (!i||!qe(i))&&(i=o$1(),c=true,l=true);if(!i||!qe(i)&&!l){let w="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:w},null,2)):(console.log(s.red(`\u274C ${w}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let f="npx workspai project workspace status --json",u;try{let w=await Nm(i,t,e.name);if(u=await sn(i,{ownedDestination:w,ownedWorkspace:l?i:void 0}),l){let P=await Bs({silent:e.json});i=P.workspacePath,d=P.created;}let y=await Ol({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});y.path!==w&&u.registerCompensation(()=>O__default.remove(y.path));try{if(r?.syncWorkspaceProjects)await r.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:P,registerWorkspaceStrict:S}=await import('./workspace-J4OGSSNO.js');await S(i,j.basename(i)),await P(i,y.name,y.path);}await u.commit(),await Jr(i,{silent:e.json});}catch(P){try{await pr(u,P);}catch(S){if(S!==P)throw S}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${P instanceof Error?P.message:String(P)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?d:false,projectWorkspaceCommand:f,commandsResolveWorkspaceFromProject:true,plan:y.ingestionPlan,importedProject:y},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${y.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${y.path}`)),console.log(s.gray(` Stack: ${y.stack} (${y.confidence})`)),console.log(s.gray(` Source: ${e.git===true||xt(t)?"git-url":"local-folder"}`)),!y.profileCompatibility.ok){let P=tn(y.profileCompatibility);console.log(s.yellow(` Profile warning: ${y.profileCompatibility.message}`)),P&&console.log(s.gray(` ${P}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${f}`)),0}catch(w){if(u)try{await pr(u,w);}catch(P){P!==w&&(w=P);}let y=w instanceof Error?w.message:String(w);return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C Import failed: ${y}`)),1}}async function mp(t,e,r){let o=j.resolve(t||process.cwd()),n=e.workspace?j.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:cp(process.cwd()),i=a.workspacePath,c=false,d=false,l=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!qe(n)){let y=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C ${y}`)),1}}else (!i||!qe(i))&&(i=o$1(),c=true,l=e.dryRun!==true);let f=c&&i!==null&&(e.dryRun===true||l);if(!i||!qe(i)&&!f){let y="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:y},null,2)):(console.log(s.red(`\u274C ${y}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let u=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),w;try{if(e.dryRun!==true&&(w=await sn(i,{projectPath:o,ownedWorkspace:l?i:void 0}),l)){let h=await Bs({silent:e.json});i=h.workspacePath,d=h.created;}let y=await ks(i,o),P=await vs({workspacePath:i,source:o,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:y}),S="npx workspai project workspace status --json",p=e.dryRun===true?b$5({startPath:o}):null,v=e.dryRun!==true||p!==null&&j.resolve(p.workspacePath)===j.resolve(i)&&(!p.projectPath||j.resolve(p.projectPath)===o);if(e.dryRun!==true)try{if(r?.registerWorkspace||r?.registerProjectInWorkspace||r?.syncWorkspaceProjects)r.registerWorkspace&&await r.registerWorkspace(i,j.basename(i)),r.registerProjectInWorkspace&&await r.registerProjectInWorkspace(i,P.name,P.path),r.syncWorkspaceProjects&&await r.syncWorkspaceProjects(i);else {let{registerProjectInWorkspaceStrict:h,registerWorkspaceStrict:g}=await import('./workspace-J4OGSSNO.js');if(await g(i,j.basename(i)),await h(i,P.name,P.path),u)throw new Error("forced sync failure for command-level adopt rollback test")}await w?.commit(),await Jr(i,{silent:e.json});}catch(h){if(w)try{await pr(w,h);}catch(g){if(g!==h)throw g}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${h instanceof Error?h.message:String(h)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?d:false,wouldCreateDefaultWorkspace:c&&e.dryRun===true?!qe(i):false,projectWorkspaceCommand:S,commandsResolveWorkspaceFromProject:v,dryRun:e.dryRun===true,plan:P.ingestionPlan,adoptedProject:P},null,2)),0;c&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${i}`)),e.dryRun===true&&(console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.gray(" Planned effects: project metadata + workspace registration + model, graph, and agent-grounding sync.")),P.effects.repositoryControlFiles.length>0&&console.log(s.gray(` Repository controls may be reconciled: ${P.effects.repositoryControlFiles.map(h=>h.path).join(", ")}.`))),console.log(s.green(`\u2714 Adopted project: ${P.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${P.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)"));let m=P.stack==="unknown"?P.frameworkDisplayName||P.runtime:P.stack;if(console.log(s.gray(` Stack: ${m} (${P.confidence})`)),!P.profileCompatibility.ok){let h=tn(P.profileCompatibility);console.log(s.yellow(` Profile warning: ${P.profileCompatibility.message}`)),h&&console.log(s.gray(` ${h}`));}return console.log(s.gray(` Report: ${P.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Check: ${S}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(y){if(w)try{await pr(w,y);}catch(S){S!==y&&(y=S);}let P=y instanceof Error?y.message:String(y);return e.json?console.log(JSON.stringify({error:P},null,2)):console.log(s.red(`\u274C Adopt failed: ${P}`)),1}}async function Fs(t){let e=new Set(["python-only","polyglot","enterprise"]),r=Tm(),o="minimal",n$1=false;try{let d=s$1(t,"workspace.json").find(f=>_.existsSync(f))??p(t,"workspace.json"),l=JSON.parse(await _.promises.readFile(d,"utf-8"));o=l.profile??"minimal",n$1=l.bootstrap_note==="python-engine-skipped"||l.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(!n$1&&e.has(o))return true;let d=await Gs(t);if(d.length===0)return false;for(let l$1 of d){let f=i$2(l$1),u=f?.module_support,w=p$3(l$1);if(n$1){if(w?.moduleSupport===true)return true;continue}if(!(j$3(f,l$1)||l(f,l$1)||m$1(f,l$1))&&u!==false)return n(f,l$1)||k$1(f,l$1),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:d}=await import('./workspace-marker-7NHMDIRL.js'),f=(await d(t))?.metadata?.npm?.installMethod;(f==="poetry"||f==="venv"||f==="pipx"||f==="pip")&&(i=f);}catch{}let c=async()=>{let d=sm(t);if(!await O__default.pathExists(d)){let w=await im(t);if(w!==0)return w}let l=f$4("DEV_PATH"),u=(l?await O__default.pathExists(l):false)&&l?["-m","pip","install",l,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await Ce(d,u,t,{timeoutMs:r})};if(i==="venv"){let d=await c();if(d!==0)return d}else if(i==="poetry"){let d=j.join(t,"pyproject.toml"),l=false;try{l=(await _.promises.readFile(d,"utf-8")).includes("rapidkit-core");}catch{l=false;}if(l){let f=await c();if(f!==0)return f}else {let f=await Ce("poetry",["install","--no-root"],t,{timeoutMs:r});if(f!==0)return f;let u=await Ce("poetry",["add","rapidkit-core"],t,{timeoutMs:r});if(u!==0)return u}}else return 0;try{let{writeWorkspaceLauncher:d}=await import('./create-TPUFKW6B.js');await d(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:d}=await import('./workspace-python-engine-state-J4QKW55K.js');await d(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function Tm(){let t=process.env.RAPIDKIT_WORKSPACE_DEPS_TIMEOUT_MS;if(t){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 12e4}async function Gs(t$1){let e=[],r=new Set,o=[t$1];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await _.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){if(!i.isDirectory()||i.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(i.name))continue;let c=j.join(n,i.name);if((await Promise.all([...t(c,"context.json"),...t(c,"project.json")].map(l=>O__default.pathExists(l)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function Mm(t){return n$2(t)}async function Bs(t={}){let e=o$1(),r=j.basename(e),o=qe(e);if(!o){let{createProject:n}=await import('./create-TPUFKW6B.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:j.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b()});}finally{t.silent&&(console.log=i,console.warn=c,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function Es(t){let r=await Ke("go",{runCommandInCwd:Ce,runCoreRapidkit:e$1}).initProject(t);return oe(r)}function oe(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Dt(t,e){let r=Ke("node",{runCommandInCwd:Ce,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return oe(n)}if(t==="dev"){let n=await r.runDev(e);return oe(n)}if(t==="test"){let n=await r.runTest(e);return oe(n)}if(t==="build"){let n=await r.runBuild(e);return oe(n)}if(t==="lint"){let n=await r.runLint?.(e);return oe(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return oe(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return oe(o)}async function ft(t,e){let r=Ke("java",{runCommandInCwd:Ce,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return oe(n)}if(t==="dev"){let n=await r.runDev(e);return oe(n)}if(t==="test"){let n=await r.runTest(e);return oe(n)}if(t==="build"){let n=await r.runBuild(e);return oe(n)}if(t==="lint"){let n=await r.runLint?.(e);return oe(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return oe(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return oe(o)}function Rs(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$8(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$a()})}async function Wm(t,e=Js){if(t.includes("--help")||t.includes("-h")||t.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(T){if(!T)return null;let G=T.trim().toLowerCase();return G==="minimal"||G==="java-only"||G==="go-only"||G==="dotnet-only"||G==="python-only"||G==="node-only"||G==="polyglot"||G==="enterprise"?G:null},i=function(T){let Je=T.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",De=(Pe,Ue)=>{let rt=T.match(new RegExp(`^\\s*${Pe}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return rt?rt[1].toLowerCase()==="true":Ue};return {mode:Je,dependency_sharing_mode:pp(T),rules:{enforce_workspace_marker:De("enforce_workspace_marker",true),enforce_toolchain_lock:De("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:De("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:De("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:De("require_mirror_lock_for_offline",true)}}};let c=["init"],d,l$1=false,f=false,u=false,w=false;for(let T=1;T<t.length;T+=1){let G=t[T];if(G==="--ci"){l$1=true;continue}if(G==="--offline"){f=true;continue}if(G==="--json"){u=true;continue}if(G==="--compliance-only"){w=true;continue}if(G==="--profile"){let de=t[T+1];if(!de||de.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;d=de,T+=1;continue}if(G.startsWith("--profile=")){d=G.slice(10);continue}c.push(G);}let y=a(d);if(d&&!y)return console.log(s.red(`Invalid profile: ${d}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let P=process.cwd(),S=c.slice(1).filter(T=>!T.startsWith("-"));if(S.length>0){let T=j.resolve(P,S[0]),G=i$2(T),de=_.existsSync(T)?await Lt(T):"unknown";if(!qe(T)&&(j$3(G,T)||l(G,T)||m$1(G,T)||k$1(G,T)||n(G,T)||de!=="unknown"))return await e(c)}let p$1=j.join(P,".rapidkit-workspace"),v=j.join(P,".rapidkit","workspace.json"),m;!_.existsSync(p$1)&&_.existsSync(v)?m=P:(m=be(P),m||(m=Sm(P)));let h=[],g=null,k=null;if(m)try{let T=s$1(m,"workspace.json").find(Je=>_.existsSync(Je))??p(m,"workspace.json"),G=await _.promises.readFile(T,"utf-8"),de=JSON.parse(G);k=a(de.profile);}catch{k=null;}let b=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],x={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},C=y;if(!!m&&!y&&!l$1&&!u&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let T=k||"minimal",{chosenProfile:G}=await b$1([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${T})`,choices:b.map(de=>({name:de===T?`${x[de]} \u2190 current`:x[de],value:de})),default:b.indexOf(T)}]);C=G;}let E=C||k||"minimal";if(m&&!w)try{let G=E==="python-only"||E==="polyglot"||E==="enterprise"?"poetry":"venv",de;try{let Ue=(await _.promises.readFile(j.join(m,".python-version"),"utf-8")).trim();Ue&&(de=Ue);}catch{}let{syncWorkspaceFoundationFiles:Je}=await import('./create-TPUFKW6B.js'),De=await Je(m,{workspaceName:j.basename(m),installMethod:G,pythonVersion:de,profile:E,writeMarker:true,writeGitignore:true,onlyIfMissing:true});h.push({id:"workspace.foundation.sync",status:De.length>0?"passed":"skipped",message:De.length>0?`Workspace foundation synchronized: ${De.join(", ")}`:"Workspace foundation files are already up to date."});}catch(T){h.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${T.message}`});}else m&&h.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(m&&!w&&C&&C!==k)try{let T=p(m,"workspace.json"),G=await _.promises.readFile(T,"utf-8"),de=JSON.parse(G);de.profile=C,await O__default.ensureDir(j.dirname(T)),await _.promises.writeFile(T,JSON.stringify(de,null,2)+`
296
296
  `,"utf-8");let{syncWorkspaceContract:Je}=await import('./workspace-contract-3BWIRSVQ.js');await Je({workspacePath:m}),h.push({id:"workspace.profile.sync",status:"passed",message:`Workspace profile synchronized to ${C} across canonical artifacts.`});}catch(T){h.push({id:"workspace.profile.sync",status:"failed",message:`Failed to synchronize workspace profile across canonical artifacts: ${T instanceof Error?T.message:String(T)}`});}let $={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},M=null;if(m)try{let T=s$1(m,"policies.yml").find(de=>_.existsSync(de));if(!T)throw new Error("policy file missing");let G=await _.promises.readFile(T,"utf-8");M=G,$=i(G);}catch{h.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else h.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(m){let T=dp(M);$.dependency_sharing_mode=T.mode,h.push({id:"policy.schema.dependency_sharing_mode",status:T.status,message:T.message}),h.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:$.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":$.dependency_sharing_mode==="shared-node-deps"?"Effective dependency mode: shared-node-deps (Node projects share workspace-level caches).":"Effective dependency mode: shared-runtime-caches (Node/Python/Go share workspace-level caches)."});let G=_.existsSync(j.join(m,".workspai-workspace"))||_.existsSync(j.join(m,".rapidkit-workspace"));h.push({id:"policy.enforce_workspace_marker",status:!$.rules.enforce_workspace_marker||G?"passed":"failed",message:!$.rules.enforce_workspace_marker||G?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let de=s$1(m,"toolchain.lock").some(Ee=>_.existsSync(Ee));h.push({id:"policy.enforce_toolchain_lock",status:!$.rules.enforce_toolchain_lock||de?"passed":"failed",message:!$.rules.enforce_toolchain_lock||de?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let Je=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||s$1(m,"trusted-sources.lock").some(Ee=>_.existsSync(Ee));h.push({id:"policy.disallow_untrusted_tool_sources",status:!$.rules.disallow_untrusted_tool_sources||Je?"passed":"failed",message:!$.rules.disallow_untrusted_tool_sources||Je?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let De=s$1(m,"compatibility-matrix.json").find(Ee=>_.existsSync(Ee))??p(m,"compatibility-matrix.json"),Pe=_.existsSync(De),Ue=$.rules.enforce_compatibility_matrix;if(h.push({id:"policy.enforce_compatibility_matrix",status:!Ue||Pe?"passed":"failed",message:!Ue||Pe?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),Pe)try{let Ee=await _.promises.readFile(De,"utf-8"),mt=JSON.parse(Ee),zs=!!mt&&typeof mt=="object";h.push({id:"compatibility.matrix.parse",status:zs?"passed":"failed",message:zs?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{h.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let rt=s$1(m,"mirror-config.json").find(Ee=>_.existsSync(Ee))??p(m,"mirror-config.json"),dr=s$1(m,"mirror.lock").find(Ee=>_.existsSync(Ee))??p(m,"mirror.lock"),ln=_.existsSync(rt),pn=_.existsSync(dr),qs={};if(ln)try{qs=JSON.parse(await _.promises.readFile(rt,"utf-8")),h.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{h.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(w)h.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let Ee=await fs(m,{ciMode:l$1,offlineMode:f});h.push(...Ee.checks.map(mt=>({id:mt.id,status:mt.status,message:mt.message}))),g=Ee.details,Ee.details.lockWritten&&(pn=true);}if(f){let Ee=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||qs.enabled===true;h.push({id:"offline.mirror.enabled",status:Ee?"passed":"failed",message:Ee?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let mt=$.rules.require_mirror_lock_for_offline;h.push({id:"offline.mirror.lock",status:!mt||pn?"passed":"failed",message:!mt||pn?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else h.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Vr=Tt({profile:E,runtimes:await Mt(m),mode:$.mode});Vr.profile!=="enterprise"?h.push({id:Vr.checkId,status:Vr.status,message:Vr.message}):(h.push({id:"profile.enterprise.ci",status:l$1?"passed":w?"skipped":"failed",message:l$1?"enterprise profile running with --ci.":w?"Enterprise runtime execution skipped by --compliance-only; --ci is not required.":"enterprise profile expects --ci for deterministic non-interactive mode."}),h.push({id:"profile.enterprise.compatibility-matrix",status:Pe?"passed":"failed",message:Pe?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),h.push({id:"profile.enterprise.mirror-config",status:ln?"passed":"failed",message:ln?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}l$1&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),f&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let A=h.some(T=>T.id.startsWith("policy.schema.")&&T.status==="failed")||$.mode==="strict"&&h.some(T=>T.status==="failed"),U=p(m||P,"reports"),q=new Date().toISOString().replace(/[:.]/g,"-"),Q=j.join(U,`bootstrap-compliance-${q}.json`),L=j.join(U,"bootstrap-compliance.latest.json"),F={schemaVersion:h$3.bootstrapCompliance.schemaVersion,command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:m,profile:E,options:{ci:l$1,offline:f,strict:$.mode==="strict",complianceOnly:w},policyMode:$.mode,policyRules:$.rules,mirrorLifecycle:g,checks:h},K=async T=>{b$l(`.workspai/reports/${j.basename(Q)}`,T),b$l(i$1.bootstrapCompliance,T),await O__default.ensureDir(U),await an(Q,T),await an(L,T);};if(A){let T=Rs({...F,result:"blocked",initExitCode:null},1,h);return await K(T),u?process.stdout.write(`${JSON.stringify(T,null,2)}
297
297
  `):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${Q}`))),1}if(u&&E==="enterprise"&&!l$1&&!w){let T=Rs({...F,result:"blocked",initExitCode:null,complianceOnly:false,bootstrapRuntimeSkipped:{reason:"enterprise JSON bootstrap requires --ci for deterministic non-interactive execution.",nextAction:"npx workspai bootstrap --profile enterprise --ci --json"}},1,h);return await K(T),process.stdout.write(`${JSON.stringify(T,null,2)}
298
- `),1}let H=async T=>{let G=process.stdout.write.bind(process.stdout),de=process.stderr.write.bind(process.stderr),Je=[],De=[];process.stdout.write=((Pe,Ue,rt)=>{let dr=typeof Ue=="function"?Ue:typeof rt=="function"?rt:void 0;return Je.push(typeof Pe=="string"?Pe:Pe instanceof Uint8Array?Buffer.from(Pe).toString("utf8"):String(Pe)),dr?.(),true}),process.stderr.write=((Pe,Ue,rt)=>{let dr=typeof Ue=="function"?Ue:typeof rt=="function"?rt:void 0;return De.push(typeof Pe=="string"?Pe:Pe instanceof Uint8Array?Buffer.from(Pe).toString("utf8"):String(Pe)),dr?.(),true});try{return {exitCode:await T(),stdout:Je.join(""),stderr:De.join("")}}finally{process.stdout.write=G,process.stderr.write=de;}},pe=T=>{let G=T.split(/\r?\n/).map(de=>de.trim()).filter(Boolean);return {bytes:Buffer.byteLength(T),excerpt:G.slice(0,12)}},ue=0,ae;if(!w)if(u){let T=await H(()=>e(c));ue=T.exitCode,ae={captured:true,stdout:pe(T.stdout),stderr:pe(T.stderr)};}else ue=await e(c);let le=h.filter(T=>T.status==="failed").length,ut=ue!==0?"failed":le>0?"ok_with_warnings":"ok",Ft=ue!==0?ue:le>0?1:0,_e=Rs({...F,result:ut,initExitCode:ue,complianceOnly:w,...ae?{initOutput:ae}:{}},Ft,h);if(await K(_e),m&&!w&&ue===0)try{let{syncWorkspaceProjects:T}=await import('./workspace-LQ77WAHC.js');await T(m,u),await Jr(m,{silent:u});}catch{}if(u)process.stdout.write(`${JSON.stringify(_e,null,2)}
298
+ `),1}let H=async T=>{let G=process.stdout.write.bind(process.stdout),de=process.stderr.write.bind(process.stderr),Je=[],De=[];process.stdout.write=((Pe,Ue,rt)=>{let dr=typeof Ue=="function"?Ue:typeof rt=="function"?rt:void 0;return Je.push(typeof Pe=="string"?Pe:Pe instanceof Uint8Array?Buffer.from(Pe).toString("utf8"):String(Pe)),dr?.(),true}),process.stderr.write=((Pe,Ue,rt)=>{let dr=typeof Ue=="function"?Ue:typeof rt=="function"?rt:void 0;return De.push(typeof Pe=="string"?Pe:Pe instanceof Uint8Array?Buffer.from(Pe).toString("utf8"):String(Pe)),dr?.(),true});try{return {exitCode:await T(),stdout:Je.join(""),stderr:De.join("")}}finally{process.stdout.write=G,process.stderr.write=de;}},pe=T=>{let G=T.split(/\r?\n/).map(de=>de.trim()).filter(Boolean);return {bytes:Buffer.byteLength(T),excerpt:G.slice(0,12)}},ue=0,ae;if(!w)if(u){let T=await H(()=>e(c));ue=T.exitCode,ae={captured:true,stdout:pe(T.stdout),stderr:pe(T.stderr)};}else ue=await e(c);let le=h.filter(T=>T.status==="failed").length,ut=ue!==0?"failed":le>0?"ok_with_warnings":"ok",Ft=ue!==0?ue:le>0?1:0,_e=Rs({...F,result:ut,initExitCode:ue,complianceOnly:w,...ae?{initOutput:ae}:{}},Ft,h);if(await K(_e),m&&!w&&ue===0)try{let{syncWorkspaceProjects:T}=await import('./workspace-J4OGSSNO.js');await T(m,u),await Jr(m,{silent:u});}catch{}if(u)process.stdout.write(`${JSON.stringify(_e,null,2)}
299
299
  `);else {let T=h.filter(G=>G.status==="failed").length;T>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${T} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${Q}`));}return Ft}finally{typeof r>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=r;}}async function Dm(t,e=Ce){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),0;let r=(t[1]||"").toLowerCase(),o=t.includes("--json"),n=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!r||!["python","node","go","java","dotnet","rust","php"].includes(r))return o?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]"},null,2)}
300
300
  `):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),1;let a=async(y,P)=>{if(y==="node"){if(!_.existsSync(j.join(P,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let p=_.existsSync(j.join(P,"pnpm-lock.yaml")),v=_.existsSync(j.join(P,"yarn.lock"));return p?{exitCode:await e("pnpm",["install","--lockfile-only","--ignore-scripts"],P)}:v?{exitCode:await e("yarn",["install","--ignore-scripts"],P)}:{exitCode:await e("npm",["install","--package-lock-only","--ignore-scripts"],P)}}if(y==="go")return _.existsSync(j.join(P,"go.mod"))?{exitCode:await e("go",["mod","download"],P)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(y==="java"){let S=_.existsSync(j.join(P,"pom.xml")),p=_.existsSync(j.join(P,"build.gradle"))||_.existsSync(j.join(P,"build.gradle.kts")),v=j.join(P,process.platform==="win32"?"gradlew.bat":"gradlew"),m=_.existsSync(v);return !S&&!p?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:S?{exitCode:await e("mvn",["-B","-q","-DskipTests","dependency:go-offline"],P)}:{exitCode:await e(m?v:"gradle",["--no-daemon","dependencies"],P)}}return y==="dotnet"?(()=>{let p=[{dir:P,depth:0}],v=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;p.length>0;){let m=p.shift();if(!m||m.depth>3)continue;let h=[];try{h=_.readdirSync(m.dir,{withFileTypes:true});}catch{continue}for(let g of h)if(g.isFile()){let k=g.name.toLowerCase();if(k.endsWith(".sln")||k.endsWith(".csproj"))return true}else g.isDirectory()&&!v.has(g.name)&&p.push({dir:j.join(m.dir,g.name),depth:m.depth+1});}return false})()?{exitCode:await e("dotnet",["restore"],P)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:y==="rust"?_.existsSync(j.join(P,"Cargo.toml"))?{exitCode:await e("cargo",["fetch"],P)}:{exitCode:0,message:"Rust warm-up skipped: Cargo.toml not found in current directory."}:y==="php"?_.existsSync(j.join(P,"composer.json"))?{exitCode:await e("composer",["install","--no-interaction","--no-scripts"],P)}:{exitCode:0,message:"PHP warm-up skipped: composer.json not found in current directory."}:{exitCode:0,message:"Dependency warm-up is not available for this runtime."}};if(o){let y=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let S=await Ke(r,{runCommandInCwd:e,runCoreRapidkit:async(g,k)=>(await g$7(g,{...k,cwd:void 0})).exitCode}).checkPrereqs(),p$1=be(process.cwd()),v=p$1||process.cwd(),m=null;if(r==="node"&&S.exitCode===0&&(m=process.version),p$1&&m){let g=s$1(p$1,"toolchain.lock").find(x=>_.existsSync(x))??p(p$1,"toolchain.lock"),k=p(p$1,"toolchain.lock"),b={};try{b=JSON.parse(await _.promises.readFile(g,"utf-8"));}catch{}(!b.runtime||typeof b.runtime!="object")&&(b.runtime={}),b.runtime[r]={version:m,detectedAt:new Date().toISOString()},await O__default.ensureDir(j.dirname(k)),await _.promises.writeFile(k,JSON.stringify(b,null,2)+`
301
301
  `,"utf-8");}let h={requested:n,status:"not-requested",exitCode:null,targets:0,messages:[]};if(n&&S.exitCode===0){let g=[v];if(r==="java"&&p$1){let R=(await Gs(p$1)).filter(E=>{let $=i$2(E);return l($,E)});R.length>0&&(g=R);}let k=[];for(let C of g)k.push(await a(r,C));let b=k.filter(C=>C.exitCode!==0),x=k.filter(C=>C.exitCode===0&&!/skipped/i.test(C.message||""));h.status=b.length>0?"failed":x.length>0?"passed":"skipped",h.exitCode=b[0]?.exitCode??0,h.targets=g.length,h.messages=k.map(C=>C.message).filter(C=>typeof C=="string");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:r,result:S.exitCode===0?"ok":"failed",exitCode:S.exitCode,workspacePath:p$1,version:m,warmDeps:n,warmDependencies:h},null,2)}
@@ -323,7 +323,7 @@ Hints:`));for(let y of d)console.log(s.gray(`- ${y}`));}return c.exitCode}functi
323
323
  `),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Config: ${u?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${w?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${y}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let u=await fs(o,{ciMode:true,offlineMode:e==="verify",forceRun:true}),w=u.checks.filter(S=>S.status==="failed"),y=u.checks.some(S=>S.id.startsWith("mirror.verify.")&&S.status==="failed");if(e==="verify"&&y){let S={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await f(),details:u.details,checks:u.checks};if(await l(S),r)return process.stdout.write(`${JSON.stringify(S,null,2)}
324
324
  `),1;console.log(s.red("\u274C Mirror verify failed."));for(let p of u.checks.filter(v=>v.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${p.id}: ${p.message}`));return 1}if(w.length>0){let S={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await f(),details:u.details,checks:u.checks};if(await l(S),r)return process.stdout.write(`${JSON.stringify(S,null,2)}
325
325
  `),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${w.length} issue(s).`));for(let p of w)console.log(s.gray(`- ${p.id}: ${p.message}`));return 1}let P={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:await f(),details:u.details,checks:u.checks};return await l(P),r?(process.stdout.write(`${JSON.stringify(P,null,2)}
326
- `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${u.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${u.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${u.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Js(t){let e=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await up(r,async()=>{let n$1=be(r),a=Ke("python",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),i=Ke("dotnet",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),c=Ke("rust",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),d=Ke("php",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),l$1=t.slice(1).filter(p=>!p.startsWith("-"));if(l$1.length>0){let p=j.resolve(r,l$1[0]),v=i$2(p),m=await Lt(p);return j$3(v,p)||m==="go"?await Es(p):l(v,p)||m==="java"?await ft("init",p):m$1(v,p)||m==="dotnet"?oe(await i.initProject(p)):k$1(v,p)||m==="node"?await xs(p):n(v,p)||m==="python"?await Ss(p,a):m==="rust"?oe(await c.initProject(p)):m==="php"?oe(await d.initProject(p)):await e$1(t,{cwd:r})}let f=i$2(r),u=!!be(r)&&r===be(r);if(!u&&j$3(f,r))return await Es(r);let w=await Lt(r);if(!u&&(l(f,r)||w==="java"))return await ft("init",r);if(!u&&(m$1(f,r)||w==="dotnet"))return oe(await i.initProject(r));if(!u&&(k$1(f,r)||w==="node"))return await xs(r);if(!u&&(n(f,r)||w==="python"))return await Ss(r,a);if(!u&&w==="rust")return oe(await c.initProject(r));if(!u&&w==="php")return oe(await d.initProject(r));let y=n$1||be(r),P=ip(r),S=P?j.dirname(j.dirname(P)):null;if(S&&S!==y){let p=i$2(S),v=await Lt(S);return j$3(p,S)||v==="go"?await Es(S):l(p,S)||v==="java"?await ft("init",S):m$1(p,S)||v==="dotnet"?oe(await i.initProject(S)):k$1(p,S)||v==="node"?await xs(S):n(p,S)||v==="python"?await Ss(S,a):v==="rust"?oe(await c.initProject(S)):v==="php"?oe(await d.initProject(S)):await e$1(["init"],{cwd:S})}if(y&&r===y){console.log(s.yellow("\u26A0\uFE0F Running `npx workspai init` at workspace root.")),console.log(s.gray(" Root `init`, `workspace init`, and `workspace run init` now share the same full-init flow:\n workspace-profile dependencies first, then project dependency initialization.\n"));let p=await Fs(y);if(p!==0)return p;let{runWorkspaceStage:v}=await import('./workspace-run-JTEFCQYQ.js');return (await v({workspacePath:y,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!y){let p=await b(),v=k$3(),{name:m}=Mm(v);await O__default.ensureDir(v);let{createProject:h}=await import('./create-ZLDOBXG4.js');return await h(m,{yes:true,userConfig:p,parentDirectory:v}),0}return await e$1(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e;}}async function tp(t){let e=be(t);if(!e)return [];let r="warn";try{let d=s$1(e,"policies.yml").find(u=>_.existsSync(u));if(!d)return [];let l=await _.promises.readFile(d,"utf-8");(l.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??l.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n$1=s$1(e,"toolchain.lock").find(d=>_.existsSync(d));if(!n$1||!_.existsSync(n$1))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await _.promises.readFile(n$1,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=i$2(t);j$3(c,t)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):k$1(c,t)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):l(c,t)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):m$1(c,t)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):n(c,t)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let d=s$1(e,"workspace.json").find(y=>_.existsSync(y));if(!d)throw new Error("workspace manifest missing");let f=JSON.parse(await _.promises.readFile(d,"utf-8")).profile??"",u=j$4(t,c),w=St({profile:f,runtime:u.runtime,subjectLabel:j.basename(t),mode:"strict"});w.ok||o.push(`${w.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function Vm(){let t$1=async h=>{if(!b$3()||!h.toLowerCase().endsWith(".cmd"))return false;try{let k=(await O__default.readFile(h,"utf8")).replace(/\r\n/g,`
326
+ `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${u.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${u.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${u.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Js(t){let e=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await up(r,async()=>{let n$1=be(r),a=Ke("python",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),i=Ke("dotnet",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),c=Ke("rust",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),d=Ke("php",{runCommandInCwd:Ce,runCoreRapidkit:e$1}),l$1=t.slice(1).filter(p=>!p.startsWith("-"));if(l$1.length>0){let p=j.resolve(r,l$1[0]),v=i$2(p),m=await Lt(p);return j$3(v,p)||m==="go"?await Es(p):l(v,p)||m==="java"?await ft("init",p):m$1(v,p)||m==="dotnet"?oe(await i.initProject(p)):k$1(v,p)||m==="node"?await xs(p):n(v,p)||m==="python"?await Ss(p,a):m==="rust"?oe(await c.initProject(p)):m==="php"?oe(await d.initProject(p)):await e$1(t,{cwd:r})}let f=i$2(r),u=!!be(r)&&r===be(r);if(!u&&j$3(f,r))return await Es(r);let w=await Lt(r);if(!u&&(l(f,r)||w==="java"))return await ft("init",r);if(!u&&(m$1(f,r)||w==="dotnet"))return oe(await i.initProject(r));if(!u&&(k$1(f,r)||w==="node"))return await xs(r);if(!u&&(n(f,r)||w==="python"))return await Ss(r,a);if(!u&&w==="rust")return oe(await c.initProject(r));if(!u&&w==="php")return oe(await d.initProject(r));let y=n$1||be(r),P=ip(r),S=P?j.dirname(j.dirname(P)):null;if(S&&S!==y){let p=i$2(S),v=await Lt(S);return j$3(p,S)||v==="go"?await Es(S):l(p,S)||v==="java"?await ft("init",S):m$1(p,S)||v==="dotnet"?oe(await i.initProject(S)):k$1(p,S)||v==="node"?await xs(S):n(p,S)||v==="python"?await Ss(S,a):v==="rust"?oe(await c.initProject(S)):v==="php"?oe(await d.initProject(S)):await e$1(["init"],{cwd:S})}if(y&&r===y){console.log(s.yellow("\u26A0\uFE0F Running `npx workspai init` at workspace root.")),console.log(s.gray(" Root `init`, `workspace init`, and `workspace run init` now share the same full-init flow:\n workspace-profile dependencies first, then project dependency initialization.\n"));let p=await Fs(y);if(p!==0)return p;let{runWorkspaceStage:v}=await import('./workspace-run-JTEIX4WA.js');return (await v({workspacePath:y,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!y){let p=await b(),v=k$3(),{name:m}=Mm(v);await O__default.ensureDir(v);let{createProject:h}=await import('./create-TPUFKW6B.js');return await h(m,{yes:true,userConfig:p,parentDirectory:v}),0}return await e$1(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e;}}async function tp(t){let e=be(t);if(!e)return [];let r="warn";try{let d=s$1(e,"policies.yml").find(u=>_.existsSync(u));if(!d)return [];let l=await _.promises.readFile(d,"utf-8");(l.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??l.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n$1=s$1(e,"toolchain.lock").find(d=>_.existsSync(d));if(!n$1||!_.existsSync(n$1))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await _.promises.readFile(n$1,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=i$2(t);j$3(c,t)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):k$1(c,t)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):l(c,t)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):m$1(c,t)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):n(c,t)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let d=s$1(e,"workspace.json").find(y=>_.existsSync(y));if(!d)throw new Error("workspace manifest missing");let f=JSON.parse(await _.promises.readFile(d,"utf-8")).profile??"",u=j$4(t,c),w=St({profile:f,runtime:u.runtime,subjectLabel:j.basename(t),mode:"strict"});w.ok||o.push(`${w.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function Vm(){let t$1=async h=>{if(!b$3()||!h.toLowerCase().endsWith(".cmd"))return false;try{let k=(await O__default.readFile(h,"utf8")).replace(/\r\n/g,`
327
327
  `).toLowerCase(),b=k.includes("\\.rapidkit\\rapidkit"),x=k.includes("\\.rapidkit\\rapidkit.cmd")||k.includes("\\.rapidkit\\rapidkit.exe")||k.includes("\\.venv\\scripts\\rapidkit.exe");return b&&!x}catch{return false}},e$2=process.cwd(),r=process.argv.slice(2),o=r[0],n$1=o==="init",a=new Set(q$2),i=!o||o==="--help"||o==="-h"||o==="help",c=qe(e$2),d=t(e$2,"project.json").some(h=>_.existsSync(h)),l$1=i$2(e$2),f=await Lt(e$2),u=j$3(l$1,e$2)||k$1(l$1,e$2)||n(l$1,e$2)||l(l$1,e$2)||m$1(l$1,e$2)||h$5(f??void 0),w=!!o&&a.has(o)&&u,y=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Fr(r)||r[0]==="create")return false;if(Ms(r))return true;if(r[0]==="init"&&c&&!d)return false;if(Ws(r))return true;try{let h=o==="shell"&&r[1]==="activate",g=o==="create",k=await Gi(e$2,{cwd:e$2,timeoutMs:1200});if(k.ok&&k.data?.isRapidkitProject&&k.data.engine==="python"){let b=g||Fr(r);if(!i&&!h&&!b&&!n$1&&!w&&On(r)){if(o&&ql.includes(o)){let C=await tp(e$2).catch(()=>[]);if(C.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
328
328
  `);for(let R of C)process.stderr.write(s.red(` \u2022 ${R}`)+`
329
329
  `);process.exit(1);}}let x=await e$1(process.argv.slice(2),{cwd:e$2});process.exit(x);}}}catch{}let P=ip(e$2),S=b$3(),p=y?[]:p$1(e$2),v=null;for(let h of p)if(await O__default.pathExists(h)){if(await t$1(h)){e.warn(`Skipping legacy/broken Windows launcher candidate: ${h}. Falling back to core bridge.`);continue}v=h;break}let m=o==="create";if(o==="init"&&c&&!d)return false;if(o&&ql.includes(o)){let h=await tp(e$2);if(h.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
@@ -366,11 +366,11 @@ Discover more:
366
366
  `)),process.exit(1));}if(e$2.dryRun){console.log(s.cyan(`
367
367
  \u{1F50D} Dry-run mode - showing what would be created:
368
368
  `)),console.log(s.white("\u{1F4C2} Path:"),c$1),console.log(s.white("\u{1F4E6} Type:"),a$2?`Project (${e$2.template})`:"Workspace"),console.log();return}if(!e$2.yes&&!a$2?await b$1([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"Workspai User"}]):e$2.yes&&console.log(s.gray(`Using default values (--yes flag)
369
- `)),a$2){let d=String(e$2.template||"").trim(),l=b$2(d);if(d$1(l)){let m=await $s(["create","project",l,t,...e$2.skipGit?["--skip-git"]:[],...e$2.skipInstall?["--skip-install"]:[]]);m!==0&&process.exit(m);return}if(!!!Ds(process.cwd())){let{registerWorkspaceAtPath:m}=await import('./create-ZLDOBXG4.js');if(e$2.createWorkspace)await m(process.cwd(),{skipGit:e$2.skipGit,yes:e$2.yes,userConfig:r});else if(!e$2.noWorkspace)if(e$2.yes)await m(process.cwd(),{skipGit:e$2.skipGit,yes:true,userConfig:r});else {let{createWs:h}=await b$1([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);h&&await m(process.cwd(),{skipGit:e$2.skipGit,yes:false,userConfig:r});}}let u=["create","project",l,t,"--output",process.cwd()];e$2.yes&&u.push("--yes");let w=be(process.cwd()),y=!!e$2.skipInstall,P=y||!!w;y&&u.push("--skip-essentials");let S=P?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,p=await f(u,{cwd:process.cwd(),env:S});p!==0&&process.exit(p),w&&!e$2.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init")));let v=Ds(process.cwd());if(v){let m=j.dirname(v),h=j.join(m,".python-version"),g=j.join(c$1,".python-version");try{if(await O__default.pathExists(h)){let k=_.readFileSync(h,"utf-8");_.writeFileSync(g,k.trim()+`
369
+ `)),a$2){let d=String(e$2.template||"").trim(),l=b$2(d);if(d$1(l)){let m=await $s(["create","project",l,t,...e$2.skipGit?["--skip-git"]:[],...e$2.skipInstall?["--skip-install"]:[]]);m!==0&&process.exit(m);return}if(!!!Ds(process.cwd())){let{registerWorkspaceAtPath:m}=await import('./create-TPUFKW6B.js');if(e$2.createWorkspace)await m(process.cwd(),{skipGit:e$2.skipGit,yes:e$2.yes,userConfig:r});else if(!e$2.noWorkspace)if(e$2.yes)await m(process.cwd(),{skipGit:e$2.skipGit,yes:true,userConfig:r});else {let{createWs:h}=await b$1([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);h&&await m(process.cwd(),{skipGit:e$2.skipGit,yes:false,userConfig:r});}}let u=["create","project",l,t,"--output",process.cwd()];e$2.yes&&u.push("--yes");let w=be(process.cwd()),y=!!e$2.skipInstall,P=y||!!w;y&&u.push("--skip-essentials");let S=P?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,p=await f(u,{cwd:process.cwd(),env:S});p!==0&&process.exit(p),w&&!e$2.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init")));let v=Ds(process.cwd());if(v){let m=j.dirname(v),h=j.join(m,".python-version"),g=j.join(c$1,".python-version");try{if(await O__default.pathExists(h)){let k=_.readFileSync(h,"utf-8");_.writeFileSync(g,k.trim()+`
370
370
  `),e.debug(`Synced Python version ${k.trim()} from workspace to project`);}}catch(k){e.debug("Could not sync Python version from workspace:",k);}}if(!e$2.skipInstall){let m=await e$1(["init",c$1],{cwd:process.cwd()});if(m!==0&&process.exit(m),v){let h=j.dirname(v),g=j.join(h,".python-version"),k=j.join(c$1,".python-version");try{if(await O__default.pathExists(g)){let b=_.readFileSync(g,"utf-8");_.writeFileSync(k,b.trim()+`
371
- `),e.debug(`Re-synced Python version ${b.trim()} after init`);}}catch(b){e.debug("Could not re-sync Python version after init:",b);}}}}else {let{createProject:d}=await import('./create-ZLDOBXG4.js');await d(t,{skipGit:e$2.skipGit,skipPythonEngine:e$2.skipPythonEngine,dryRun:e$2.dryRun,yes:e$2.yes,userConfig:n,installMethod:e$2.installMethod,profile:e$2.profile,parentDirectory:j.dirname(c$1)});}}catch(r){r instanceof a$1?(e.error(`
371
+ `),e.debug(`Re-synced Python version ${b.trim()} after init`);}}catch(b){e.debug("Could not re-sync Python version after init:",b);}}}}else {let{createProject:d}=await import('./create-TPUFKW6B.js');await d(t,{skipGit:e$2.skipGit,skipPythonEngine:e$2.skipPythonEngine,dryRun:e$2.dryRun,yes:e$2.yes,userConfig:n,installMethod:e$2.installMethod,profile:e$2.profile,parentDirectory:j.dirname(c$1)});}}catch(r){r instanceof a$1?(e.error(`
372
372
  \u274C ${r.message}`),r.details&&e.warn(`\u{1F4A1} ${r.details}`),e.debug("Error code:",r.code)):(e.error(`
373
- \u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Et=null;}});lc(fe);fc(fe);zc(fe);fe.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{bm({json:t.json});});fe.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:r}=await import('./analyze-FYNMI5KT.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});Ui(fe);fe.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t$1=>{t$1!=="activate"&&(console.log(s.red(`Unknown shell command: ${t$1}`)),process.exit(1));let e=process.cwd();function r(d){let l=d;for(;;){let f=t(l,"context.json").find(w=>_.existsSync(w));if(f)return f;let u=j.dirname(l);if(u===l)break;l=u;}return null}let o$1=r(e);function n(d){let l=d;for(;;){let f=j.join(l,".venv"),u=[j.join(l,".workspai","activate"),j.join(l,".rapidkit","activate")].find(y=>_.existsSync(y))??j.join(l,".workspai","activate");if(_.existsSync(u)||_.existsSync(f))return {venv:f,activateFile:u};let w=j.dirname(l);if(w===l)break;l=w;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&_.existsSync(a.activateFile)?i=a.activateFile:a&&_.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$3();console.log(c?`call "${i}"`:`. "${i}"`);});fe.command(k.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$4({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});fe.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:r}=await import('./pipeline-NICVJLZF.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});fe.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Os({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-IRXB2VOH.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});fe.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ls(t,e);r!==0&&process.exit(r);});fe.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await mp(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});fe.command("goal [intent]").description("Compile a plain-language engineering intent into a governed, evidence-bound Goal Pack").option("--workspace <path>","Explicit canonical workspace path").option("--scope <scope>","Bound the Goal to workspace, project:<name>, or projects:<name>,<name>").addOption(new Option("--runtime <runtime>","Bind a coverage Goal to a canonical runtime in its scope").choices(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"])).addOption(new Option("--for-agent <consumer>","Portable handoff consumer").choices(["generic","claude","codex"]).default("generic")).option("--max-attempts <count>","Maximum bounded proposal attempts","5").option("--refresh","Refresh the canonical Workspace Intelligence chain before planning").option("--dry-run","Validate and preview the Goal Pack without writing artifacts").option("--status [goal-id]","Inspect the active or named Goal Pack and validate its bindings").option("--list","List registered Goal Packs in the resolved workspace").option("--activate <goal-id>","Make a registered Goal Pack the active agent objective").option("--cancel <goal-id>","Cancel a registered Goal Pack without deleting evidence").option("--prepare <goal-id>","Create and link the deterministic CLI verification contract").option("--verify <goal-id>","Run CLI-owned verification for a prepared Goal Pack").option("--no-run","Read verification evidence without executing producer commands").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let{validateGoalCommandSelection:r}=await import('./goal-command-contract-43E22XQD.js'),o=r({intent:t,...e});if(o.operation!=="plan"){let u=b$5({startPath:process.cwd(),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!u)throw new Error("No canonical Workspai workspace could be resolved.");let{buildGoalLifecycleResult:w,inspectGoalLifecycle:y,prepareGoalVerification:P,transitionGoalLifecycle:S,verifyGoalLifecycle:p}=await import('./goal-lifecycle-OV6NZDD6.js'),v=e.prepare?await P({workspacePath:u.workspacePath,goalId:e.prepare}):null,m=e.verify?await p({workspacePath:u.workspacePath,goalId:e.verify,run:e.run!==false}):null,h=e.activate?await S({workspacePath:u.workspacePath,goalId:e.activate,action:"activate"}):e.cancel?await S({workspacePath:u.workspacePath,goalId:e.cancel,action:"cancel"}):null,g=await y({workspacePath:u.workspacePath,goalId:typeof e.status=="string"?e.status:h?.goal.id??v?.goal.id??m?.goal.id,validateBindings:!(e.list||e.cancel)}),k=w({operation:o.operation,activeGoalId:g.index.activeGoalId,goal:g.active,goals:g.index.goals,goalPack:g.goalPack,verifiedGoalId:m?.verifiedGoalId??v?.verifiedGoalId??null,verification:m?.verification??null});if(e.json)console.log(JSON.stringify(k,null,2));else if(e.list){console.log(s.bold(`Goals \xB7 ${g.index.goals.length}`));for(let b of g.index.goals)console.log(`${b.id===g.index.activeGoalId?s.green("\u25CF"):s.gray("\u25CB")} ${b.objective} \xB7 ${b.lifecycle} \xB7 ${b.state}`);}else g.active?(console.log(s.bold(g.active.objective)),console.log(s.gray(` Goal: ${g.active.id}`)),console.log(s.gray(` Lifecycle: ${g.active.lifecycle}`)),console.log(s.gray(` Planning state: ${g.active.state}`))):console.log(s.yellow("No active Goal Pack is registered."));return}let n=Number(e.maxAttempts??5),{planGoalPack:a}=await import('./goal-pack-Q3O2Z7R5.js'),c=e.json!==true&&process.stdin.isTTY===true&&process.stdout.isTTY===true?await import('./goal-interactive-selection-6YJOK4WC.js'):null,d=await a({startPath:process.cwd(),intent:o.intent,workspacePath:e.workspace,scope:e.scope,runtime:e.runtime,consumer:e.forAgent,maxAttempts:n,refresh:e.refresh===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),...c?{selectScope:c.selectGoalScopeInteractively,selectCoverageRuntime:c.selectGoalCoverageRuntimeInteractively}:{}});if(e.json){console.log(JSON.stringify(d,null,2));return}let l=d.goalPack,f=l.state==="ready-to-plan"?s.green("\u2714 Governed Goal Pack ready to plan"):l.state==="blocked"?s.red("\u25A0 Goal Pack blocked by missing bounded evidence"):l.state==="needs-evidence"?s.yellow("\u25C6 Goal Pack needs measurement evidence"):s.yellow("\u25C6 Goal Pack needs clarification");console.log(f),console.log(s.bold(` ${l.intent.statement}`)),console.log(s.gray(` Goal: ${l.id}`)),console.log(s.gray(` Scope: ${l.scope.kind} \xB7 ${l.scope.projects.length} project(s) \xB7 ${l.baseline.runtimes.length} runtime(s)`)),console.log(s.gray(` Evidence: ${l.baseline.graph.entities} entities \xB7 ${l.baseline.graph.relationships} relationships \xB7 ${l.baseline.graph.proofCoveragePercent}% relation proof coverage`)),console.log(s.gray(" Mutation: proposal only \xB7 explicit approval \xB7 CLI-owned verify/rollback")),l.decision&&console.log(s.yellow(` Decision: ${l.decision.question}`)),d.dryRun?console.log(s.cyan(" Preview only; no artifacts were written.")):(console.log(s.gray(` Goal Pack: ${l.artifacts.goalPack}`)),console.log(s.gray(` Agent handoff: ${l.artifacts.agentHandoff}`))),console.log(s.gray(` Next: ${l.commands.planVerifiedGoal??l.commands.inspectGraph}`));}catch(r){let o=r instanceof Error?r.message:String(r),n=e.verify?"verify":e.prepare?"prepare":e.activate?"activate":e.cancel?"cancel":e.list?"list":e.status!==void 0?"status":null;e.json?console.log(JSON.stringify(c$1({operation:n?`goal.${n}`:"goal.plan",code:n?`goal.${n}.failed`:"goal.plan.failed",message:o,context:{scope:e.scope??null,runtime:e.runtime??null,refresh:e.refresh===true,goalId:e.prepare??e.verify??e.activate??e.cancel??(typeof e.status=="string"?e.status:null)}}),null,2)):console.log(s.red(`\u274C Goal ${n?`${n} operation`:"planning"} failed: ${o}`)),process.exit(1);}});var cn=fe.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");cn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Eo({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot create",code:"snapshot.create.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});cn.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Cc({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){t.json&&(console.log(JSON.stringify(c$1({operation:"snapshot list",code:"snapshot.list.failed",message:e.message,context:{workspacePath:t.workspace??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});cn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await bc({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot inspect",code:"snapshot.inspect.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});cn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await xc({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot restore",code:"snapshot.restore.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});function Bm(t){return (t instanceof Error?t.message:String(t)).replace(/file:\/\/\/[^\s"']+/g,"<local-path>").replace(/\\\\[^\\\s"']+[\\][^\s"']+/g,"<local-path>").replace(/[A-Za-z]:[\\/][^\s"']+/g,"<local-path>").replace(/\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\/[^\s"']+/g,"<local-path>")}async function gp(t){try{let{buildAgentBootstrapReceipt:e}=await import('./project-agent-entry-DVPKQST7.js'),r=await e({startPath:t.project,forAgent:t.forAgent,validateLiveInputs:t.liveInputs!==false});if(t.json)console.log(JSON.stringify(r,null,2));else {let o=r.status==="ready"?s.green:r.status==="degraded"?s.yellow:s.red;console.log(o(`Agent entry: ${r.status}`)),console.log(s.gray(` Project: ${r.project.name}`)),console.log(s.gray(` Workspace: ${r.workspace.name}`)),console.log(s.gray(` Consumer: ${r.resolvedHost}`)),console.log(s.gray(` Receipt: ${r.receiptId.slice(0,16)}`));for(let n of r.checks.filter(a=>a.status!=="passed"))console.log((n.status==="failed"?s.red:s.yellow)(` ${n.id}: ${n.message}`));console.log(s.gray(` Next: ${r.nextActions[0]}`));}(r.status==="blocked"||t.strict&&r.status!=="ready")&&process.exit(2);}catch(e){let r=Bm(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"agent.entry.bootstrap.failed",message:r}),null,2)):console.log(s.red(`Agent entry failed: ${r}`)),process.exit(1);}}var qm=fe.command("agent").description("Bootstrap coding agents from canonical Workspai project evidence");qm.command("bootstrap").description("Issue a portable canonical-first grounding receipt for the current project").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier","generic").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless the complete entry receipt is ready").option("--json","Emit the versioned machine-readable receipt").action(async t=>gp({...t,operation:"agent bootstrap"}));var Rt=fe.command("project").description("Safe workspace project lifecycle operations");Rt.command("agent-entry [action]").description("Verify canonical-first project entry coverage for supported agent hosts").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier or all","all").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless all selected entry checks are ready").option("--json","Emit the versioned machine-readable receipt").action(async(t,e)=>{let r=t??"verify";if(r!=="verify"){let o=`Unknown project agent-entry action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project agent-entry",code:"project.agent-entry.action.invalid",message:o}),null,2)):(console.log(s.red(o)),console.log(s.gray(" workspai project agent-entry verify [--for-agent <agent|all>] [--strict] [--json]"))),process.exit(1);}await gp({...e,operation:"project agent-entry verify"});});Rt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{sp({json:t.json});});Rt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$5({startPath:j.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??j.join(o.projectPath,f$1),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json",pathPolicy:{classification:"machine-local",portable:false,persistence:"forbidden",disclosure:"forbidden",purpose:"runtime-workspace-resolution"}};if(ml(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});Rt.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-E2Q4QL44.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let d of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${d.path}: ${d.percent===null?"unknown":`${d.percent}%`} (${d.uncovered} uncovered)`));}for(let d of o.diagnostics)console.log(s.gray(` ${d}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});Rt.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await qn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Rt.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await zn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});Rt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Oc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});Rt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Ic({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});fe.command(k.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json [mode]","Output JSON: full (default) or summary").option("--fresh","Bypass Doctor project scan cache and refresh live evidence").option("--verbose","Show every probe, lifecycle capability, and detailed project signal").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate an action or lifecycle plan without applying or executing changes").option("--apply","Apply remediation plan non-interactively").option("--runtime <runtime>","Filter Doctor capability truth by runtime family").option("--framework <framework>","Filter Doctor capability truth by framework").option("--validate","Run the versioned Doctor disease validation corpus").option("--write","Write Doctor capability/validation artifacts inside the workspace").action(async(t,e)=>{if(t&&t!=="workspace"&&t!=="project"&&t!=="capabilities"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project, capabilities")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project | npx workspai doctor capabilities")),process.exit(1)),typeof e.json=="string"&&!["full","summary"].includes(e.json)&&(console.log(s.red(`Invalid Doctor JSON mode: ${e.json}. Use full or summary.`)),process.exit(1)),t==="capabilities"){(e.fix||e.plan||e.apply||e.project)&&(console.log(s.red("Doctor capability inspection cannot be combined with repair or project-scope flags.")),process.exit(1));let{runDoctorCapabilities:i}=await import('./capabilities-command-VBLZXP2T.js'),c=await i({runtime:e.runtime,framework:e.framework,validate:e.validate===true,write:e.write===true,workspace:typeof e.workspace=="string"?e.workspace:void 0,json:!!e.json});c!==0&&process.exit(c);return}(e.runtime||e.framework||e.validate||e.write)&&(console.log(s.red('Doctor capability flags require the "doctor capabilities" scope.')),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await Cm({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-MAPZ2ZCD.js'),a=await n({...e,json:e.json==="summary"?"summary":!!e.json,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});fe.command(k.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
373
+ \u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Et=null;}});lc(fe);fc(fe);zc(fe);fe.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{bm({json:t.json});});fe.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:r}=await import('./analyze-K6JDMF5C.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});Ui(fe);fe.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t$1=>{t$1!=="activate"&&(console.log(s.red(`Unknown shell command: ${t$1}`)),process.exit(1));let e=process.cwd();function r(d){let l=d;for(;;){let f=t(l,"context.json").find(w=>_.existsSync(w));if(f)return f;let u=j.dirname(l);if(u===l)break;l=u;}return null}let o$1=r(e);function n(d){let l=d;for(;;){let f=j.join(l,".venv"),u=[j.join(l,".workspai","activate"),j.join(l,".rapidkit","activate")].find(y=>_.existsSync(y))??j.join(l,".workspai","activate");if(_.existsSync(u)||_.existsSync(f))return {venv:f,activateFile:u};let w=j.dirname(l);if(w===l)break;l=w;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&_.existsSync(a.activateFile)?i=a.activateFile:a&&_.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$3();console.log(c?`call "${i}"`:`. "${i}"`);});fe.command(k.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$4({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});fe.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:r}=await import('./pipeline-BY2YL7C6.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});fe.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Os({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-7Q5JT7YN.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});fe.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ls(t,e);r!==0&&process.exit(r);});fe.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await mp(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});fe.command("goal [intent]").description("Compile a plain-language engineering intent into a governed, evidence-bound Goal Pack").option("--workspace <path>","Explicit canonical workspace path").option("--scope <scope>","Bound the Goal to workspace, project:<name>, or projects:<name>,<name>").addOption(new Option("--runtime <runtime>","Bind a coverage Goal to a canonical runtime in its scope").choices(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"])).addOption(new Option("--for-agent <consumer>","Portable handoff consumer").choices(["generic","claude","codex"]).default("generic")).option("--max-attempts <count>","Maximum bounded proposal attempts","5").option("--refresh","Refresh the canonical Workspace Intelligence chain before planning").option("--dry-run","Validate and preview the Goal Pack without writing artifacts").option("--status [goal-id]","Inspect the active or named Goal Pack and validate its bindings").option("--list","List registered Goal Packs in the resolved workspace").option("--activate <goal-id>","Make a registered Goal Pack the active agent objective").option("--cancel <goal-id>","Cancel a registered Goal Pack without deleting evidence").option("--prepare <goal-id>","Create and link the deterministic CLI verification contract").option("--verify <goal-id>","Run CLI-owned verification for a prepared Goal Pack").option("--no-run","Read verification evidence without executing producer commands").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let{validateGoalCommandSelection:r}=await import('./goal-command-contract-43E22XQD.js'),o=r({intent:t,...e});if(o.operation!=="plan"){let u=b$5({startPath:process.cwd(),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!u)throw new Error("No canonical Workspai workspace could be resolved.");let{buildGoalLifecycleResult:w,inspectGoalLifecycle:y,prepareGoalVerification:P,transitionGoalLifecycle:S,verifyGoalLifecycle:p}=await import('./goal-lifecycle-BNLXDHED.js'),v=e.prepare?await P({workspacePath:u.workspacePath,goalId:e.prepare}):null,m=e.verify?await p({workspacePath:u.workspacePath,goalId:e.verify,run:e.run!==false}):null,h=e.activate?await S({workspacePath:u.workspacePath,goalId:e.activate,action:"activate"}):e.cancel?await S({workspacePath:u.workspacePath,goalId:e.cancel,action:"cancel"}):null,g=await y({workspacePath:u.workspacePath,goalId:typeof e.status=="string"?e.status:h?.goal.id??v?.goal.id??m?.goal.id,validateBindings:!(e.list||e.cancel)}),k=w({operation:o.operation,activeGoalId:g.index.activeGoalId,goal:g.active,goals:g.index.goals,goalPack:g.goalPack,verifiedGoalId:m?.verifiedGoalId??v?.verifiedGoalId??null,verification:m?.verification??null});if(e.json)console.log(JSON.stringify(k,null,2));else if(e.list){console.log(s.bold(`Goals \xB7 ${g.index.goals.length}`));for(let b of g.index.goals)console.log(`${b.id===g.index.activeGoalId?s.green("\u25CF"):s.gray("\u25CB")} ${b.objective} \xB7 ${b.lifecycle} \xB7 ${b.state}`);}else g.active?(console.log(s.bold(g.active.objective)),console.log(s.gray(` Goal: ${g.active.id}`)),console.log(s.gray(` Lifecycle: ${g.active.lifecycle}`)),console.log(s.gray(` Planning state: ${g.active.state}`))):console.log(s.yellow("No active Goal Pack is registered."));return}let n=Number(e.maxAttempts??5),{planGoalPack:a}=await import('./goal-pack-2PF775AU.js'),c=e.json!==true&&process.stdin.isTTY===true&&process.stdout.isTTY===true?await import('./goal-interactive-selection-6YJOK4WC.js'):null,d=await a({startPath:process.cwd(),intent:o.intent,workspacePath:e.workspace,scope:e.scope,runtime:e.runtime,consumer:e.forAgent,maxAttempts:n,refresh:e.refresh===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),...c?{selectScope:c.selectGoalScopeInteractively,selectCoverageRuntime:c.selectGoalCoverageRuntimeInteractively}:{}});if(e.json){console.log(JSON.stringify(d,null,2));return}let l=d.goalPack,f=l.state==="ready-to-plan"?s.green("\u2714 Governed Goal Pack ready to plan"):l.state==="blocked"?s.red("\u25A0 Goal Pack blocked by missing bounded evidence"):l.state==="needs-evidence"?s.yellow("\u25C6 Goal Pack needs measurement evidence"):s.yellow("\u25C6 Goal Pack needs clarification");console.log(f),console.log(s.bold(` ${l.intent.statement}`)),console.log(s.gray(` Goal: ${l.id}`)),console.log(s.gray(` Scope: ${l.scope.kind} \xB7 ${l.scope.projects.length} project(s) \xB7 ${l.baseline.runtimes.length} runtime(s)`)),console.log(s.gray(` Evidence: ${l.baseline.graph.entities} entities \xB7 ${l.baseline.graph.relationships} relationships \xB7 ${l.baseline.graph.proofCoveragePercent}% relation proof coverage`)),console.log(s.gray(" Mutation: proposal only \xB7 explicit approval \xB7 CLI-owned verify/rollback")),l.decision&&console.log(s.yellow(` Decision: ${l.decision.question}`)),d.dryRun?console.log(s.cyan(" Preview only; no artifacts were written.")):(console.log(s.gray(` Goal Pack: ${l.artifacts.goalPack}`)),console.log(s.gray(` Agent handoff: ${l.artifacts.agentHandoff}`))),console.log(s.gray(` Next: ${l.commands.planVerifiedGoal??l.commands.inspectGraph}`));}catch(r){let o=r instanceof Error?r.message:String(r),n=e.verify?"verify":e.prepare?"prepare":e.activate?"activate":e.cancel?"cancel":e.list?"list":e.status!==void 0?"status":null;e.json?console.log(JSON.stringify(c$1({operation:n?`goal.${n}`:"goal.plan",code:n?`goal.${n}.failed`:"goal.plan.failed",message:o,context:{scope:e.scope??null,runtime:e.runtime??null,refresh:e.refresh===true,goalId:e.prepare??e.verify??e.activate??e.cancel??(typeof e.status=="string"?e.status:null)}}),null,2)):console.log(s.red(`\u274C Goal ${n?`${n} operation`:"planning"} failed: ${o}`)),process.exit(1);}});var cn=fe.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");cn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Eo({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot create",code:"snapshot.create.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});cn.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Cc({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){t.json&&(console.log(JSON.stringify(c$1({operation:"snapshot list",code:"snapshot.list.failed",message:e.message,context:{workspacePath:t.workspace??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});cn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await bc({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot inspect",code:"snapshot.inspect.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});cn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await xc({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot restore",code:"snapshot.restore.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});function Bm(t){return (t instanceof Error?t.message:String(t)).replace(/file:\/\/\/[^\s"']+/g,"<local-path>").replace(/\\\\[^\\\s"']+[\\][^\s"']+/g,"<local-path>").replace(/[A-Za-z]:[\\/][^\s"']+/g,"<local-path>").replace(/\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\/[^\s"']+/g,"<local-path>")}async function gp(t){try{let{buildAgentBootstrapReceipt:e}=await import('./project-agent-entry-VXCOXRJB.js'),r=await e({startPath:t.project,forAgent:t.forAgent,validateLiveInputs:t.liveInputs!==false});if(t.json)console.log(JSON.stringify(r,null,2));else {let o=r.status==="ready"?s.green:r.status==="degraded"?s.yellow:s.red;console.log(o(`Agent entry: ${r.status}`)),console.log(s.gray(` Project: ${r.project.name}`)),console.log(s.gray(` Workspace: ${r.workspace.name}`)),console.log(s.gray(` Consumer: ${r.resolvedHost}`)),console.log(s.gray(` Receipt: ${r.receiptId.slice(0,16)}`));for(let n of r.checks.filter(a=>a.status!=="passed"))console.log((n.status==="failed"?s.red:s.yellow)(` ${n.id}: ${n.message}`));console.log(s.gray(` Next: ${r.nextActions[0]}`));}(r.status==="blocked"||t.strict&&r.status!=="ready")&&process.exit(2);}catch(e){let r=Bm(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"agent.entry.bootstrap.failed",message:r}),null,2)):console.log(s.red(`Agent entry failed: ${r}`)),process.exit(1);}}var qm=fe.command("agent").description("Bootstrap coding agents from canonical Workspai project evidence");qm.command("bootstrap").description("Issue a portable canonical-first grounding receipt for the current project").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier","generic").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless the complete entry receipt is ready").option("--json","Emit the versioned machine-readable receipt").action(async t=>gp({...t,operation:"agent bootstrap"}));var Rt=fe.command("project").description("Safe workspace project lifecycle operations");Rt.command("agent-entry [action]").description("Verify canonical-first project entry coverage for supported agent hosts").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier or all","all").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless all selected entry checks are ready").option("--json","Emit the versioned machine-readable receipt").action(async(t,e)=>{let r=t??"verify";if(r!=="verify"){let o=`Unknown project agent-entry action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project agent-entry",code:"project.agent-entry.action.invalid",message:o}),null,2)):(console.log(s.red(o)),console.log(s.gray(" workspai project agent-entry verify [--for-agent <agent|all>] [--strict] [--json]"))),process.exit(1);}await gp({...e,operation:"project agent-entry verify"});});Rt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{sp({json:t.json});});Rt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$5({startPath:j.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??j.join(o.projectPath,f$1),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json",pathPolicy:{classification:"machine-local",portable:false,persistence:"forbidden",disclosure:"forbidden",purpose:"runtime-workspace-resolution"}};if(ml(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});Rt.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-E2Q4QL44.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let d of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${d.path}: ${d.percent===null?"unknown":`${d.percent}%`} (${d.uncovered} uncovered)`));}for(let d of o.diagnostics)console.log(s.gray(` ${d}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});Rt.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await qn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Rt.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await zn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});Rt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Oc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});Rt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Ic({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});fe.command(k.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json [mode]","Output JSON: full (default) or summary").option("--fresh","Bypass Doctor project scan cache and refresh live evidence").option("--verbose","Show every probe, lifecycle capability, and detailed project signal").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate an action or lifecycle plan without applying or executing changes").option("--apply","Apply remediation plan non-interactively").option("--runtime <runtime>","Filter Doctor capability truth by runtime family").option("--framework <framework>","Filter Doctor capability truth by framework").option("--validate","Run the versioned Doctor disease validation corpus").option("--write","Write Doctor capability/validation artifacts inside the workspace").action(async(t,e)=>{if(t&&t!=="workspace"&&t!=="project"&&t!=="capabilities"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project, capabilities")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project | npx workspai doctor capabilities")),process.exit(1)),typeof e.json=="string"&&!["full","summary"].includes(e.json)&&(console.log(s.red(`Invalid Doctor JSON mode: ${e.json}. Use full or summary.`)),process.exit(1)),t==="capabilities"){(e.fix||e.plan||e.apply||e.project)&&(console.log(s.red("Doctor capability inspection cannot be combined with repair or project-scope flags.")),process.exit(1));let{runDoctorCapabilities:i}=await import('./capabilities-command-VBLZXP2T.js'),c=await i({runtime:e.runtime,framework:e.framework,validate:e.validate===true,write:e.write===true,workspace:typeof e.workspace=="string"?e.workspace:void 0,json:!!e.json});c!==0&&process.exit(c);return}(e.runtime||e.framework||e.validate||e.write)&&(console.log(s.red('Doctor capability flags require the "doctor capabilities" scope.')),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await Cm({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-MAPZ2ZCD.js'),a=await n({...e,json:e.json==="summary"?"summary":!!e.json,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});fe.command(k.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
374
374
  workspace run <stage> \u2014 fleet stage execution across discovered projects
375
375
  stages: init | test | build | start | <custom-from-context>
376
376
  workspace explain|why \u2014 blocker/project narrative (--write for artifact)
@@ -386,18 +386,18 @@ 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=p=>{let v=n.workspace?j.resolve(n.workspace):null,m=null,h=null;try{m=b$5({startPath:process.cwd(),explicitWorkspacePath:v,strict:true})?.workspacePath??null;}catch(b){if(b instanceof a$2)h=b;else throw b}if(!m||!qe(m)){let b=h?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${p}`,code:h?.code??"workspace.root.required",message:b,context:{cwd:j.resolve(process.cwd()),...v?{requestedWorkspace:v}:{},...h?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${b}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let g=j.resolve(process.cwd()),k=j.resolve(m);return g!==k&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${m} for "${p}" (current directory: ${g}).`)),m},i=p=>process.argv.includes(p),c=p=>Oe(process.argv,p),d=()=>n.output||c("--output"),l=()=>{if(!n.scanDepth)return;let p=Number.parseInt(n.scanDepth,10);return Number.isFinite(p)?p:void 0},f=(p,v)=>{if(!p)return;let m=p.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!m)throw new Error(`${v} must be a byte size such as 500gb or 2tb.`);let h={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},g=Number(m[1])*h[m[2]||"b"];if(!Number.isSafeInteger(Math.floor(g))||g<=0)throw new Error(`${v} is outside the supported numeric range.`);return Math.floor(g)},u=()=>{let p=n.downloadTimeoutMs,v=p===void 0?void 0:Number.parseInt(p,10);if(v!==void 0&&(!Number.isFinite(v)||v<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:f(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:f(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:v,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},w=new Set(Object.values(Or).flatMap(p=>[...p.flags])),y=new Set(process.argv.slice(2).filter(p=>p.startsWith("--")).map(p=>p.split("=",1)[0]).filter(p=>w.has(p))),P=Or[t]?.flags,S=P?[...y].filter(p=>!P.includes(p)):[];if(S.length>0){let p=`${S.join(", ")} ${S.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||y.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:p,exitCode:2,context:{action:t,unsupportedFlags:S,allowedFlags:P}}),null,2)):(console.log(s.red(`\u274C ${p}`)),console.log(s.gray(` Allowed flags: ${P.join(", ")||"none"}`))),process.exit(2);}if((tl(t)||t==="trace"||t==="feedback"||t==="mcp")&&c$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:p}=await import('./workspace-LQ77WAHC.js');await p({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let p=a("intelligence"),{runWorkspaceIntelligenceChain:v}=await import('./workspace-intelligence-runner-T6CVJIQQ.js'),m=await v({workspacePath:p,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(m,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${m.status}`));for(let h of m.stages)console.log(s.gray(` ${h.id}: ${h.status} \u2014 ${h.message}`));console.log(s.gray(` Evidence: ${m.artifactPath}`));}m.exitCode!==0&&process.exit(m.exitCode);}else if(t==="model"){let p=a("model"),{buildWorkspaceModelCached:v,buildWorkspaceModelIncremental:m,createWorkspaceModelBuildProvenance:h,writeWorkspaceModel:g}=await import('./workspace-model-ETCLINRB.js'),k=n.incremental===true||i("--incremental"),b=n.cache===true||i("--cache")||k,x={workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l(),strict:n.strict===true||i("--strict")},C,R;if(k){let M=await m(x);C=M.model,R=M.mode;}else {let M=await v({...x,cache:b});C=M.model,R=M.cache;}C={...C,build:h({mode:k?"incremental":b?"cache":"full",engineStatus:R})};let E;(n.write===true||i("--write"))&&(E=await g(C,p));let $=(n.strict===true||i("--strict"))&&C.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...C,...E?{outputPath:E}:{}},null,2)),$&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${C.workspace.name}`)),k?console.log(s.gray(` Build: ${R} (incremental)`)):b&&console.log(s.gray(` Cache: ${R}`)),console.log(s.gray(` Projects: ${C.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${C.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${C.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${C.identity.workspaceType}`)),console.log(s.gray(` Validation: ${C.validation?.status??"unknown"} (${C.validation?.errors??0} error, ${C.validation?.warnings??0} warning)`)),console.log(E?s.gray(` Written: ${E}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),$&&process.exit(1);}else if(t==="agent-sync"){let p=a("agent-sync"),{syncWorkspaceAgentGrounding:v,parseAgentGroundingTargets:m}=await import('./workspace-agent-sync-YLP75OWF.js'),h=n.strict===true||i("--strict"),g=n.write===true||i("--write"),k=i("--dry-run"),b=await v({workspacePath:p,scope:n.scope,agent:n.forAgent,write:g&&!k,dryRun:k,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:m(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(b,null,2));else {console.log(s.green(`\u2714 Agent grounding ${g&&!k?"synced":"planned"}`)),console.log(s.gray(` Index: ${b.indexPath}`)),b.contextPath&&console.log(s.gray(` Context: ${b.contextPath}`)),b.blockers.length>0&&console.log(s.yellow(` Blockers: ${b.blockers.slice(0,3).join(" \xB7 ")}`));let x=g&&!k?b.writtenFiles:b.skippedFiles;if(x.length>0&&console.log(s.gray(` Files: ${x.join(", ")}`)),b.strictViolations.length>0)for(let C of b.strictViolations)console.log(s.red(`\u274C ${C}`));}h&&b.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let p=e??"status",{approveWorkspaceRepair:v,cancelWorkspaceRepair:m,decideWorkspaceRepair:h,executeWorkspaceRepair:g,inspectWorkspaceRepairCapabilities:k,listWorkspaceRepairTransactions:b,planWorkspaceRepair:x,planWorkspaceRepairProposal:C,readWorkspaceRepairTransaction:R,rollbackWorkspaceRepair:E}=await import('./workspace-repair-engine-SZZKV3JF.js');if(p==="capabilities"){let U;if(n.workspace)U=a("repair capabilities");else try{let Q=b$5({startPath:process.cwd(),strict:false})?.workspacePath;Q&&qe(Q)&&(U=Q);}catch{}let q=await k(U?{workspacePath:U,project:n.project}:n.project?{project:n.project}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(q,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${q.adapters.length}`));for(let Q of q.adapters)console.log(s.gray(` ${Q.id.padEnd(14)} ${Q.support.padEnd(11)} ${Q.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let $=a("repair"),M=n.transaction??(["plan","propose","capabilities"].includes(p)?void 0:r),N=()=>{if(!M?.trim())throw new Error(`workspace repair ${p} requires --transaction <id> (or the id as the next positional argument).`);return M.trim()},A;if(p==="plan"){let U=n.card??r;if(!U?.trim())throw new Error("workspace repair plan requires --card <id>.");A=await x({workspacePath:$,cardId:U.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(p==="propose"){let U=n.proposal??r;if(!U?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let q=j.resolve($,U.trim()),Q=j.relative($,q);if(Q.startsWith("..")||j.isAbsolute(Q))throw new Error("The repair proposal file must be inside the canonical workspace.");let L=await O__default.lstat(q).catch(()=>{});if(!L?.isFile()||L.isSymbolicLink()||L.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");A=await C({workspacePath:$,proposal:await O__default.readJson(q),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(p==="approve")A=await v({workspacePath:$,transactionId:N(),approvedBy:n.approvedBy});else if(p==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");A=await h({workspacePath:$,transactionId:N(),decision:n.decision});}else if(p==="execute"||p==="resume")A=await g({workspacePath:$,transactionId:N()});else if(p==="status")A=await R({workspacePath:$,transactionId:N()});else if(p==="list")A=await b($);else if(p==="rollback")A=await E({workspacePath:$,transactionId:N()});else if(p==="cancel")A=await m({workspacePath:$,transactionId:N()});else throw new Error(`Unknown workspace repair action: ${p}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let X=j.join($,e$2.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$6(`workspace repair ${p}`,A,X),null,2));else if(Array.isArray(A)){console.log(s.green(`\u2714 Workspace repair transactions: ${A.length}`));for(let U of A.slice(0,20))console.log(s.gray(` ${U.transactionId} \xB7 ${U.target.cardId} \xB7 ${U.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${A.state}`)),console.log(s.gray(` Transaction: ${A.transactionId}`)),console.log(s.gray(` Target: ${A.target.cardId}`));for(let U of A.stages)console.log(s.gray(` ${U.status.padEnd(8)} ${U.kind}: ${U.summary}`));A.decision&&console.log(s.yellow(` Decision: ${A.decision.reason}`)),console.log(s.gray(` Evidence: ${e$2.repairTransaction}`));}Array.isArray(A)||(A.state==="decision-required"&&process.exit(2),(A.state==="rolled-back"||A.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let p=a("remediation-plan"),{buildArtifactRemediationPlan:v,writeArtifactRemediationPlan:m}=await import('./artifact-remediation-plan-HPNQTNJ2.js'),h=await v({workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),g;if((n.write===true||i("--write"))&&(g=await m(h,p)),n.json===true||i("--json")){console.log(JSON.stringify(b$6("workspace remediation-plan",h,g),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${h.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${h.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${h.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${h.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${h.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${h.summary.risk.safe}, guarded=${h.summary.risk.guarded}, invasive=${h.summary.risk.invasive}`));for(let k of h.actions.slice(0,8))console.log(s.gray(` \u2022 ${k.cardId}: ${k.title} (${k.mode}, ${k.risk})`));h.actions.length>8&&console.log(s.gray(` \u2026 ${h.actions.length-8} more action(s)`)),console.log(g?s.gray(` Written: ${g}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let p=a("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:v,writeWorkspaceAgentContext:m}=await import('./workspace-context-YAK5XX27.js'),h=n.strict===true||i("--strict"),g=await v({workspacePath:p,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l(),strict:false}),k,b;if((n.write===true||i("--write"))&&(k=await m(g,p),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:R,parseAgentGroundingTargets:E}=await import('./workspace-agent-sync-YLP75OWF.js');if(b=await R({workspacePath:p,scope:n.scope,agent:g.agent,write:true,refreshContext:false,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",targets:E(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${b.writtenFiles.length} file(s) updated`)),h&&b.strictViolations.length>0){for(let $ of b.strictViolations)console.log(s.red(`\u274C ${$}`));process.exit(1);}}let x=h&&g.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...g,...k?{outputPath:k}:{},...b?{agentGroundingSync:b}:{}},null,2)),x&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${g.workspace.name}`)),console.log(s.gray(` Agent: ${g.agent}`)),console.log(s.gray(` Scope: ${g.scope.activeProject??g.scope.requested}`)),console.log(s.gray(` Projects included: ${g.projects.length}`)),console.log(s.gray(` Safe commands: ${g.safeCommands.length}`)),console.log(s.gray(` Validation: ${g.validation.status} (${g.validation.errors} error, ${g.validation.warnings} warning)`)),console.log(k?s.gray(` Written: ${k}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),x){for(let C of g.validation.issues)console.log(s.red(`\u274C ${C.severity}:${C.code}:${C.target}`));process.exit(1);}}else if(t==="snapshot"){let p=a("snapshot"),{buildWorkspaceModelSnapshot:v,writeWorkspaceModelSnapshot:m}=await import('./workspace-intelligence-625UN27X.js'),h=await v({workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()}),g=await m(h,p);if(n.json){console.log(JSON.stringify(b$6("workspace snapshot",h,g),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${h.model.workspace.name}`)),console.log(s.gray(` Hash: ${h.modelHash}`)),console.log(s.gray(` Projects: ${h.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${h.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${g}`));}else if(t==="diff"){let p=a("diff"),v=n.from||e;v||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:p},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:m,writeWorkspaceModelDiff:h}=await import('./workspace-intelligence-625UN27X.js'),g;try{g=await m({workspacePath:p,fromPath:v,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:x.message,context:{workspacePath:p,fromPath:v},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),x}let k=await h(g,p);if(n.json){console.log(JSON.stringify(b$6("workspace diff",g,k),null,2));return}let b=g.summary.changed?s.yellow:s.green;console.log(b(`\u2714 Workspace model diff: ${g.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Added projects: ${g.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${g.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${g.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${g.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${g.summary.validationChanges}`)),g.git?.available&&console.log(s.gray(` Git: ${g.git.dirty?"dirty":"clean"} (${g.summary.gitChangedFiles} mapped change(s))`));for(let x of g.changes.slice(0,12))console.log(s.gray(` \u2022 ${x.type} ${x.target}: ${x.message}`));g.changes.length>12&&console.log(s.gray(` \u2026 ${g.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${k}`));}else if(t==="impact"){let p=a("impact"),v=n.from||e;v||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:p},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:m,writeWorkspaceImpact:h}=await import('./workspace-intelligence-625UN27X.js'),g;try{g=await m({workspacePath:p,fromPath:v,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:x.message,context:{workspacePath:p,fromPath:v},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),x}let k=await h(g,p);if(n.json){console.log(JSON.stringify(b$6("workspace impact",g,k),null,2));return}let b=g.summary.risk==="critical"||g.summary.risk==="high"?s.red:g.summary.risk==="medium"?s.yellow:s.green;console.log(b(`\u2714 Workspace impact: ${g.summary.risk}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Affected projects: ${g.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${g.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${g.summary.recommendedCommands}`));for(let x of g.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${x.title}: ${x.summary}`));g.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${g.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${k}`));}else if(t==="verify"){let p=a("verify"),{buildWorkspaceVerify:v,writeWorkspaceVerify:m,evaluateWorkspaceVerifyGate:h}=await import('./workspace-verify-7ENGIY4S.js'),g=await v({workspacePath:p,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()}),k=await m(g,p),b=h(g,{strict:n.strict===true||i("--strict")}),x=b.exitCode,{recordWorkspaceHistory:C,historyEntryFromVerify:R}=await import('./workspace-history-SYCDK7FO.js');if(await C(p,R(g,b.passed)),n.json){console.log(JSON.stringify(b$6("workspace verify",{...g,gate:b},k,x),null,2)),x!==0&&process.exit(x);return}let E=g.summary.verdict==="ready"?s.green:g.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(E(`\u2714 Workspace verify: ${g.summary.verdict}`)),console.log(s.gray(` Freshness: ${g.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${g.impact.risk}`)),console.log(s.gray(` Steps: ${g.steps.length}`)),console.log(s.gray(` Passed ${g.summary.stepsPassed}, warn ${g.summary.stepsWarn}, failed ${g.summary.stepsFailed}, missing ${g.summary.stepsMissing}`));for(let $ of g.steps.slice(0,10))console.log(s.gray(` \u2022 ${$.id}: ${$.status} \u2014 ${$.message}`));if(g.steps.length>10&&console.log(s.gray(` \u2026 ${g.steps.length-10} more step(s)`)),g.policyViolations.length>0){console.log(s.gray(` Policy (${g.policyMode}): ${g.policyViolations.length} violation(s)`));for(let $ of g.policyViolations.slice(0,5)){let M=$.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${M} [${$.source}] ${$.code}: ${$.message}`);}}console.log(s.gray(` Gate (${b.mode}): ${b.passed?"passed":"blocked"}`));for(let $ of b.reasons.slice(0,5))console.log(s.red(` \u2717 ${$}`));console.log(s.gray(` Written: ${k}`)),x!==0&&process.exit(x);}else if(t==="graph"){let p=a("graph"),{buildWorkspaceModel:v,workspaceModelProjectTopology:m}=await import('./workspace-model-ETCLINRB.js'),{buildGraphEmit:h,renderGraphDot:g,renderGraphMermaid:k,explainGraphNode:b}=await import('./workspace-graph-2A5THUCI.js'),x=(e||"emit").toLowerCase(),C=new Set(["benchmark","entities","evidence","path","search"]),R=n.refreshGraph===true||i("--refresh-graph"),E=C.has(x)&&!R?await(await import('./workspace-knowledge-graph-snapshot-ZI4W735H.js')).readWorkspaceKnowledgeGraphSnapshot(p):null,$=E?.status==="hit"?E.graph:null,M=E?.status==="hit"?E.model:await v({workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()}),N=m(M);N||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:x,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let A=async()=>{if($)return $;let{buildWorkspaceKnowledgeGraph:L}=await import('./workspace-knowledge-graph-3ZBPSAS7.js'),{hashWorkspaceModel:F}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:K}=await import('./workspace-contract-3BWIRSVQ.js'),te=null;try{te=(await K({workspacePath:p})).contract;}catch{}return L({workspacePath:p,workspace:{name:M.workspace.name,...M.workspace.profile?{profile:M.workspace.profile}:{}},projects:M.projects.map(H=>({id:H.name,path:H.path,...H.absolutePath?{absolutePath:H.absolutePath}:{},runtime:H.runtime,runtimeCandidates:H.runtimeCandidates,framework:H.framework,...H.kit?{kit:H.kit}:{}})),projectTopology:N,contract:te,now:new Date(M.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:F(M)}})};if(x==="dot"||x==="mermaid"){let L=x==="dot"?g(N):k(N),F=d();if(F){let K=j.resolve(p,F);await O__default.outputFile(K,`${L}
389
+ See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=p=>{let v=n.workspace?j.resolve(n.workspace):null,m=null,h=null;try{m=b$5({startPath:process.cwd(),explicitWorkspacePath:v,strict:true})?.workspacePath??null;}catch(b){if(b instanceof a$2)h=b;else throw b}if(!m||!qe(m)){let b=h?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${p}`,code:h?.code??"workspace.root.required",message:b,context:{cwd:j.resolve(process.cwd()),...v?{requestedWorkspace:v}:{},...h?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${b}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let g=j.resolve(process.cwd()),k=j.resolve(m);return g!==k&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${m} for "${p}" (current directory: ${g}).`)),m},i=p=>process.argv.includes(p),c=p=>Oe(process.argv,p),d=()=>n.output||c("--output"),l=()=>{if(!n.scanDepth)return;let p=Number.parseInt(n.scanDepth,10);return Number.isFinite(p)?p:void 0},f=(p,v)=>{if(!p)return;let m=p.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!m)throw new Error(`${v} must be a byte size such as 500gb or 2tb.`);let h={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},g=Number(m[1])*h[m[2]||"b"];if(!Number.isSafeInteger(Math.floor(g))||g<=0)throw new Error(`${v} is outside the supported numeric range.`);return Math.floor(g)},u=()=>{let p=n.downloadTimeoutMs,v=p===void 0?void 0:Number.parseInt(p,10);if(v!==void 0&&(!Number.isFinite(v)||v<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:f(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:f(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:v,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},w=new Set(Object.values(Or).flatMap(p=>[...p.flags])),y=new Set(process.argv.slice(2).filter(p=>p.startsWith("--")).map(p=>p.split("=",1)[0]).filter(p=>w.has(p))),P=Or[t]?.flags,S=P?[...y].filter(p=>!P.includes(p)):[];if(S.length>0){let p=`${S.join(", ")} ${S.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||y.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:p,exitCode:2,context:{action:t,unsupportedFlags:S,allowedFlags:P}}),null,2)):(console.log(s.red(`\u274C ${p}`)),console.log(s.gray(` Allowed flags: ${P.join(", ")||"none"}`))),process.exit(2);}if((tl(t)||t==="trace"||t==="feedback"||t==="mcp")&&c$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:p}=await import('./workspace-J4OGSSNO.js');await p({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let p=a("intelligence"),{runWorkspaceIntelligenceChain:v}=await import('./workspace-intelligence-runner-DEW3CZKA.js'),m=await v({workspacePath:p,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(m,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${m.status}`));for(let h of m.stages)console.log(s.gray(` ${h.id}: ${h.status} \u2014 ${h.message}`));console.log(s.gray(` Evidence: ${m.artifactPath}`));}m.exitCode!==0&&process.exit(m.exitCode);}else if(t==="model"){let p=a("model"),{buildWorkspaceModelCached:v,buildWorkspaceModelIncremental:m,createWorkspaceModelBuildProvenance:h,writeWorkspaceModel:g}=await import('./workspace-model-ETCLINRB.js'),k=n.incremental===true||i("--incremental"),b=n.cache===true||i("--cache")||k,x={workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l(),strict:n.strict===true||i("--strict")},C,R;if(k){let M=await m(x);C=M.model,R=M.mode;}else {let M=await v({...x,cache:b});C=M.model,R=M.cache;}C={...C,build:h({mode:k?"incremental":b?"cache":"full",engineStatus:R})};let E;(n.write===true||i("--write"))&&(E=await g(C,p));let $=(n.strict===true||i("--strict"))&&C.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...C,...E?{outputPath:E}:{}},null,2)),$&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${C.workspace.name}`)),k?console.log(s.gray(` Build: ${R} (incremental)`)):b&&console.log(s.gray(` Cache: ${R}`)),console.log(s.gray(` Projects: ${C.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${C.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${C.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${C.identity.workspaceType}`)),console.log(s.gray(` Validation: ${C.validation?.status??"unknown"} (${C.validation?.errors??0} error, ${C.validation?.warnings??0} warning)`)),console.log(E?s.gray(` Written: ${E}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),$&&process.exit(1);}else if(t==="agent-sync"){let p=a("agent-sync"),{syncWorkspaceAgentGrounding:v,parseAgentGroundingTargets:m}=await import('./workspace-agent-sync-MU7W3C4S.js'),h=n.strict===true||i("--strict"),g=n.write===true||i("--write"),k=i("--dry-run"),b=await v({workspacePath:p,scope:n.scope,agent:n.forAgent,write:g&&!k,dryRun:k,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:m(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(b,null,2));else {console.log(s.green(`\u2714 Agent grounding ${g&&!k?"synced":"planned"}`)),console.log(s.gray(` Index: ${b.indexPath}`)),b.contextPath&&console.log(s.gray(` Context: ${b.contextPath}`)),b.blockers.length>0&&console.log(s.yellow(` Blockers: ${b.blockers.slice(0,3).join(" \xB7 ")}`));let x=g&&!k?b.writtenFiles:b.skippedFiles;if(x.length>0&&console.log(s.gray(` Files: ${x.join(", ")}`)),b.strictViolations.length>0)for(let C of b.strictViolations)console.log(s.red(`\u274C ${C}`));}h&&b.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let p=e??"status",{approveWorkspaceRepair:v,cancelWorkspaceRepair:m,decideWorkspaceRepair:h,executeWorkspaceRepair:g,inspectWorkspaceRepairCapabilities:k,listWorkspaceRepairTransactions:b,planWorkspaceRepair:x,planWorkspaceRepairProposal:C,readWorkspaceRepairTransaction:R,rollbackWorkspaceRepair:E}=await import('./workspace-repair-engine-3OLRNXD6.js');if(p==="capabilities"){let U;if(n.workspace)U=a("repair capabilities");else try{let Q=b$5({startPath:process.cwd(),strict:false})?.workspacePath;Q&&qe(Q)&&(U=Q);}catch{}let q=await k(U?{workspacePath:U,project:n.project}:n.project?{project:n.project}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(q,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${q.adapters.length}`));for(let Q of q.adapters)console.log(s.gray(` ${Q.id.padEnd(14)} ${Q.support.padEnd(11)} ${Q.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let $=a("repair"),M=n.transaction??(["plan","propose","capabilities"].includes(p)?void 0:r),N=()=>{if(!M?.trim())throw new Error(`workspace repair ${p} requires --transaction <id> (or the id as the next positional argument).`);return M.trim()},A;if(p==="plan"){let U=n.card??r;if(!U?.trim())throw new Error("workspace repair plan requires --card <id>.");A=await x({workspacePath:$,cardId:U.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(p==="propose"){let U=n.proposal??r;if(!U?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let q=j.resolve($,U.trim()),Q=j.relative($,q);if(Q.startsWith("..")||j.isAbsolute(Q))throw new Error("The repair proposal file must be inside the canonical workspace.");let L=await O__default.lstat(q).catch(()=>{});if(!L?.isFile()||L.isSymbolicLink()||L.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");A=await C({workspacePath:$,proposal:await O__default.readJson(q),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(p==="approve")A=await v({workspacePath:$,transactionId:N(),approvedBy:n.approvedBy});else if(p==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");A=await h({workspacePath:$,transactionId:N(),decision:n.decision});}else if(p==="execute"||p==="resume")A=await g({workspacePath:$,transactionId:N()});else if(p==="status")A=await R({workspacePath:$,transactionId:N()});else if(p==="list")A=await b($);else if(p==="rollback")A=await E({workspacePath:$,transactionId:N()});else if(p==="cancel")A=await m({workspacePath:$,transactionId:N()});else throw new Error(`Unknown workspace repair action: ${p}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let X=j.join($,e$2.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$6(`workspace repair ${p}`,A,X),null,2));else if(Array.isArray(A)){console.log(s.green(`\u2714 Workspace repair transactions: ${A.length}`));for(let U of A.slice(0,20))console.log(s.gray(` ${U.transactionId} \xB7 ${U.target.cardId} \xB7 ${U.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${A.state}`)),console.log(s.gray(` Transaction: ${A.transactionId}`)),console.log(s.gray(` Target: ${A.target.cardId}`));for(let U of A.stages)console.log(s.gray(` ${U.status.padEnd(8)} ${U.kind}: ${U.summary}`));A.decision&&console.log(s.yellow(` Decision: ${A.decision.reason}`)),console.log(s.gray(` Evidence: ${e$2.repairTransaction}`));}Array.isArray(A)||(A.state==="decision-required"&&process.exit(2),(A.state==="rolled-back"||A.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let p=a("remediation-plan"),{buildArtifactRemediationPlan:v,writeArtifactRemediationPlan:m}=await import('./artifact-remediation-plan-HPNQTNJ2.js'),h=await v({workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),g;if((n.write===true||i("--write"))&&(g=await m(h,p)),n.json===true||i("--json")){console.log(JSON.stringify(b$6("workspace remediation-plan",h,g),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${h.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${h.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${h.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${h.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${h.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${h.summary.risk.safe}, guarded=${h.summary.risk.guarded}, invasive=${h.summary.risk.invasive}`));for(let k of h.actions.slice(0,8))console.log(s.gray(` \u2022 ${k.cardId}: ${k.title} (${k.mode}, ${k.risk})`));h.actions.length>8&&console.log(s.gray(` \u2026 ${h.actions.length-8} more action(s)`)),console.log(g?s.gray(` Written: ${g}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let p=a("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:v,writeWorkspaceAgentContext:m}=await import('./workspace-context-MDACPLHD.js'),h=n.strict===true||i("--strict"),g=await v({workspacePath:p,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l(),strict:false}),k,b;if((n.write===true||i("--write"))&&(k=await m(g,p),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:R,parseAgentGroundingTargets:E}=await import('./workspace-agent-sync-MU7W3C4S.js');if(b=await R({workspacePath:p,scope:n.scope,agent:g.agent,write:true,refreshContext:false,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",targets:E(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${b.writtenFiles.length} file(s) updated`)),h&&b.strictViolations.length>0){for(let $ of b.strictViolations)console.log(s.red(`\u274C ${$}`));process.exit(1);}}let x=h&&g.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...g,...k?{outputPath:k}:{},...b?{agentGroundingSync:b}:{}},null,2)),x&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${g.workspace.name}`)),console.log(s.gray(` Agent: ${g.agent}`)),console.log(s.gray(` Scope: ${g.scope.activeProject??g.scope.requested}`)),console.log(s.gray(` Projects included: ${g.projects.length}`)),console.log(s.gray(` Safe commands: ${g.safeCommands.length}`)),console.log(s.gray(` Validation: ${g.validation.status} (${g.validation.errors} error, ${g.validation.warnings} warning)`)),console.log(k?s.gray(` Written: ${k}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),x){for(let C of g.validation.issues)console.log(s.red(`\u274C ${C.severity}:${C.code}:${C.target}`));process.exit(1);}}else if(t==="snapshot"){let p=a("snapshot"),{buildWorkspaceModelSnapshot:v,writeWorkspaceModelSnapshot:m}=await import('./workspace-intelligence-625UN27X.js'),h=await v({workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()}),g=await m(h,p);if(n.json){console.log(JSON.stringify(b$6("workspace snapshot",h,g),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${h.model.workspace.name}`)),console.log(s.gray(` Hash: ${h.modelHash}`)),console.log(s.gray(` Projects: ${h.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${h.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${g}`));}else if(t==="diff"){let p=a("diff"),v=n.from||e;v||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:p},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:m,writeWorkspaceModelDiff:h}=await import('./workspace-intelligence-625UN27X.js'),g;try{g=await m({workspacePath:p,fromPath:v,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:x.message,context:{workspacePath:p,fromPath:v},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),x}let k=await h(g,p);if(n.json){console.log(JSON.stringify(b$6("workspace diff",g,k),null,2));return}let b=g.summary.changed?s.yellow:s.green;console.log(b(`\u2714 Workspace model diff: ${g.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Added projects: ${g.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${g.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${g.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${g.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${g.summary.validationChanges}`)),g.git?.available&&console.log(s.gray(` Git: ${g.git.dirty?"dirty":"clean"} (${g.summary.gitChangedFiles} mapped change(s))`));for(let x of g.changes.slice(0,12))console.log(s.gray(` \u2022 ${x.type} ${x.target}: ${x.message}`));g.changes.length>12&&console.log(s.gray(` \u2026 ${g.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${k}`));}else if(t==="impact"){let p=a("impact"),v=n.from||e;v||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:p},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:m,writeWorkspaceImpact:h}=await import('./workspace-intelligence-625UN27X.js'),g;try{g=await m({workspacePath:p,fromPath:v,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:x.message,context:{workspacePath:p,fromPath:v},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),x}let k=await h(g,p);if(n.json){console.log(JSON.stringify(b$6("workspace impact",g,k),null,2));return}let b=g.summary.risk==="critical"||g.summary.risk==="high"?s.red:g.summary.risk==="medium"?s.yellow:s.green;console.log(b(`\u2714 Workspace impact: ${g.summary.risk}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Affected projects: ${g.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${g.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${g.summary.recommendedCommands}`));for(let x of g.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${x.title}: ${x.summary}`));g.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${g.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${k}`));}else if(t==="verify"){let p=a("verify"),{buildWorkspaceVerify:v,writeWorkspaceVerify:m,evaluateWorkspaceVerifyGate:h}=await import('./workspace-verify-7ENGIY4S.js'),g=await v({workspacePath:p,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()}),k=await m(g,p),b=h(g,{strict:n.strict===true||i("--strict")}),x=b.exitCode,{recordWorkspaceHistory:C,historyEntryFromVerify:R}=await import('./workspace-history-SYCDK7FO.js');if(await C(p,R(g,b.passed)),n.json){console.log(JSON.stringify(b$6("workspace verify",{...g,gate:b},k,x),null,2)),x!==0&&process.exit(x);return}let E=g.summary.verdict==="ready"?s.green:g.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(E(`\u2714 Workspace verify: ${g.summary.verdict}`)),console.log(s.gray(` Freshness: ${g.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${g.impact.risk}`)),console.log(s.gray(` Steps: ${g.steps.length}`)),console.log(s.gray(` Passed ${g.summary.stepsPassed}, warn ${g.summary.stepsWarn}, failed ${g.summary.stepsFailed}, missing ${g.summary.stepsMissing}`));for(let $ of g.steps.slice(0,10))console.log(s.gray(` \u2022 ${$.id}: ${$.status} \u2014 ${$.message}`));if(g.steps.length>10&&console.log(s.gray(` \u2026 ${g.steps.length-10} more step(s)`)),g.policyViolations.length>0){console.log(s.gray(` Policy (${g.policyMode}): ${g.policyViolations.length} violation(s)`));for(let $ of g.policyViolations.slice(0,5)){let M=$.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${M} [${$.source}] ${$.code}: ${$.message}`);}}console.log(s.gray(` Gate (${b.mode}): ${b.passed?"passed":"blocked"}`));for(let $ of b.reasons.slice(0,5))console.log(s.red(` \u2717 ${$}`));console.log(s.gray(` Written: ${k}`)),x!==0&&process.exit(x);}else if(t==="graph"){let p=a("graph"),{buildWorkspaceModel:v,workspaceModelProjectTopology:m}=await import('./workspace-model-ETCLINRB.js'),{buildGraphEmit:h,renderGraphDot:g,renderGraphMermaid:k,explainGraphNode:b}=await import('./workspace-graph-2A5THUCI.js'),x=(e||"emit").toLowerCase(),C=new Set(["benchmark","entities","evidence","path","search"]),R=n.refreshGraph===true||i("--refresh-graph"),E=C.has(x)&&!R?await(await import('./workspace-knowledge-graph-snapshot-ZI4W735H.js')).readWorkspaceKnowledgeGraphSnapshot(p):null,$=E?.status==="hit"?E.graph:null,M=E?.status==="hit"?E.model:await v({workspacePath:p,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:l()}),N=m(M);N||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:x,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let A=async()=>{if($)return $;let{buildWorkspaceKnowledgeGraph:L}=await import('./workspace-knowledge-graph-3ZBPSAS7.js'),{hashWorkspaceModel:F}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:K}=await import('./workspace-contract-3BWIRSVQ.js'),te=null;try{te=(await K({workspacePath:p})).contract;}catch{}return L({workspacePath:p,workspace:{name:M.workspace.name,...M.workspace.profile?{profile:M.workspace.profile}:{}},projects:M.projects.map(H=>({id:H.name,path:H.path,...H.absolutePath?{absolutePath:H.absolutePath}:{},runtime:H.runtime,runtimeCandidates:H.runtimeCandidates,framework:H.framework,...H.kit?{kit:H.kit}:{}})),projectTopology:N,contract:te,now:new Date(M.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:F(M)}})};if(x==="dot"||x==="mermaid"){let L=x==="dot"?g(N):k(N),F=d();if(F){let K=j.resolve(p,F);await O__default.outputFile(K,`${L}
390
390
  `,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${x}`,{format:x,nodeCount:N.stats.nodeCount,edgeCount:N.stats.edgeCount},K),null,2)):(console.log(s.green(`\u2714 Workspace dependency graph exported as ${x}`)),console.log(s.gray(` Written: ${K}`)));return}console.log(L);return}if(x==="jsonld"||x==="graphml"||x==="gexf"){let L=await A(),{renderWorkspaceKnowledgeGraphGexf:F,renderWorkspaceKnowledgeGraphGraphMl:K,renderWorkspaceKnowledgeGraphJsonLd:te}=await import('./workspace-knowledge-graph-export-UYAYFTWX.js'),H=x==="jsonld"?te(L):x==="graphml"?K(L):F(L),pe=d();if(pe){let ue=j.resolve(p,pe);await O__default.outputFile(ue,`${H}
391
391
  `,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${x}`,{format:x,entityCount:L.entities.length,relationCount:L.relations.length,proofCount:L.proofs.length},ue),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${x}`)),console.log(s.gray(` Written: ${ue}`)));return}console.log(H);return}if(x==="explain"){let L=(n.scope?.replace(/^project:/,"")||r||"").trim();L||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let F=b(N,L);if(n.json){console.log(JSON.stringify(F,null,2)),F.found||process.exit(1);return}F.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${L}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${F.project}`)),F.centrality&&console.log(s.gray(` Centrality: fanIn ${F.centrality.fanIn}, fanOut ${F.centrality.fanOut}, reach ${F.centrality.reach}, betweenness ${F.centrality.betweenness}${F.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${F.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${F.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${F.transitiveDependents.length}`));for(let K of F.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${K.id} (d${K.distance}, via ${K.via??"\u2014"})`));return}if(x==="entities"){let L=await A(),{queryKnowledgeEntities:F}=await import('./workspace-knowledge-graph-query-ON45H6Y7.js'),K=F(L,r);if(n.json){console.log(JSON.stringify({schemaVersion:L.schemaVersion,generatedAt:L.generatedAt,kind:r??null,count:K.length,entities:K},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${r?`: ${r}`:""}`)),console.log(s.gray(` Count: ${K.length}`));for(let te of K)console.log(s.gray(` \u2022 ${te.kind}: ${te.label} [${te.id}]`));return}if(x==="search"||x==="benchmark"){let L=(r||"").trim();L||(console.log(s.red(`\u274C workspace graph ${x} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${x} "authentication endpoint" --json`)),process.exit(1));let F=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(F)||F<1||F>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let K=await A();if(x==="benchmark"){let ue=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,{buildWorkspaceGraphTokenEfficiencyReport:ae}=await import('./workspace-graph-token-efficiency-D7CUT6NX.js'),ze=await ae({workspacePath:p,graph:K,query:L,limit:F,...ue?{projectId:ue}:{}});n.json?console.log(JSON.stringify(ze,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${L}`)),console.log(s.gray(` Estimated tokens: ${ze.corpus.estimatedTokens} corpus \u2192 ${ze.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${ze.savings.reductionRatio}\xD7 (${ze.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${ze.retrieval.matchCount}`)),console.log(s.yellow(` ${ze.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:te}=await import('./workspace-knowledge-graph-query-ON45H6Y7.js'),H=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,pe=te(K,{query:L,limit:F,...H?{projectId:H}:{},projection:"agent"});if(n.json)console.log(JSON.stringify(pe,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${L}`)),console.log(s.gray(` ${pe.entities.length}/${pe.totalMatches} match(es)${pe.truncated?" (bounded)":""}`));for(let ue of pe.entities)console.log(s.gray(` \u2022 ${ue.kind}: ${ue.label} [${ue.id}]`));}return}if(x==="evidence"){let L=(r||"").trim();L||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let F=await A(),{queryKnowledgeEvidence:K}=await import('./workspace-knowledge-graph-query-ON45H6Y7.js'),te=K(F,L);if(n.json)console.log(JSON.stringify(te,null,2));else if(te.found){console.log(s.green(`\u2714 Graph evidence: ${L}`));for(let H of te.proofs)console.log(s.gray(` \u2022 ${H.artifact}${H.pointer?`#${H.pointer}`:""} [${H.provider}/${H.trust}/${H.confidence}]`));}else {console.log(s.red(te.candidates.length>0?`\u274C Graph query is ambiguous: ${L}`:`\u274C Graph entity or relation not found: ${L}`));for(let H of te.candidates.slice(0,10))console.log(s.gray(` \u2022 ${H}`));}te.found||process.exit(1);return}if(x==="path"){let L=(r||"").trim(),F=(o||"").trim();(!L||!F)&&(console.log(s.red("\u274C workspace graph path requires <from> and <to>.")),console.log(s.gray(" npx workspai workspace graph path <from> <to> --json")),process.exit(1));let K=await A(),{queryKnowledgePath:te}=await import('./workspace-knowledge-graph-query-ON45H6Y7.js'),H=te(K,L,F);if(n.json)console.log(JSON.stringify(H,null,2));else if(H.found){console.log(s.green(`\u2714 Graph proof path: ${L} \u2192 ${F}`));for(let pe of H.hops)console.log(s.gray(` \u2022 ${pe.from} ${pe.direction==="forward"?"\u2192":"\u2190"} ${pe.to} [${pe.kind}]`));console.log(s.gray(` Proofs: ${H.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${L} and ${F}.`));H.found||process.exit(1);return}if(x==="overlay"){let L=(n.from||r||"").trim();L||(console.log(s.red("\u274C workspace graph overlay requires --from <graph.json>.")),console.log(s.gray(" npx workspai workspace graph overlay --from <graph.json> --json")),process.exit(1));let F=j.resolve(p,L),K;try{K=JSON.parse(await O__default.readFile(F,"utf8"));}catch(ut){console.log(s.red(`\u274C Could not read the base knowledge graph: ${ut instanceof Error?ut.message:String(ut)}`)),process.exit(1);}let te=K&&typeof K=="object"?K:{},H=te.graph,pe=H&&typeof H=="object"?H:{},ue=te.schemaVersion===f$2.knowledgeGraph?te:te.knowledgeGraph??pe.knowledgeGraph;(!ue||typeof ue!="object"||ue.schemaVersion!==f$2.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${f$2.knowledgeGraph} document.`)),process.exit(1));let ae=await A(),{buildWorkspaceKnowledgeGraphChangeOverlay:ze}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),le=ze(ue,ae);if(n.json){console.log(JSON.stringify(le,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${L}`)),console.log(s.gray(` Risk: ${le.summary.risk}`)),console.log(s.gray(` Entities: +${le.summary.entityAdds} -${le.summary.entityRemovals} ~${le.summary.entityChanges}`)),console.log(s.gray(` Relations: +${le.summary.relationAdds} -${le.summary.relationRemovals} ~${le.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${le.summary.proofAdds} -${le.summary.proofRemovals} ~${le.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${le.summary.impactedEntities} entities \xB7 ${le.summary.changedArtifacts} proof artifacts`));return}let X=h(N),U=await A(),q={...X,knowledgeGraph:U},Q=d();if(Q){let L=j.resolve(p,Q);await O__default.outputFile(L,`${JSON.stringify(q,null,2)}
392
- `,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace graph emit",{format:"json",nodeCount:N.stats.nodeCount,edgeCount:N.stats.edgeCount,entityCount:U.entities.length,relationCount:U.relations.length,proofCount:U.proofs.length},L),null,2)):(console.log(s.green("\u2714 Workspace graph artifact exported as JSON")),console.log(s.gray(` Written: ${L}`)));return}if(n.json){console.log(JSON.stringify(q,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${X.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${X.graph.stats.edgeCount} (inferred ${X.graph.stats.inferredEdges}, contract ${X.graph.stats.contractEdges}, manual ${X.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${X.integrity.ok?"ok":"issues"} (cycles ${X.integrity.stats.cycleCount}, dangling ${X.integrity.stats.danglingCount}, orphans ${X.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${X.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${U.quality.entityCount} entities \xB7 ${U.quality.relationCount} relations \xB7 ${U.quality.proofCount} proofs \xB7 ${U.providers.length} providers`)),console.log(s.gray(" Query: workspace graph search <query> | entities [kind] | path <from> <to> | evidence <entity-or-relation> | overlay --from <graph.json>")),console.log(s.gray(" Render: workspace graph dot | mermaid | jsonld | graphml | gexf [--output <file>]"));}else if(t==="watch"){let p=a("watch"),{runWorkspaceWatch:v}=await import('./workspace-watch-2YFSB2WL.js'),m=n.once===true||i("--once"),h=n.graphStream===true||i("--graph-stream"),g=n.json===true||h,k=h?new(await import('./workspace-graph-stream-XTSDKRLM.js')).WorkspaceGraphStreamPublisher({workspacePath:p}):null,b=new AbortController,x=()=>b.abort();process.once("SIGINT",x),process.once("SIGTERM",x),g||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await v({workspacePath:p,once:m,signal:b.signal,buildOptions:{workspacePath:p,observableScanDepth:l()},onProgress:C=>{g||console.error(s.gray(` ${C}`));},onModel:k?async C=>{let R=(await import('./workspace-model-ETCLINRB.js')).workspaceModelProjectTopology(C);if(!R)return;let{buildWorkspaceKnowledgeGraph:E}=await import('./workspace-knowledge-graph-3ZBPSAS7.js'),{readWorkspaceContract:$}=await import('./workspace-contract-3BWIRSVQ.js'),M=null;try{M=(await $({workspacePath:p})).contract;}catch{}let N=await E({workspacePath:p,workspace:{name:C.workspace.name,...C.workspace.profile?{profile:C.workspace.profile}:{}},projects:C.projects.map(A=>({id:A.name,path:A.path,...A.absolutePath?{absolutePath:A.absolutePath}:{},runtime:A.runtime,runtimeCandidates:A.runtimeCandidates,framework:A.framework,...A.kit?{kit:A.kit}:{}})),projectTopology:R,contract:M,now:new Date(C.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(C)}});console.log(JSON.stringify(k.publish(C,N)));}:void 0,emit:C=>{if(h)return;if(g){console.log(JSON.stringify(C));return}if(C.kind==="ready"){console.log(s.gray(` Ready: ${C.graph.nodeCount} nodes, ${C.graph.edgeCount} edges (hash ${C.modelHash.slice(0,12)})`));return}if(C.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${C.error??"unknown error"}`));return}if(C.kind==="unchanged"){console.log(s.gray(` No structural change (${C.mode}, ${C.durationMs}ms)`));return}let R=[];C.changedProjects.length>0&&R.push(`changed: ${C.changedProjects.join(", ")}`),C.addedProjects.length>0&&R.push(`added: ${C.addedProjects.join(", ")}`),C.removedProjects.length>0&&R.push(`removed: ${C.removedProjects.join(", ")}`),C.graph.edgesAdded.length>0&&R.push(`+${C.graph.edgesAdded.length} edges`),C.graph.edgesRemoved.length>0&&R.push(`-${C.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${C.mode}, ${C.durationMs}ms): ${R.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",x),process.removeListener("SIGTERM",x),!g&&!m&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let p=a("sync"),{syncWorkspaceProjects:v}=await import('./workspace-LQ77WAHC.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${j.basename(p)}`));let m=await v(p,n.json===true);await Jr(p,{silent:n.json===true});let{syncWorkspaceProjectLenses:h}=await import('./project-intelligence-lens-RLYSPJB2.js'),g=await h({workspacePath:p,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:k}=await import('./workspace-registry-summary-VSOBKAJG.js'),b=await k(p);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:p,registry:m,contractSynced:true,projectLenses:{synced:g.projects.length,skipped:g.skipped},registrySummary:b},null,2));}else if(t==="registry"){let p=a("registry"),v=e||"status";v!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${v}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:m,resolveWorkspaceRegisteredProjects:h}=await import('./workspace-registry-summary-VSOBKAJG.js'),g=await m(p);if(n.json){console.log(JSON.stringify(g,null,2));return}let k=await h(p);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${g.authority}`)),console.log(s.gray(` Projects: ${g.projectCount}`)),console.log(s.gray(` Summary: ${g.registrySummaryPath}`)),k.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let p=a("foundation"),v=e||"ensure";v!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${v}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:m}=await import('./workspace-foundation-G4KPT5CN.js'),h=await m(p,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(h,null,2));return}h.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${h.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let p=a("policy"),v=await Gm(p,e,r,o,n.json===true||i("--json"));v!==0&&process.exit(v);}else if(t==="contract"){let p=a("contract"),{buildWorkspaceContractGraph:v,readWorkspaceContract:m,verifyWorkspaceContract:h,writeWorkspaceContract:g,WORKSPACE_CONTRACT_PATH:k}=await import('./workspace-contract-3BWIRSVQ.js'),b=e||"inspect",x=d(),C=b==="graph"?void 0:x;try{if(b==="init"){let R=await g({workspacePath:p,outputPath:C,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(R,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${R.contractPath}`)),console.log(s.gray(` Projects: ${R.contract.projects.length}`));return}if(b==="inspect"){let R=await m({workspacePath:p,contractPath:C});if(n.json){console.log(JSON.stringify(R,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${R.contractPath}`)),console.log(s.gray(` Workspace: ${R.contract.workspace.name}`)),console.log(s.gray(` Projects: ${R.contract.projects.length}`)),console.log(s.gray(` Schema: v${R.contract.schemaVersion}`));return}if(b==="verify"){let R=await h({workspacePath:p,contractPath:C,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:E}=await import('./workspace-contract-3BWIRSVQ.js'),$=await E({workspacePath:p,result:R});if(n.json)console.log(JSON.stringify({...R,evidencePath:$},null,2));else {let M=R.status==="passed"?s.green:s.red;console.log(M(`\u2714 Workspace contract verification ${R.status}: ${R.contractPath}`)),console.log(s.gray(` Projects: ${R.projectCount}`));for(let N of R.checks){let A=N.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${A} ${N.id}: ${N.message}`));}for(let N of R.violations)console.log(s.gray(` Violation: ${N}`));}(R.status==="failed"||R.status!=="passed"&&n.strict)&&process.exit(1);return}if(b==="graph"){let R=await v({workspacePath:p,contractPath:C});if(x){let E=j.resolve(p,x);await O__default.outputFile(E,`${JSON.stringify(R,null,2)}
393
- `,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace contract graph",{projectCount:R.graph.summary.projectCount,relationshipEdges:R.graph.summary.relationshipEdges,entityCount:R.graph.summary.entityCount,knowledgeRelations:R.graph.summary.knowledgeRelations,proofCount:R.graph.summary.proofCount},E),null,2)):(console.log(s.green("\u2714 Workspace contract graph exported as JSON")),console.log(s.gray(` Written: ${E}`)));return}if(n.json){console.log(JSON.stringify(R,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${R.contractPath}`)),console.log(s.gray(` Workspace: ${R.graph.workspace.name}`)),console.log(s.gray(` Projects: ${R.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${R.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${R.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${R.graph.summary.relationshipEdges} (${R.graph.summary.inferredEdges} inferred, ${R.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${R.graph.summary.connectedProjects}/${R.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(R.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(R.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${R.graph.summary.orphanProjects} \xB7 Hotspots: ${R.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${R.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${R.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${R.graph.summary.entityCount} entities \xB7 ${R.graph.summary.knowledgeRelations} relations \xB7 ${R.graph.summary.proofCount} proofs \xB7 ${R.graph.summary.providerCount} providers \xB7 ${R.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${R.graph.summary.portCount}`));for(let E of R.graph.nodes){let $=E.ports.map(N=>`${N.name}:${N.port}`).join(", ")||"none",M=E.operationalProfile?` risk=${E.operationalProfile.weight}/${E.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${E.id} (${E.runtime||"unknown"}${E.framework?`/${E.framework}`:""}) ports=${$} manifests=${E.files.manifests.length}${M}`));}for(let E of R.graph.edges){let $=E.type==="event"?`event:${E.label}`:E.label;console.log(s.gray(` ${E.from} -> ${E.to} [${$}]`));}if(R.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let E of R.graph.dependencyGraph.edges)console.log(s.gray(` ${E.from} -> ${E.to} [${E.kind}/${E.source}/${E.confidence}] evidence=${E.evidence.length}`));}for(let E of R.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${E.severity}: ${E.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${b}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${k}]`)),process.exit(1);}catch(R){n.json&&(console.log(JSON.stringify({command:`workspace contract ${b}`,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${b}.failed`,message:R.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${b} failed: ${R.message}`)),process.exit(1);}}else if(t==="share"){let p=a("share"),v=d()||e,{createWorkspaceShareBundle:m}=await import('./workspace-LQ77WAHC.js'),h=await m(p,{outputPath:v,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:p,bundlePath:h,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${h}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let p=a("export");try{let{exportWorkspaceArchive:v}=await import('./workspace-archive-ZBCKJHXS.js'),m=n.archiveCompression?.trim().toLowerCase()??"store";if(m!=="store"&&m!=="deflate")throw new Error("--archive-compression must be store or deflate.");let h=await v({workspacePath:p,outputPath:d()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:m});if(n.json){console.log(JSON.stringify(h,null,2));return}let g=(h.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.manifest.files.length}`)),console.log(s.gray(` Size: ${g} MB`)),h.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(v){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:v.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${v.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let p=r;p||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:v,inspectWorkspaceArchive:m,verifyWorkspaceArchive:h}=await import('./workspace-archive-ZBCKJHXS.js');try{if(e==="inspect"){let k=await m({archivePathOrUrl:p,safety:u()});if(n.json){console.log(JSON.stringify(k,null,2));return}let b=(k.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${k.archivePath}`)),console.log(s.gray(` Workspace: ${k.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${k.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${k.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${k.fileCount}`)),console.log(s.gray(` Payload: ${b} MB`));return}if(e==="doctor"){let k=await v({archivePathOrUrl:p,strict:n.strict===true||i("--strict"),safety:u()});if(n.json)console.log(JSON.stringify(k,null,2));else {let b=k.status==="passed"?s.green:k.status==="warning"?s.yellow:s.red;console.log(b(`\u2714 Workspace archive doctor ${k.status}: ${k.archivePath}`)),console.log(s.gray(` Workspace: ${k.workspaceName}`)),console.log(s.gray(` Files: ${k.fileCount}`));for(let x of k.checks){let C=x.status==="passed"?"\u2714":x.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${C} ${x.id}: ${x.message}`));}for(let x of k.recommendedActions)console.log(s.gray(` Next: ${x}`));}(k.status==="failed"||k.status==="warning"&&n.strict)&&process.exit(1);return}let g=await h({archivePathOrUrl:p,requireChecksums:n.strict===true||i("--strict"),safety:u()});if(n.json)console.log(JSON.stringify(g,null,2));else if(g.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${g.archivePath}`)),console.log(s.gray(` Files: ${g.verifiedFiles}/${g.fileCount}`));else {let k=g.status==="failed"?s.red:s.yellow;console.log(k(`\u274C Workspace archive verification ${g.status}: ${g.archivePath}`)),g.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${g.missingArchiveEntries.join(", ")}`)),g.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${g.extraArchiveEntries.join(", ")}`)),g.mismatches.length&&console.log(s.gray(` Mismatches: ${g.mismatches.map(b=>b.path).join(", ")}`)),g.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${g.missingChecksumFiles.join(", ")}`));}(g.status==="failed"||g.status==="warning"&&n.strict)&&process.exit(1);}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:p,error:{code:`workspace.archive.${e}.failed`,message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${g.message}`)),process.exit(1);}}else if(t==="connect"){let p=j.resolve(e||process.cwd());try{let v=await Ps({workspacePath:p,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(v.status==="preview"?`\u2714 Workspace connection preview: ${p}`:`\u2714 Workspace connected: ${p}`));for(let m of v.warnings)console.log(s.yellow(` \u26A0 ${m}`));}catch(v){let m=v instanceof Error?v.message:String(v);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:m}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${m}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let p=e;p||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let v=await js({archivePathOrUrl:p,outputPath:d(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:u()});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(v.status==="preview"?`\u2714 Workspace import preview: ${v.workspacePath}`:`\u2714 Workspace imported and registered: ${v.workspacePath}`));for(let m of v.warnings)console.log(s.yellow(` \u26A0 ${m}`));}else {let{hydrateWorkspaceArchive:v}=await import('./workspace-archive-ZBCKJHXS.js'),m=await v({archivePathOrUrl:p,outputPath:d(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:u()});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.dryRun?`\u2714 Workspace archive hydrate preview: ${m.outputPath}`:`\u2714 Workspace archive hydrated: ${m.outputPath}`)),console.log(s.gray(` Files: ${m.files.length}`)),m.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${m.manifest.workspaceName}`));}}catch(v){let m=v instanceof Error?v.message:String(v);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:m,context:{archivePathOrUrl:p,...d()?{outputPath:d()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:p,...d()?{outputPath:d()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:m}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${m}`)),process.exit(1);}}else if(t==="run"){let p=a(`run ${e||""}`.trim()),v=new Set(["init","test","build","start"]),m=e?.trim()??"";m||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .workspai/context.json commands")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2)),v.has(m)||(!/^[a-z][a-z0-9_-]*$/i.test(m)||m==="dev"||m==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${m}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),m==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let h=Os({raw:n.maxWorkers,operation:`workspace run ${m}`,json:n.json===true||i("--json")});if(m==="init"&&n.json!==true){let b=await Fs(p);b!==0&&process.exit(b);}let{runWorkspaceStage:g}=await import('./workspace-run-JTEFCQYQ.js'),k=await g({workspacePath:p,stage:m,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:h,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true,planOnly:n.plan===true,runtime:n.runtime});n.json&&console.log(JSON.stringify(k,null,2)),k.summary.exitCode!==0&&process.exit(k.summary.exitCode);}else if(t==="explain"||t==="why"){let p=a(t),{parseWorkspaceExplainTarget:v}=await import('./workspace-explain-contract-ZL4NMLZI.js'),{buildWorkspaceExplain:m,writeWorkspaceExplainReport:h}=await import('./workspace-explain-QH4FXQW5.js'),g=(e??r??"").trim();!g&&n.scope&&(g=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),g||(g="release-blocked");let k=v(g);k||(console.log(s.red(`\u274C Invalid explain target: ${g}`)),process.exit(1));let b=await m({workspacePath:p,target:k}),x=n.write===true||i("--write"),C;if(x&&(C=await h(b,p,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$6(`workspace ${t}`,b,C),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${b.summary}`));for(let R of b.sections)console.log(s.bold(`
392
+ `,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace graph emit",{format:"json",nodeCount:N.stats.nodeCount,edgeCount:N.stats.edgeCount,entityCount:U.entities.length,relationCount:U.relations.length,proofCount:U.proofs.length},L),null,2)):(console.log(s.green("\u2714 Workspace graph artifact exported as JSON")),console.log(s.gray(` Written: ${L}`)));return}if(n.json){console.log(JSON.stringify(q,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${X.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${X.graph.stats.edgeCount} (inferred ${X.graph.stats.inferredEdges}, contract ${X.graph.stats.contractEdges}, manual ${X.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${X.integrity.ok?"ok":"issues"} (cycles ${X.integrity.stats.cycleCount}, dangling ${X.integrity.stats.danglingCount}, orphans ${X.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${X.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${U.quality.entityCount} entities \xB7 ${U.quality.relationCount} relations \xB7 ${U.quality.proofCount} proofs \xB7 ${U.providers.length} providers`)),console.log(s.gray(" Query: workspace graph search <query> | entities [kind] | path <from> <to> | evidence <entity-or-relation> | overlay --from <graph.json>")),console.log(s.gray(" Render: workspace graph dot | mermaid | jsonld | graphml | gexf [--output <file>]"));}else if(t==="watch"){let p=a("watch"),{runWorkspaceWatch:v}=await import('./workspace-watch-2YFSB2WL.js'),m=n.once===true||i("--once"),h=n.graphStream===true||i("--graph-stream"),g=n.json===true||h,k=h?new(await import('./workspace-graph-stream-XTSDKRLM.js')).WorkspaceGraphStreamPublisher({workspacePath:p}):null,b=new AbortController,x=()=>b.abort();process.once("SIGINT",x),process.once("SIGTERM",x),g||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await v({workspacePath:p,once:m,signal:b.signal,buildOptions:{workspacePath:p,observableScanDepth:l()},onProgress:C=>{g||console.error(s.gray(` ${C}`));},onModel:k?async C=>{let R=(await import('./workspace-model-ETCLINRB.js')).workspaceModelProjectTopology(C);if(!R)return;let{buildWorkspaceKnowledgeGraph:E}=await import('./workspace-knowledge-graph-3ZBPSAS7.js'),{readWorkspaceContract:$}=await import('./workspace-contract-3BWIRSVQ.js'),M=null;try{M=(await $({workspacePath:p})).contract;}catch{}let N=await E({workspacePath:p,workspace:{name:C.workspace.name,...C.workspace.profile?{profile:C.workspace.profile}:{}},projects:C.projects.map(A=>({id:A.name,path:A.path,...A.absolutePath?{absolutePath:A.absolutePath}:{},runtime:A.runtime,runtimeCandidates:A.runtimeCandidates,framework:A.framework,...A.kit?{kit:A.kit}:{}})),projectTopology:R,contract:M,now:new Date(C.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(C)}});console.log(JSON.stringify(k.publish(C,N)));}:void 0,emit:C=>{if(h)return;if(g){console.log(JSON.stringify(C));return}if(C.kind==="ready"){console.log(s.gray(` Ready: ${C.graph.nodeCount} nodes, ${C.graph.edgeCount} edges (hash ${C.modelHash.slice(0,12)})`));return}if(C.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${C.error??"unknown error"}`));return}if(C.kind==="unchanged"){console.log(s.gray(` No structural change (${C.mode}, ${C.durationMs}ms)`));return}let R=[];C.changedProjects.length>0&&R.push(`changed: ${C.changedProjects.join(", ")}`),C.addedProjects.length>0&&R.push(`added: ${C.addedProjects.join(", ")}`),C.removedProjects.length>0&&R.push(`removed: ${C.removedProjects.join(", ")}`),C.graph.edgesAdded.length>0&&R.push(`+${C.graph.edgesAdded.length} edges`),C.graph.edgesRemoved.length>0&&R.push(`-${C.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${C.mode}, ${C.durationMs}ms): ${R.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",x),process.removeListener("SIGTERM",x),!g&&!m&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let p=a("sync"),{syncWorkspaceProjects:v}=await import('./workspace-J4OGSSNO.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${j.basename(p)}`));let m=await v(p,n.json===true);await Jr(p,{silent:n.json===true});let{syncWorkspaceProjectLenses:h}=await import('./project-intelligence-lens-BA6JLXQH.js'),g=await h({workspacePath:p,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:k}=await import('./workspace-registry-summary-VSOBKAJG.js'),b=await k(p);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:p,registry:m,contractSynced:true,projectLenses:{synced:g.projects.length,skipped:g.skipped},registrySummary:b},null,2));}else if(t==="registry"){let p=a("registry"),v=e||"status";v!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${v}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:m,resolveWorkspaceRegisteredProjects:h}=await import('./workspace-registry-summary-VSOBKAJG.js'),g=await m(p);if(n.json){console.log(JSON.stringify(g,null,2));return}let k=await h(p);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${g.authority}`)),console.log(s.gray(` Projects: ${g.projectCount}`)),console.log(s.gray(` Summary: ${g.registrySummaryPath}`)),k.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let p=a("foundation"),v=e||"ensure";v!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${v}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:m}=await import('./workspace-foundation-3X5OBEMM.js'),h=await m(p,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(h,null,2));return}h.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${h.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let p=a("policy"),v=await Gm(p,e,r,o,n.json===true||i("--json"));v!==0&&process.exit(v);}else if(t==="contract"){let p=a("contract"),{buildWorkspaceContractGraph:v,readWorkspaceContract:m,verifyWorkspaceContract:h,writeWorkspaceContract:g,WORKSPACE_CONTRACT_PATH:k}=await import('./workspace-contract-3BWIRSVQ.js'),b=e||"inspect",x=d(),C=b==="graph"?void 0:x;try{if(b==="init"){let R=await g({workspacePath:p,outputPath:C,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(R,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${R.contractPath}`)),console.log(s.gray(` Projects: ${R.contract.projects.length}`));return}if(b==="inspect"){let R=await m({workspacePath:p,contractPath:C});if(n.json){console.log(JSON.stringify(R,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${R.contractPath}`)),console.log(s.gray(` Workspace: ${R.contract.workspace.name}`)),console.log(s.gray(` Projects: ${R.contract.projects.length}`)),console.log(s.gray(` Schema: v${R.contract.schemaVersion}`));return}if(b==="verify"){let R=await h({workspacePath:p,contractPath:C,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:E}=await import('./workspace-contract-3BWIRSVQ.js'),$=await E({workspacePath:p,result:R});if(n.json)console.log(JSON.stringify({...R,evidencePath:$},null,2));else {let M=R.status==="passed"?s.green:s.red;console.log(M(`\u2714 Workspace contract verification ${R.status}: ${R.contractPath}`)),console.log(s.gray(` Projects: ${R.projectCount}`));for(let N of R.checks){let A=N.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${A} ${N.id}: ${N.message}`));}for(let N of R.violations)console.log(s.gray(` Violation: ${N}`));}(R.status==="failed"||R.status!=="passed"&&n.strict)&&process.exit(1);return}if(b==="graph"){let R=await v({workspacePath:p,contractPath:C});if(x){let E=j.resolve(p,x);await O__default.outputFile(E,`${JSON.stringify(R,null,2)}
393
+ `,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace contract graph",{projectCount:R.graph.summary.projectCount,relationshipEdges:R.graph.summary.relationshipEdges,entityCount:R.graph.summary.entityCount,knowledgeRelations:R.graph.summary.knowledgeRelations,proofCount:R.graph.summary.proofCount},E),null,2)):(console.log(s.green("\u2714 Workspace contract graph exported as JSON")),console.log(s.gray(` Written: ${E}`)));return}if(n.json){console.log(JSON.stringify(R,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${R.contractPath}`)),console.log(s.gray(` Workspace: ${R.graph.workspace.name}`)),console.log(s.gray(` Projects: ${R.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${R.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${R.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${R.graph.summary.relationshipEdges} (${R.graph.summary.inferredEdges} inferred, ${R.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${R.graph.summary.connectedProjects}/${R.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(R.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(R.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${R.graph.summary.orphanProjects} \xB7 Hotspots: ${R.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${R.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${R.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${R.graph.summary.entityCount} entities \xB7 ${R.graph.summary.knowledgeRelations} relations \xB7 ${R.graph.summary.proofCount} proofs \xB7 ${R.graph.summary.providerCount} providers \xB7 ${R.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${R.graph.summary.portCount}`));for(let E of R.graph.nodes){let $=E.ports.map(N=>`${N.name}:${N.port}`).join(", ")||"none",M=E.operationalProfile?` risk=${E.operationalProfile.weight}/${E.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${E.id} (${E.runtime||"unknown"}${E.framework?`/${E.framework}`:""}) ports=${$} manifests=${E.files.manifests.length}${M}`));}for(let E of R.graph.edges){let $=E.type==="event"?`event:${E.label}`:E.label;console.log(s.gray(` ${E.from} -> ${E.to} [${$}]`));}if(R.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let E of R.graph.dependencyGraph.edges)console.log(s.gray(` ${E.from} -> ${E.to} [${E.kind}/${E.source}/${E.confidence}] evidence=${E.evidence.length}`));}for(let E of R.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${E.severity}: ${E.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${b}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${k}]`)),process.exit(1);}catch(R){n.json&&(console.log(JSON.stringify({command:`workspace contract ${b}`,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${b}.failed`,message:R.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${b} failed: ${R.message}`)),process.exit(1);}}else if(t==="share"){let p=a("share"),v=d()||e,{createWorkspaceShareBundle:m}=await import('./workspace-J4OGSSNO.js'),h=await m(p,{outputPath:v,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:p,bundlePath:h,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${h}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let p=a("export");try{let{exportWorkspaceArchive:v}=await import('./workspace-archive-ZBCKJHXS.js'),m=n.archiveCompression?.trim().toLowerCase()??"store";if(m!=="store"&&m!=="deflate")throw new Error("--archive-compression must be store or deflate.");let h=await v({workspacePath:p,outputPath:d()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:m});if(n.json){console.log(JSON.stringify(h,null,2));return}let g=(h.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.manifest.files.length}`)),console.log(s.gray(` Size: ${g} MB`)),h.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(v){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:v.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${v.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let p=r;p||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:v,inspectWorkspaceArchive:m,verifyWorkspaceArchive:h}=await import('./workspace-archive-ZBCKJHXS.js');try{if(e==="inspect"){let k=await m({archivePathOrUrl:p,safety:u()});if(n.json){console.log(JSON.stringify(k,null,2));return}let b=(k.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${k.archivePath}`)),console.log(s.gray(` Workspace: ${k.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${k.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${k.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${k.fileCount}`)),console.log(s.gray(` Payload: ${b} MB`));return}if(e==="doctor"){let k=await v({archivePathOrUrl:p,strict:n.strict===true||i("--strict"),safety:u()});if(n.json)console.log(JSON.stringify(k,null,2));else {let b=k.status==="passed"?s.green:k.status==="warning"?s.yellow:s.red;console.log(b(`\u2714 Workspace archive doctor ${k.status}: ${k.archivePath}`)),console.log(s.gray(` Workspace: ${k.workspaceName}`)),console.log(s.gray(` Files: ${k.fileCount}`));for(let x of k.checks){let C=x.status==="passed"?"\u2714":x.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${C} ${x.id}: ${x.message}`));}for(let x of k.recommendedActions)console.log(s.gray(` Next: ${x}`));}(k.status==="failed"||k.status==="warning"&&n.strict)&&process.exit(1);return}let g=await h({archivePathOrUrl:p,requireChecksums:n.strict===true||i("--strict"),safety:u()});if(n.json)console.log(JSON.stringify(g,null,2));else if(g.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${g.archivePath}`)),console.log(s.gray(` Files: ${g.verifiedFiles}/${g.fileCount}`));else {let k=g.status==="failed"?s.red:s.yellow;console.log(k(`\u274C Workspace archive verification ${g.status}: ${g.archivePath}`)),g.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${g.missingArchiveEntries.join(", ")}`)),g.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${g.extraArchiveEntries.join(", ")}`)),g.mismatches.length&&console.log(s.gray(` Mismatches: ${g.mismatches.map(b=>b.path).join(", ")}`)),g.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${g.missingChecksumFiles.join(", ")}`));}(g.status==="failed"||g.status==="warning"&&n.strict)&&process.exit(1);}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:p,error:{code:`workspace.archive.${e}.failed`,message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${g.message}`)),process.exit(1);}}else if(t==="connect"){let p=j.resolve(e||process.cwd());try{let v=await Ps({workspacePath:p,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(v.status==="preview"?`\u2714 Workspace connection preview: ${p}`:`\u2714 Workspace connected: ${p}`));for(let m of v.warnings)console.log(s.yellow(` \u26A0 ${m}`));}catch(v){let m=v instanceof Error?v.message:String(v);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:m}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${m}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let p=e;p||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let v=await js({archivePathOrUrl:p,outputPath:d(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:u()});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(v.status==="preview"?`\u2714 Workspace import preview: ${v.workspacePath}`:`\u2714 Workspace imported and registered: ${v.workspacePath}`));for(let m of v.warnings)console.log(s.yellow(` \u26A0 ${m}`));}else {let{hydrateWorkspaceArchive:v}=await import('./workspace-archive-ZBCKJHXS.js'),m=await v({archivePathOrUrl:p,outputPath:d(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:u()});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.dryRun?`\u2714 Workspace archive hydrate preview: ${m.outputPath}`:`\u2714 Workspace archive hydrated: ${m.outputPath}`)),console.log(s.gray(` Files: ${m.files.length}`)),m.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${m.manifest.workspaceName}`));}}catch(v){let m=v instanceof Error?v.message:String(v);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:m,context:{archivePathOrUrl:p,...d()?{outputPath:d()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:p,...d()?{outputPath:d()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:m}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${m}`)),process.exit(1);}}else if(t==="run"){let p=a(`run ${e||""}`.trim()),v=new Set(["init","test","build","start"]),m=e?.trim()??"";m||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .workspai/context.json commands")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2)),v.has(m)||(!/^[a-z][a-z0-9_-]*$/i.test(m)||m==="dev"||m==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${m}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),m==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let h=Os({raw:n.maxWorkers,operation:`workspace run ${m}`,json:n.json===true||i("--json")});if(m==="init"&&n.json!==true){let b=await Fs(p);b!==0&&process.exit(b);}let{runWorkspaceStage:g}=await import('./workspace-run-JTEIX4WA.js'),k=await g({workspacePath:p,stage:m,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:h,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true,planOnly:n.plan===true,runtime:n.runtime});n.json&&console.log(JSON.stringify(k,null,2)),k.summary.exitCode!==0&&process.exit(k.summary.exitCode);}else if(t==="explain"||t==="why"){let p=a(t),{parseWorkspaceExplainTarget:v}=await import('./workspace-explain-contract-JWFM22L4.js'),{buildWorkspaceExplain:m,writeWorkspaceExplainReport:h}=await import('./workspace-explain-NWP3JTFR.js'),g=(e??r??"").trim();!g&&n.scope&&(g=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),g||(g="release-blocked");let k=v(g);k||(console.log(s.red(`\u274C Invalid explain target: ${g}`)),process.exit(1));let b=await m({workspacePath:p,target:k}),x=n.write===true||i("--write"),C;if(x&&(C=await h(b,p,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$6(`workspace ${t}`,b,C),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${b.summary}`));for(let R of b.sections)console.log(s.bold(`
394
394
  ${R.title}`)),console.log(R.body);C&&console.log(s.gray(`
395
- Written: ${C}`));}else if(t==="trace"){let p=a("trace"),v=n.from||e;v||(console.log(s.red("\u274C workspace trace requires --from <diff-ref>")),console.log(s.gray(" npx workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{resolveWorkspaceTraceTarget:m}=await import('./workspace-explain-contract-ZL4NMLZI.js'),{buildWorkspaceExplain:h,writeWorkspaceExplainReport:g}=await import('./workspace-explain-QH4FXQW5.js'),k=m(v);(!k||k.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${v}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.workspai/reports/workspace-model-diff-last-run.json")),process.exit(1));let b=await h({workspacePath:p,target:k}),x=n.write===true||i("--write"),C;if(x&&(C=await g(b,p,"trace")),n.json){console.log(JSON.stringify(b$6("workspace trace",b,C),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${b.summary}`));for(let R of b.sections)console.log(s.bold(`
395
+ Written: ${C}`));}else if(t==="trace"){let p=a("trace"),v=n.from||e;v||(console.log(s.red("\u274C workspace trace requires --from <diff-ref>")),console.log(s.gray(" npx workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{resolveWorkspaceTraceTarget:m}=await import('./workspace-explain-contract-JWFM22L4.js'),{buildWorkspaceExplain:h,writeWorkspaceExplainReport:g}=await import('./workspace-explain-NWP3JTFR.js'),k=m(v);(!k||k.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${v}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.workspai/reports/workspace-model-diff-last-run.json")),process.exit(1));let b=await h({workspacePath:p,target:k}),x=n.write===true||i("--write"),C;if(x&&(C=await g(b,p,"trace")),n.json){console.log(JSON.stringify(b$6("workspace trace",b,C),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${b.summary}`));for(let R of b.sections)console.log(s.bold(`
396
396
  ${R.title}`)),console.log(R.body);C&&console.log(s.gray(`
397
397
  Written: ${C}`));}else if(t==="eval"){let p=a("eval"),v=(e||"status").toLowerCase(),{WORKSPACE_EVALUATION_LAST_RUN_PATH:m,WORKSPACE_EVALUATION_LIVE_PATH:h,appendWorkspaceEvaluationEvent:g,compareWorkspaceEvaluations:k,createWorkspaceEvaluation:b,finalizeWorkspaceEvaluation:x,readWorkspaceEvaluation:C,writeWorkspaceEvaluation:R}=await import('./workspace-intelligence-evaluation-CQDKOYZZ.js');if(v==="init"){let E=(r||"").trim(),$=(o||"workspace-intelligence").trim(),M=["full-corpus","grep","vector","graph","workspace-intelligence","custom"];(!E||!M.includes($))&&(console.log(s.red("\u274C workspace eval init requires <task> and an optional valid strategy.")),console.log(s.gray(` Strategies: ${M.join(" | ")}
398
- npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:N}=await import('./workspace-marker-7NHMDIRL.js'),A=await N(p),X=b({workspacePath:p,workspaceName:A?.name,taskId:E,strategy:$}),U=await R(p,X);if(n.json){console.log(JSON.stringify(b$6("workspace eval init",X,U),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${E}`)),console.log(s.gray(` Run: ${X.runId}`)),console.log(s.gray(` Strategy: ${X.configuration.strategy}`)),console.log(s.gray(` Live: ${U}`));return}if(v==="record"){!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace eval record requires --json and a stdin event.")),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace eval record requires piped JSON on stdin.")),process.exit(1));let{parseFeedbackStdinPayload:E,readStdinAll:$}=await import('./workspace-feedback-RQ4TGJW6.js'),M=E(await $());M||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let N=await g({workspacePath:p,payload:M});console.log(JSON.stringify(N,null,2));}catch(N){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:N instanceof Error?N.message:String(N),context:{workspacePath:p}}),null,2)),process.exit(1);}return}if(v==="report"){let E=await x({workspacePath:p}),$=d(),M=E.outputPath;if($){let N=j.resolve(p,$);j.resolve(E.outputPath)!==N&&await O__default.copy(E.outputPath,N,{overwrite:true}),M=N;}if(n.json){console.log(JSON.stringify(b$6("workspace eval report",E.report,M),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${E.report.runId}`)),console.log(s.gray(` Tokens: ${E.report.summary.tokens.observedTotal} \xB7 model calls ${E.report.summary.modelCalls} \xB7 tool calls ${E.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${E.report.summary.outcome.status}${E.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${M}`));return}if(v==="compare"){let E=(n.from||r||"").trim();E||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let $=await C(p,m),M=await C(p,E),N=k($,M);if(n.json){console.log(JSON.stringify(N,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${N.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${N.delta.tokens}`)),console.log(s.gray(` Reduction: ${N.delta.reductionPercent===null?"unavailable":`${N.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${N.comparableOutcome?"yes":"no"}`));return}if(v==="status"){let E;try{E=await C(p,h);}catch{E=await C(p,m);}if(n.json){console.log(JSON.stringify(E,null,2));return}console.log(s.green(`\u2714 Evaluation ${E.status}: ${E.configuration.taskId}`)),console.log(s.gray(` Run: ${E.runId}`)),console.log(s.gray(` Events: ${E.events.length}`)),console.log(s.gray(` Tokens: ${E.summary.tokens.observedTotal} (${E.summary.tokenSources.providerReported} provider-reported calls, ${E.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${v}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let p=a("feedback"),v=(e||"record").toLowerCase();v!=="record"&&(console.log(s.red(`Unknown feedback action: ${v}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace feedback record requires --json (stdin payload)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace feedback record requires piped JSON on stdin (not a TTY)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:m,parseFeedbackStdinPayload:h,readStdinAll:g}=await import('./workspace-feedback-RQ4TGJW6.js'),k=await g(),b=h(k);b||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let x=await m({workspacePath:p,payload:b});n.json?console.log(JSON.stringify(x,null,2)):x.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${x.historyPath}`))):console.log(s.red(`\u274C ${x.error??"Failed to record feedback"}`)),x.ok||process.exit(1);}else if(t==="goal"){let p=a("goal"),v=(e||"status").toLowerCase(),m=r?.trim(),{planVerifiedGoal:h,readVerifiedGoal:g,verifyVerifiedGoal:k,VERIFIED_GOAL_SCHEMA_VERSION:b}=await import('./verified-goal-2BRQZQBL.js'),x=C=>{if(n.json){console.log(JSON.stringify(C,null,2));return}let R=C.goal;console.log(C.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(C.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),R&&console.log(s.bold(` ${R.summary}`)),console.log(s.gray(` Goal: ${C.status.goalId}`)),console.log(s.gray(` Progress: ${C.status.progress.message}`)),console.log(s.gray(` State: ${C.status.state}`)),C.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${C.status.blockingReasons[0]}`)),C.status.nextActions.length>0&&console.log(s.gray(` Next: ${C.status.nextActions[0]}`)),console.log(s.gray(` Status: ${C.status.artifactPath}`));};if(v==="plan"){if(!m||!["release-readiness","dependency-security","test-coverage"].includes(m)){let N="Goal kind must be release-readiness, dependency-security, or test-coverage.";n.json?console.log(JSON.stringify(c$1({operation:"workspace goal plan",code:"workspace.goal.kind.invalid",message:N}),null,2)):console.log(s.red(`\u274C ${N}`)),process.exit(1);}let R=Number(n.target??80);if(!Number.isFinite(R)||R<0||R>100)throw new Error("--target must be a number from 0 to 100.");let E=["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"],$=n.runtime;if(m==="test-coverage"&&$!==void 0&&!E.includes($))throw new Error(`--runtime must be one of: ${E.join(", ")}.`);let M=await h({workspacePath:p,kind:m,scope:n.scope,target:R,runtime:m==="test-coverage"?$:void 0,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});x(M);}else if(v==="status"){if(!m)throw new Error("workspace goal status requires a goal id.");let C=await g(p,m);x({...C,resumed:C.status.state!=="verified"});}else if(v==="verify"){if(!m)throw new Error("workspace goal verify requires a goal id.");let C=await g(p,m),R=await k({workspacePath:p,goalId:m,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});x({goal:C.goal,status:R}),R.state!=="verified"&&process.exit(2);}else {let C=`Unknown workspace goal action: ${v}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:C,context:{schemaVersion:b,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${C}`)),process.exit(1);}}else if(t==="mcp"){let p=a("mcp"),v=(e||"serve").toLowerCase();v!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:v,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${v}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${v}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:m}=await import('./workspace-mcp-serve-ALIZV72K.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await m({workspacePath:p});}else if(t==="init"){n.json||(console.log(s.yellow("\u2139 workspace init is an alias of: npx workspai workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
398
+ npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:N}=await import('./workspace-marker-7NHMDIRL.js'),A=await N(p),X=b({workspacePath:p,workspaceName:A?.name,taskId:E,strategy:$}),U=await R(p,X);if(n.json){console.log(JSON.stringify(b$6("workspace eval init",X,U),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${E}`)),console.log(s.gray(` Run: ${X.runId}`)),console.log(s.gray(` Strategy: ${X.configuration.strategy}`)),console.log(s.gray(` Live: ${U}`));return}if(v==="record"){!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace eval record requires --json and a stdin event.")),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace eval record requires piped JSON on stdin.")),process.exit(1));let{parseFeedbackStdinPayload:E,readStdinAll:$}=await import('./workspace-feedback-RQ4TGJW6.js'),M=E(await $());M||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let N=await g({workspacePath:p,payload:M});console.log(JSON.stringify(N,null,2));}catch(N){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:N instanceof Error?N.message:String(N),context:{workspacePath:p}}),null,2)),process.exit(1);}return}if(v==="report"){let E=await x({workspacePath:p}),$=d(),M=E.outputPath;if($){let N=j.resolve(p,$);j.resolve(E.outputPath)!==N&&await O__default.copy(E.outputPath,N,{overwrite:true}),M=N;}if(n.json){console.log(JSON.stringify(b$6("workspace eval report",E.report,M),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${E.report.runId}`)),console.log(s.gray(` Tokens: ${E.report.summary.tokens.observedTotal} \xB7 model calls ${E.report.summary.modelCalls} \xB7 tool calls ${E.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${E.report.summary.outcome.status}${E.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${M}`));return}if(v==="compare"){let E=(n.from||r||"").trim();E||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let $=await C(p,m),M=await C(p,E),N=k($,M);if(n.json){console.log(JSON.stringify(N,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${N.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${N.delta.tokens}`)),console.log(s.gray(` Reduction: ${N.delta.reductionPercent===null?"unavailable":`${N.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${N.comparableOutcome?"yes":"no"}`));return}if(v==="status"){let E;try{E=await C(p,h);}catch{E=await C(p,m);}if(n.json){console.log(JSON.stringify(E,null,2));return}console.log(s.green(`\u2714 Evaluation ${E.status}: ${E.configuration.taskId}`)),console.log(s.gray(` Run: ${E.runId}`)),console.log(s.gray(` Events: ${E.events.length}`)),console.log(s.gray(` Tokens: ${E.summary.tokens.observedTotal} (${E.summary.tokenSources.providerReported} provider-reported calls, ${E.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${v}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let p=a("feedback"),v=(e||"record").toLowerCase();v!=="record"&&(console.log(s.red(`Unknown feedback action: ${v}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace feedback record requires --json (stdin payload)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace feedback record requires piped JSON on stdin (not a TTY)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:m,parseFeedbackStdinPayload:h,readStdinAll:g}=await import('./workspace-feedback-RQ4TGJW6.js'),k=await g(),b=h(k);b||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let x=await m({workspacePath:p,payload:b});n.json?console.log(JSON.stringify(x,null,2)):x.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${x.historyPath}`))):console.log(s.red(`\u274C ${x.error??"Failed to record feedback"}`)),x.ok||process.exit(1);}else if(t==="goal"){let p=a("goal"),v=(e||"status").toLowerCase(),m=r?.trim(),{planVerifiedGoal:h,readVerifiedGoal:g,verifyVerifiedGoal:k,VERIFIED_GOAL_SCHEMA_VERSION:b}=await import('./verified-goal-5OV4BALK.js'),x=C=>{if(n.json){console.log(JSON.stringify(C,null,2));return}let R=C.goal;console.log(C.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(C.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),R&&console.log(s.bold(` ${R.summary}`)),console.log(s.gray(` Goal: ${C.status.goalId}`)),console.log(s.gray(` Progress: ${C.status.progress.message}`)),console.log(s.gray(` State: ${C.status.state}`)),C.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${C.status.blockingReasons[0]}`)),C.status.nextActions.length>0&&console.log(s.gray(` Next: ${C.status.nextActions[0]}`)),console.log(s.gray(` Status: ${C.status.artifactPath}`));};if(v==="plan"){if(!m||!["release-readiness","dependency-security","test-coverage"].includes(m)){let N="Goal kind must be release-readiness, dependency-security, or test-coverage.";n.json?console.log(JSON.stringify(c$1({operation:"workspace goal plan",code:"workspace.goal.kind.invalid",message:N}),null,2)):console.log(s.red(`\u274C ${N}`)),process.exit(1);}let R=Number(n.target??80);if(!Number.isFinite(R)||R<0||R>100)throw new Error("--target must be a number from 0 to 100.");let E=["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"],$=n.runtime;if(m==="test-coverage"&&$!==void 0&&!E.includes($))throw new Error(`--runtime must be one of: ${E.join(", ")}.`);let M=await h({workspacePath:p,kind:m,scope:n.scope,target:R,runtime:m==="test-coverage"?$:void 0,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});x(M);}else if(v==="status"){if(!m)throw new Error("workspace goal status requires a goal id.");let C=await g(p,m);x({...C,resumed:C.status.state!=="verified"});}else if(v==="verify"){if(!m)throw new Error("workspace goal verify requires a goal id.");let C=await g(p,m),R=await k({workspacePath:p,goalId:m,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});x({goal:C.goal,status:R}),R.state!=="verified"&&process.exit(2);}else {let C=`Unknown workspace goal action: ${v}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:C,context:{schemaVersion:b,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${C}`)),process.exit(1);}}else if(t==="mcp"){let p=a("mcp"),v=(e||"serve").toLowerCase();v!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:v,result:"error",workspacePath:p,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${v}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${v}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:m}=await import('./workspace-mcp-serve-S5IXSJJL.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await m({workspacePath:p});}else if(t==="init"){n.json||(console.log(s.yellow("\u2139 workspace init is an alias of: npx workspai workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
399
399
  npx workspai init | npx workspai workspace init | npx workspai workspace run init
400
- `)));let p=a("init"),v=Os({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let g=await Fs(p);g!==0&&process.exit(g);}let{runWorkspaceStage:m}=await import('./workspace-run-JTEFCQYQ.js'),h=await m({workspacePath:p,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:v,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(h,null,2)),h.summary.exitCode!==0&&process.exit(h.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:Ir}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${Ir.join(", ")}`)),process.exit(1);});function Lr(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function fp(){let t=n=>n.replace(/\bnpx (?:rapidkit|workspai)\b/g,As),e=(n,a)=>{let i=t(n);if(i.length>65){console.log(s.cyan(` ${i}`)),console.log(s.gray(` ${a}`));return}console.log(s.cyan(` ${i.padEnd(67)} `)+s.gray(a));},r=(n,a)=>{console.log(s.white(` ${n}`));for(let i=0;i<a.length;i+=8)console.log(s.gray(` ${a.slice(i,i+8).join(" \xB7 ")}`));};console.log(s.white(`Usage:
400
+ `)));let p=a("init"),v=Os({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let g=await Fs(p);g!==0&&process.exit(g);}let{runWorkspaceStage:m}=await import('./workspace-run-JTEIX4WA.js'),h=await m({workspacePath:p,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:v,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(h,null,2)),h.summary.exitCode!==0&&process.exit(h.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:Ir}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${Ir.join(", ")}`)),process.exit(1);});function Lr(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function fp(){let t=n=>n.replace(/\bnpx (?:rapidkit|workspai)\b/g,As),e=(n,a)=>{let i=t(n);if(i.length>65){console.log(s.cyan(` ${i}`)),console.log(s.gray(` ${a}`));return}console.log(s.cyan(` ${i.padEnd(67)} `)+s.gray(a));},r=(n,a)=>{console.log(s.white(` ${n}`));for(let i=0;i<a.length;i+=8)console.log(s.gray(` ${a.slice(i,i+8).join(" \xB7 ")}`));};console.log(s.white(`Usage:
401
401
  `)),console.log(s.cyan(` ${As} <command> [options]
402
402
  `)),Km==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${As}.
403
403
  `)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems