workspai 0.47.0 → 0.49.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 (103) hide show
  1. package/README.md +247 -136
  2. package/contracts/agent-customization-pack.v1.json +5 -0
  3. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +4 -0
  4. package/contracts/extension-cli-compatibility.v1.json +8 -2
  5. package/contracts/published-contract-catalog.v1.json +33 -1
  6. package/contracts/runtime-command-surface.v1.json +163 -3
  7. package/contracts/workspace-intelligence/model-usage-event.v1.json +82 -0
  8. package/contracts/workspace-intelligence/workspace-graph-stream.v1.json +262 -0
  9. package/contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json +53 -0
  10. package/contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json +120 -0
  11. package/contracts/workspace-intelligence-architecture.v1.json +31 -2
  12. package/contracts/workspace-intelligence-chain.v1.json +44 -3
  13. package/dist/analyze-EEEU3MIF.js +1 -0
  14. package/dist/{artifact-remediation-plan-EPALZ2LC.js → artifact-remediation-plan-SPOUHMK5.js} +1 -1
  15. package/dist/autopilot-release-R4XRTWEM.js +1 -0
  16. package/dist/{chunk-2TEDAKP6.js → chunk-32OJDBIG.js} +1 -1
  17. package/dist/{chunk-ZDN7RHXJ.js → chunk-37CVKXBD.js} +1 -1
  18. package/dist/{chunk-YCL3I2JO.js → chunk-3NU32T4A.js} +1 -1
  19. package/dist/chunk-3VFA7D5T.js +1 -0
  20. package/dist/{chunk-CW7PGBIQ.js → chunk-4HDYADHT.js} +1 -1
  21. package/dist/{chunk-PBHP6JNY.js → chunk-54EP5CEV.js} +1 -1
  22. package/dist/{chunk-NOFM7MNA.js → chunk-AFL3ACCR.js} +1 -1
  23. package/dist/{chunk-MEMHNE7Y.js → chunk-BFLJ2R4D.js} +1 -1
  24. package/dist/{chunk-6SWRNA47.js → chunk-BGPXQQNY.js} +1 -1
  25. package/dist/chunk-BMWFQXGW.js +1 -0
  26. package/dist/{chunk-2GHUZDYA.js → chunk-CRHYBQI3.js} +1 -1
  27. package/dist/{chunk-KZZ36CK5.js → chunk-E2KJ5QWY.js} +1 -1
  28. package/dist/{chunk-BSRVO52Y.js → chunk-EKZLUMCS.js} +2 -2
  29. package/dist/{chunk-76YOPAOT.js → chunk-ESLPI3XZ.js} +1 -1
  30. package/dist/{chunk-DV6GJD4K.js → chunk-HDXNIN4N.js} +1 -1
  31. package/dist/{chunk-TNQI5VCW.js → chunk-HZDXO65G.js} +14 -14
  32. package/dist/{chunk-COARSXRC.js → chunk-J5ENLXDF.js} +1 -1
  33. package/dist/{chunk-QDWYIRHR.js → chunk-K4X3DM7R.js} +1 -1
  34. package/dist/chunk-LHOZXC2M.js +2 -0
  35. package/dist/{chunk-RWRLFSKW.js → chunk-NAJCUQ4X.js} +1 -1
  36. package/dist/{chunk-ZM5NQ5Z2.js → chunk-OW42TZFB.js} +1 -1
  37. package/dist/{chunk-SK6XRKGG.js → chunk-P3D5YQB2.js} +1 -1
  38. package/dist/{chunk-TWNFECMN.js → chunk-PHXQR6PX.js} +1 -1
  39. package/dist/{chunk-ITCAMC2E.js → chunk-PRTR2DQ2.js} +1 -1
  40. package/dist/{chunk-7VLCK5JW.js → chunk-RHQW3DTP.js} +1 -1
  41. package/dist/{chunk-22NJ2ZMG.js → chunk-T4YR4RAI.js} +1 -1
  42. package/dist/{chunk-VBSQ7MF6.js → chunk-TIE2XMGH.js} +20 -20
  43. package/dist/{chunk-HSGFUKCN.js → chunk-VU7NZHPM.js} +1 -1
  44. package/dist/{chunk-U5EZHZBX.js → chunk-YJZOMRAS.js} +1 -1
  45. package/dist/{create-7JKJDAQV.js → create-S64IWHAP.js} +1 -1
  46. package/dist/{doctor-PGPNIS76.js → doctor-4NNUDNGZ.js} +1 -1
  47. package/dist/{dotnet-webapi-clean-6TVFBTVI.js → dotnet-webapi-clean-A6MVDYXX.js} +4 -4
  48. package/dist/{gofiber-standard-2BL7GWZB.js → gofiber-standard-I5YPQG5V.js} +1 -1
  49. package/dist/{gogin-standard-XGP3KBXA.js → gogin-standard-VY2L4QT5.js} +1 -1
  50. package/dist/index.d.ts +35 -11
  51. package/dist/index.js +138 -136
  52. package/dist/{pipeline-IB6ILJSV.js → pipeline-LHTPE3DR.js} +1 -1
  53. package/dist/{springboot-standard-JJNUID6M.js → springboot-standard-55XKCBIZ.js} +4 -4
  54. package/dist/{workspace-H3QXBFGB.js → workspace-PJPRBUMQ.js} +1 -1
  55. package/dist/{workspace-agent-sync-C7SG2Z5W.js → workspace-agent-sync-662QHXGF.js} +1 -1
  56. package/dist/{workspace-context-BKQBKA4C.js → workspace-context-23YYCUCP.js} +1 -1
  57. package/dist/{workspace-contract-RPQQBQXR.js → workspace-contract-TU2I7GC2.js} +1 -1
  58. package/dist/{workspace-dependency-graph-23BI2HG7.js → workspace-dependency-graph-BP4EXYQ5.js} +1 -1
  59. package/dist/workspace-explain-MWUEN643.js +1 -0
  60. package/dist/workspace-explain-contract-ZPI3JXJU.js +1 -0
  61. package/dist/{workspace-feedback-WAID3IOE.js → workspace-feedback-SUVH2LUJ.js} +1 -1
  62. package/dist/{workspace-foundation-5OOJEO2D.js → workspace-foundation-WPLD7OEO.js} +1 -1
  63. package/dist/workspace-graph-stream-KAGGQPJT.js +1 -0
  64. package/dist/{workspace-history-C6OP3IAQ.js → workspace-history-BANOJRQ2.js} +1 -1
  65. package/dist/{workspace-intelligence-VKDL3H2J.js → workspace-intelligence-MFJE7W67.js} +1 -1
  66. package/dist/workspace-intelligence-evaluation-IPH7M3WV.js +1 -0
  67. package/dist/{workspace-intelligence-runner-LVALAZY7.js → workspace-intelligence-runner-OTYTHV6B.js} +1 -1
  68. package/dist/{workspace-knowledge-graph-FE2NTZKV.js → workspace-knowledge-graph-ARDC6HHG.js} +1 -1
  69. package/dist/workspace-knowledge-graph-export-UYAYFTWX.js +10 -0
  70. package/dist/workspace-mcp-serve-EZR6O76D.js +3 -0
  71. package/dist/{workspace-model-S33CIB2R.js → workspace-model-7OU2M3LE.js} +1 -1
  72. package/dist/{workspace-registry-summary-A3YDL63D.js → workspace-registry-summary-ORDK7A36.js} +1 -1
  73. package/dist/workspace-run-QND2SIYA.js +1 -0
  74. package/dist/{workspace-verify-ZGH3NXAH.js → workspace-verify-EBVL7FWT.js} +1 -1
  75. package/dist/workspace-watch-7HWGA5TF.js +1 -0
  76. package/docs/GLOSSARY.md +28 -24
  77. package/docs/OPEN_SOURCE_USER_SCENARIOS.md +11 -8
  78. package/docs/README.md +62 -23
  79. package/docs/README_CONTENT_CONTRACT.md +154 -0
  80. package/docs/ci-workflows.md +3 -3
  81. package/docs/commands-reference.md +16 -3
  82. package/docs/contracts/ARTIFACT_CATALOG.md +35 -20
  83. package/docs/contracts/README.md +3 -0
  84. package/docs/creating-workspaces-and-projects.md +16 -12
  85. package/docs/doctor-command.md +30 -28
  86. package/docs/examples/ci-agent-grounding.yml +1 -1
  87. package/docs/from-code-to-shared-understanding.md +2 -2
  88. package/docs/graph-benchmark-methodology.md +2 -2
  89. package/docs/workspace-intelligence-evaluation.md +149 -0
  90. package/docs/workspace-intelligence-runner.md +17 -6
  91. package/docs/workspace-knowledge-graph.md +31 -10
  92. package/docs/workspace-operations.md +13 -5
  93. package/package.json +9 -4
  94. package/templates/kits/fastapi-ddd/README.md.j2 +1 -1
  95. package/dist/analyze-UVXPRGYZ.js +0 -1
  96. package/dist/autopilot-release-5BQ6F5L2.js +0 -1
  97. package/dist/chunk-LNRAB7UY.js +0 -1
  98. package/dist/chunk-NRYS4CLR.js +0 -2
  99. package/dist/workspace-explain-WVN7JH3U.js +0 -1
  100. package/dist/workspace-explain-contract-SEFTVF6J.js +0 -1
  101. package/dist/workspace-mcp-serve-KT2I676Z.js +0 -3
  102. package/dist/workspace-run-M4LNJILC.js +0 -1
  103. package/dist/workspace-watch-EVBJTMV7.js +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {f as f$3,c as c$3,b as b$g,a as a$v}from'./chunk-52PBRX7F.js';import {a as a$j}from'./chunk-ICGWHIMK.js';import {c as c$2,b as b$7,a as a$w}from'./chunk-FPJNWPKU.js';import {b as b$6,a as a$7}from'./chunk-6SWRNA47.js';import {a as a$i}from'./chunk-2E6WGUN6.js';import {a as a$p}from'./chunk-FB7SCXAZ.js';import {a as a$n}from'./chunk-CV5HKU4P.js';import {a as a$o}from'./chunk-WDKNMTJQ.js';import {a as a$h}from'./chunk-3ZK2GU7C.js';import {b as b$9,d as d$4,a as a$6,c as c$5,f as f$8,e as e$5}from'./chunk-T3GJ7YVG.js';import {a as a$4}from'./chunk-22DT744Z.js';import {a as a$k}from'./chunk-HSGFUKCN.js';import {b as b$e,a as a$l,l as l$3}from'./chunk-TNQI5VCW.js';import {c as c$7,a as a$u}from'./chunk-NRYS4CLR.js';import {c as c$8,a as a$r}from'./chunk-ZM5NQ5Z2.js';import {f as f$6}from'./chunk-NOFM7MNA.js';import {f as f$5,d as d$7,e as e$3,g as g$1,a as a$s}from'./chunk-ZDN7RHXJ.js';import {a as a$m}from'./chunk-76YOPAOT.js';import {a as a$t}from'./chunk-COARSXRC.js';import {a as a$q}from'./chunk-RWRLFSKW.js';import {b as b$2,c as c$1,d,i,g,h as h$1,f as f$2,a as a$g}from'./chunk-SK6XRKGG.js';import {a,b as b$4}from'./chunk-NHN4QXPP.js';import {b as b$b,a as a$a}from'./chunk-THIOE2PB.js';import {h,a as a$1,l as l$2,k as k$2,m as m$1,j as j$1,n as n$2}from'./chunk-MER6ZBN2.js';import {a as a$c}from'./chunk-7VLCK5JW.js';import {d as d$6,i as i$5,b as b$f}from'./chunk-22NJ2ZMG.js';import {c as c$4,b as b$d,a as a$y}from'./chunk-FXQJX34Z.js';import {b as b$5,d as d$1,a as a$2,e as e$1,w,i as i$2,p as p$1,j,l as l$1,m,n as n$1,k as k$1,s as s$1,o as o$2,y,q as q$2,h as h$2,r as r$1,x as x$1,z,t,v,f as f$7,u}from'./chunk-TWNFECMN.js';export{r as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-TWNFECMN.js';import {i as i$3}from'./chunk-4KUIFXHM.js';import {d as d$5,a as a$b,b as b$c}from'./chunk-2TEDAKP6.js';import {a as a$e}from'./chunk-GZTYAEWX.js';import {a as a$8}from'./chunk-A5FBGRJA.js';import {b as b$i}from'./chunk-YCL3I2JO.js';import {a as a$3}from'./chunk-KB44JP4M.js';import {d as d$2,b as b$8,a as a$5,c as c$6,e as e$4}from'./chunk-LNRAB7UY.js';import {c,b as b$3,a as a$f}from'./chunk-Y45WZR5N.js';import {f,d as d$3,b as b$a}from'./chunk-7YHK5NM3.js';import {a as a$d}from'./chunk-TQEMLBAG.js';import {c as c$9}from'./chunk-RO73VVHW.js';import {f as f$1,e,a as a$9,d as d$8,i as i$4,g as g$3}from'./chunk-FTY7GGXJ.js';import {i as i$1,p,k,r,l,o as o$1,q,e as e$2,f as f$4,a as a$x,b as b$h,g as g$2,j as j$2}from'./chunk-5XATWNME.js';import {b as b$1,n,o,p as p$2,q as q$1,l as l$4,h as h$3,i as i$6,e as e$6,g as g$4,c as c$a}from'./chunk-EYJ2CQSK.js';import {c as c$b}from'./chunk-2FIX2MDC.js';import {Command,Option}from'commander';import s from'chalk';import b from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import gd from'vm';import*as I from'fs-extra';import I__default from'fs-extra';import x,{existsSync,promises,createWriteStream}from'fs';import pn,{tmpdir}from'os';import {execa}from'execa';import ft,{randomUUID,createVerify,createHash,createHmac}from'crypto';import sc from'http';import ac from'https';function Gc(){return i$6()}function Uc(t,e){return t==="py"?["-3",...e]:e}function Bc(t){return typeof t=="object"&&t!==null}async function Hc(t,e,o,r=c$b()){try{let n=await execa(t,e,{cwd:o,timeout:r,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function qc(t,e){let o=["-m","rapidkit",...t],r=Gc();for(let n of r){let a=await Hc(n,Uc(n,o),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return Bc(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 Ra(t,e){let o=await qc(["project","detect","--path",t,"--json"],e);return !o.ok||!o.data||o.data.schema_version!==1?{ok:false,command:o.command,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr}:o}var Aa=new Set(["create"]),nn=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),zc=new Set(["pip","poetry","venv","pipx","python"]);function _a(t){return typeof t=="string"&&zc.has(t)}function sn(t,e){return !t||Aa.has(t)?false:a$9.has(t)?true:e?.has(t)??false}function an(t,e=null){let o=t[0];return !o||o.startsWith("-")||Aa.has(o)||o==="init"?false:sn(o,e)?true:t.filter(n=>!n.startsWith("-")&&!nn.has(n)).length<=1?false:t.length>1}var Ot=b.join(pn.homedir(),".workspairc.json"),Yc=b.join(pn.homedir(),".rapidkitrc.json"),Qc=b.join(pn.homedir(),".rapidkit","config.json");function cn(t){try{if(!x.existsSync(t))return {};let e=x.readFileSync(t,"utf-8"),o=JSON.parse(e);return !o||typeof o!="object"||Array.isArray(o)?{}:o}catch{return {}}}function Ia(t){if(process.platform!=="win32")try{x.chmodSync(t,384);}catch{}}function Nt(){let t=cn(Ot),e=cn(Yc),o=cn(Qc);return x.existsSync(Ot)&&Ia(Ot),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??o.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??o.aiEnabled,telemetry:t.telemetry??e.telemetry??o.telemetry}}function qo(t){let o={...Nt(),...t};x.writeFileSync(Ot,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),Ia(Ot);}function lo(){return process.env.OPENAI_API_KEY||Nt().openaiApiKey||null}function dn(){return Nt().aiEnabled!==false}function un(){return Ot}function $a(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async o=>{let r=o.key;r?r.startsWith("sk-")||(console.log(s.red(`
2
+ import {f as f$3,c as c$3,b as b$h,a as a$w}from'./chunk-52PBRX7F.js';import {c as c$7,b as b$f,a as a$n}from'./chunk-3VFA7D5T.js';import {a as a$j}from'./chunk-ICGWHIMK.js';import {c as c$2,b as b$7,a as a$x}from'./chunk-FPJNWPKU.js';import {b as b$6,a as a$7}from'./chunk-BGPXQQNY.js';import {a as a$i}from'./chunk-2E6WGUN6.js';import {a as a$q}from'./chunk-FB7SCXAZ.js';import {a as a$o}from'./chunk-CV5HKU4P.js';import {a as a$p}from'./chunk-WDKNMTJQ.js';import {a as a$h}from'./chunk-3ZK2GU7C.js';import {b as b$9,d as d$4,a as a$6,c as c$5,f as f$8,e as e$5}from'./chunk-T3GJ7YVG.js';import {a as a$5}from'./chunk-22DT744Z.js';import {a as a$k}from'./chunk-VU7NZHPM.js';import {b as b$e,a as a$l,l as l$3}from'./chunk-HZDXO65G.js';import {c as c$8,a as a$v}from'./chunk-LHOZXC2M.js';import {c as c$9,a as a$s}from'./chunk-OW42TZFB.js';import {f as f$6}from'./chunk-AFL3ACCR.js';import {f as f$5,d as d$7,e as e$3,g as g$1,a as a$t}from'./chunk-37CVKXBD.js';import {a as a$m}from'./chunk-ESLPI3XZ.js';import {a as a$u}from'./chunk-J5ENLXDF.js';import {a as a$r}from'./chunk-NAJCUQ4X.js';import {b as b$2,c as c$1,d,i,g,h as h$1,f as f$2,a as a$g}from'./chunk-P3D5YQB2.js';import {a,b as b$4}from'./chunk-NHN4QXPP.js';import {b as b$b,a as a$a}from'./chunk-THIOE2PB.js';import {h,a as a$1,l as l$2,k as k$2,m as m$1,j as j$1,n as n$2}from'./chunk-MER6ZBN2.js';import {a as a$c}from'./chunk-RHQW3DTP.js';import {d as d$6,i as i$5,b as b$g}from'./chunk-T4YR4RAI.js';import {c as c$4,b as b$d,a as a$z}from'./chunk-FXQJX34Z.js';import {b as b$5,d as d$1,a as a$3,e as e$1,w,i as i$2,p as p$1,j,l as l$1,m,n as n$1,k as k$1,s as s$1,o as o$2,y,q as q$2,h as h$2,r as r$1,x,z,t,v,f as f$7,u}from'./chunk-PHXQR6PX.js';export{r as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-PHXQR6PX.js';import {i as i$3}from'./chunk-4KUIFXHM.js';import {d as d$5,a as a$b,b as b$c}from'./chunk-32OJDBIG.js';import {a as a$e}from'./chunk-GZTYAEWX.js';import {a as a$8}from'./chunk-A5FBGRJA.js';import {b as b$j}from'./chunk-3NU32T4A.js';import {a as a$4}from'./chunk-KB44JP4M.js';import {d as d$2,b as b$8,a as a$2,c as c$6,e as e$4}from'./chunk-BMWFQXGW.js';import {c,b as b$3,a as a$f}from'./chunk-Y45WZR5N.js';import {f,d as d$3,b as b$a}from'./chunk-7YHK5NM3.js';import {a as a$d}from'./chunk-TQEMLBAG.js';import {c as c$a}from'./chunk-RO73VVHW.js';import {f as f$1,e,a as a$9,d as d$8,i as i$4,g as g$3}from'./chunk-FTY7GGXJ.js';import {i as i$1,p,k,r,l,o as o$1,q,e as e$2,f as f$4,a as a$y,b as b$i,g as g$2,j as j$2}from'./chunk-5XATWNME.js';import {b as b$1,n,o,p as p$2,q as q$1,l as l$4,h as h$3,i as i$6,e as e$6,g as g$4,c as c$b}from'./chunk-EYJ2CQSK.js';import {c as c$c}from'./chunk-2FIX2MDC.js';import {Command,Option}from'commander';import s from'chalk';import b from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import wd from'vm';import*as O from'fs-extra';import O__default from'fs-extra';import E,{existsSync,promises,createWriteStream}from'fs';import pn,{tmpdir}from'os';import {execa}from'execa';import ft,{randomUUID,createVerify,createHash,createHmac}from'crypto';import cc from'http';import lc from'https';function Hc(){return i$6()}function qc(t,e){return t==="py"?["-3",...e]:e}function zc(t){return typeof t=="object"&&t!==null}async function Yc(t,e,o,r=c$c()){try{let n=await execa(t,e,{cwd:o,timeout:r,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function Qc(t,e){let o=["-m","rapidkit",...t],r=Hc();for(let n of r){let a=await Yc(n,qc(n,o),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return zc(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 Ia(t,e){let o=await Qc(["project","detect","--path",t,"--json"],e);return !o.ok||!o.data||o.data.schema_version!==1?{ok:false,command:o.command,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr}:o}var $a=new Set(["create"]),nn=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),Xc=new Set(["pip","poetry","venv","pipx","python"]);function Oa(t){return typeof t=="string"&&Xc.has(t)}function sn(t,e){return !t||$a.has(t)?false:a$9.has(t)?true:e?.has(t)??false}function an(t,e=null){let o=t[0];return !o||o.startsWith("-")||$a.has(o)||o==="init"?false:sn(o,e)?true:t.filter(n=>!n.startsWith("-")&&!nn.has(n)).length<=1?false:t.length>1}var Ot=b.join(pn.homedir(),".workspairc.json"),Zc=b.join(pn.homedir(),".rapidkitrc.json"),el=b.join(pn.homedir(),".rapidkit","config.json");function cn(t){try{if(!E.existsSync(t))return {};let e=E.readFileSync(t,"utf-8"),o=JSON.parse(e);return !o||typeof o!="object"||Array.isArray(o)?{}:o}catch{return {}}}function Na(t){if(process.platform!=="win32")try{E.chmodSync(t,384);}catch{}}function Nt(){let t=cn(Ot),e=cn(Zc),o=cn(el);return E.existsSync(Ot)&&Na(Ot),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??o.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??o.aiEnabled,telemetry:t.telemetry??e.telemetry??o.telemetry}}function qo(t){let o={...Nt(),...t};E.writeFileSync(Ot,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),Na(Ot);}function lo(){return process.env.OPENAI_API_KEY||Nt().openaiApiKey||null}function dn(){return Nt().aiEnabled!==false}function un(){return Ot}function Ma(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async o=>{let r=o.key;r?r.startsWith("sk-")||(console.log(s.red(`
3
3
  \u274C Invalid API key format (should start with sk-)
4
4
  `)),process.exit(1)):r=(await b$4([{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,qo({openaiApiKey:r}),console.log(s.green(`
5
5
  \u2705 OpenAI API key saved successfully!
@@ -20,7 +20,7 @@ Cancelled
20
20
  \u274C Invalid action: ${o}`)),console.log(s.gray(`Use: workspai config ai enable|disable
21
21
  `)),process.exit(1));let r=o==="enable";qo({aiEnabled:r}),console.log(s.green(`
22
22
  \u2705 AI features ${r?"enabled":"disabled"}
23
- `));});}var po=null,zo=false,mn=null;async function Xc(){return mn||(mn=(await import('openai')).default),mn}function Oa(){zo=true;}function Na(t){let o=new Array(1536),r=0;for(let a=0;a<t.length;a++)r=(r<<5)-r+t.charCodeAt(a),r=r&r;for(let a=0;a<1536;a++)r=r*1664525+1013904223&4294967295,o[a]=r/4294967295*2-1;let n=Math.sqrt(o.reduce((a,i)=>a+i*i,0));return o.map(a=>a/n)}async function Yo(t){if(!t.trim()){po=null;return}let e=await Xc();po=new e({apiKey:t});}function Ma(){if(!po)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return po}async function gn(t){return zo?Na(t):(await Ma().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function Ta(t){return zo?t.map(Na):(await Ma().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(r=>r.embedding)}function Wa(){return po!==null}function Mt(){return zo}function fn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Zc(t){return !t||typeof t!="object"?{}:t}var yn=[{id:"authentication-core",name:"Authentication Core",category:"auth",description:"Complete authentication system with password hashing, JWT tokens, OAuth 2.0, and secure session management",longDescription:"Production-ready authentication with bcrypt password hashing, JWT access/refresh tokens, OAuth 2.0 providers (Google, GitHub, etc), rate limiting, and security best practices.",keywords:["auth","login","password","jwt","oauth","token","authentication","security","signin","signup"],framework:"both",dependencies:[],useCases:["User login and logout","Password reset flow","OAuth social login (Google, GitHub)","JWT authentication","Secure session management","Token refresh","Rate limiting"]},{id:"users-core",name:"Users Core",category:"auth",description:"User management system with profiles, roles, permissions, and user CRUD operations",longDescription:"Complete user management with user profiles, role-based access control (RBAC), permissions, user search, soft delete, and audit trails.",keywords:["user","profile","role","permission","rbac","management","admin","accounts"],framework:"both",dependencies:["authentication-core"],useCases:["User registration","User profile management","Role management (admin, user, etc)","Permission system","User administration dashboard","Soft delete users"]},{id:"session-management",name:"Session Management",category:"auth",description:"Secure session handling with Redis storage, session rotation, and device tracking",longDescription:"Advanced session management with Redis-backed storage, automatic session rotation, device fingerprinting, IP tracking, and session revocation.",keywords:["session","redis","cookie","storage","device","tracking"],framework:"both",dependencies:["authentication-core","redis-cache"],useCases:["User session management","Remember me functionality","Device tracking","Session security","Logout from all devices","Session expiration"]},{id:"db-postgres",name:"PostgreSQL",category:"database",description:"PostgreSQL integration with async SQLAlchemy, migrations, connection pooling, and query optimization",longDescription:"Production-ready PostgreSQL with async SQLAlchemy 2.0, Alembic migrations, connection pooling, query optimization, JSON support, and full-text search.",keywords:["postgres","postgresql","database","sql","sqlalchemy","migration","orm","relational"],framework:"both",dependencies:[],useCases:["Relational database","Complex SQL queries","Database transactions","Data integrity","Production-grade database","ACID compliance"]},{id:"db-mongodb",name:"MongoDB",category:"database",description:"MongoDB integration with Motor async driver, schema validation, and aggregation pipelines",longDescription:"Async MongoDB with Motor driver, Pydantic schema validation, aggregation pipelines, indexes, and Atlas integration.",keywords:["mongodb","mongo","nosql","document","database","motor"],framework:"both",dependencies:[],useCases:["Document storage","Flexible schema","Real-time data","JSON documents","Unstructured data","Analytics"]},{id:"stripe-payment",name:"Stripe Payment",category:"payment",description:"Stripe integration with payment intents, subscriptions, webhooks, and customer portal",longDescription:"Complete Stripe integration with Payment Intents API, subscription management, automatic webhooks, customer portal, refunds, and SCA compliance.",keywords:["stripe","payment","subscription","billing","checkout","webhook","credit card"],framework:"both",dependencies:[],useCases:["Accept credit card payments","Subscription billing","One-time payments","Checkout flow","Payment webhooks","Refunds and disputes"]},{id:"email",name:"Email",category:"communication",description:"Email sending with templates, SMTP/SendGrid/AWS SES support, and queue management",longDescription:"Production email system with Jinja2 templates, multiple providers (SMTP, SendGrid, AWS SES), queue management, retry logic, and bounce handling.",keywords:["email","mail","smtp","sendgrid","ses","template","notification"],framework:"both",dependencies:[],useCases:["Welcome emails","Password reset emails","Notifications","Marketing emails","Transactional emails","Email templates"]},{id:"sms",name:"SMS",category:"communication",description:"SMS sending with Twilio, verification codes, and delivery tracking",longDescription:"SMS integration with Twilio, verification codes, two-factor authentication, delivery tracking, and international support.",keywords:["sms","twilio","text","message","2fa","verification","otp"],framework:"both",dependencies:[],useCases:["2FA verification codes","SMS notifications","Phone verification","OTP generation","SMS alerts"]},{id:"redis-cache",name:"Redis Cache",category:"infrastructure",description:"Redis caching with decorators, TTL management, and cache invalidation patterns",longDescription:"Redis integration with async client, caching decorators, TTL management, cache invalidation, pub/sub, and rate limiting.",keywords:["redis","cache","memory","performance","speed","pubsub"],framework:"both",dependencies:[],useCases:["API response caching","Session storage","Rate limiting","Real-time features","Performance optimization","Pub/sub messaging"]},{id:"celery",name:"Celery",category:"infrastructure",description:"Background task processing with Celery, periodic tasks, and monitoring",longDescription:"Celery task queue with Redis/RabbitMQ backend, periodic tasks (cron), task monitoring, retry logic, and failure handling.",keywords:["celery","task","background","queue","async","worker","job","cron"],framework:"fastapi",dependencies:["redis-cache"],useCases:["Background email sending","Data processing","Report generation","Scheduled tasks","Long-running jobs"]},{id:"storage",name:"Storage",category:"infrastructure",description:"File storage with S3, local filesystem, and image processing",longDescription:"Unified storage interface for AWS S3, local files, image resizing, format conversion, CDN integration, and presigned URLs.",keywords:["storage","s3","file","upload","image","cdn","aws"],framework:"both",dependencies:[],useCases:["File uploads","Image storage","Document management","Profile pictures","Media files","CDN integration"]}],mt=null,hn=0,el=300*1e3;function tl(t){let e=Zc(t),o=e.slug||e.name||e.id||e.module_id||"",r=fn(e.keywords??e.tags);return {id:o,name:e.display_name||e.name||"",category:ol(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:r.map(n=>n.toLowerCase()),framework:rl(e.framework),dependencies:fn(e.dependencies),useCases:fn(e.use_cases??e.useCases)}}function ol(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function rl(t){if(!t)return "both";if(typeof t=="string"){if(t.toLowerCase().includes("fastapi"))return "fastapi";if(t.toLowerCase().includes("nest"))return "nestjs"}return "both"}async function nl(){try{let t=await g$3(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.trim(),o;try{o=JSON.parse(e);}catch{let n=e.indexOf("{"),a=e.indexOf("["),i=[n,a].filter(m=>m>=0);if(i.length===0)throw new Error("Python Core modules response did not contain JSON");let c=Math.min(...i),l=e[c]==="["?"]":"}",p=e.lastIndexOf(l);if(p<c)throw new Error("Python Core modules response contained incomplete JSON");o=JSON.parse(e.slice(c,p+1));}let r=[];if(Array.isArray(o))r=o;else if(o&&typeof o=="object"){let n=o;Array.isArray(n.modules)?r=n.modules:Array.isArray(n.data)&&(r=n.data);}return r.map(tl).filter(n=>n.id&&n.name)}catch(t){return console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",t.message),console.warn(" Using fallback module catalog (11 modules)"),yn}}async function Qo(){let t=Date.now();return Mt()?(mt=yn,hn=t,mt):(mt&&t-hn<el||(mt=await nl(),hn=t,mt.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),mt=yn)),mt)}var al=fileURLToPath(import.meta.url),La=b.dirname(al),Tt=null,Fa=new Map;function il(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function cl(t){let e=Fa.get(t.id);if(e)return e;let o=await gn(il(t));return Fa.set(t.id,o),o}function ll(){if(Tt)return Tt;let t=[b.join(La,"../../data/modules-embeddings.json"),b.join(La,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(x.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let o=x.readFileSync(e,"utf-8"),r=JSON.parse(o);if(Array.isArray(r)?Tt={model:"mock-or-text-embedding-3-small",dimension:r[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:r}:Tt=r,!Tt)throw new Error("failed to load embeddings data");return Tt}function Ja(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let o=0,r=0,n=0;for(let i=0;i<t.length;i++)o+=t[i]*e[i],r+=t[i]*t[i],n+=e[i]*e[i];let a=Math.sqrt(r)*Math.sqrt(n);return a===0?0:o/a}function Ka(t,e){let o=e.toLowerCase(),r=t.keywords.filter(n=>o.includes(n)||n.includes(o));return r.length>0?`Matches: ${r.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function Va(t,e=5){let o=await Qo(),r=await gn(t);if(Mt()){let i=await Promise.all(o.map(async c=>{let l=await cl(c);return {module:c,score:Ja(r,l),reason:Ka(c,t)}}));return i.sort((c,l)=>l.score-c.score),i.slice(0,e)}let a=ll().modules.map(i=>{let c=o.find(p=>p.id===i.id);if(!c)return null;let l=Ja(r,i.embedding);return {module:c,score:l,reason:Ka(c,t)}}).filter(i=>i!==null);return a.sort((i,c)=>c.score-i.score),a.slice(0,e)}var dl=fileURLToPath(import.meta.url),Ga=b.dirname(dl);function Ua(t){return t instanceof Error?t.message:String(t)}function ul(){return [b.join(Ga,"../../data/modules-embeddings.json"),b.join(Ga,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")]}function Ba(){let t=ul();for(let e of t)if(x.existsSync(e))try{let o=JSON.parse(x.readFileSync(e,"utf-8")),r=Array.isArray(o)?o:o.modules||[];return {exists:true,path:e,moduleCount:r.length,generatedAt:o.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function Zo(t=true,e){try{if(!Wa()&&!Mt())return console.log(s.red(`
23
+ `));});}var po=null,zo=false,mn=null;async function tl(){return mn||(mn=(await import('openai')).default),mn}function Ta(){zo=true;}function Wa(t){let o=new Array(1536),r=0;for(let a=0;a<t.length;a++)r=(r<<5)-r+t.charCodeAt(a),r=r&r;for(let a=0;a<1536;a++)r=r*1664525+1013904223&4294967295,o[a]=r/4294967295*2-1;let n=Math.sqrt(o.reduce((a,i)=>a+i*i,0));return o.map(a=>a/n)}async function Yo(t){if(!t.trim()){po=null;return}let e=await tl();po=new e({apiKey:t});}function Da(){if(!po)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return po}async function gn(t){return zo?Wa(t):(await Da().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function La(t){return zo?t.map(Wa):(await Da().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(r=>r.embedding)}function Fa(){return po!==null}function Mt(){return zo}function fn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function ol(t){return !t||typeof t!="object"?{}:t}var yn=[{id:"authentication-core",name:"Authentication Core",category:"auth",description:"Complete authentication system with password hashing, JWT tokens, OAuth 2.0, and secure session management",longDescription:"Production-ready authentication with bcrypt password hashing, JWT access/refresh tokens, OAuth 2.0 providers (Google, GitHub, etc), rate limiting, and security best practices.",keywords:["auth","login","password","jwt","oauth","token","authentication","security","signin","signup"],framework:"both",dependencies:[],useCases:["User login and logout","Password reset flow","OAuth social login (Google, GitHub)","JWT authentication","Secure session management","Token refresh","Rate limiting"]},{id:"users-core",name:"Users Core",category:"auth",description:"User management system with profiles, roles, permissions, and user CRUD operations",longDescription:"Complete user management with user profiles, role-based access control (RBAC), permissions, user search, soft delete, and audit trails.",keywords:["user","profile","role","permission","rbac","management","admin","accounts"],framework:"both",dependencies:["authentication-core"],useCases:["User registration","User profile management","Role management (admin, user, etc)","Permission system","User administration dashboard","Soft delete users"]},{id:"session-management",name:"Session Management",category:"auth",description:"Secure session handling with Redis storage, session rotation, and device tracking",longDescription:"Advanced session management with Redis-backed storage, automatic session rotation, device fingerprinting, IP tracking, and session revocation.",keywords:["session","redis","cookie","storage","device","tracking"],framework:"both",dependencies:["authentication-core","redis-cache"],useCases:["User session management","Remember me functionality","Device tracking","Session security","Logout from all devices","Session expiration"]},{id:"db-postgres",name:"PostgreSQL",category:"database",description:"PostgreSQL integration with async SQLAlchemy, migrations, connection pooling, and query optimization",longDescription:"Production-ready PostgreSQL with async SQLAlchemy 2.0, Alembic migrations, connection pooling, query optimization, JSON support, and full-text search.",keywords:["postgres","postgresql","database","sql","sqlalchemy","migration","orm","relational"],framework:"both",dependencies:[],useCases:["Relational database","Complex SQL queries","Database transactions","Data integrity","Production-grade database","ACID compliance"]},{id:"db-mongodb",name:"MongoDB",category:"database",description:"MongoDB integration with Motor async driver, schema validation, and aggregation pipelines",longDescription:"Async MongoDB with Motor driver, Pydantic schema validation, aggregation pipelines, indexes, and Atlas integration.",keywords:["mongodb","mongo","nosql","document","database","motor"],framework:"both",dependencies:[],useCases:["Document storage","Flexible schema","Real-time data","JSON documents","Unstructured data","Analytics"]},{id:"stripe-payment",name:"Stripe Payment",category:"payment",description:"Stripe integration with payment intents, subscriptions, webhooks, and customer portal",longDescription:"Complete Stripe integration with Payment Intents API, subscription management, automatic webhooks, customer portal, refunds, and SCA compliance.",keywords:["stripe","payment","subscription","billing","checkout","webhook","credit card"],framework:"both",dependencies:[],useCases:["Accept credit card payments","Subscription billing","One-time payments","Checkout flow","Payment webhooks","Refunds and disputes"]},{id:"email",name:"Email",category:"communication",description:"Email sending with templates, SMTP/SendGrid/AWS SES support, and queue management",longDescription:"Production email system with Jinja2 templates, multiple providers (SMTP, SendGrid, AWS SES), queue management, retry logic, and bounce handling.",keywords:["email","mail","smtp","sendgrid","ses","template","notification"],framework:"both",dependencies:[],useCases:["Welcome emails","Password reset emails","Notifications","Marketing emails","Transactional emails","Email templates"]},{id:"sms",name:"SMS",category:"communication",description:"SMS sending with Twilio, verification codes, and delivery tracking",longDescription:"SMS integration with Twilio, verification codes, two-factor authentication, delivery tracking, and international support.",keywords:["sms","twilio","text","message","2fa","verification","otp"],framework:"both",dependencies:[],useCases:["2FA verification codes","SMS notifications","Phone verification","OTP generation","SMS alerts"]},{id:"redis-cache",name:"Redis Cache",category:"infrastructure",description:"Redis caching with decorators, TTL management, and cache invalidation patterns",longDescription:"Redis integration with async client, caching decorators, TTL management, cache invalidation, pub/sub, and rate limiting.",keywords:["redis","cache","memory","performance","speed","pubsub"],framework:"both",dependencies:[],useCases:["API response caching","Session storage","Rate limiting","Real-time features","Performance optimization","Pub/sub messaging"]},{id:"celery",name:"Celery",category:"infrastructure",description:"Background task processing with Celery, periodic tasks, and monitoring",longDescription:"Celery task queue with Redis/RabbitMQ backend, periodic tasks (cron), task monitoring, retry logic, and failure handling.",keywords:["celery","task","background","queue","async","worker","job","cron"],framework:"fastapi",dependencies:["redis-cache"],useCases:["Background email sending","Data processing","Report generation","Scheduled tasks","Long-running jobs"]},{id:"storage",name:"Storage",category:"infrastructure",description:"File storage with S3, local filesystem, and image processing",longDescription:"Unified storage interface for AWS S3, local files, image resizing, format conversion, CDN integration, and presigned URLs.",keywords:["storage","s3","file","upload","image","cdn","aws"],framework:"both",dependencies:[],useCases:["File uploads","Image storage","Document management","Profile pictures","Media files","CDN integration"]}],mt=null,hn=0,rl=300*1e3;function nl(t){let e=ol(t),o=e.slug||e.name||e.id||e.module_id||"",r=fn(e.keywords??e.tags);return {id:o,name:e.display_name||e.name||"",category:sl(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:r.map(n=>n.toLowerCase()),framework:al(e.framework),dependencies:fn(e.dependencies),useCases:fn(e.use_cases??e.useCases)}}function sl(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function al(t){if(!t)return "both";if(typeof t=="string"){if(t.toLowerCase().includes("fastapi"))return "fastapi";if(t.toLowerCase().includes("nest"))return "nestjs"}return "both"}async function il(){try{let t=await g$3(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.trim(),o;try{o=JSON.parse(e);}catch{let n=e.indexOf("{"),a=e.indexOf("["),i=[n,a].filter(m=>m>=0);if(i.length===0)throw new Error("Python Core modules response did not contain JSON");let c=Math.min(...i),l=e[c]==="["?"]":"}",p=e.lastIndexOf(l);if(p<c)throw new Error("Python Core modules response contained incomplete JSON");o=JSON.parse(e.slice(c,p+1));}let r=[];if(Array.isArray(o))r=o;else if(o&&typeof o=="object"){let n=o;Array.isArray(n.modules)?r=n.modules:Array.isArray(n.data)&&(r=n.data);}return r.map(nl).filter(n=>n.id&&n.name)}catch(t){return console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",t.message),console.warn(" Using fallback module catalog (11 modules)"),yn}}async function Qo(){let t=Date.now();return Mt()?(mt=yn,hn=t,mt):(mt&&t-hn<rl||(mt=await il(),hn=t,mt.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),mt=yn)),mt)}var ll=fileURLToPath(import.meta.url),Ka=b.dirname(ll),Tt=null,Va=new Map;function pl(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function dl(t){let e=Va.get(t.id);if(e)return e;let o=await gn(pl(t));return Va.set(t.id,o),o}function ul(){if(Tt)return Tt;let t=[b.join(Ka,"../../data/modules-embeddings.json"),b.join(Ka,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if(E.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let o=E.readFileSync(e,"utf-8"),r=JSON.parse(o);if(Array.isArray(r)?Tt={model:"mock-or-text-embedding-3-small",dimension:r[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:r}:Tt=r,!Tt)throw new Error("failed to load embeddings data");return Tt}function Ga(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let o=0,r=0,n=0;for(let i=0;i<t.length;i++)o+=t[i]*e[i],r+=t[i]*t[i],n+=e[i]*e[i];let a=Math.sqrt(r)*Math.sqrt(n);return a===0?0:o/a}function Ua(t,e){let o=e.toLowerCase(),r=t.keywords.filter(n=>o.includes(n)||n.includes(o));return r.length>0?`Matches: ${r.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function Ba(t,e=5){let o=await Qo(),r=await gn(t);if(Mt()){let i=await Promise.all(o.map(async c=>{let l=await dl(c);return {module:c,score:Ga(r,l),reason:Ua(c,t)}}));return i.sort((c,l)=>l.score-c.score),i.slice(0,e)}let a=ul().modules.map(i=>{let c=o.find(p=>p.id===i.id);if(!c)return null;let l=Ga(r,i.embedding);return {module:c,score:l,reason:Ua(c,t)}}).filter(i=>i!==null);return a.sort((i,c)=>c.score-i.score),a.slice(0,e)}var gl=fileURLToPath(import.meta.url),Ha=b.dirname(gl);function qa(t){return t instanceof Error?t.message:String(t)}function fl(){return [b.join(Ha,"../../data/modules-embeddings.json"),b.join(Ha,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")]}function za(){let t=fl();for(let e of t)if(E.existsSync(e))try{let o=JSON.parse(E.readFileSync(e,"utf-8")),r=Array.isArray(o)?o:o.modules||[];return {exists:true,path:e,moduleCount:r.length,generatedAt:o.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function Zo(t=true,e){try{if(!Fa()&&!Mt())return console.log(s.red(`
24
24
  \u274C OpenAI not initialized`)),console.log(s.yellow("Please set your API key:")),console.log(s.white(" workspai config set-api-key")),console.log(s.gray(` OR set: export OPENAI_API_KEY="sk-..."
25
25
  `)),false;console.log(s.blue(`
26
26
  \u{1F916} Generating AI embeddings for Workspai modules...
@@ -28,17 +28,17 @@ Cancelled
28
28
  `));let r=o.length*50/1e6*.02;if(console.log(s.cyan(`\u{1F4B0} Estimated cost: ~$${r.toFixed(3)}`)),console.log(s.gray(` (Based on ${o.length} modules at $0.02/1M tokens)
29
29
  `)),t){let{confirm:i}=await b$4([{type:"confirm",name:"confirm",message:"Generate embeddings now?",default:true}]);if(!i)return console.log(s.yellow(`
30
30
  \u26A0\uFE0F Embeddings generation cancelled
31
- `)),false}let n=o.map(i=>`${i.name}. ${i.description}. ${i.longDescription}. Keywords: ${i.keywords.join(", ")}. Use cases: ${i.useCases.join(", ")}.`),a=b$a(`Generating embeddings for ${o.length} modules...`,{component:"ai",phase:"embeddings.generate"});try{let i=await Ta(n);a.succeed(`Generated embeddings for ${o.length} modules`);let c={model:"text-embedding-3-small",dimension:i[0].length,generated_at:new Date().toISOString(),modules:o.map((m,d)=>({id:m.id,name:m.name,embedding:i[d]}))},l=e||b.join(process.cwd(),"data","modules-embeddings.json"),p=b.dirname(l);return x.existsSync(p)||x.mkdirSync(p,{recursive:true}),x.writeFileSync(l,JSON.stringify(c,null,2)),console.log(s.green(`
31
+ `)),false}let n=o.map(i=>`${i.name}. ${i.description}. ${i.longDescription}. Keywords: ${i.keywords.join(", ")}. Use cases: ${i.useCases.join(", ")}.`),a=b$a(`Generating embeddings for ${o.length} modules...`,{component:"ai",phase:"embeddings.generate"});try{let i=await La(n);a.succeed(`Generated embeddings for ${o.length} modules`);let c={model:"text-embedding-3-small",dimension:i[0].length,generated_at:new Date().toISOString(),modules:o.map((m,d)=>({id:m.id,name:m.name,embedding:i[d]}))},l=e||b.join(process.cwd(),"data","modules-embeddings.json"),p=b.dirname(l);return E.existsSync(p)||E.mkdirSync(p,{recursive:true}),E.writeFileSync(l,JSON.stringify(c,null,2)),console.log(s.green(`
32
32
  \u2705 Embeddings generated successfully!`)),console.log(s.gray(`\u{1F4C1} Saved to: ${l}`)),console.log(s.gray(`\u{1F4CA} Size: ${o.length} modules, ${i[0].length} dimensions
33
- `)),true}catch(i){a.fail("Failed to generate embeddings");let c=Ua(i);return c.includes("429")?(console.log(s.red(`
33
+ `)),true}catch(i){a.fail("Failed to generate embeddings");let c=qa(i);return c.includes("429")?(console.log(s.red(`
34
34
  \u274C OpenAI API quota exceeded`)),console.log(s.yellow(`Please check your billing: https://platform.openai.com/account/billing
35
35
  `))):c.includes("401")?(console.log(s.red(`
36
36
  \u274C Invalid API key`)),console.log(s.yellow("Please set a valid API key:")),console.log(s.white(` workspai config set-api-key
37
37
  `))):console.log(s.red(`
38
38
  \u274C Error: ${c}
39
39
  `)),false}}catch(o){return console.log(s.red(`
40
- \u274C Failed to generate embeddings: ${Ua(o)}
41
- `)),false}}async function Ha(t=true){if(Ba().exists)return true;if(console.log(s.yellow(`
40
+ \u274C Failed to generate embeddings: ${qa(o)}
41
+ `)),false}}async function Ya(t=true){if(za().exists)return true;if(console.log(s.yellow(`
42
42
  \u26A0\uFE0F Module embeddings not found`)),console.log(s.gray(`AI recommendations require embeddings to be generated.
43
43
  `)),!t)return console.log(s.red("\u274C Cannot generate embeddings in non-interactive mode")),console.log(s.white(`Run: workspai ai generate-embeddings
44
44
  `)),false;let{action:o}=await b$4([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"\u{1F680} Generate embeddings now (OpenAI key for production, or mock mode for testing)",value:"generate"},{name:"\u{1F4DD} Show me how to generate them manually",value:"manual"},{name:"\u274C Cancel",value:"cancel"}]}]);return o==="generate"?await Zo(true):(o==="manual"&&(console.log(s.cyan(`
@@ -46,37 +46,37 @@ Cancelled
46
46
  `)),console.log(s.white("1. Get OpenAI API key from: https://platform.openai.com/api-keys")),console.log(s.white("2. Set the API key:")),console.log(s.gray(" workspai config set-api-key")),console.log(s.gray(` OR: export OPENAI_API_KEY="sk-..."
47
47
  `)),console.log(s.white("3. Generate embeddings:")),console.log(s.gray(` workspai ai generate-embeddings
48
48
  `)),console.log(s.cyan(`\u{1F4B0} Cost: ~$0.50 one-time
49
- `))),false)}async function qa(){let t=Ba();return t.exists?(console.log(s.blue(`
49
+ `))),false)}async function Qa(){let t=za();return t.exists?(console.log(s.blue(`
50
50
  \u{1F504} Updating embeddings...`)),console.log(s.gray(`Current: ${t.moduleCount} modules`)),console.log(s.gray(`Generated: ${t.generatedAt||"unknown"}
51
51
  `)),t.path?await Zo(true,t.path):false):(console.log(s.yellow(`
52
52
  \u26A0\uFE0F No existing embeddings found`)),console.log(s.gray(`Use: workspai ai generate-embeddings
53
- `)),false)}function wn(t){if(t&&typeof t=="object"){let e=t;return {message:typeof e.message=="string"?e.message:String(t),code:typeof e.code=="string"?e.code:void 0}}return {message:String(t)}}function za(t,e=0){console.log(JSON.stringify(t,null,2)),e!==0&&process.exit(e);}function Ya(t){let e=t.command("ai").description("AI-powered features");e.command("recommend").description("Get AI-powered module recommendations").argument("[query]",'What do you want to build? (e.g., "user authentication with email")').option("-n, --number <count>","Number of recommendations","5").option("--json","Output as JSON").action(async(o,r)=>{try{dn()||(r.json&&za({ok:false,error:{code:"AI_DISABLED",message:"AI features are disabled",remediation:"workspai config ai enable"}},1),console.log(s.yellow(`
53
+ `)),false)}function wn(t){if(t&&typeof t=="object"){let e=t;return {message:typeof e.message=="string"?e.message:String(t),code:typeof e.code=="string"?e.code:void 0}}return {message:String(t)}}function Xa(t,e=0){console.log(JSON.stringify(t,null,2)),e!==0&&process.exit(e);}function Za(t){let e=t.command("ai").description("AI-powered features");e.command("recommend").description("Get AI-powered module recommendations").argument("[query]",'What do you want to build? (e.g., "user authentication with email")').option("-n, --number <count>","Number of recommendations","5").option("--json","Output as JSON").action(async(o,r)=>{try{dn()||(r.json&&Xa({ok:false,error:{code:"AI_DISABLED",message:"AI features are disabled",remediation:"workspai config ai enable"}},1),console.log(s.yellow(`
54
54
  \u26A0\uFE0F AI features are disabled`)),console.log(s.gray(`Enable with: workspai config ai enable
55
55
  `)),process.exit(1));let n=lo();n?await Yo(n):(r.json||(console.log(s.yellow(`
56
56
  \u26A0\uFE0F OpenAI API key not configured - using MOCK MODE for testing
57
57
  `)),console.log(s.gray("\u{1F4DD} Note: Mock embeddings provide approximate results for testing.")),console.log(s.gray(` For production, configure your OpenAI API key:
58
58
  `)),console.log(s.white(" 1. Get your key from: https://platform.openai.com/api-keys")),console.log(s.white(" 2. Configure it: workspai config set-api-key")),console.log(s.gray(` OR set: export OPENAI_API_KEY="sk-proj-..."
59
- `))),Oa());let a=o;a||(a=(await b$4([{type:"input",name:"query",message:"\u{1F916} What do you want to build?",validate:h=>h.length===0?"Please enter a description":h.length<3?"Please be more specific (at least 3 characters)":true}])).query),r.json||console.log(s.blue(`
59
+ `))),Ta());let a=o;a||(a=(await b$4([{type:"input",name:"query",message:"\u{1F916} What do you want to build?",validate:w=>w.length===0?"Please enter a description":w.length<3?"Please be more specific (at least 3 characters)":true}])).query),r.json||console.log(s.blue(`
60
60
  \u{1F916} Analyzing your request...
61
- `)),!n||await Ha(!r.json)||(r.json&&za({ok:false,query:a,error:{code:"EMBEDDINGS_MISSING",message:"Module embeddings are not available",remediation:"workspai ai generate-embeddings"}},1),console.log(s.yellow(`
61
+ `)),!n||await Ya(!r.json)||(r.json&&Xa({ok:false,query:a,error:{code:"EMBEDDINGS_MISSING",message:"Module embeddings are not available",remediation:"workspai ai generate-embeddings"}},1),console.log(s.yellow(`
62
62
  \u26A0\uFE0F Cannot proceed without embeddings
63
- `)),process.exit(1));let c=parseInt(r.number,10),l=await Va(a,c);if(l.length===0||l[0].score<.3)if(console.log(s.yellow(`
63
+ `)),process.exit(1));let c=parseInt(r.number,10),l=await Ba(a,c);if(l.length===0||l[0].score<.3)if(console.log(s.yellow(`
64
64
  \u26A0\uFE0F No matching modules found in RapidKit Core registry.
65
65
  `)),console.log(s.cyan(`\u{1F4A1} Options:
66
66
  `)),console.log(s.white("1. Create custom module:")),console.log(s.gray(" npx workspai modules scaffold <name> --category <category>")),console.log(s.gray(` Example: npx workspai modules scaffold blockchain-integration --category integrations
67
67
  `)),console.log(s.white("2. Search with different keywords")),console.log(s.gray(` Try more general terms (e.g., "storage" instead of "blockchain")
68
- `)),console.log(s.white("3. Request feature:")),console.log(s.gray(` https://github.com/rapidkitlabs/workspai/issues
68
+ `)),console.log(s.white("3. Request feature:")),console.log(s.gray(` https://github.com/chistiq/workspai/issues
69
69
  `)),l.length>0)console.log(s.yellow(`\u26A0\uFE0F Low confidence matches found:
70
70
  `));else return;if(r.json){console.log(JSON.stringify({query:a,recommendations:l},null,2));return}console.log(s.green.bold(`\u{1F4E6} Recommended Modules:
71
- `)),l.forEach((d,h)=>{let g=(d.score*100).toFixed(1),k=d.score>.8?" \u2B50":"";console.log(s.bold(`${h+1}. ${d.module.name}${k}`)),console.log(s.gray(` ${d.module.description}`)),console.log(s.cyan(` Match: ${g}%`)+s.gray(` - ${d.reason}`)),console.log(s.yellow(` Category: ${d.module.category}`)),d.module.dependencies.length>0&&console.log(s.magenta(` Requires: ${d.module.dependencies.join(", ")}`)),console.log();});let p=l.slice(0,3).map(d=>d.module.id);console.log(s.cyan("\u{1F4A1} Quick install (top 3):")),console.log(s.white(` npx workspai add module ${p.join(" ")}
72
- `));let{shouldInstall:m}=await b$4([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(m){let{selectedModules:d}=await b$4([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:l.map(g=>({name:`${g.module.name} - ${g.module.description}`,value:g.module.id,checked:g.score>.7}))}]),h=d;if(h.length>0){console.log(s.blue(`
73
- \u{1F4E6} Installing ${h.length} modules...
74
- `)),console.log(s.gray(`Command: npx workspai add module ${h.join(" ")}`));let k=w(process.cwd()).commandMap.add;if(!k||k.status!=="supported"){console.log(s.red(`
75
- \u274C RapidKit Core modules are not available for this project.`)),console.log(s.gray(` ${k?.reason??"Module commands require RapidKit Core module-enabled project metadata."}
76
- `));return}let C=await f$1(["add","module",...h],{cwd:process.cwd()});console.log(C===0?s.green(`
71
+ `)),l.forEach((d,w)=>{let g=(d.score*100).toFixed(1),P=d.score>.8?" \u2B50":"";console.log(s.bold(`${w+1}. ${d.module.name}${P}`)),console.log(s.gray(` ${d.module.description}`)),console.log(s.cyan(` Match: ${g}%`)+s.gray(` - ${d.reason}`)),console.log(s.yellow(` Category: ${d.module.category}`)),d.module.dependencies.length>0&&console.log(s.magenta(` Requires: ${d.module.dependencies.join(", ")}`)),console.log();});let p=l.slice(0,3).map(d=>d.module.id);console.log(s.cyan("\u{1F4A1} Quick install (top 3):")),console.log(s.white(` npx workspai add module ${p.join(" ")}
72
+ `));let{shouldInstall:m}=await b$4([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(m){let{selectedModules:d}=await b$4([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:l.map(g=>({name:`${g.module.name} - ${g.module.description}`,value:g.module.id,checked:g.score>.7}))}]),w$1=d;if(w$1.length>0){console.log(s.blue(`
73
+ \u{1F4E6} Installing ${w$1.length} modules...
74
+ `)),console.log(s.gray(`Command: npx workspai add module ${w$1.join(" ")}`));let P=w(process.cwd()).commandMap.add;if(!P||P.status!=="supported"){console.log(s.red(`
75
+ \u274C RapidKit Core modules are not available for this project.`)),console.log(s.gray(` ${P?.reason??"Module commands require RapidKit Core module-enabled project metadata."}
76
+ `));return}let j=await f$1(["add","module",...w$1],{cwd:process.cwd()});console.log(j===0?s.green(`
77
77
  \u2705 Selected modules installed successfully
78
78
  `):s.red(`
79
- \u274C Module installation failed (exit code: ${C})
79
+ \u274C Module installation failed (exit code: ${j})
80
80
  `));}else console.log(s.gray(`
81
81
  No modules selected
82
82
  `));}}catch(n){let a=wn(n);f.error(`
@@ -101,33 +101,33 @@ No modules selected
101
101
  `))),process.exit(r?0:1);}catch(o){let r=wn(o);f.error("Failed to generate embeddings:",r.message),process.exit(1);}}),e.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let o=lo();o||(console.log(s.red(`
102
102
  \u274C OpenAI API key not configured
103
103
  `)),console.log(s.white(`Set your API key: workspai config set-api-key
104
- `)),process.exit(1)),Yo(o);let r=await qa();process.exit(r?0:1);}catch(o){let r=wn(o);f.error("Failed to update embeddings:",r.message),process.exit(1);}});}var gl="rapidkit.product-factory-plan.v1",fl="rapidkit.private-product-manifest.v1";function Qa(t){let e=process.argv;for(let o=0;o<e.length;o+=1){let r=e[o];if(r===t){let n=e[o+1];return n&&!n.startsWith("-")?n:void 0}if(r.startsWith(`${t}=`))return r.slice(t.length+1)}}function mo(t,e=""){return typeof t=="string"&&t.trim()?t.trim():e}function kn(t){return typeof t=="string"&&t.trim()?t.trim():null}function hl(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function Xa(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function ei(t){if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(t))throw new Error(`Invalid product slug "${t}". Use lowercase letters, numbers, and hyphens.`)}function yl(t,e,o){let r=mo(t.slug);if(!r)throw new Error(`Backlog product at index ${e} is missing slug.`);ei(r);let n=Xa(t.modules),a=Xa(t.moduleGaps);return {rank:hl(t.rank,e+1),slug:r,title:mo(t.title,r),category:mo(t.category,"Uncategorized"),tier:mo(t.tier,"pro"),summary:mo(t.summary),modules:n,moduleGaps:a,recommendedKit:o,workspaceProfile:"enterprise",readiness:{status:a.length>0?"blocked-by-module-gaps":"ready-for-private-manifest",blockingGaps:a}}}function wl(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Backlog must be a JSON object.");return t}async function kl(t){let e=b.resolve(process.cwd(),t),o=wl(await I__default.readJson(e));if(!Array.isArray(o.products))throw new Error("Backlog must contain a products array.");return {absolutePath:e,payload:o}}function vl(t,e){let o=[...t];if(e.tier){let r=e.tier.toLowerCase();o=o.filter(n=>n.tier.toLowerCase()===r);}if(e.category){let r=e.category.toLowerCase();o=o.filter(n=>n.category.toLowerCase()===r);}if(e.limit){let r=Number.parseInt(e.limit,10);if(!Number.isInteger(r)||r<1)throw new Error("--limit must be a positive integer.");o=o.slice(0,r);}return o}async function ti(t){let e=t.kit?.trim()||"fastapi.standard",{absolutePath:o,payload:r}=await kl(t.backlogPath),n=r.products,a=n.map((m,d)=>yl(m,d,e)),i=vl(a,t),c=new Set(i.flatMap(m=>m.modules)),l=i.flatMap(m=>m.moduleGaps),p=i.filter(m=>m.readiness.status==="ready-for-private-manifest").length;return {schemaVersion:gl,generatedAt:(t.now??new Date).toISOString(),source:{backlogPath:o,backlogSchemaVersion:kn(r.schemaVersion),purpose:kn(r.purpose),publicationRule:kn(r.publicationRule)},defaults:{kit:e,workspaceProfile:"enterprise",projectSlug:"api"},stats:{totalProducts:n.length,plannedProducts:i.length,readyProducts:p,blockedProducts:i.length-p,uniqueModules:c.size,knownModuleGaps:l.length},products:i}}function Dt(t){return JSON.stringify(t,null,2)}function Pl(t){return `sha256:${ft.createHash("sha256").update(Dt(t)).digest("hex")}`}function bl(t){return t.replace(/\\/g,"/")}async function jl(t){let e=await ti({backlogPath:t.backlogPath,kit:t.kit,now:t.now}),o=e.products.find(a=>a.slug===t.slug);if(!o)throw new Error(`Product "${t.slug}" was not found in backlog.`);let r=t.outputRoot||"../workspai-examples-pro",n={schemaVersion:fl,generatedAt:e.generatedAt,product:{rank:o.rank,slug:o.slug,title:o.title,category:o.category,tier:o.tier,summary:o.summary},workspace:{name:o.slug,profile:"enterprise",outputHint:bl(b.join(r,o.slug))},projects:[{slug:"api",kit:o.recommendedKit,runtime:"python",framework:"fastapi",modules:o.modules,moduleGaps:o.moduleGaps}],factory:{sourceBacklogPath:e.source.backlogPath,manifestChecksum:"",requiredCommands:[`npx workspai create workspace ${o.slug} --yes --profile enterprise`,`npx workspai create project ${o.recommendedKit} api --yes --skip-install`,"npx workspai init","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"],releaseEvidencePath:`.workspai/product-factory/${o.slug}/release-evidence.json`}};return {...n,factory:{...n.factory,manifestChecksum:Pl({...n,factory:{...n.factory,manifestChecksum:""}})}}}async function Za(t,e,o=false){let r=b.resolve(process.cwd(),t);if(!o&&await I__default.pathExists(r))throw new Error(`Refusing to overwrite existing file: ${r}. Use --force.`);await I__default.ensureDir(b.dirname(r)),await I__default.writeFile(r,`${Dt(e)}
105
- `,"utf-8");}function Cl(t,e){let o=b.join(".workspai","product-factory","manifests",`${e}.manifest.json`);return t?t.endsWith(".json")?t:b.join(t,`${e}.manifest.json`):o}function Sl(t,e){console.log(s.bold(`
104
+ `)),process.exit(1)),Yo(o);let r=await Qa();process.exit(r?0:1);}catch(o){let r=wn(o);f.error("Failed to update embeddings:",r.message),process.exit(1);}});}var yl="rapidkit.product-factory-plan.v1",wl="rapidkit.private-product-manifest.v1";function ei(t){let e=process.argv;for(let o=0;o<e.length;o+=1){let r=e[o];if(r===t){let n=e[o+1];return n&&!n.startsWith("-")?n:void 0}if(r.startsWith(`${t}=`))return r.slice(t.length+1)}}function mo(t,e=""){return typeof t=="string"&&t.trim()?t.trim():e}function kn(t){return typeof t=="string"&&t.trim()?t.trim():null}function kl(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function ti(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function ri(t){if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(t))throw new Error(`Invalid product slug "${t}". Use lowercase letters, numbers, and hyphens.`)}function vl(t,e,o){let r=mo(t.slug);if(!r)throw new Error(`Backlog product at index ${e} is missing slug.`);ri(r);let n=ti(t.modules),a=ti(t.moduleGaps);return {rank:kl(t.rank,e+1),slug:r,title:mo(t.title,r),category:mo(t.category,"Uncategorized"),tier:mo(t.tier,"pro"),summary:mo(t.summary),modules:n,moduleGaps:a,recommendedKit:o,workspaceProfile:"enterprise",readiness:{status:a.length>0?"blocked-by-module-gaps":"ready-for-private-manifest",blockingGaps:a}}}function Pl(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Backlog must be a JSON object.");return t}async function bl(t){let e=b.resolve(process.cwd(),t),o=Pl(await O__default.readJson(e));if(!Array.isArray(o.products))throw new Error("Backlog must contain a products array.");return {absolutePath:e,payload:o}}function jl(t,e){let o=[...t];if(e.tier){let r=e.tier.toLowerCase();o=o.filter(n=>n.tier.toLowerCase()===r);}if(e.category){let r=e.category.toLowerCase();o=o.filter(n=>n.category.toLowerCase()===r);}if(e.limit){let r=Number.parseInt(e.limit,10);if(!Number.isInteger(r)||r<1)throw new Error("--limit must be a positive integer.");o=o.slice(0,r);}return o}async function ni(t){let e=t.kit?.trim()||"fastapi.standard",{absolutePath:o,payload:r}=await bl(t.backlogPath),n=r.products,a=n.map((m,d)=>vl(m,d,e)),i=jl(a,t),c=new Set(i.flatMap(m=>m.modules)),l=i.flatMap(m=>m.moduleGaps),p=i.filter(m=>m.readiness.status==="ready-for-private-manifest").length;return {schemaVersion:yl,generatedAt:(t.now??new Date).toISOString(),source:{backlogPath:o,backlogSchemaVersion:kn(r.schemaVersion),purpose:kn(r.purpose),publicationRule:kn(r.publicationRule)},defaults:{kit:e,workspaceProfile:"enterprise",projectSlug:"api"},stats:{totalProducts:n.length,plannedProducts:i.length,readyProducts:p,blockedProducts:i.length-p,uniqueModules:c.size,knownModuleGaps:l.length},products:i}}function Dt(t){return JSON.stringify(t,null,2)}function Cl(t){return `sha256:${ft.createHash("sha256").update(Dt(t)).digest("hex")}`}function Sl(t){return t.replace(/\\/g,"/")}async function xl(t){let e=await ni({backlogPath:t.backlogPath,kit:t.kit,now:t.now}),o=e.products.find(a=>a.slug===t.slug);if(!o)throw new Error(`Product "${t.slug}" was not found in backlog.`);let r=t.outputRoot||"../workspai-examples-pro",n={schemaVersion:wl,generatedAt:e.generatedAt,product:{rank:o.rank,slug:o.slug,title:o.title,category:o.category,tier:o.tier,summary:o.summary},workspace:{name:o.slug,profile:"enterprise",outputHint:Sl(b.join(r,o.slug))},projects:[{slug:"api",kit:o.recommendedKit,runtime:"python",framework:"fastapi",modules:o.modules,moduleGaps:o.moduleGaps}],factory:{sourceBacklogPath:e.source.backlogPath,manifestChecksum:"",requiredCommands:[`npx workspai create workspace ${o.slug} --yes --profile enterprise`,`npx workspai create project ${o.recommendedKit} api --yes --skip-install`,"npx workspai init","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"],releaseEvidencePath:`.workspai/product-factory/${o.slug}/release-evidence.json`}};return {...n,factory:{...n.factory,manifestChecksum:Cl({...n,factory:{...n.factory,manifestChecksum:""}})}}}async function oi(t,e,o=false){let r=b.resolve(process.cwd(),t);if(!o&&await O__default.pathExists(r))throw new Error(`Refusing to overwrite existing file: ${r}. Use --force.`);await O__default.ensureDir(b.dirname(r)),await O__default.writeFile(r,`${Dt(e)}
105
+ `,"utf-8");}function El(t,e){let o=b.join(".workspai","product-factory","manifests",`${e}.manifest.json`);return t?t.endsWith(".json")?t:b.join(t,`${e}.manifest.json`):o}function Rl(t,e){console.log(s.bold(`
106
106
  Workspai Product Factory Plan
107
107
  `)),console.log(s.cyan("Products:"),s.white(String(t.stats.plannedProducts))),console.log(s.cyan("Ready:"),s.green(String(t.stats.readyProducts))),console.log(s.cyan("Blocked:"),s.yellow(String(t.stats.blockedProducts))),console.log(s.cyan("Unique modules:"),s.white(String(t.stats.uniqueModules))),console.log(s.cyan("Known gaps:"),s.yellow(String(t.stats.knownModuleGaps))),e&&console.log(s.gray(`
108
108
  Wrote plan: ${b.resolve(process.cwd(),e)}`)),console.log(s.gray(`
109
109
  Next: npx workspai product manifest create <slug> --from-backlog <file>
110
- `));}function xl(t,e){console.log(s.bold(`
110
+ `));}function Al(t,e){console.log(s.bold(`
111
111
  Workspai Private Product Manifest
112
112
  `)),console.log(s.cyan("Product:"),s.white(t.product.slug)),console.log(s.cyan("Kit:"),s.white(t.projects[0].kit)),console.log(s.cyan("Modules:"),s.white(String(t.projects[0].modules.length))),console.log(s.cyan("Module gaps:"),s.yellow(String(t.projects[0].moduleGaps.length))),console.log(s.cyan("Checksum:"),s.white(t.factory.manifestChecksum)),console.log(s.gray(`
113
113
  Wrote manifest: ${b.resolve(process.cwd(),e)}
114
- `));}function oi(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(o,r)=>{try{let n=r.output||Qa("--output"),a=await ti({backlogPath:o,kit:r.kit,tier:r.tier,category:r.category,limit:r.limit});a$3(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await Za(n,a,true),r.json?console.log(Dt(a)):Sl(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);r.json?console.log(Dt({ok:false,error:{message:a}})):console.error(s.red(`Product plan failed: ${a}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(o,r)=>{try{let n=r.output||Qa("--output");ei(o);let a=await jl({backlogPath:r.fromBacklog,slug:o,kit:r.kit,outputRoot:r.workspaceOutput});a$3(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=Cl(n,o);await Za(i,a,r.force===true),r.json?console.log(Dt(a)):xl(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);r.json?console.log(Dt({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var si="rapidkit-workspace-snapshot-v1",fo="rapidkit-workspace-snapshot-v2",El=si,ai="rapidkit-project-archive-v1",nt="workspai-archive.json",tr="rapidkit-archive.json",Rl=[".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"],Al=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),go={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function Ft(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function or(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 _l(t){try{let e=await I__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Il(t,e){if(!t)return e;let o=t.trim().toLowerCase();return ["true","yes","1","on"].includes(o)?true:["false","no","0","off"].includes(o)?false:e}async function $l(t){let e=o$1(t,"policies.yml").find(o=>existsSync(o))??l(t,"policies.yml");if(!await I__default.pathExists(e))return {...go};try{let o=await I__default.readFile(e,"utf-8"),r=(n,a)=>{let i=o.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return Il(i?.[1],a)};return {requireReasonForDestructiveOps:r("require_reason_for_destructive_ops",go.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:r("require_safety_snapshot_for_destructive_ops",go.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:r("allow_permanent_delete",go.allowPermanentDelete)}}catch{return {...go}}}function Ol(t){return l(t,"audit","events.jsonl")}async function Ge(t,e){let o={schema:"rapidkit-workspace-audit-event-v1",id:ft.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},r=Ol(t);return await I__default.ensureDir(b.dirname(r)),await I__default.appendFile(r,`${JSON.stringify(o)}
115
- `,"utf-8"),o}async function rr(t,e,o){let r=await $l(t);if(r.requireReasonForDestructiveOps&&!o.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(r.requireSafetySnapshotForDestructiveOps&&o.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(o.permanent&&!r.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return r}function vn(t=process.cwd()){let e=b.resolve(t),o=b.resolve(pn.tmpdir());for(;;){if(e!==o&&f$4(e))return e;let r=b.dirname(e);if(r===e)return null;e=r;}}function ht(t){let e=t?b.resolve(t):vn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!f$4(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function ii(t){let e=await _l(o$1(t,"workspace.json").find(r=>existsSync(r))??l(t,"workspace.json")),o=e?.workspace_name??e?.name;return typeof o=="string"&&o.trim()?o.trim():b.basename(t)}function Jt(t){return l(t,"snapshots")}function ho(t){return l(t,"archive","projects")}function Lt(t){return b.join(t,"files")}function Nl(t){return b.join(pn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${ft.randomBytes(4).toString("hex")}`)}function Ml(t,e){return b.join(Jt(t),`.tmp-${process.pid}-${e}-${ft.randomBytes(4).toString("hex")}`)}function nr(t,e){let o=b.relative(t,e);if(!o)return true;let r=o.split(b.sep);return (r[0]===".workspai"||r[0]===".rapidkit")&&["snapshots","archive","audit"].includes(r[1]||"")?false:!r.some(n=>Al.has(n))}async function Tl(t){return (await a$e(t,{descendIntoMatchedProjects:false})).map(o=>({name:b.basename(o),relativePath:b.relative(t,o)}))}async function Wl(t,e){let o=[],r$1=new Set;for(let n of Rl){let a=b.join(t,n);if(!await I__default.pathExists(a))continue;let i=r(n);if(r$1.has(i))continue;let c=b.join(e,i);await I__default.copy(a,c,{filter:l=>nr(t,l)}),o.push(i),r$1.add(i);}return o}async function ci(t){let e=[];async function o(r){let n=[];try{n=await I__default.readdir(r,{withFileTypes:true});}catch{return}for(let a of n){let i=b.join(r,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await o(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await o(t),e.sort((r,n)=>n.length-r.length);for(let r$1 of e){let n=b.join(b.dirname(r$1),b.basename(r(b.basename(r$1))));await I__default.copy(r$1,n,{overwrite:false,errorOnExist:false}),await I__default.remove(r$1);}}async function li(t,e){let o=e.schema===fo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$3(e,o,"Workspace snapshot manifest"),await I__default.writeJson(b.join(t,"snapshot.json"),e,{spaces:2});}async function Pn(t){let e=b.join(t,"snapshot.json"),o=await I__default.readJson(e);if(!o||typeof o!="object"||![si,fo].includes(o.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let r=o,n=r.schema===fo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$3(r,n,"Workspace snapshot manifest"),r.mode==="project"&&(r.schema!==fo||r.recoveryScope?.kind!=="project"||!r.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return r}async function Dl(t){let e=0,o=0,r=[t];for(;r.length>0;){let n=r.shift();if(!n)continue;let a=[];try{a=await I__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=b.join(n,i.name);if(i.isDirectory()){r.push(c);continue}if(i.isFile())try{let l=await I__default.stat(c);e+=1,o+=l.size;}catch{}}}return {files:e,bytes:o}}async function sr(t={}){let e=ht(t.workspacePath),o=t.name?t.name:`snapshot-${Ft()}`,r=or(o),n=b.join(Jt(e),r),a=Nl(r);if(await I__default.pathExists(n))throw new Error(`Snapshot already exists: ${r}`);let i=Lt(a);try{await I__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",l=c==="full"?["."]:await Wl(e,i);c==="full"&&(await I__default.copy(e,i,{filter:m=>nr(e,m)}),await ci(i));let p={schema:El,name:r,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await ii(e),workspacePath:e,copiedPaths:l,projects:await Tl(e)};return await li(a,p),await I__default.ensureDir(b.dirname(n)),await I__default.move(a,n,{overwrite:false}),await Ge(e,{action:"snapshot.create",target:r,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:l,snapshotPath:n,projectCount:p.projects.length}}),{manifest:p,snapshotPath:n}}catch(c){throw await I__default.remove(a),await Ge(e,{action:"snapshot.create",target:r,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function ar(t){let e=b.resolve(t.workspacePath),o=b.resolve(t.projectPath),r=b.relative(e,o);if(!r||r.startsWith("..")||b.isAbsolute(r)||r.split(b.sep).some(m=>m===".workspai"||m===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${o}`);let n=b.basename(o),a=or(`${t.namePrefix}-${n}-${Ft()}-${ft.randomBytes(3).toString("hex")}`),i=b.join(Jt(e),a),c=Ml(e,a),l=b.join(Lt(c),r),p=false;try{await I__default.ensureDir(b.dirname(l)),t.moveSource?(await I__default.move(o,l,{overwrite:false}),p=true):await I__default.copy(o,l,{overwrite:false,errorOnExist:true,filter:d=>nr(o,d)});let m={schema:fo,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await ii(e),workspacePath:e,copiedPaths:[r],projects:[{name:n,relativePath:r}],recoveryScope:{kind:"project",projectName:n,relativePath:r}};return await li(c,m),await I__default.move(c,i,{overwrite:false}),await Ge(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[r],snapshotPath:i,projectCount:1}}),{manifest:m,snapshotPath:i}}catch(m){if(p&&!await I__default.pathExists(o)){let d=await I__default.pathExists(l)?l:b.join(Lt(i),r);await I__default.pathExists(d)&&(await I__default.ensureDir(b.dirname(o)),await I__default.move(d,o,{overwrite:false}));}throw await I__default.remove(c),await I__default.remove(i),await Ge(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:m instanceof Error?m.message:String(m)}}),m}}async function pi(t){let e=ht(t.workspacePath),o=b.join(Jt(e),or(t.name));if(!await I__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await Pn(o),n=Lt(o),a=await Dl(n);return {manifest:r,snapshotPath:o,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function di(t={}){let e=ht(t.workspacePath),o=Jt(e);if(!await I__default.pathExists(o))return [];let r=await I__default.readdir(o,{withFileTypes:true}),n=[];for(let a of r){if(!a.isDirectory())continue;let i=b.join(o,a.name);try{n.push({...await Pn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var Ll=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function Fl(t){let e=b.dirname(t.workspacePath),o=b.basename(t.workspacePath),r=`${Ft()}-${ft.randomBytes(4).toString("hex")}`,n=b.join(e,`.${o}.restore-staging-${r}`),a=b.join(e,`.${o}.pre-restore-${r}`),i=b.join(e,`.${o}.restore-failed-${r}`),c=[],l=false,p=false;try{await I__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:m=>nr(t.filesRoot,m)}),await ci(n),await I__default.rename(t.workspacePath,a),l=true,await I__default.rename(n,t.workspacePath),p=true;for(let m of Ll){let d=b.join(a,m);if(!await I__default.pathExists(d))continue;let h=b.join(t.workspacePath,m);if(await I__default.pathExists(h))throw new Error(`Full restore operational path collision: ${m}`);await I__default.ensureDir(b.dirname(h)),await I__default.rename(d,h),c.push(m);}return a}catch(m){for(let d of [...c].reverse()){let h=b.join(t.workspacePath,d),g=b.join(a,d);await I__default.pathExists(h)&&(await I__default.ensureDir(b.dirname(g)),await I__default.rename(h,g));}throw p&&await I__default.pathExists(t.workspacePath)&&await I__default.rename(t.workspacePath,i),l&&await I__default.pathExists(a)&&await I__default.rename(a,t.workspacePath),await I__default.remove(i),await I__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${m instanceof Error?m.message:String(m)}`)}}async function ui(t,e){let o=t.manifest.recoveryScope?.relativePath;if(!o)return;let r=b.join(Lt(t.snapshotPath),o),n=b.join(e,o);await I__default.pathExists(r)&&!await I__default.pathExists(n)&&(await I__default.ensureDir(b.dirname(n)),await I__default.move(r,n,{overwrite:false})),await I__default.remove(t.snapshotPath);}async function mi(t){let e=ht(t.workspacePath),o=b.join(Jt(e),or(t.name));if(!await I__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r$1=await Pn(o),n=Lt(o),a=r$1.mode==="full"?["."]:Array.from(new Set(r$1.copiedPaths.map(l=>{let p=r(l);return p.startsWith(".workspai/")?".workspai":p})));if(t.dryRun)return await Ge(e,{action:"snapshot.restore",target:r$1.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:o,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await rr(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(r$1.mode==="full")i=await Fl({workspacePath:e,filesRoot:n,snapshotName:r$1.name});else if(r$1.mode==="project"){let l=r$1.recoveryScope?.relativePath;if(!l)throw new Error(`Project recovery snapshot is missing recoveryScope: ${r$1.name}`);let p=b.join(n,l),m=b.join(e,l),d=await I__default.pathExists(m),h,g=b.join(b.dirname(m),`.${b.basename(m)}.pre-restore-${process.pid}-${ft.randomBytes(4).toString("hex")}`),k=false;d&&t.safetySnapshot!==false?(h=await ar({workspacePath:e,projectPath:m,namePrefix:`pre-restore-${r$1.name}`,reason:`Automatic project recovery snapshot before restoring ${r$1.name}`,moveSource:true}),i=h.snapshotPath):d&&(await I__default.rename(m,g),k=true);let C=b.join(b.dirname(m),`.${b.basename(m)}.restore-${process.pid}-${ft.randomBytes(4).toString("hex")}`);try{await I__default.copy(p,C,{overwrite:false,errorOnExist:true}),await I__default.rename(C,m),k&&await I__default.remove(g);}catch(A){throw await I__default.remove(C),k&&await I__default.pathExists(g)&&(await I__default.remove(m),await I__default.rename(g,m)),h&&await ui(h,e),A}}else t.safetySnapshot!==false&&(i=(await sr({workspacePath:e,name:`pre-restore-${r$1.name}-${Ft()}`,reason:`Automatic safety snapshot before restoring ${r$1.name}`,includeProjects:false})).snapshotPath);if(r$1.mode==="metadata"){let l=new Set;for(let p of r$1.copiedPaths){let m=r(p);l.has(m)||(await I__default.copy(b.join(n,p),b.join(e,m),{overwrite:true,errorOnExist:false}),l.add(m));}}let c={workspacePath:e,snapshotPath:o,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await Ge(e,{action:"snapshot.restore",target:r$1.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function gi(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function fi(t,e){let o=gi(e),r=b.isAbsolute(o)?b.resolve(o):b.resolve(t,o);if(r.startsWith(`${b.resolve(t)}${b.sep}`)&&await I__default.pathExists(r))return r;let a=(await a$e(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=b.relative(t,i);return b.basename(i)===o||c===o});if(a.length===0)throw new Error(`Project not found in workspace: ${e}`);if(a.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return a[0]}async function bn(t){try{let{syncWorkspaceProjects:e}=await import('./workspace-H3QXBFGB.js');await e(t,true);}catch{}}function Jl(t,e){let o=ft.randomBytes(4).toString("hex");return b.join(ho(t),`${e}-${Ft()}-${o}`)}async function hi(t){let e=yi(t),o=await I__default.readJson(e);if(!o||typeof o!="object"||o.schema!==ai)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$3(o,"contracts/project-archive.v1.json","Project archive manifest"),o}function yi(t){return [nt,tr].map(e=>b.join(t,e)).find(e=>I__default.existsSync(e))??b.join(t,nt)}async function jn(t={}){let e=ht(t.workspacePath),o=ho(e);if(!await I__default.pathExists(o))return [];let r=await I__default.readdir(o,{withFileTypes:true}),n=[];for(let a of r){if(!a.isDirectory())continue;let i=b.join(o,a.name),c=[nt,tr].map(l=>b.join(i,l)).find(l=>I__default.existsSync(l))??b.join(i,nt);try{n.push({...await hi(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function Kl(t,e){let o=gi(e),r=b.isAbsolute(o)?b.resolve(o):b.resolve(ho(t),o);if(r.startsWith(`${b.resolve(ho(t))}${b.sep}`)&&(await I__default.pathExists(b.join(r,nt))||await I__default.pathExists(b.join(r,tr))))return r;let a=(await jn({workspacePath:t})).filter(i=>b.basename(i.archivePath)===o||i.projectName===o||b.relative(ho(t),i.archivePath)===o);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function Cn(t){let e=ht(t.workspacePath),o=await fi(e,t.project),r=b.basename(o),n=Jl(e,r),a=b.join(n,nt),i=`${n}.tmp-${process.pid}`,c=b.join(i,nt);for(let d of [nt,tr])if(await I__default.pathExists(b.join(o,d)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${d}`);if(t.dryRun)return await Ge(e,{action:"project.archive",target:r,status:"planned",reason:t.reason,details:{projectPath:o,archivePath:n}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await rr(e,"project.archive",{reason:t.reason,safetySnapshot:true});let l=await ar({workspacePath:e,projectPath:o,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${r}`,moveSource:false}),p={schema:ai,projectName:r,originalPath:o,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:l.snapshotPath};a$3(p,"contracts/project-archive.v1.json","Project archive manifest");let m=false;try{await I__default.ensureDir(b.dirname(n)),await I__default.move(o,i,{overwrite:false}),m=true,await I__default.writeJson(c,p,{spaces:2}),await I__default.rename(i,n);}catch(d){if(m&&!await I__default.pathExists(o)){let h=await I__default.pathExists(i)?i:n;await I__default.pathExists(h)&&(await I__default.remove(b.join(h,nt)),await I__default.move(h,o,{overwrite:false}));}throw await I__default.remove(i),d}return await c$4(e,[o]),await bn(e),await Ge(e,{action:"project.archive",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath,dryRun:false}}async function wi(t){if(!t.permanent)return Cn(t);let e=ht(t.workspacePath),o=await fi(e,t.project),r=b.basename(o);if(t.confirm!==r)throw new Error(`Permanent delete requires --confirm ${r}`);if(t.dryRun)return await Ge(e,{action:"project.delete",target:r,status:"planned",reason:t.reason,details:{projectPath:o,permanent:true}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",dryRun:true};await rr(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await ar({workspacePath:e,projectPath:o,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${r}`,moveSource:true});return await c$4(e,[o]),await bn(e),await Ge(e,{action:"project.delete",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function ki(t){let e=ht(t.workspacePath),o=await Kl(e,t.archive),r=await hi(o),n=t.targetName?.trim()||r.projectName,a=b.join(e,n);if(!a.startsWith(`${b.resolve(e)}${b.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await I__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await Ge(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:o,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:o,manifestPath:b.join(o,nt),dryRun:true};await rr(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await I__default.pathExists(a),c=i?await ar({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await sr({workspacePath:e,name:`pre-restore-project-${n}-${Ft()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),l$1=yi(o),p=l(e,"audit","restores",`${b.basename(o)}.json`);try{await I__default.move(o,a,{overwrite:false}),await I__default.ensureDir(b.dirname(p)),await I__default.move(b.join(a,b.basename(l$1)),p,{overwrite:false});}catch(m){throw await I__default.pathExists(a)&&(await I__default.pathExists(p)&&await I__default.move(p,b.join(a,b.basename(l$1)),{overwrite:false}),await I__default.pathExists(o)||await I__default.move(a,o,{overwrite:false})),i&&await ui(c,e),m}return await bn(e),await Ge(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:o,projectPath:a,restoreReceiptPath:p,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:o,manifestPath:p,safetySnapshotPath:c.snapshotPath,dryRun:false}}var Gl="rapidkit.infra-stack.v1",Pi="rapidkit.infra-plan.v1",Kt=".workspai/infra/docker-compose.yml",Vt=".workspai/reports/infra-plan.json",En=".workspai/infra/.env.example";function Ul(){let t=b.dirname(fileURLToPath(import.meta.url)),e=[b.join(t,"../../contracts/infra-stack.v1.json"),b.join(t,"../contracts/infra-stack.v1.json")];for(let o of e)if(x.existsSync(o))return o;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var xn=null;function jt(t){if(xn)return xn;let e=Ul(),o=x.readFileSync(e,"utf-8"),r=JSON.parse(o);if(r.schemaVersion!==Gl)throw new Error(`Unsupported infra stack schema: ${r.schemaVersion}`);return Bl(r),(xn=r),r}function Bl(t){let e=new Set(Object.keys(t.services));for(let[o,r]of Object.entries(t.moduleMappings)){if(!Array.isArray(r))throw new Error(`Invalid moduleMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`moduleMappings/${o} references unknown service '${n}'`)}for(let[o,r]of Object.entries(t.envVarMappings)){if(!Array.isArray(r))throw new Error(`Invalid envVarMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`envVarMappings/${o} references unknown service '${n}'`)}}function bi(t,e){let o=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[o]||[]}function Gt(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function ji(t,e){let o={};for(let r of e){let n=t.services[r];n&&Object.assign(o,n.connectionEnv);}return o}async function ql(t){let e=b.join(t,"registry.json");if(!await I__default.pathExists(e))return [];try{let r=(await I__default.readJson(e)).installed_modules||[];return [...new Set(r.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function zl(t){let e=b.join(t,".env.example");if(!await I__default.pathExists(e))return [];try{let o=await I__default.readFile(e,"utf-8"),r=[];for(let n of o.split(`
116
- `)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&r.push(i[1]);}return r}catch{return []}}async function Yl(t){let e=o$1(t,"infra","overrides.json").find(o=>existsSync(o));if(!e)return [];try{let o=await I__default.readJson(e);return Array.isArray(o.services)?[...new Set(o.services.filter(r=>typeof r=="string"&&r.trim().length>0))]:[]}catch{return []}}async function Ql(t){let e=await d$5(t,".workspai/workspace.contract.json");if(!e)return [];try{let o=await I__default.readJson(e),r=[];for(let n of o.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&r.push({project:a,env:i.trim().toUpperCase()});}return r}catch{return []}}function ir(t,e,o,r){t.add(o),e.push(r);}async function Ci(t){let e=b.resolve(t.workspacePath),o=t.contract||jt(),r=new Set,n=[],a=new Set,i=new Set,c=new Set,l=await i$5(e);for(let p of l){let m=b.dirname(b.dirname(p)),d=b.basename(m);for(let h of await ql(m)){a.add(h);for(let g of bi(o,h))ir(r,n,g,{kind:"module",value:h,project:d});}for(let h of await zl(m)){i.add(h);for(let g of Gt(o,h))ir(r,n,g,{kind:"env-var",value:h,project:d});}}for(let p of await Ql(e)){i.add(p.env);for(let m of Gt(o,p.env))ir(r,n,m,{kind:"contract-env",value:p.env,project:p.project});}for(let p of await Yl(e))c.add(p),ir(r,n,p,{kind:"override",value:p});return {modules:[...a].sort(),envVars:[...i].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...r].sort()}}function Xl(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let o=e.indexOf("=");if(o<=0)return null;let r=e.slice(0,o).trim();if(!/^[A-Z0-9_]+$/.test(r))return null;let n=e.slice(o+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let a=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),i=(a?a[1]:n).trim();return i?{key:r,value:i}:null}async function Zl(t){if(!await I__default.pathExists(t))return {};try{let e=await I__default.readFile(t,"utf-8"),o={};for(let r of e.split(`
117
- `)){let n=Xl(r);n&&(o[n.key]=n.value);}return o}catch{return {}}}async function xi(t){let e={},o=await i$5(t.workspacePath);for(let r of o){let n=b.dirname(b.dirname(r)),a=await Zl(b.join(n,".env.example"));for(let[i,c]of Object.entries(a))Gt(t.contract,i).length>0&&(e[i]=c);}return e}function Ei(t,e){return t.filter(o=>Gt(e,o).length>0).sort()}function Ri(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let o=new URL(e),r=o.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(o.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(o.password||"postgres"),POSTGRES_DB:r||"postgres"}}catch{return}}function Ai(t){let e=t.POSTGRES_USER||"postgres",o=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${o}`]}function ep(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
118
- `)?JSON.stringify(t):t}function _i(t,e){return Object.entries(t).map(([o,r])=>`${e}${o}: ${ep(r)}`).join(`
119
- `)}function tp(t,e){let o=t.test.map(r=>JSON.stringify(r)).join(", ");return [`${e}healthcheck:`,`${e} test: [${o}]`,`${e} interval: ${t.interval}`,`${e} timeout: ${t.timeout}`,`${e} retries: ${t.retries}`].join(`
120
- `)}function Ii(t){let e=["# Generated by Workspai infra plan \u2014 do not edit manually.",`# Workspace: ${t.workspaceName}`,`# Generated at: ${t.plan.generatedAt}`,"name: workspai-infra"],o=new Set;if(t.plan.services.length===0)return e.push("services: {}"),e.push(""),e.join(`
121
- `);e.push("services:");for(let r of t.plan.services){let n=t.contract.services[r.id];if(n){if(e.push(` ${r.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: workspai-${r.id}`),n.command?.length){let a=n.command.map(i=>JSON.stringify(i)).join(", ");e.push(` command: [${a}]`);}if(n.env&&Object.keys(n.env).length>0){e.push(" environment:");let a={...n.env,...t.plan.serviceEnvOverrides?.[r.id]||{}};e.push(_i(a," "));}else t.plan.serviceEnvOverrides?.[r.id]&&(e.push(" environment:"),e.push(_i(t.plan.serviceEnvOverrides[r.id]," ")));if(n.ports.length>0){e.push(" ports:");for(let a of n.ports)e.push(` - "${a.host}:${a.container}"`);}if(n.volumes?.length){e.push(" volumes:");for(let a of n.volumes){e.push(` - ${a}`);let i=a.split(":")[0];i&&!i.startsWith("/")&&o.add(i);}}if(n.healthcheck){let a=t.plan.serviceEnvOverrides?.[r.id];if(r.id==="postgres"&&a){let i=Ai(a).map(c=>JSON.stringify(c)).join(", ");e.push(" healthcheck:"),e.push(` test: [${i}]`),e.push(` interval: ${n.healthcheck.interval}`),e.push(` timeout: ${n.healthcheck.timeout}`),e.push(` retries: ${n.healthcheck.retries}`);}else e.push(tp(n.healthcheck," "));}e.push(" restart: unless-stopped");}}if(o.size>0){e.push("volumes:");for(let r of [...o].sort())e.push(` ${r}:`),e.push(" driver: local");}return e.push(""),e.join(`
122
- `)}function rp(t,e,o){return t.kind==="override"?t.value===e:t.kind==="module"?o.moduleMappings[t.value]?.includes(e)??false:o.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function np(t){let e=new Map,o=[];for(let r of t)for(let n of r.ports){let a=e.get(n.host);a&&a!==r.id?o.push(`Port collision on host ${n.host} between services '${a}' and '${r.id}'`):e.set(n.host,r.id);}return o}async function sp(t){let e=o$1(t,"workspace.json").find(o=>existsSync(o));if(e)try{let o=await I__default.readJson(e);return o.workspace_name||o.name}catch{return}}async function An(t){let e=b.resolve(t.workspacePath),o=jt(),r=await Ci({workspacePath:e,contract:o}),n=r.serviceIds.map(h=>{let g=o.services[h];return g?{id:h,displayName:g.displayName,category:g.category,image:g.image,ports:g.ports,sources:r.sources.filter(k=>rp(k,h,o))}:null}).filter(h=>h!==null),a=np(n);n.length===0&&a.push("No infrastructure services detected. Install modules with infra dependencies or add .workspai/infra/overrides.json");for(let h of r.overrides)o.services[h]||a.push(`Override references unknown service '${h}'`);let i=await d$5(e,".workspai/workspace.contract.json")?".workspai/workspace.contract.json":void 0,c=ji(o,r.serviceIds),l=await xi({workspacePath:e,contract:o}),p={...c,...l};l.RAPIDKIT_DB_POSTGRES_URL&&(p.DATABASE_URL=l.RAPIDKIT_DB_POSTGRES_URL);let m={},d=Ri(p);return d&&r.serviceIds.includes("postgres")&&(m.postgres=d),{schemaVersion:Pi,generatedAt:(t.now||(()=>new Date))().toISOString(),workspacePath:e,workspaceName:await sp(e),contractPath:i,strategy:"sidecar",composePath:Kt,envExamplePath:En,services:n,connectionEnv:p,serviceEnvOverrides:Object.keys(m).length>0?m:void 0,sources:{modules:r.modules,envVars:r.envVars,overrides:r.overrides},warnings:a}}async function _n(t){let e=b.resolve(t.workspacePath),o=b.join(e,Kt),r=b.join(e,Vt),n=b.join(e,En),a=jt();a$3(t.plan,"contracts/infra-plan.v1.json","Workspai infrastructure plan");let i=Ii({plan:t.plan,contract:a,workspaceName:t.plan.workspaceName||b.basename(e)}),c=["# Generated by: npx workspai infra plan","# Copy values into project .env files as needed.",...Object.entries(t.plan.connectionEnv).map(([l,p])=>`${l}=${p}`),""].join(`
123
- `);return t.dryRun?{composePath:o,planPath:r,envExamplePath:n}:(await I__default.ensureDir(b.dirname(o)),await I__default.ensureDir(b.dirname(r)),await I__default.writeFile(o,i,"utf-8"),await I__default.writeFile(r,`${JSON.stringify(t.plan,null,2)}
124
- `,"utf-8"),await I__default.writeFile(n,c,"utf-8"),{composePath:o,planPath:r,envExamplePath:n})}function ap(t){return b.resolve(t).split(b.sep).join("/")}async function Oi(){if((await execa("docker",["compose","version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker",prefixArgs:["compose"]};if((await execa("docker-compose",["version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker-compose",prefixArgs:[]};throw new Error("Docker Compose is not available. Install Docker Desktop or the docker-compose plugin, then verify with: docker compose version")}async function ip(){if((await execa("docker",["version"],{reject:false,timeout:5e3})).exitCode!==0)throw new Error("Docker is not available in PATH. Install Docker and ensure the daemon is running before using rapidkit infra.");await Oi();}function Ni(t){let e=t.toLowerCase();return e.includes("no space left on device")?"Docker failed because the disk is full. Free space with: docker system prune -f (or docker system prune -a --volumes -f).":e.includes("address already in use")||e.includes("bind")?"Docker failed to bind a host port. Stop the conflicting service or adjust ports in contracts/infra-stack.v1.json via .workspai/infra/overrides.json.":e.includes("cannot connect to the docker daemon")?"Docker daemon is not running. Start Docker Desktop or the docker service, then retry.":null}async function Mi(t){await ip();let e=await Oi(),o=ap(t.composePath),r=await execa(e.command,[...e.prefixArgs,"-f",o,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:r.exitCode??1,stdout:r.stdout,stderr:r.stderr}}function lr(t){let e=t?b.resolve(t):vn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");return a$8(e)}function cp(t){return b.join(t,Kt)}async function In(t){let e=b.join(t,Vt);if(!await I__default.pathExists(e))throw new Error(`Infra plan not found at ${Vt}. Run: npx workspai infra plan`);let o=await I__default.readJson(e);return a$3(o,"contracts/infra-plan.v1.json",`Infra plan ${e}`),o}async function $n(t){let e=cp(t.workspacePath);if(!await I__default.pathExists(e))throw new Error(`Compose file not found at ${Kt}. Run: npx workspai infra plan`);return Mi({composePath:e,workspacePath:t.workspacePath,args:t.args})}function lp(t,e={}){if(console.log(s.bold(`
114
+ `));}function si(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(o,r)=>{try{let n=r.output||ei("--output"),a=await ni({backlogPath:o,kit:r.kit,tier:r.tier,category:r.category,limit:r.limit});a$4(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await oi(n,a,true),r.json?console.log(Dt(a)):Rl(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);r.json?console.log(Dt({ok:false,error:{message:a}})):console.error(s.red(`Product plan failed: ${a}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(o,r)=>{try{let n=r.output||ei("--output");ri(o);let a=await xl({backlogPath:r.fromBacklog,slug:o,kit:r.kit,outputRoot:r.workspaceOutput});a$4(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=El(n,o);await oi(i,a,r.force===true),r.json?console.log(Dt(a)):Al(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);r.json?console.log(Dt({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var ci="rapidkit-workspace-snapshot-v1",fo="rapidkit-workspace-snapshot-v2",_l=ci,li="rapidkit-project-archive-v1",st="workspai-archive.json",tr="rapidkit-archive.json",Il=[".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"],$l=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),go={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function Ft(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function or(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 Ol(t){try{let e=await O__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Nl(t,e){if(!t)return e;let o=t.trim().toLowerCase();return ["true","yes","1","on"].includes(o)?true:["false","no","0","off"].includes(o)?false:e}async function Ml(t){let e=o$1(t,"policies.yml").find(o=>existsSync(o))??l(t,"policies.yml");if(!await O__default.pathExists(e))return {...go};try{let o=await O__default.readFile(e,"utf-8"),r=(n,a)=>{let i=o.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return Nl(i?.[1],a)};return {requireReasonForDestructiveOps:r("require_reason_for_destructive_ops",go.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:r("require_safety_snapshot_for_destructive_ops",go.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:r("allow_permanent_delete",go.allowPermanentDelete)}}catch{return {...go}}}function Tl(t){return l(t,"audit","events.jsonl")}async function Ge(t,e){let o={schema:"rapidkit-workspace-audit-event-v1",id:ft.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},r=Tl(t);return await O__default.ensureDir(b.dirname(r)),await O__default.appendFile(r,`${JSON.stringify(o)}
115
+ `,"utf-8"),o}async function rr(t,e,o){let r=await Ml(t);if(r.requireReasonForDestructiveOps&&!o.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(r.requireSafetySnapshotForDestructiveOps&&o.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(o.permanent&&!r.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return r}function vn(t=process.cwd()){let e=b.resolve(t),o=b.resolve(pn.tmpdir());for(;;){if(e!==o&&f$4(e))return e;let r=b.dirname(e);if(r===e)return null;e=r;}}function ht(t){let e=t?b.resolve(t):vn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!f$4(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function pi(t){let e=await Ol(o$1(t,"workspace.json").find(r=>existsSync(r))??l(t,"workspace.json")),o=e?.workspace_name??e?.name;return typeof o=="string"&&o.trim()?o.trim():b.basename(t)}function Jt(t){return l(t,"snapshots")}function ho(t){return l(t,"archive","projects")}function Lt(t){return b.join(t,"files")}function Wl(t){return b.join(pn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${ft.randomBytes(4).toString("hex")}`)}function Dl(t,e){return b.join(Jt(t),`.tmp-${process.pid}-${e}-${ft.randomBytes(4).toString("hex")}`)}function nr(t,e){let o=b.relative(t,e);if(!o)return true;let r=o.split(b.sep);return (r[0]===".workspai"||r[0]===".rapidkit")&&["snapshots","archive","audit"].includes(r[1]||"")?false:!r.some(n=>$l.has(n))}async function Ll(t){return (await a$e(t,{descendIntoMatchedProjects:false})).map(o=>({name:b.basename(o),relativePath:b.relative(t,o)}))}async function Fl(t,e){let o=[],r$1=new Set;for(let n of Il){let a=b.join(t,n);if(!await O__default.pathExists(a))continue;let i=r(n);if(r$1.has(i))continue;let c=b.join(e,i);await O__default.copy(a,c,{filter:l=>nr(t,l)}),o.push(i),r$1.add(i);}return o}async function di(t){let e=[];async function o(r){let n=[];try{n=await O__default.readdir(r,{withFileTypes:true});}catch{return}for(let a of n){let i=b.join(r,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await o(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await o(t),e.sort((r,n)=>n.length-r.length);for(let r$1 of e){let n=b.join(b.dirname(r$1),b.basename(r(b.basename(r$1))));await O__default.copy(r$1,n,{overwrite:false,errorOnExist:false}),await O__default.remove(r$1);}}async function ui(t,e){let o=e.schema===fo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,o,"Workspace snapshot manifest"),await O__default.writeJson(b.join(t,"snapshot.json"),e,{spaces:2});}async function Pn(t){let e=b.join(t,"snapshot.json"),o=await O__default.readJson(e);if(!o||typeof o!="object"||![ci,fo].includes(o.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let r=o,n=r.schema===fo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(r,n,"Workspace snapshot manifest"),r.mode==="project"&&(r.schema!==fo||r.recoveryScope?.kind!=="project"||!r.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return r}async function Jl(t){let e=0,o=0,r=[t];for(;r.length>0;){let n=r.shift();if(!n)continue;let a=[];try{a=await O__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=b.join(n,i.name);if(i.isDirectory()){r.push(c);continue}if(i.isFile())try{let l=await O__default.stat(c);e+=1,o+=l.size;}catch{}}}return {files:e,bytes:o}}async function sr(t={}){let e=ht(t.workspacePath),o=t.name?t.name:`snapshot-${Ft()}`,r=or(o),n=b.join(Jt(e),r),a=Wl(r);if(await O__default.pathExists(n))throw new Error(`Snapshot already exists: ${r}`);let i=Lt(a);try{await O__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",l=c==="full"?["."]:await Fl(e,i);c==="full"&&(await O__default.copy(e,i,{filter:m=>nr(e,m)}),await di(i));let p={schema:_l,name:r,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await pi(e),workspacePath:e,copiedPaths:l,projects:await Ll(e)};return await ui(a,p),await O__default.ensureDir(b.dirname(n)),await O__default.move(a,n,{overwrite:false}),await Ge(e,{action:"snapshot.create",target:r,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:l,snapshotPath:n,projectCount:p.projects.length}}),{manifest:p,snapshotPath:n}}catch(c){throw await O__default.remove(a),await Ge(e,{action:"snapshot.create",target:r,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function ar(t){let e=b.resolve(t.workspacePath),o=b.resolve(t.projectPath),r=b.relative(e,o);if(!r||r.startsWith("..")||b.isAbsolute(r)||r.split(b.sep).some(m=>m===".workspai"||m===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${o}`);let n=b.basename(o),a=or(`${t.namePrefix}-${n}-${Ft()}-${ft.randomBytes(3).toString("hex")}`),i=b.join(Jt(e),a),c=Dl(e,a),l=b.join(Lt(c),r),p=false;try{await O__default.ensureDir(b.dirname(l)),t.moveSource?(await O__default.move(o,l,{overwrite:false}),p=true):await O__default.copy(o,l,{overwrite:false,errorOnExist:true,filter:d=>nr(o,d)});let m={schema:fo,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await pi(e),workspacePath:e,copiedPaths:[r],projects:[{name:n,relativePath:r}],recoveryScope:{kind:"project",projectName:n,relativePath:r}};return await ui(c,m),await O__default.move(c,i,{overwrite:false}),await Ge(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[r],snapshotPath:i,projectCount:1}}),{manifest:m,snapshotPath:i}}catch(m){if(p&&!await O__default.pathExists(o)){let d=await O__default.pathExists(l)?l:b.join(Lt(i),r);await O__default.pathExists(d)&&(await O__default.ensureDir(b.dirname(o)),await O__default.move(d,o,{overwrite:false}));}throw await O__default.remove(c),await O__default.remove(i),await Ge(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:m instanceof Error?m.message:String(m)}}),m}}async function mi(t){let e=ht(t.workspacePath),o=b.join(Jt(e),or(t.name));if(!await O__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await Pn(o),n=Lt(o),a=await Jl(n);return {manifest:r,snapshotPath:o,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function gi(t={}){let e=ht(t.workspacePath),o=Jt(e);if(!await O__default.pathExists(o))return [];let r=await O__default.readdir(o,{withFileTypes:true}),n=[];for(let a of r){if(!a.isDirectory())continue;let i=b.join(o,a.name);try{n.push({...await Pn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var Kl=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function Vl(t){let e=b.dirname(t.workspacePath),o=b.basename(t.workspacePath),r=`${Ft()}-${ft.randomBytes(4).toString("hex")}`,n=b.join(e,`.${o}.restore-staging-${r}`),a=b.join(e,`.${o}.pre-restore-${r}`),i=b.join(e,`.${o}.restore-failed-${r}`),c=[],l=false,p=false;try{await O__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:m=>nr(t.filesRoot,m)}),await di(n),await O__default.rename(t.workspacePath,a),l=true,await O__default.rename(n,t.workspacePath),p=true;for(let m of Kl){let d=b.join(a,m);if(!await O__default.pathExists(d))continue;let w=b.join(t.workspacePath,m);if(await O__default.pathExists(w))throw new Error(`Full restore operational path collision: ${m}`);await O__default.ensureDir(b.dirname(w)),await O__default.rename(d,w),c.push(m);}return a}catch(m){for(let d of [...c].reverse()){let w=b.join(t.workspacePath,d),g=b.join(a,d);await O__default.pathExists(w)&&(await O__default.ensureDir(b.dirname(g)),await O__default.rename(w,g));}throw p&&await O__default.pathExists(t.workspacePath)&&await O__default.rename(t.workspacePath,i),l&&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}: ${m instanceof Error?m.message:String(m)}`)}}async function fi(t,e){let o=t.manifest.recoveryScope?.relativePath;if(!o)return;let r=b.join(Lt(t.snapshotPath),o),n=b.join(e,o);await O__default.pathExists(r)&&!await O__default.pathExists(n)&&(await O__default.ensureDir(b.dirname(n)),await O__default.move(r,n,{overwrite:false})),await O__default.remove(t.snapshotPath);}async function hi(t){let e=ht(t.workspacePath),o=b.join(Jt(e),or(t.name));if(!await O__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r$1=await Pn(o),n=Lt(o),a=r$1.mode==="full"?["."]:Array.from(new Set(r$1.copiedPaths.map(l=>{let p=r(l);return p.startsWith(".workspai/")?".workspai":p})));if(t.dryRun)return await Ge(e,{action:"snapshot.restore",target:r$1.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:o,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await rr(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(r$1.mode==="full")i=await Vl({workspacePath:e,filesRoot:n,snapshotName:r$1.name});else if(r$1.mode==="project"){let l=r$1.recoveryScope?.relativePath;if(!l)throw new Error(`Project recovery snapshot is missing recoveryScope: ${r$1.name}`);let p=b.join(n,l),m=b.join(e,l),d=await O__default.pathExists(m),w,g=b.join(b.dirname(m),`.${b.basename(m)}.pre-restore-${process.pid}-${ft.randomBytes(4).toString("hex")}`),P=false;d&&t.safetySnapshot!==false?(w=await ar({workspacePath:e,projectPath:m,namePrefix:`pre-restore-${r$1.name}`,reason:`Automatic project recovery snapshot before restoring ${r$1.name}`,moveSource:true}),i=w.snapshotPath):d&&(await O__default.rename(m,g),P=true);let j=b.join(b.dirname(m),`.${b.basename(m)}.restore-${process.pid}-${ft.randomBytes(4).toString("hex")}`);try{await O__default.copy(p,j,{overwrite:false,errorOnExist:true}),await O__default.rename(j,m),P&&await O__default.remove(g);}catch(A){throw await O__default.remove(j),P&&await O__default.pathExists(g)&&(await O__default.remove(m),await O__default.rename(g,m)),w&&await fi(w,e),A}}else t.safetySnapshot!==false&&(i=(await sr({workspacePath:e,name:`pre-restore-${r$1.name}-${Ft()}`,reason:`Automatic safety snapshot before restoring ${r$1.name}`,includeProjects:false})).snapshotPath);if(r$1.mode==="metadata"){let l=new Set;for(let p of r$1.copiedPaths){let m=r(p);l.has(m)||(await O__default.copy(b.join(n,p),b.join(e,m),{overwrite:true,errorOnExist:false}),l.add(m));}}let c={workspacePath:e,snapshotPath:o,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await Ge(e,{action:"snapshot.restore",target:r$1.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function yi(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function wi(t,e){let o=yi(e),r=b.isAbsolute(o)?b.resolve(o):b.resolve(t,o);if(r.startsWith(`${b.resolve(t)}${b.sep}`)&&await O__default.pathExists(r))return r;let a=(await a$e(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=b.relative(t,i);return b.basename(i)===o||c===o});if(a.length===0)throw new Error(`Project not found in workspace: ${e}`);if(a.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return a[0]}async function bn(t){try{let{syncWorkspaceProjects:e}=await import('./workspace-PJPRBUMQ.js');await e(t,true);}catch{}}function Gl(t,e){let o=ft.randomBytes(4).toString("hex");return b.join(ho(t),`${e}-${Ft()}-${o}`)}async function ki(t){let e=vi(t),o=await O__default.readJson(e);if(!o||typeof o!="object"||o.schema!==li)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(o,"contracts/project-archive.v1.json","Project archive manifest"),o}function vi(t){return [st,tr].map(e=>b.join(t,e)).find(e=>O__default.existsSync(e))??b.join(t,st)}async function jn(t={}){let e=ht(t.workspacePath),o=ho(e);if(!await O__default.pathExists(o))return [];let r=await O__default.readdir(o,{withFileTypes:true}),n=[];for(let a of r){if(!a.isDirectory())continue;let i=b.join(o,a.name),c=[st,tr].map(l=>b.join(i,l)).find(l=>O__default.existsSync(l))??b.join(i,st);try{n.push({...await ki(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function Ul(t,e){let o=yi(e),r=b.isAbsolute(o)?b.resolve(o):b.resolve(ho(t),o);if(r.startsWith(`${b.resolve(ho(t))}${b.sep}`)&&(await O__default.pathExists(b.join(r,st))||await O__default.pathExists(b.join(r,tr))))return r;let a=(await jn({workspacePath:t})).filter(i=>b.basename(i.archivePath)===o||i.projectName===o||b.relative(ho(t),i.archivePath)===o);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function Cn(t){let e=ht(t.workspacePath),o=await wi(e,t.project),r=b.basename(o),n=Gl(e,r),a=b.join(n,st),i=`${n}.tmp-${process.pid}`,c=b.join(i,st);for(let d of [st,tr])if(await O__default.pathExists(b.join(o,d)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${d}`);if(t.dryRun)return await Ge(e,{action:"project.archive",target:r,status:"planned",reason:t.reason,details:{projectPath:o,archivePath:n}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await rr(e,"project.archive",{reason:t.reason,safetySnapshot:true});let l=await ar({workspacePath:e,projectPath:o,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${r}`,moveSource:false}),p={schema:li,projectName:r,originalPath:o,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:l.snapshotPath};a$4(p,"contracts/project-archive.v1.json","Project archive manifest");let m=false;try{await O__default.ensureDir(b.dirname(n)),await O__default.move(o,i,{overwrite:false}),m=true,await O__default.writeJson(c,p,{spaces:2}),await O__default.rename(i,n);}catch(d){if(m&&!await O__default.pathExists(o)){let w=await O__default.pathExists(i)?i:n;await O__default.pathExists(w)&&(await O__default.remove(b.join(w,st)),await O__default.move(w,o,{overwrite:false}));}throw await O__default.remove(i),d}return await c$4(e,[o]),await bn(e),await Ge(e,{action:"project.archive",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath,dryRun:false}}async function Pi(t){if(!t.permanent)return Cn(t);let e=ht(t.workspacePath),o=await wi(e,t.project),r=b.basename(o);if(t.confirm!==r)throw new Error(`Permanent delete requires --confirm ${r}`);if(t.dryRun)return await Ge(e,{action:"project.delete",target:r,status:"planned",reason:t.reason,details:{projectPath:o,permanent:true}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",dryRun:true};await rr(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await ar({workspacePath:e,projectPath:o,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${r}`,moveSource:true});return await c$4(e,[o]),await bn(e),await Ge(e,{action:"project.delete",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function bi(t){let e=ht(t.workspacePath),o=await Ul(e,t.archive),r=await ki(o),n=t.targetName?.trim()||r.projectName,a=b.join(e,n);if(!a.startsWith(`${b.resolve(e)}${b.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await O__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await Ge(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:o,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:o,manifestPath:b.join(o,st),dryRun:true};await rr(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await O__default.pathExists(a),c=i?await ar({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await sr({workspacePath:e,name:`pre-restore-project-${n}-${Ft()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),l$1=vi(o),p=l(e,"audit","restores",`${b.basename(o)}.json`);try{await O__default.move(o,a,{overwrite:false}),await O__default.ensureDir(b.dirname(p)),await O__default.move(b.join(a,b.basename(l$1)),p,{overwrite:false});}catch(m){throw await O__default.pathExists(a)&&(await O__default.pathExists(p)&&await O__default.move(p,b.join(a,b.basename(l$1)),{overwrite:false}),await O__default.pathExists(o)||await O__default.move(a,o,{overwrite:false})),i&&await fi(c,e),m}return await bn(e),await Ge(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:o,projectPath:a,restoreReceiptPath:p,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:o,manifestPath:p,safetySnapshotPath:c.snapshotPath,dryRun:false}}var Hl="rapidkit.infra-stack.v1",Ci="rapidkit.infra-plan.v1",Kt=".workspai/infra/docker-compose.yml",Vt=".workspai/reports/infra-plan.json",En=".workspai/infra/.env.example";function ql(){let t=b.dirname(fileURLToPath(import.meta.url)),e=[b.join(t,"../../contracts/infra-stack.v1.json"),b.join(t,"../contracts/infra-stack.v1.json")];for(let o of e)if(E.existsSync(o))return o;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var xn=null;function Ct(t){if(xn)return xn;let e=ql(),o=E.readFileSync(e,"utf-8"),r=JSON.parse(o);if(r.schemaVersion!==Hl)throw new Error(`Unsupported infra stack schema: ${r.schemaVersion}`);return zl(r),(xn=r),r}function zl(t){let e=new Set(Object.keys(t.services));for(let[o,r]of Object.entries(t.moduleMappings)){if(!Array.isArray(r))throw new Error(`Invalid moduleMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`moduleMappings/${o} references unknown service '${n}'`)}for(let[o,r]of Object.entries(t.envVarMappings)){if(!Array.isArray(r))throw new Error(`Invalid envVarMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`envVarMappings/${o} references unknown service '${n}'`)}}function Si(t,e){let o=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[o]||[]}function Gt(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function xi(t,e){let o={};for(let r of e){let n=t.services[r];n&&Object.assign(o,n.connectionEnv);}return o}async function Ql(t){let e=b.join(t,"registry.json");if(!await O__default.pathExists(e))return [];try{let r=(await O__default.readJson(e)).installed_modules||[];return [...new Set(r.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function Xl(t){let e=b.join(t,".env.example");if(!await O__default.pathExists(e))return [];try{let o=await O__default.readFile(e,"utf-8"),r=[];for(let n of o.split(`
116
+ `)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&r.push(i[1]);}return r}catch{return []}}async function Zl(t){let e=o$1(t,"infra","overrides.json").find(o=>existsSync(o));if(!e)return [];try{let o=await O__default.readJson(e);return Array.isArray(o.services)?[...new Set(o.services.filter(r=>typeof r=="string"&&r.trim().length>0))]:[]}catch{return []}}async function ep(t){let e=await d$5(t,".workspai/workspace.contract.json");if(!e)return [];try{let o=await O__default.readJson(e),r=[];for(let n of o.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&r.push({project:a,env:i.trim().toUpperCase()});}return r}catch{return []}}function ir(t,e,o,r){t.add(o),e.push(r);}async function Ei(t){let e=b.resolve(t.workspacePath),o=t.contract||Ct(),r=new Set,n=[],a=new Set,i=new Set,c=new Set,l=await i$5(e);for(let p of l){let m=b.dirname(b.dirname(p)),d=b.basename(m);for(let w of await Ql(m)){a.add(w);for(let g of Si(o,w))ir(r,n,g,{kind:"module",value:w,project:d});}for(let w of await Xl(m)){i.add(w);for(let g of Gt(o,w))ir(r,n,g,{kind:"env-var",value:w,project:d});}}for(let p of await ep(e)){i.add(p.env);for(let m of Gt(o,p.env))ir(r,n,m,{kind:"contract-env",value:p.env,project:p.project});}for(let p of await Zl(e))c.add(p),ir(r,n,p,{kind:"override",value:p});return {modules:[...a].sort(),envVars:[...i].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...r].sort()}}function tp(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let o=e.indexOf("=");if(o<=0)return null;let r=e.slice(0,o).trim();if(!/^[A-Z0-9_]+$/.test(r))return null;let n=e.slice(o+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let a=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),i=(a?a[1]:n).trim();return i?{key:r,value:i}:null}async function op(t){if(!await O__default.pathExists(t))return {};try{let e=await O__default.readFile(t,"utf-8"),o={};for(let r of e.split(`
117
+ `)){let n=tp(r);n&&(o[n.key]=n.value);}return o}catch{return {}}}async function Ai(t){let e={},o=await i$5(t.workspacePath);for(let r of o){let n=b.dirname(b.dirname(r)),a=await op(b.join(n,".env.example"));for(let[i,c]of Object.entries(a))Gt(t.contract,i).length>0&&(e[i]=c);}return e}function _i(t,e){return t.filter(o=>Gt(e,o).length>0).sort()}function Ii(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let o=new URL(e),r=o.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(o.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(o.password||"postgres"),POSTGRES_DB:r||"postgres"}}catch{return}}function $i(t){let e=t.POSTGRES_USER||"postgres",o=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${o}`]}function rp(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
118
+ `)?JSON.stringify(t):t}function Oi(t,e){return Object.entries(t).map(([o,r])=>`${e}${o}: ${rp(r)}`).join(`
119
+ `)}function np(t,e){let o=t.test.map(r=>JSON.stringify(r)).join(", ");return [`${e}healthcheck:`,`${e} test: [${o}]`,`${e} interval: ${t.interval}`,`${e} timeout: ${t.timeout}`,`${e} retries: ${t.retries}`].join(`
120
+ `)}function Ni(t){let e=["# Generated by Workspai infra plan \u2014 do not edit manually.",`# Workspace: ${t.workspaceName}`,`# Generated at: ${t.plan.generatedAt}`,"name: workspai-infra"],o=new Set;if(t.plan.services.length===0)return e.push("services: {}"),e.push(""),e.join(`
121
+ `);e.push("services:");for(let r of t.plan.services){let n=t.contract.services[r.id];if(n){if(e.push(` ${r.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: workspai-${r.id}`),n.command?.length){let a=n.command.map(i=>JSON.stringify(i)).join(", ");e.push(` command: [${a}]`);}if(n.env&&Object.keys(n.env).length>0){e.push(" environment:");let a={...n.env,...t.plan.serviceEnvOverrides?.[r.id]||{}};e.push(Oi(a," "));}else t.plan.serviceEnvOverrides?.[r.id]&&(e.push(" environment:"),e.push(Oi(t.plan.serviceEnvOverrides[r.id]," ")));if(n.ports.length>0){e.push(" ports:");for(let a of n.ports)e.push(` - "${a.host}:${a.container}"`);}if(n.volumes?.length){e.push(" volumes:");for(let a of n.volumes){e.push(` - ${a}`);let i=a.split(":")[0];i&&!i.startsWith("/")&&o.add(i);}}if(n.healthcheck){let a=t.plan.serviceEnvOverrides?.[r.id];if(r.id==="postgres"&&a){let i=$i(a).map(c=>JSON.stringify(c)).join(", ");e.push(" healthcheck:"),e.push(` test: [${i}]`),e.push(` interval: ${n.healthcheck.interval}`),e.push(` timeout: ${n.healthcheck.timeout}`),e.push(` retries: ${n.healthcheck.retries}`);}else e.push(np(n.healthcheck," "));}e.push(" restart: unless-stopped");}}if(o.size>0){e.push("volumes:");for(let r of [...o].sort())e.push(` ${r}:`),e.push(" driver: local");}return e.push(""),e.join(`
122
+ `)}function ap(t,e,o){return t.kind==="override"?t.value===e:t.kind==="module"?o.moduleMappings[t.value]?.includes(e)??false:o.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function ip(t){let e=new Map,o=[];for(let r of t)for(let n of r.ports){let a=e.get(n.host);a&&a!==r.id?o.push(`Port collision on host ${n.host} between services '${a}' and '${r.id}'`):e.set(n.host,r.id);}return o}async function cp(t){let e=o$1(t,"workspace.json").find(o=>existsSync(o));if(e)try{let o=await O__default.readJson(e);return o.workspace_name||o.name}catch{return}}async function An(t){let e=b.resolve(t.workspacePath),o=Ct(),r=await Ei({workspacePath:e,contract:o}),n=r.serviceIds.map(w=>{let g=o.services[w];return g?{id:w,displayName:g.displayName,category:g.category,image:g.image,ports:g.ports,sources:r.sources.filter(P=>ap(P,w,o))}:null}).filter(w=>w!==null),a=ip(n);n.length===0&&a.push("No infrastructure services detected. Install modules with infra dependencies or add .workspai/infra/overrides.json");for(let w of r.overrides)o.services[w]||a.push(`Override references unknown service '${w}'`);let i=await d$5(e,".workspai/workspace.contract.json")?".workspai/workspace.contract.json":void 0,c=xi(o,r.serviceIds),l=await Ai({workspacePath:e,contract:o}),p={...c,...l};l.RAPIDKIT_DB_POSTGRES_URL&&(p.DATABASE_URL=l.RAPIDKIT_DB_POSTGRES_URL);let m={},d=Ii(p);return d&&r.serviceIds.includes("postgres")&&(m.postgres=d),{schemaVersion:Ci,generatedAt:(t.now||(()=>new Date))().toISOString(),workspacePath:e,workspaceName:await cp(e),contractPath:i,strategy:"sidecar",composePath:Kt,envExamplePath:En,services:n,connectionEnv:p,serviceEnvOverrides:Object.keys(m).length>0?m:void 0,sources:{modules:r.modules,envVars:r.envVars,overrides:r.overrides},warnings:a}}async function _n(t){let e=b.resolve(t.workspacePath),o=b.join(e,Kt),r=b.join(e,Vt),n=b.join(e,En),a=Ct();a$4(t.plan,"contracts/infra-plan.v1.json","Workspai infrastructure plan");let i=Ni({plan:t.plan,contract:a,workspaceName:t.plan.workspaceName||b.basename(e)}),c=["# Generated by: npx workspai infra plan","# Copy values into project .env files as needed.",...Object.entries(t.plan.connectionEnv).map(([l,p])=>`${l}=${p}`),""].join(`
123
+ `);return t.dryRun?{composePath:o,planPath:r,envExamplePath:n}:(await O__default.ensureDir(b.dirname(o)),await O__default.ensureDir(b.dirname(r)),await O__default.writeFile(o,i,"utf-8"),await O__default.writeFile(r,`${JSON.stringify(t.plan,null,2)}
124
+ `,"utf-8"),await O__default.writeFile(n,c,"utf-8"),{composePath:o,planPath:r,envExamplePath:n})}function lp(t){return b.resolve(t).split(b.sep).join("/")}async function Ti(){if((await execa("docker",["compose","version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker",prefixArgs:["compose"]};if((await execa("docker-compose",["version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker-compose",prefixArgs:[]};throw new Error("Docker Compose is not available. Install Docker Desktop or the docker-compose plugin, then verify with: docker compose version")}async function pp(){if((await execa("docker",["version"],{reject:false,timeout:5e3})).exitCode!==0)throw new Error("Docker is not available in PATH. Install Docker and ensure the daemon is running before using rapidkit infra.");await Ti();}function Wi(t){let e=t.toLowerCase();return e.includes("no space left on device")?"Docker failed because the disk is full. Free space with: docker system prune -f (or docker system prune -a --volumes -f).":e.includes("address already in use")||e.includes("bind")?"Docker failed to bind a host port. Stop the conflicting service or adjust ports in contracts/infra-stack.v1.json via .workspai/infra/overrides.json.":e.includes("cannot connect to the docker daemon")?"Docker daemon is not running. Start Docker Desktop or the docker service, then retry.":null}async function Di(t){await pp();let e=await Ti(),o=lp(t.composePath),r=await execa(e.command,[...e.prefixArgs,"-f",o,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:r.exitCode??1,stdout:r.stdout,stderr:r.stderr}}function lr(t){let e=t?b.resolve(t):vn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");return a$8(e)}function dp(t){return b.join(t,Kt)}async function In(t){let e=b.join(t,Vt);if(!await O__default.pathExists(e))throw new Error(`Infra plan not found at ${Vt}. Run: npx workspai infra plan`);let o=await O__default.readJson(e);return a$4(o,"contracts/infra-plan.v1.json",`Infra plan ${e}`),o}async function $n(t){let e=dp(t.workspacePath);if(!await O__default.pathExists(e))throw new Error(`Compose file not found at ${Kt}. Run: npx workspai infra plan`);return Di({composePath:e,workspacePath:t.workspacePath,args:t.args})}function up(t,e={}){if(console.log(s.bold(`
125
125
  Workspai infra plan
126
- `)),console.log(s.gray(`Workspace: ${t.workspacePath}`)),t.workspaceName&&console.log(s.gray(`Name: ${t.workspaceName}`)),console.log(s.gray(`Strategy: ${t.strategy} (sidecar compose)`)),console.log(s.gray(`Compose: ${t.composePath}`)),console.log(s.gray(`Plan report: ${Vt}`)),console.log(s.gray(`Env example: ${t.envExamplePath}`)),console.log(""),t.services.length===0)console.log(s.yellow("No infrastructure services detected."));else {console.log(s.bold("Services:"));for(let o of t.services){let r=o.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${o.id}`),s.gray(`(${o.displayName})`),r?s.white(`ports ${r}`):"");}}if(t.sources.modules.length>0&&(console.log(""),console.log(s.bold("Detected from modules:")),console.log(s.gray(` ${t.sources.modules.join(", ")}`))),t.sources.envVars.length>0){let o=jt(),r=Ei(t.sources.envVars,o);console.log(s.bold("Detected from env vars (infra-mapped):")),r.length>0?console.log(s.gray(` ${r.join(", ")}`)):console.log(s.gray(" none"));let n=t.sources.envVars.length-r.length;if(n>0&&!e.verbose)console.log(s.gray(` (${n} other project env vars scanned \u2014 use --verbose to list all)`));else if(e.verbose){let a=t.sources.envVars.filter(i=>!r.includes(i));a.length>0&&console.log(s.gray(` Other scanned env vars: ${a.join(", ")}`));}}if(t.sources.overrides.length>0&&(console.log(s.bold("Overrides:")),console.log(s.gray(` ${t.sources.overrides.join(", ")}`))),Object.keys(t.connectionEnv).length>0){console.log(""),console.log(s.bold("Connection env (preview):"));for(let[o,r]of Object.entries(t.connectionEnv))console.log(s.gray(` ${o}=${r}`));}if(t.warnings.length>0){console.log(""),console.log(s.yellow("Warnings:"));for(let o of t.warnings)console.log(s.yellow(` - ${o}`));}console.log("");}function Ti(t){let e=t.command("infra").description("Plan and manage workspace infrastructure (Docker sidecar stack)");e.command("plan").description("Discover infra needs and generate compose plan artifacts").option("--workspace <path>","Workspace root path").option("--json","Print plan as JSON").option("--dry-run","Compute plan without writing artifacts").option("--verbose","Show all scanned project env vars").action(async o=>{try{let r=lr(o.workspace),n=await An({workspacePath:r}),a=await _n({workspacePath:r,plan:n,dryRun:o.dryRun});if(o.json){console.log(JSON.stringify({...n,artifacts:o.dryRun?{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath,dryRun:true}:{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath}},null,2));return}lp(n,{verbose:o.verbose}),o.dryRun?console.log(s.yellow(`Dry run \u2014 no files written.
126
+ `)),console.log(s.gray(`Workspace: ${t.workspacePath}`)),t.workspaceName&&console.log(s.gray(`Name: ${t.workspaceName}`)),console.log(s.gray(`Strategy: ${t.strategy} (sidecar compose)`)),console.log(s.gray(`Compose: ${t.composePath}`)),console.log(s.gray(`Plan report: ${Vt}`)),console.log(s.gray(`Env example: ${t.envExamplePath}`)),console.log(""),t.services.length===0)console.log(s.yellow("No infrastructure services detected."));else {console.log(s.bold("Services:"));for(let o of t.services){let r=o.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${o.id}`),s.gray(`(${o.displayName})`),r?s.white(`ports ${r}`):"");}}if(t.sources.modules.length>0&&(console.log(""),console.log(s.bold("Detected from modules:")),console.log(s.gray(` ${t.sources.modules.join(", ")}`))),t.sources.envVars.length>0){let o=Ct(),r=_i(t.sources.envVars,o);console.log(s.bold("Detected from env vars (infra-mapped):")),r.length>0?console.log(s.gray(` ${r.join(", ")}`)):console.log(s.gray(" none"));let n=t.sources.envVars.length-r.length;if(n>0&&!e.verbose)console.log(s.gray(` (${n} other project env vars scanned \u2014 use --verbose to list all)`));else if(e.verbose){let a=t.sources.envVars.filter(i=>!r.includes(i));a.length>0&&console.log(s.gray(` Other scanned env vars: ${a.join(", ")}`));}}if(t.sources.overrides.length>0&&(console.log(s.bold("Overrides:")),console.log(s.gray(` ${t.sources.overrides.join(", ")}`))),Object.keys(t.connectionEnv).length>0){console.log(""),console.log(s.bold("Connection env (preview):"));for(let[o,r]of Object.entries(t.connectionEnv))console.log(s.gray(` ${o}=${r}`));}if(t.warnings.length>0){console.log(""),console.log(s.yellow("Warnings:"));for(let o of t.warnings)console.log(s.yellow(` - ${o}`));}console.log("");}function Li(t){let e=t.command("infra").description("Plan and manage workspace infrastructure (Docker sidecar stack)");e.command("plan").description("Discover infra needs and generate compose plan artifacts").option("--workspace <path>","Workspace root path").option("--json","Print plan as JSON").option("--dry-run","Compute plan without writing artifacts").option("--verbose","Show all scanned project env vars").action(async o=>{try{let r=lr(o.workspace),n=await An({workspacePath:r}),a=await _n({workspacePath:r,plan:n,dryRun:o.dryRun});if(o.json){console.log(JSON.stringify({...n,artifacts:o.dryRun?{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath,dryRun:true}:{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath}},null,2));return}up(n,{verbose:o.verbose}),o.dryRun?console.log(s.yellow(`Dry run \u2014 no files written.
127
127
  `)):(console.log(s.green("Artifacts written:")),console.log(s.gray(` ${a.composePath}`)),console.log(s.gray(` ${a.planPath}`)),console.log(s.gray(` ${a.envExamplePath}
128
128
  `)));}catch(r){console.error(s.red(`
129
129
  \u274C ${r instanceof Error?r.message:String(r)}
130
- `)),process.exit(1);}}),e.command("up").description("Start planned infrastructure services via Docker Compose").option("--workspace <path>","Workspace root path").option("--detach","Run containers in background",true).option("--build","Build images before starting").option("--no-plan","Skip refreshing plan artifacts before starting").action(async o=>{try{let r=lr(o.workspace);if(o.plan!==false){let c=await An({workspacePath:r});await _n({workspacePath:r,plan:c});}if((await In(r)).services.length===0)throw new Error("Infra plan has no services. Run: npx workspai infra plan (from a workspace with .env.example, core modules, or .workspai/infra/overrides.json)");let a=["up"];o.detach!==false&&a.push("-d"),o.build&&a.push("--build");let i=await $n({workspacePath:r,args:a});if(i.stdout&&process.stdout.write(i.stdout),i.stderr&&process.stderr.write(i.stderr),i.exitCode!==0){let c=Ni(i.stderr);c&&console.error(s.yellow(`
130
+ `)),process.exit(1);}}),e.command("up").description("Start planned infrastructure services via Docker Compose").option("--workspace <path>","Workspace root path").option("--detach","Run containers in background",true).option("--build","Build images before starting").option("--no-plan","Skip refreshing plan artifacts before starting").action(async o=>{try{let r=lr(o.workspace);if(o.plan!==false){let c=await An({workspacePath:r});await _n({workspacePath:r,plan:c});}if((await In(r)).services.length===0)throw new Error("Infra plan has no services. Run: npx workspai infra plan (from a workspace with .env.example, core modules, or .workspai/infra/overrides.json)");let a=["up"];o.detach!==false&&a.push("-d"),o.build&&a.push("--build");let i=await $n({workspacePath:r,args:a});if(i.stdout&&process.stdout.write(i.stdout),i.stderr&&process.stderr.write(i.stderr),i.exitCode!==0){let c=Wi(i.stderr);c&&console.error(s.yellow(`
131
131
  \u26A0\uFE0F ${c}
132
132
  `)),process.exit(i.exitCode);}o.detach!==false&&(console.log(s.green(`
133
133
  \u2705 Infrastructure stack started.
@@ -144,40 +144,40 @@ Workspai infra status
144
144
  `))),i.exitCode!==0&&(i.stderr&&process.stderr.write(i.stderr),process.exit(i.exitCode)),o.strict&&/Restarting|Exit|unhealthy/i.test(i.stdout)&&(console.log(""),console.log(s.red("One or more infra containers are not healthy.")),console.log(s.gray(`Inspect logs with: docker logs workspai-postgres (or redis/mailpit)
145
145
  `)),process.exit(1));}catch(r){console.error(s.red(`
146
146
  \u274C ${r instanceof Error?r.message:String(r)}
147
- `)),process.exit(1);}});}function dp(t){try{let e=b.join(t,"Makefile");return x.existsSync(e)?x.readFileSync(e,"utf8"):""}catch{return ""}}function st(t,e){let o=dp(t);return o?new RegExp(`^${e}\\s*:`,"m").test(o):false}var dr=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureDotnetInstalled(e){return (await this.run("dotnet",["--version"],e)).exitCode===0?null:{exitCode:1,message:".NET SDK is not installed or not available on PATH. Install .NET 8+ from https://dotnet.microsoft.com/download and retry."}}findFilesBySuffix(e,o,r=3){let n=[],a=[{dir:e,depth:0}],i=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;a.length>0;){let c=a.shift();if(!c||c.depth>r)continue;let l=[];try{l=x.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let p of l){let m=b.join(c.dir,p.name);if(p.isDirectory()){i.has(p.name)||a.push({dir:m,depth:c.depth+1});continue}p.name.toLowerCase().endsWith(o.toLowerCase())&&n.push(m);}}return n.sort()}findProjectFile(e){let o=this.findFilesBySuffix(e,".csproj");return o.find(r=>!r.toLowerCase().includes(".tests.csproj"))||o[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(r=>r.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let o=await this.ensureDotnetInstalled(e);return o||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=await this.run("dotnet",r?["restore",r]:["restore"],e);return n.exitCode===0?n:{exitCode:n.exitCode,message:"dotnet restore failed. Check NuGet connectivity, package references, and .NET SDK workload availability, then retry."}}async runDev(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=r?["watch","--project",r,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",r?["test",r]:["test"],e)}async runBuild(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["build",r,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["run","--project",r]:["run"],e)}async runLint(e){if(!b$1()&&st(e,"lint"))return this.run("make",["lint"],e);let o=b.join(e,"Directory.Build.props");if(x.existsSync(o)&&x.readFileSync(o,"utf-8").includes("EnforceCodeStyleInBuild")){let r=await this.ensureDotnetInstalled(e);if(r)return r;let n=this.findProjectFile(e);return this.run("dotnet",n?["build",n,"-warnaserror"]:["build","-warnaserror"],e)}return {exitCode:1,message:"No .NET lint tooling detected. Add a Makefile lint target or enable EnforceCodeStyleInBuild in Directory.Build.props."}}async runFormat(e){if(!b$1()&&st(e,"format"))return this.run("make",["format"],e);let o=await this.ensureDotnetInstalled(e);return o||(x.existsSync(b.join(e,".editorconfig"))?this.run("dotnet",["format","--verify-no-changes"],e):{exitCode:1,message:"No .NET format tooling detected. Add a Makefile format target or an .editorconfig file for dotnet format."})}async doctorHints(e){return ["Install .NET 8+ SDK and ensure dotnet is on PATH.","Run dotnet restore after changing package references.","Use dotnet format --verify-no-changes in CI for deterministic code style."]}};var ur=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureGoInstalled(e){return (await this.run("go",["version"],e)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findGoRunTarget(e){let o=b.join(e,"main.go");if(x.existsSync(o))return "./main.go";let r=b.join(e,"cmd");try{let n=x.readdirSync(r,{withFileTypes:true}).filter(a=>a.isDirectory()).map(a=>a.name).sort();for(let a of n)if(x.existsSync(b.join(r,a,"main.go")))return `./cmd/${a}`}catch{}return "./."}findWorkspaceRoot(e){let o=e;for(;;){if(x.existsSync(b.join(o,".workspai-workspace"))||x.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o$1(r,"policies.yml").find(a=>x.existsSync(a));if(!n)return "isolated";try{let c=x.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withGoCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","go"):b.join(e,".workspai","cache","go"),i=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=b.join(a,"mod"),process.env.GOCACHE=b.join(a,"build"),o().finally(()=>{typeof i>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=i,typeof c>"u"?delete process.env.GOCACHE:process.env.GOCACHE=c;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(e){return this.withGoCacheEnv(e,async()=>{try{return process.env.GOMODCACHE&&x.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&x.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let o=await this.ensureGoInstalled(e);if(o)return o;let r=b.join(e,"Makefile");return !b$1()&&x.existsSync(r)?this.run("make",["run"],e):this.run("go",["run",this.findGoRunTarget(e)],e)})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let r=(b$1()?[b.join(e,"server.exe"),b.join(e,"server")]:[b.join(e,"server")]).find(a=>x.existsSync(a));if(r)return this.run(r,[],e);let n=await this.ensureGoInstalled(e);return n||this.run("go",["run",this.findGoRunTarget(e)],e)})}async runLint(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(!b$1()&&st(e,"lint")?this.run("make",["lint"],e):x.existsSync(b.join(e,".golangci.yml"))||x.existsSync(b.join(e,".golangci.yaml"))?this.run("golangci-lint",["run","./..."],e):{exitCode:1,message:"No Go lint tooling detected. Add a Makefile lint target or .golangci.yml configuration."})})}async runFormat(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(!b$1()&&st(e,"fmt")?this.run("make",["fmt"],e):!b$1()&&st(e,"format")?this.run("make",["format"],e):this.run("go",["fmt","./..."],e))})}async doctorHints(e){return ["Install Go from https://go.dev/dl/ if missing.","Run go mod tidy when dependencies are out of sync.","Use make run for hot-reload if Makefile exists."]}};var mr=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return (x.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return x.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let o=process.env.JAVA_HOME?.trim();if(!o)return "java";let r=b.join(o,"bin",process.platform==="win32"?"java.exe":"java");return x.existsSync(r)?r:"java"}parseMajorJavaVersion(e){if(!e)return null;let r=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(r,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let o=b.join(e,"pom.xml");if(!x.existsSync(o))return 21;try{let n=x.readFileSync(o,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,o){try{let r=await execa(e,["-version"],{cwd:o,timeout:5e3,reject:false});if(r.exitCode!==0)return null;let n=`${r.stdout||""}
147
+ `)),process.exit(1);}});}function gp(t){try{let e=b.join(t,"Makefile");return E.existsSync(e)?E.readFileSync(e,"utf8"):""}catch{return ""}}function at(t,e){let o=gp(t);return o?new RegExp(`^${e}\\s*:`,"m").test(o):false}var dr=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureDotnetInstalled(e){return (await this.run("dotnet",["--version"],e)).exitCode===0?null:{exitCode:1,message:".NET SDK is not installed or not available on PATH. Install .NET 8+ from https://dotnet.microsoft.com/download and retry."}}findFilesBySuffix(e,o,r=3){let n=[],a=[{dir:e,depth:0}],i=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;a.length>0;){let c=a.shift();if(!c||c.depth>r)continue;let l=[];try{l=E.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let p of l){let m=b.join(c.dir,p.name);if(p.isDirectory()){i.has(p.name)||a.push({dir:m,depth:c.depth+1});continue}p.name.toLowerCase().endsWith(o.toLowerCase())&&n.push(m);}}return n.sort()}findProjectFile(e){let o=this.findFilesBySuffix(e,".csproj");return o.find(r=>!r.toLowerCase().includes(".tests.csproj"))||o[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(r=>r.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let o=await this.ensureDotnetInstalled(e);return o||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=await this.run("dotnet",r?["restore",r]:["restore"],e);return n.exitCode===0?n:{exitCode:n.exitCode,message:"dotnet restore failed. Check NuGet connectivity, package references, and .NET SDK workload availability, then retry."}}async runDev(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=r?["watch","--project",r,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",r?["test",r]:["test"],e)}async runBuild(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["build",r,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["run","--project",r]:["run"],e)}async runLint(e){if(!b$1()&&at(e,"lint"))return this.run("make",["lint"],e);let o=b.join(e,"Directory.Build.props");if(E.existsSync(o)&&E.readFileSync(o,"utf-8").includes("EnforceCodeStyleInBuild")){let r=await this.ensureDotnetInstalled(e);if(r)return r;let n=this.findProjectFile(e);return this.run("dotnet",n?["build",n,"-warnaserror"]:["build","-warnaserror"],e)}return {exitCode:1,message:"No .NET lint tooling detected. Add a Makefile lint target or enable EnforceCodeStyleInBuild in Directory.Build.props."}}async runFormat(e){if(!b$1()&&at(e,"format"))return this.run("make",["format"],e);let o=await this.ensureDotnetInstalled(e);return o||(E.existsSync(b.join(e,".editorconfig"))?this.run("dotnet",["format","--verify-no-changes"],e):{exitCode:1,message:"No .NET format tooling detected. Add a Makefile format target or an .editorconfig file for dotnet format."})}async doctorHints(e){return ["Install .NET 8+ SDK and ensure dotnet is on PATH.","Run dotnet restore after changing package references.","Use dotnet format --verify-no-changes in CI for deterministic code style."]}};var ur=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureGoInstalled(e){return (await this.run("go",["version"],e)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findGoRunTarget(e){let o=b.join(e,"main.go");if(E.existsSync(o))return "./main.go";let r=b.join(e,"cmd");try{let n=E.readdirSync(r,{withFileTypes:true}).filter(a=>a.isDirectory()).map(a=>a.name).sort();for(let a of n)if(E.existsSync(b.join(r,a,"main.go")))return `./cmd/${a}`}catch{}return "./."}findWorkspaceRoot(e){let o=e;for(;;){if(E.existsSync(b.join(o,".workspai-workspace"))||E.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o$1(r,"policies.yml").find(a=>E.existsSync(a));if(!n)return "isolated";try{let c=E.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withGoCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","go"):b.join(e,".workspai","cache","go"),i=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=b.join(a,"mod"),process.env.GOCACHE=b.join(a,"build"),o().finally(()=>{typeof i>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=i,typeof c>"u"?delete process.env.GOCACHE:process.env.GOCACHE=c;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(e){return this.withGoCacheEnv(e,async()=>{try{return process.env.GOMODCACHE&&E.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&E.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let o=await this.ensureGoInstalled(e);if(o)return o;let r=b.join(e,"Makefile");return !b$1()&&E.existsSync(r)?this.run("make",["run"],e):this.run("go",["run",this.findGoRunTarget(e)],e)})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let r=(b$1()?[b.join(e,"server.exe"),b.join(e,"server")]:[b.join(e,"server")]).find(a=>E.existsSync(a));if(r)return this.run(r,[],e);let n=await this.ensureGoInstalled(e);return n||this.run("go",["run",this.findGoRunTarget(e)],e)})}async runLint(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(!b$1()&&at(e,"lint")?this.run("make",["lint"],e):E.existsSync(b.join(e,".golangci.yml"))||E.existsSync(b.join(e,".golangci.yaml"))?this.run("golangci-lint",["run","./..."],e):{exitCode:1,message:"No Go lint tooling detected. Add a Makefile lint target or .golangci.yml configuration."})})}async runFormat(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(!b$1()&&at(e,"fmt")?this.run("make",["fmt"],e):!b$1()&&at(e,"format")?this.run("make",["format"],e):this.run("go",["fmt","./..."],e))})}async doctorHints(e){return ["Install Go from https://go.dev/dl/ if missing.","Run go mod tidy when dependencies are out of sync.","Use make run for hot-reload if Makefile exists."]}};var mr=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return (E.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return E.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let o=process.env.JAVA_HOME?.trim();if(!o)return "java";let r=b.join(o,"bin",process.platform==="win32"?"java.exe":"java");return E.existsSync(r)?r:"java"}parseMajorJavaVersion(e){if(!e)return null;let r=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(r,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let o=b.join(e,"pom.xml");if(!E.existsSync(o))return 21;try{let n=E.readFileSync(o,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,o){try{let r=await execa(e,["-version"],{cwd:o,timeout:5e3,reject:false});if(r.exitCode!==0)return null;let n=`${r.stdout||""}
148
148
  ${r.stderr||""}`,a=n.match(/version\s+"([^"]+)"/i);if(a?.[1])return this.parseMajorJavaVersion(a[1]);let i=n.match(/(?:openjdk|java)\s+(\d+(?:[._]\d+)?)/i);return i?.[1]?this.parseMajorJavaVersion(i[1]):null}catch{return null}}parseMavenVersion(e){if(!e)return null;let o=e.match(/Apache Maven\s+(\d+)\.(\d+)\.(\d+)/i);return o?[Number.parseInt(o[1],10),Number.parseInt(o[2],10),Number.parseInt(o[3],10)]:null}isMavenVersionAtLeast(e,o){for(let r=0;r<3;r+=1){if(e[r]>o[r])return true;if(e[r]<o[r])return false}return true}async checkSystemMavenVersion(e){try{let o=await execa("mvn",["-version"],{cwd:e,timeout:5e3,reject:false});if(o.exitCode!==0)return {exitCode:o.exitCode||1,message:"Maven is required and must be available on PATH (3.9+)."};let r=this.parseMavenVersion(`${o.stdout||""}
149
- ${o.stderr||""}`);return r?this.isMavenVersionAtLeast(r,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${r.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let o=x.existsSync(b.join(e,"pom.xml")),r=x.existsSync(b.join(e,"mvnw"))||x.existsSync(b.join(e,"mvnw.cmd")),n=x.existsSync(b.join(e,"build.gradle"))||x.existsSync(b.join(e,"build.gradle.kts"))||x.existsSync(b.join(e,"settings.gradle"))||x.existsSync(b.join(e,"settings.gradle.kts")),a=x.existsSync(b.join(e,"gradlew"))||x.existsSync(b.join(e,"gradlew.bat"));return {hasMavenProject:o||r,hasMavenWrapper:r,hasGradleProject:n||a,hasGradleWrapper:a}}findWorkspaceRoot(e){let o=e;for(;;){if(x.existsSync(b.join(o,".workspai-workspace"))||x.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o$1(r,"policies.yml").find(a=>x.existsSync(a));if(!n)return "isolated";try{let c=x.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let o=b.join(e,"mvnw.cmd");if(process.platform==="win32"&&x.existsSync(o))return {command:o,baseArgs:[]};let r=b.join(e,"mvnw");return x.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let o=b.join(e,"gradlew.bat");if(process.platform==="win32"&&x.existsSync(o))return {command:o,baseArgs:[]};let r=b.join(e,"gradlew");return x.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let o=[],r=new Set,n=[e];for(;n.length>0;){let a=n.shift();if(!a||r.has(a))continue;r.add(a);let i=[];try{i=x.readdirSync(a,{withFileTypes:true});}catch{continue}for(let c of i){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let l=b.join(a,c.name),p=this.inspectJavaProject(l);(p.hasMavenProject||p.hasGradleProject)&&o.push(l),n.push(l);}}return o}withJavaCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","m2"):b.join(e,".workspai","cache","java","m2"),i=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","gradle"):b.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,l=process.env.GRADLE_USER_HOME,p=`-Dmaven.repo.local=${a}`;return process.env.MAVEN_OPTS=c?`${c} ${p}`:p,process.env.GRADLE_USER_HOME=i,o().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof l>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=l;})}async runBuildTool(e,o,r=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:a}=this.buildToolCommand(e),i=await this.runCommand(n,[...a,...o],e);if(i===0||!r)return {exitCode:i};let c=x.existsSync(b.join(e,"pom.xml")),l=x.existsSync(b.join(e,"build.gradle"))||x.existsSync(b.join(e,"build.gradle.kts"));return {exitCode:i,message:c||l?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let o=[b.join(e,"target"),b.join(e,"build","libs")];for(let r of o){if(!x.existsSync(r))continue;let a=x.readdirSync(r).filter(i=>i.toLowerCase().endsWith(".jar")).find(i=>!i.toLowerCase().endsWith("-sources.jar")&&!i.toLowerCase().endsWith("-javadoc.jar")&&!i.toLowerCase().endsWith("-plain.jar"));if(a)return b.join(r,a)}return null}commandArgsFor(e,o){if(e==="gradle"){let r=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return o==="init"?[...r,"dependencies"]:o==="dev"?[...r,"bootRun"]:o==="test"?[...r,"test"]:[...r,"bootJar"]}return o==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:o==="dev"?["spring-boot:run"]:o==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),o=this.resolveJavaCommand(e),r=await this.runCommand(o,["-version"],e);if(r!==0)return {exitCode:r,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),l=await this.detectInstalledJavaMajor(o,e);if(l!==null&&l<c)return {exitCode:1,message:`Detected Java ${l}, but project requires Java ${c}+.`};let p=b.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&x.existsSync(p))try{let d=x.readFileSync(p,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),h=this.parseMajorJavaVersion(d?.[1]);if(h!==null&&h<c)return {exitCode:1,message:`Detected JAVA_HOME version ${h}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),l=c==="gradle"?["--version"]:["-version"],p=await this.runBuildTool(e,l);return p.exitCode!==0?p:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):p}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let l=c.reduce((d,h)=>Math.max(d,this.readRequiredJavaMajor(h)),0);if(l>0){let d=await this.detectInstalledJavaMajor(o,e);if(d!==null&&d<l){let h=c.filter(g=>this.readRequiredJavaMajor(g)>d).map(g=>b.relative(e,g)).join(", ");return {exitCode:1,message:`Detected Java ${d}, but workspace project(s) [${h}] require Java ${l}+.`}}}let p=false,m=false;for(let d of c){let h=this.inspectJavaProject(d);h.hasMavenProject&&!h.hasMavenWrapper&&(p=true),h.hasGradleProject&&!h.hasGradleWrapper&&(m=true);}if(p){let d=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(d!==0)return {exitCode:d,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let h=await this.checkSystemMavenVersion(e);if(h.exitCode!==0)return h}if(m){let d=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(d!==0)return {exitCode:d,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(a===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return i===0?{exitCode:0}:{exitCode:a||i||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let o=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return o&&x.mkdirSync(o,{recursive:true}),process.env.GRADLE_USER_HOME&&x.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let o=this.resolveJarPath(e);if(o)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",o],e)};let r=await this.runBuild(e);if(r.exitCode!==0)return r;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(st(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let o=b.join(e,"pom.xml");if(x.existsSync(o)){let r=x.readFileSync(o,"utf-8");if(r.includes("spotless-maven-plugin"))return this.runBuildTool(e,["spotless:check"]);if(r.includes("checkstyle"))return this.runBuildTool(e,["checkstyle:check"])}return {exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){if(st(e,"format"))return {exitCode:await this.runCommand("make",["format"],e)};let o=b.join(e,"pom.xml");return x.existsSync(o)&&x.readFileSync(o,"utf-8").includes("spotless-maven-plugin")?this.runBuildTool(e,["spotless:apply"]):["build.gradle","build.gradle.kts"].map(n=>b.join(e,n)).filter(n=>x.existsSync(n)).some(n=>x.readFileSync(n,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure Spotless in Maven/Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run npx workspai init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var gr=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}findWorkspaceRoot(e){let o=e;for(;;){if(x.existsSync(b.join(o,".workspai-workspace"))||x.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o$1(r,"policies.yml").find(a=>x.existsSync(a));if(!n)return "isolated";try{let c=x.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,o,r){let n=this.resolveDependencyMode(e),a=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=n==="isolated"?b.join(e,".workspai","cache","node"):b.join(a||e,".workspai","cache","node"),c=process.env.npm_config_cache,l=process.env.npm_config_store_dir,p=process.env.RAPIDKIT_DEP_SHARING_MODE,m=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,a&&(process.env.RAPIDKIT_WORKSPACE_PATH=a),o==="pnpm"?(process.env.npm_config_store_dir=b.join(i,"pnpm-store"),process.env.npm_config_cache=b.join(i,"pnpm-cache")):o==="yarn"?process.env.npm_config_cache=b.join(i,"yarn-cache"):process.env.npm_config_cache=b.join(i,"npm-cache"),r().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof l>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=l,typeof p>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=p,typeof m>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=m;})}detectPackageManager(e){if(x.existsSync(b.join(e,"package-lock.json")))return "npm";if(x.existsSync(b.join(e,"pnpm-lock.yaml")))return "pnpm";if(x.existsSync(b.join(e,"yarn.lock")))return "yarn";if(!this.commandAvailable("npm")){if(this.commandAvailable("pnpm"))return "pnpm";if(this.commandAvailable("yarn"))return "yarn"}return "npm"}hasPinnedPackageManager(e){return x.existsSync(b.join(e,"package-lock.json"))||x.existsSync(b.join(e,"pnpm-lock.yaml"))||x.existsSync(b.join(e,"yarn.lock"))}availablePackageManagers(e){let o=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[o]:[o,...["npm","pnpm","yarn"].filter(n=>n!==o&&this.commandAvailable(n))]}commandAvailable(e){let o=e$6(e);return spawnSync(o.command,[...o.prefixArgs,"--version"],{stdio:"ignore",shell:c$a(),env:g$4()}).status===0}scriptArgs(e,o){return e==="npm"?["run-script",o,"--foreground-scripts"]:["run",o]}async runScriptWithFallback(e,o){let r={exitCode:1};for(let n of this.availablePackageManagers(e))if(r=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,o),e)),r.exitCode===0)return r;return r}async runLifecycle(e,o){let r=i$2(e),n=i$3(e,r),a=t(e,o,{framework:n.key});return a?this.runScriptWithFallback(e,a.scriptName):{exitCode:1,message:`No npm script available for \`${o}\`. Add a "${o}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let o=this.detectPackageManager(e);return this.withDependencyEnv(e,o,async()=>{try{return process.env.npm_config_cache&&x.mkdirSync(process.env.npm_config_cache,{recursive:true}),o==="pnpm"&&process.env.npm_config_store_dir&&x.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let o=this.detectPackageManager(e),r=this.resolveDependencyMode(e),n=r==="shared-runtime-caches"||r==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,o,()=>this.run(o,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var hr=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,o){return {exitCode:await this.withPythonCacheEnv(o,()=>this.runCore(e,o))}}findWorkspaceRoot(e){let o=e;for(;;){if(x.existsSync(b.join(o,".workspai-workspace"))||x.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o$1(r,"policies.yml").find(a=>x.existsSync(a));if(!n)return "isolated";try{let c=x.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","python"):b.join(e,".workspai","cache","python"),i=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=b.join(a,"pip"),process.env.POETRY_CACHE_DIR=b.join(a,"poetry"),o().finally(()=>{typeof i>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=i,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),o=await this.run(["doctor","check"],e);return o.exitCode===0?o:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx workspai doctor workspace" for a full workspace scan.','Use "npx workspai init" after adding or changing modules.',"Use `npx workspai <command>` from the project root to avoid environment drift."]}};function mp(){let t={...process.env},e=t.PATH||"";if(e){let o=e.split(b.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter);t.PATH=o;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||h$3(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ze(t,e){return t==="go"?new ur((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="node"?new gr((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="java"?new mr((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="dotnet"?new dr((o,r,n)=>e.runCommandInCwd(o,r,n)):new hr((o,r)=>e.runCoreRapidkit(o,{cwd:r,env:mp()}))}var Fi=b.join(pn.homedir(),".workspai","cache"),Ji=1440*60*1e3;function Tn(){let t=a$f("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?b.join(Fi,`vitest-${e}`):Fi}var wr=class t{static instance;memoryCache=new Map;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getCacheKey(e){return createHash("md5").update(e).digest("hex")}getCachePath(e){return b.join(Tn(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let o=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${o}.tmp`}async get(e,o="1.0"){let r=this.memoryCache.get(e);if(r&&r.version===o&&Date.now()-r.timestamp<Ji)return f.debug(`Cache hit (memory): ${e}`),r.data;try{let n=this.getCachePath(e),a=await promises.readFile(n,"utf-8"),i=JSON.parse(a);if(i.version===o&&Date.now()-i.timestamp<Ji)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,i),i.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,o,r="1.0"){let n={data:o,timestamp:Date.now(),version:r};this.memoryCache.set(e,n);try{await promises.mkdir(Tn(),{recursive:true});let a=this.getCachePath(e),i=this.getTempCachePath(a);await promises.writeFile(i,JSON.stringify(n),"utf-8"),await promises.rename(i,a),f.debug(`Cache set: ${e}`);}catch(a){f.debug(`Cache write failed: ${e}`,a);}}async invalidate(e){this.memoryCache.delete(e);try{let o=this.getCachePath(e);await promises.unlink(o),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=Tn(),o=await promises.readdir(e);await Promise.all(o.map(r=>promises.unlink(b.join(e,r)))),f.debug("Cache cleared");}catch{}}};var yo=["list","sync","registry","foundation","intelligence","model","snapshot","diff","impact","verify","graph","watch","context","agent-sync","remediation-plan","explain","why","trace","feedback","mcp","policy","contract","share","export","archive","hydrate","import","run","init"],kr=["intelligence","model","snapshot","diff","impact","contract","verify","graph","watch","context","agent-sync","remediation-plan","explain","why","trace","feedback","mcp"];function Ki(t){return kr.includes(t)}var Vi="workspai-project-entry-capability-v1";var Wn="workspai-cli-runtime-command-inventory-v1",vr=[...e$4,"autopilot","pipeline","import","adopt","snapshot","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands","create","project"],Dn=["bootstrap","setup","cache","mirror"],Pr="create",hp=[...Dn,Pr],yp={bootstrap:"Bootstrap project or workspace dependencies through runtime-aware setup rules.",setup:"Prepare a selected runtime toolchain through the supported adapter boundary.",cache:"Inspect or clear Workspai cache state through the managed cache boundary.",mirror:"Coordinate supported mirror lifecycle operations for the current project.",create:"Create a supported workspace or project through the canonical planner boundary."},br=[["ai","generate-embeddings"],["ai","info"],["ai","recommend"],["ai","update-embeddings"],["config","ai"],["config","remove-api-key"],["config","set-api-key"],["config","show"],["infra","down"],["infra","plan"],["infra","status"],["infra","up"],["product","manifest"],["product","manifest","create"],["product","plan"],["project","commands"],["project","archives"],["project","archive"],["project","restore"],["project","delete"],["snapshot","create"],["snapshot","inspect"],["snapshot","list"],["snapshot","restore"]];function wp(t,e,o,r){let n=new Set(t),a=new Set(e),i=t.filter(h=>!a.has(h)).sort(),c=e.filter(h=>!n.has(h)).sort(),l=new Set(o),p=new Set(r),m=o.filter(h=>!p.has(h)).sort(),d=r.filter(h=>!l.has(h)).sort();return {ok:i.length===0&&c.length===0&&m.length===0&&d.length===0,registeredButUndeclared:i,declaredButUnregistered:c,registeredScopedButUndeclared:m,declaredScopedButUnregistered:d}}function Gi(t,e=[]){return t.commands.flatMap(o=>{let r=o.name(),n=[...e,r];return [{path:n,command:r,parent:e.length>0?e.join(" "):null,registrationKind:"commander",aliases:o.aliases?.()??[],description:o.description?.()??"",hidden:o._hidden===true,arguments:(o.registeredArguments??[]).map(i=>({name:i.name(),required:i.required,variadic:i.variadic})),options:(o.options??[]).map(i=>({flags:i.flags,attributeName:i.attributeName?.()??null}))},...Gi(o,n)]})}function Ui(t){let e=Gi(t),o=e.filter(c=>c.path.length===1).map(c=>c.command),r=new Set(o),n=hp.filter(c=>!r.has(c)).map(c=>({path:[c],command:c,parent:null,registrationKind:"manual-handler",aliases:[],description:yp[c],hidden:false,arguments:[],options:[]})),a=[...e,...n].sort((c,l)=>c.path.join(" ").localeCompare(l.path.join(" "))),i=[...new Set(a.filter(c=>c.path.length===1).map(c=>c.command))].sort();return {schemaVersion:Wn,commands:a,topLevelCommands:i,integrity:wp(i,vr,e.filter(c=>c.path.length>1).map(c=>c.path.join(" ")),br.map(c=>c.join(" ")))}}function Bi(t){return `CLI command surface integrity violation (${[t.registeredButUndeclared.length>0?`registered but undeclared: ${t.registeredButUndeclared.join(", ")}`:null,t.declaredButUnregistered.length>0?`declared but unreachable: ${t.declaredButUnregistered.join(", ")}`:null,t.registeredScopedButUndeclared.length>0?`registered scoped but undeclared: ${t.registeredScopedButUndeclared.join(", ")}`:null,t.declaredScopedButUnregistered.length>0?`declared scoped but unreachable: ${t.declaredScopedButUnregistered.join(", ")}`:null].filter(o=>o!==null).join("; ")})`}var Hi="rapidkit-runtime-command-surface-v1";var qi="doctor-remediation-plan-v2";var zi="workspai-workspace-intelligence-architecture-v1";var Yi={autopilotRelease:"autopilot-release-v1",workspaceList:"rapidkit-workspace-list-v1",workspaceSync:"rapidkit-workspace-sync-v1",compatibilityMatrix:"rapidkit.compatibility-matrix.v1",mcpDesign:"workspai-mcp-design.v1",agentHooks:"workspai-agent-hooks.v1",projectArchive:"rapidkit-project-archive-v1",workspaceSnapshot:"rapidkit-workspace-snapshot-v1",workspaceSnapshotV2:"rapidkit-workspace-snapshot-v2",infraPlan:"rapidkit.infra-plan.v1",privateProductManifest:"rapidkit.private-product-manifest.v1",productFactoryPlan:"rapidkit.product-factory-plan.v1",workspaceModelCache:"workspace-model-cache.v1",workspaceWatchEvent:"workspace-watch-event.v1",doctorProjectScan:"doctor-project-scan-v2",doctorWorkspaceCache:"doctor-workspace-cache-v2"};var kp="workspai-published-contract-catalog-v1";function wo(){return {workspaceContract:1,runtimeCommandSurface:Hi,cliRuntimeCommandInventory:Wn,cliOperationResult:a$w,publishedContractCatalog:kp,workspaceArchiveCapabilities:a$v,workspaceArchiveManifest:b$g,workspaceArchiveOperationResult:c$3,projectEntryCapability:Vi,workspaceIntelligenceArchitecture:zi,workspaceIntelligenceChain:a$u,workspaceIntelligenceArtifacts:b$8,cliLogEvent:c$9,freshnessMetadata:a$t,factFreshness:a$s,blockerResolution:a$r,workspaceModel:g$1,workspaceImpact:f$6,workspaceVerify:c$8,workspaceContext:c$7,workspaceDependencyGraph:b$f,workspaceKnowledgeGraph:a$q,workspaceKnowledgeGraphChangeOverlay:a$p,workspaceKnowledgeSearch:a$o,workspaceGraphTokenEfficiency:a$n,workspaceIntelligenceHistory:a$m,agentCustomizationPackCapabilities:l$3,agentCustomizationPackReport:b$8.agentCustomizationPack,agentReportsIndex:b$8.agentIndex,workspaceOperationalSkill:a$l,workspaceSkillsIndex:b$e,workspaceExplain:a$k,agentActionOutcome:a$j,doctorRemediationPlan:qi,artifactRemediationPlan:a$i,doctorFixResult:a$h,...Yi}}function jr(){let t=wo(),e={workspaceContract:"contracts/workspace-contract.v1.json",runtimeCommandSurface:"contracts/runtime-command-surface.v1.json",cliRuntimeCommandInventory:"contracts/cli-runtime-command-inventory.v1.snapshot.json",cliOperationResult:"contracts/cli-operation-result.v1.json",publishedContractCatalog:"contracts/published-contract-catalog.v1.json",workspaceArchiveCapabilities:"contracts/workspace-archive-capabilities.v1.json",workspaceArchiveManifest:"contracts/workspace-archive-manifest.v1.json",workspaceArchiveOperationResult:"contracts/workspace-archive-operation-result.v1.json",projectEntryCapability:"contracts/project-entry-capability.v1.json",workspaceIntelligenceArchitecture:"contracts/workspace-intelligence-architecture.v1.json",workspaceIntelligenceChain:"contracts/workspace-intelligence-chain.v1.json",workspaceIntelligenceArtifacts:null,cliLogEvent:"contracts/cli-log-event.v1.json",freshnessMetadata:null,factFreshness:"contracts/workspace-intelligence/fact-freshness.v1.json",blockerResolution:"contracts/workspace-intelligence/blocker-resolution.v1.json",workspaceModel:"contracts/workspace-intelligence/workspace-model.v1.json",workspaceImpact:"contracts/workspace-intelligence/workspace-impact.v1.json",workspaceVerify:"contracts/workspace-intelligence/workspace-verify.v1.json",workspaceContext:"contracts/workspace-intelligence/workspace-context.v1.json",workspaceDependencyGraph:"contracts/workspace-intelligence/workspace-dependency-graph.v1.json",workspaceKnowledgeGraph:"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json",workspaceKnowledgeGraphChangeOverlay:"contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json",workspaceKnowledgeSearch:"contracts/workspace-intelligence/workspace-knowledge-search.v1.json",workspaceGraphTokenEfficiency:"contracts/workspace-intelligence/workspace-graph-token-efficiency.v1.json",workspaceIntelligenceHistory:"contracts/workspace-intelligence/workspace-intelligence-history.v1.json",agentCustomizationPackCapabilities:"contracts/agent-customization-pack.v1.json",agentCustomizationPackReport:"contracts/workspace-intelligence/agent-customization-pack-report.v1.json",agentReportsIndex:"contracts/workspace-intelligence/agent-reports-index.v1.json",workspaceOperationalSkill:"contracts/workspace-intelligence/workspace-operational-skill.v1.json",workspaceSkillsIndex:"contracts/workspace-intelligence/workspace-skills-index.v1.json",workspaceExplain:"contracts/workspace-intelligence/workspace-explain.v1.json",agentActionOutcome:"contracts/workspace-intelligence/agent-action-outcome.v1.json",doctorRemediationPlan:"contracts/doctor-remediation-plan.v2.json",artifactRemediationPlan:"contracts/artifact-remediation-plan.v1.json",doctorFixResult:"contracts/workspace-intelligence/doctor-fix-result.v1.json",autopilotRelease:"contracts/autopilot-release.v1.json",workspaceList:"contracts/workspace-list.v1.json",workspaceSync:"contracts/workspace-sync.v1.json",compatibilityMatrix:"contracts/compatibility-matrix.v1.json",mcpDesign:"contracts/workspace-intelligence/mcp-design.v1.json",agentHooks:"contracts/workspace-intelligence/agent-hooks.v1.json",projectArchive:"contracts/project-archive.v1.json",workspaceSnapshot:"contracts/workspace-snapshot.v1.json",workspaceSnapshotV2:"contracts/workspace-snapshot.v2.json",infraPlan:"contracts/infra-plan.v1.json",privateProductManifest:"contracts/private-product-manifest.v1.json",productFactoryPlan:"contracts/product-factory-plan.v1.json",workspaceModelCache:"contracts/workspace-model-cache.v1.json",workspaceWatchEvent:"contracts/workspace-watch-event.v1.json",doctorProjectScan:"contracts/doctor-project-scan.v2.json",doctorWorkspaceCache:"contracts/doctor-workspace-cache.v2.json"};return Object.fromEntries(Object.entries(t).map(([o,r])=>{let n=e[o];return [o,{schemaVersion:r,contractPath:n,publication:n?o==="runtimeCommandSurface"||o==="cliRuntimeCommandInventory"||o.endsWith("Capabilities")?"capability-contract":"json-schema":"embedded-type",...o==="workspaceIntelligenceArtifacts"?{artifacts:Object.fromEntries(Object.keys(a$5).map(a=>[a,{path:a$5[a],schemaVersion:b$8[a],contractPath:c$6[a]}]))}:{}}]}))}var Ln="rapidkit-command-capabilities-v1",Qi="rapidkit-version-v1";var vp=["catalog","pulse","nova","orbit","atlas","vertex","summit","beacon","ledger","flux","nexus","apex","harbor","forge","spark","portal","studio","canvas","quantum","vault","zenith","compass","vector","catalyst","saas","commerce","radar","stellar","prism","cedar","momentum","signal","cipher","lumen","trail","ridge"],Pp={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},bp={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"};function jp(t){return t[Math.floor(Math.random()*t.length)]}function Fn(t){let e=jp(vp),o=j$1(t);if(o){let a=bp[o.id]??"app";return `${e}-${a}`}let r=a$2(t),n=r?Pp[r.id]??"service":"app";return `${e}-${n}`}async function Ep(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function Rp(t){if(!await I.pathExists(t))return [];let e=[],o=[t];for(;o.length>0;){let r=o.shift();if(r)for(let n of await promises.readdir(r,{withFileTypes:true})){let a=b.join(r,n.name);n.isFile()?e.push(a):n.isDirectory()&&o.push(a);}}return e}async function Zi(t,e){await I.outputFile(t,`${JSON.stringify(e,null,2)}
150
- `,"utf-8");}function et(t,e){return b.isAbsolute(e)?e:b.join(t,e)}function Ap(t,e){if(!e.trim()||b.isAbsolute(e)||/^[a-zA-Z]:[\\/]/.test(e))throw new Error(`Mirror artifact target must be a non-empty relative path: ${e}`);let o=b.resolve(t),r=b.resolve(o,e),n=b.relative(o,r);if(!n||n.startsWith("..")||b.isAbsolute(n))throw new Error(`Mirror artifact target escapes the managed artifact directory: ${e}`);return r}async function ec(t,e){let o=b.relative(t,e),r=t;for(let a of o.split(b.sep).slice(0,-1)){r=b.join(r,a);let i=await promises.lstat(r).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: ${r}`);if(!i.isDirectory())throw new Error(`Mirror artifact target parent is not a directory: ${r}`)}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 _p(t,e){let o=b.resolve(t),r=b.relative(o,b.resolve(e));if(!r||r.startsWith("..")||b.isAbsolute(r))throw new Error("Managed mirror directory escapes the workspace.");let n=o;for(let a of r.split(b.sep)){n=b.join(n,a);let i=await promises.lstat(n);if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Managed mirror path must contain only real directories: ${n}`)}}function Ip(t,e){if(t.target)return t.target;if(t.source)return b.basename(t.source);if(t.url)try{let o=new URL(t.url).pathname,r=b.basename(o);if(r&&r!=="/")return r}catch{}return `${e}.artifact`}async function $p(t){let e=o$1(t,"trusted-sources.lock").find(r=>existsSync(r)),o=new Set(["localhost","127.0.0.1"]);if(!e)return o;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));for(let a of n)o.add(a.toLowerCase());}catch{}return o}async function Op(t,e,o){await I.ensureDir(b.dirname(e)),await new Promise((r,n)=>{let i=(t.startsWith("https://")?ac:sc).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let l=createWriteStream(e);c.pipe(l),l.on("finish",()=>{l.close(),r();}),l.on("error",p=>{n(p);});});i.setTimeout(o,()=>{i.destroy(new Error(`Request timeout after ${o}ms`));}),i.on("error",c=>{n(c);});});}async function Np(t,e,o,r,n){let a=new URL(t),i=JSON.stringify(e),c=a.protocol==="https:"?ac:sc;await new Promise((l,p)=>{let m=c.request({method:"POST",hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:`${a.pathname}${a.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...r?{Authorization:`Bearer ${r}`}:{},...n||{}}},d=>{if(!d.statusCode||d.statusCode<200||d.statusCode>=300){p(new Error(`HTTP ${d.statusCode||"unknown"}`)),d.resume();return}d.resume(),l();});m.setTimeout(o,()=>{m.destroy(new Error(`Request timeout after ${o}ms`));}),m.on("error",d=>{p(d);}),m.write(i),m.end();});}function tc(t){return new Promise(e=>setTimeout(e,t))}async function Mp(t,e,o,r){let n=et(t,e||".workspai/reports/evidence-export-dead-letter.ndjson");return await I.ensureDir(b.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:r,payload:o})}
151
- `,"utf-8"),n}function Tp(t,e){if(!e?.enabled)return {headers:{}};let o=process.env[e.hmacKeyEnv];if(!o)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let r=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(r,o).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":r}}}async function Wp(t,e,o){let r=(o.algorithm||"sha256").toLowerCase(),n=et(t,o.publicKeyPath);if(!await I.pathExists(n))return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(r);c.update(i),c.end();let l=Buffer.from(o.signature,"base64"),p=c.verify(a,l),m=createHash("sha256").update(a).digest("hex");return {verified:p,algorithm:r,publicKeyPath:n,publicKeyFingerprint:m,signature:o.signature,message:p?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Attestation verification error: ${a.message}`}}}async function Dp(t,e,o,r){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};let a=o.signaturePath?et(t,o.signaturePath):null;if(!a||!await I.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=o.certificatePath?et(t,o.certificatePath):null;c&&i.push("--certificate",c);let l=o.bundlePath?et(t,o.bundlePath):null;l&&i.push("--bundle",l);let p=o.keyPath?et(t,o.keyPath):null;p&&i.push("--key",p),o.identity&&i.push("--certificate-identity",o.identity),o.issuer&&i.push("--certificate-oidc-issuer",o.issuer),o.rekorUrl&&i.push("--rekor-url",o.rekorUrl),r.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let m=await execa("cosign",i,{reject:false});return m.exitCode===0?{verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${m.stderr||m.stdout||"unknown error"}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}catch(m){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${m.message}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}}async function Lp(t,e){let o=e.algorithm||"sha256",r=et(t,e.policyPath),n=et(t,e.signaturePath),a=et(t,e.publicKeyPath);if(!await I.pathExists(r))return {verified:false,message:`Governance policy bundle not found: ${r}`,policies:null};if(!await I.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await I.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(r,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),l=await promises.readFile(a,"utf-8"),p=createVerify(o);return p.update(i),p.end(),p.verify(l,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function Jn(t,e){let o=[],r={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=o$1(t,"mirror-config.json").find(W=>existsSync(W))??l(t,"mirror-config.json"),a=l(t,"mirror.lock"),i=l(t,"mirror","artifacts"),c=l(t,"reports"),l$1=await $p(t);if(!await I.pathExists(n))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:o,details:r};let p={};try{p=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return o.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:o,details:r}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||p.mode==="offline-only"))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:o,details:r};await I.ensureDir(i);try{await _p(t,i);}catch(W){return o.push({id:"mirror.root.safety",status:"failed",message:W instanceof Error?W.message:String(W)}),{checks:o,details:r}}let d=Math.max(0,p.prefetch?.retries??2),h=Math.max(0,p.prefetch?.backoffMs??250),g=Math.max(1e3,p.prefetch?.timeoutMs??15e3),k=p.security?.requireAttestation===true,C=p.security?.requireSigstore===true,A=p.security?.requireTransparencyLog===true,w=p.security?.requireSignedGovernance===true,y=p.security?.evidenceExport,f=(process.env.RAPIDKIT_ENV||p.security?.governance?.environment||"dev").toLowerCase(),v=p.security?.governance?.policies||{};if(p.security?.governanceBundle){let W=await Lp(t,p.security.governanceBundle);if(o.push({id:"governance.bundle.verify",status:W.verified?"passed":"failed",message:W.message}),W.verified&&W.policies)v=W.policies,r.governanceBundleVerified=true;else if(w)return {checks:o,details:r}}let u=v[f],j=A||u?.requireTransparencyLog===true,P=[],E=Array.isArray(p.artifacts)?p.artifacts:[],S=[];for(let W=0;W<E.length;W+=1){let N=E[W],R=N.id||`artifact-${W+1}`,H=N.source?et(t,N.source):null,G=Ip(N,R),D;try{D=Ap(i,G),await ec(i,D);}catch(ve){o.push({id:`mirror.target.${R}`,status:"failed",message:ve instanceof Error?ve.message:String(ve)});continue}let q=false,ee=D,Re=false,de=async()=>{Re&&await promises.rm(ee,{force:true}).catch(()=>{});},ne={sourceType:"path",source:H||N.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(H&&await I.pathExists(H))await I.ensureDir(b.dirname(D)),ee=`${D}.${process.pid}.${randomUUID()}.tmp`,Re=true,await promises.copyFile(H,ee),r.syncedArtifacts+=1,q=true,ne={sourceType:"path",source:H,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},o.push({id:`mirror.sync.${R}`,status:"passed",message:`Mirrored artifact ${R} from source path.`});else if(N.url){let ve="";try{ve=new URL(N.url).hostname.toLowerCase();}catch{o.push({id:`mirror.prefetch.${R}`,status:"failed",message:`Invalid URL for ${R}: ${N.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||l$1.has(ve))){o.push({id:`mirror.prefetch.trust.${R}`,status:"failed",message:`Untrusted mirror host for ${R}: ${ve}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await I.pathExists(D)?(q=true,ne={sourceType:"url",source:N.url,host:ve,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},o.push({id:`mirror.prefetch.${R}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${R}.`})):o.push({id:`mirror.prefetch.${R}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${R} without an existing mirrored copy.`}),!q))continue;if(!q){await I.ensureDir(b.dirname(D)),ee=`${D}.${process.pid}.${randomUUID()}.tmp`,Re=true;let Pe=null,O=0;for(let F=1;F<=d+1;F+=1){O=F;try{await promises.rm(ee,{force:true}).catch(()=>{}),await Op(N.url,ee,g),r.syncedArtifacts+=1,q=true,ne={sourceType:"url",source:N.url,host:ve,fetchedAt:new Date().toISOString(),attempts:O,trusted:true},o.push({id:`mirror.prefetch.${R}`,status:"passed",message:O>1?`Prefetched artifact ${R} from ${ve} after ${O} attempts.`:`Prefetched artifact ${R} from ${ve}.`});break}catch(te){if(Pe=te,F<=d){await tc(h*F);continue}}}if(!q){await de(),o.push({id:`mirror.prefetch.${R}`,status:"failed",message:`Failed to prefetch ${R} after ${d+1} attempt(s): ${Pe?.message||"unknown error"}`});continue}}if(!q){o.push({id:`mirror.prefetch.${R}`,status:"failed",message:`Failed to prefetch ${R}.`});continue}}if(!q){N.required||e.offlineMode?o.push({id:`mirror.sync.${R}`,status:"failed",message:`Mirror source missing for ${R}${H?`: ${H}`:""}`}):o.push({id:`mirror.sync.${R}`,status:"skipped",message:`Mirror source not found for optional artifact ${R}.`});continue}let Ae=await Ep(ee);if(N.sha256&&N.sha256.toLowerCase()!==Ae.toLowerCase()){o.push({id:`mirror.verify.${R}`,status:"failed",message:`Checksum mismatch for ${R}.`}),await de();continue}r.verifiedArtifacts+=1,o.push({id:`mirror.verify.${R}`,status:"passed",message:`Checksum verified for ${R}.`});let Oe=N.attestation?await Wp(t,ee,N.attestation):null;if(N.attestation){if(o.push({id:`mirror.attest.${R}`,status:Oe?.verified?"passed":"failed",message:Oe?.message||"Attestation verification failed."}),!Oe?.verified){await de();continue}}else if(k){o.push({id:`mirror.attest.${R}`,status:"failed",message:`Attestation is required but missing for ${R}.`}),await de();continue}else o.push({id:`mirror.attest.${R}`,status:"skipped",message:`No attestation provided for ${R}.`});let Ne=N.attestation?.sigstore,oe=Ne?await Dp(t,ee,Ne,{requireTransparencyLog:j}):null;if(Ne){if(o.push({id:`mirror.sigstore.${R}`,status:oe?.verified?"passed":"failed",message:oe?.message||"Sigstore verification failed."}),P.push({artifactId:R,verified:!!oe?.verified,tlogVerified:!!oe?.tlogVerified,identity:oe?.identity||null,issuer:oe?.issuer||null,rekorUrl:oe?.rekorUrl||null,timestamp:new Date().toISOString(),environment:f}),!oe?.verified){await de();continue}}else if(C){o.push({id:`mirror.sigstore.${R}`,status:"failed",message:`Sigstore attestation is required but missing for ${R}.`}),await de();continue}else o.push({id:`mirror.sigstore.${R}`,status:"skipped",message:`No Sigstore attestation provided for ${R}.`});if(Ne&&oe?.verified&&u){let ve=u.allowedIdentities||[];if(ve.length>0){let Pe=!!oe.identity&&ve.includes(oe.identity);if(o.push({id:`mirror.sigstore.policy.identity.${R}`,status:Pe?"passed":"failed",message:Pe?`Sigstore identity policy passed for ${R} in ${f}.`:`Sigstore identity policy failed for ${R} in ${f}.`}),!Pe){await de();continue}}let Zt=u.allowedIssuers||[];if(Zt.length>0){let Pe=!!oe.issuer&&Zt.includes(oe.issuer);if(o.push({id:`mirror.sigstore.policy.issuer.${R}`,status:Pe?"passed":"failed",message:Pe?`Sigstore issuer policy passed for ${R} in ${f}.`:`Sigstore issuer policy failed for ${R} in ${f}.`}),!Pe){await de();continue}}let At=u.allowedRekorUrls||[];if(At.length>0){let Pe=!!oe.rekorUrl&&At.includes(oe.rekorUrl);if(o.push({id:`mirror.sigstore.policy.rekor.${R}`,status:Pe?"passed":"failed",message:Pe?`Sigstore Rekor policy passed for ${R} in ${f}.`:`Sigstore Rekor policy failed for ${R} in ${f}.`}),!Pe){await de();continue}}}else u&&o.push({id:`mirror.sigstore.policy.${R}`,status:"skipped",message:`Sigstore governance policy configured for ${f} but no verified Sigstore attestation for ${R}.`});Re&&(await ec(i,D),await promises.rename(ee,D),Re=false);let ms=await promises.stat(D);S.push({id:R,path:b.relative(t,D),sha256:Ae,size:ms.size,provenance:ne,attestation:{detached:{provided:!!N.attestation,verified:Oe?.verified||false,algorithm:Oe?.algorithm||null,publicKeyPath:Oe?.publicKeyPath||null,publicKeyFingerprint:Oe?.publicKeyFingerprint||null,signature:Oe?.signature||null,verifiedAt:Oe?.verified?new Date().toISOString():null},sigstore:{provided:!!Ne,verified:oe?.verified||false,tlogVerified:oe?.tlogVerified||false,identity:oe?.identity||null,issuer:oe?.issuer||null,rekorUrl:oe?.rekorUrl||null,bundlePath:oe?.bundlePath||null,certificatePath:oe?.certificatePath||null,signaturePath:oe?.signaturePath||null,verifiedAt:oe?.verified?new Date().toISOString():null}}});}let $=p.retention?.keepLast;if(typeof $=="number"&&$>0){let W=new Set(S.map(R=>b.resolve(t,R.path))),N=(await Rp(i)).filter(R=>!W.has(b.resolve(R)));if(N.length>$){let R=await Promise.all(N.map(async G=>({filePath:G,stat:await promises.stat(G)})));R.sort((G,D)=>D.stat.mtimeMs-G.stat.mtimeMs);let H=R.slice($);for(let G of H)await promises.unlink(G.filePath),r.rotatedFiles+=1;}}o.push({id:"mirror.rotate",status:"passed",message:r.rotatedFiles>0?`Mirror retention rotation removed ${r.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let L={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:p.mode||null,environment:f,artifacts:S};if(await promises.writeFile(a,`${JSON.stringify(L,null,2)}
152
- `,"utf-8"),r.lockWritten=true,o.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${b.relative(t,a)}.`}),r.transparencyEvidenceRecords=P.length,P.length>0){let W={schemaVersion:"transparency-evidence.v1",generatedAt:new Date().toISOString(),environment:f,records:P},N=new Date().toISOString().replace(/[:.]/g,"-"),R=b.join(c,`transparency-evidence-${N}.json`),H=b.join(c,"transparency-evidence.latest.json");if(b$i(`.workspai/reports/${b.basename(R)}`,W),b$i(".workspai/reports/transparency-evidence.latest.json",W),await I.ensureDir(c),await Zi(R,W),await Zi(H,W),r.transparencyEvidenceWritten=true,o.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${b.relative(t,H)}.`}),y?.enabled){let G=Math.max(1e3,y.timeoutMs??1e4);if(y.target==="file")if(!y.filePath)o.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let D=et(t,y.filePath);await I.ensureDir(b.dirname(D)),await promises.appendFile(D,`${JSON.stringify(W)}
153
- `,"utf-8"),r.evidenceExported=true,r.evidenceExportTarget=D,o.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${D}.`});}catch(D){o.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${D.message}`});}else if(y.target==="http")if(!y.endpoint)o.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let D=Math.max(0,y.retries??0),q=Math.max(0,y.backoffMs??500),ee=Tp(W,y.signing);ee.error&&o.push({id:"sigstore.evidence.export.http",status:"failed",message:ee.error});try{let Re=y.authTokenEnv?process.env[y.authTokenEnv]:void 0,de=false,ne=null;for(let Ae=1;Ae<=D+1;Ae+=1)try{if(ee.error)throw new Error(ee.error);await Np(y.endpoint,W,G,Re,ee.headers),r.evidenceExported=true,r.evidenceExportTarget=y.endpoint,o.push({id:"sigstore.evidence.export.http",status:"passed",message:Ae>1?`Transparency evidence exported to HTTP endpoint ${y.endpoint} after ${Ae} attempts.`:`Transparency evidence exported to HTTP endpoint ${y.endpoint}.`}),de=true;break}catch(Oe){ne=Oe,Ae<=D&&await tc(q*Ae);}if(!de)throw ne||new Error("unknown evidence export error")}catch(Re){let de=`Evidence HTTP export failed: ${Re.message}`;o.push({id:"sigstore.evidence.export.http",status:"failed",message:de});try{let ne=await Mp(t,y.deadLetterPath,W,de);o.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${ne}.`});}catch(ne){o.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${ne.message}`});}}}if(y.failOnError&&o.some(q=>q.status==="failed"&&(q.id==="sigstore.evidence.export.file"||q.id==="sigstore.evidence.export.http")))return {checks:o,details:r}}else o.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else o.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),o.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:o,details:r}}function Cr(t){let e=f$7(t.detection.runtime),o=u({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),r=[];r.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),r.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),r.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),r.push({id:"lifecycle-commands",status:o.lifecycleCommands.length>1?"pass":"warn",message:o.lifecycleCommands.length>1?`Lifecycle commands available: ${o.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:o.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=r.some(i=>i.status==="fail"),a=r.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:o.lifecycleCommands,unsupportedLifecycleCommands:o.unsupportedLifecycleCommands,moduleCommands:o.moduleCommands},checks:r}}function Fp(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function Sr(t){if(t.existingProjectJson?.module_support===true){let e=Fp(t.existingProjectJson),o=e?a$2(e):void 0;return o?.owner==="core"&&o.moduleSupport===true}return false}function ic(t){return t.replace(/\\/g,"/")}function Jp(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function Kp(t,e){let o=ic(b.relative(t,e));return !o||o.startsWith("..")?true:o.split("/").filter(Boolean).some(r=>r==="..")}function ko(t){let e=ic(b.relative(t.workspacePath,t.projectPath)),o=Kp(t.workspacePath,t.projectPath),r=Jp(t.projectName,b.basename(t.projectPath)),n=o?`external/${r}`:e||r;return {relativePath:e||n,contractRelativePath:n,isExternal:o}}var cc=[a$x,b$h];function Vp(t,e){let o=b.relative(t,e);return o===""||o.length>0&&!o.startsWith("..")&&!b.isAbsolute(o)}async function Be(t){let e=await I__default.realpath(t);for(let o of cc){let r=b.join(t,o),n=await I__default.lstat(r).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: ${r}`);let a=await I__default.realpath(r);if(!Vp(e,a))throw new Error(`Project metadata directory resolves outside the project: ${r}`)}}async function lc(t){let e=b.basename(t);return cc.includes(e)?(await I__default.lstat(t)).isSymbolicLink():false}var uc={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},Bp={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"},Hp={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},pc=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function Vn(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function Gn(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function vo(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 Rr(t){let e=new Set;for(let o of t)e.add(vo(o));return [...e].sort((o,r)=>pc.indexOf(o)-pc.indexOf(r))}function qp(t){let e=Rr(t).filter(o=>o!=="unknown");if(e.length!==0)return e.length===1?Hp[e[0]]:"polyglot"}function dc(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function zp(t,e){return t?"none":e==="strict"?"error":"warning"}function Po(t){let e=t.ok?void 0:qp(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?dc(e):void 0,ciRecommendedCommand:e?dc(e,{ci:true}):void 0,severity:zp(t.ok,t.mode)}}function St(t){let e=Gn(t.profile),o=Rr(t.runtimes),r=t.mode??"warn",n=uc[e];if(n){let a=o.length===0||o.every(i=>Vn(i)===n);return Po({ok:a,checkId:`profile.${e}`,profile:e,runtimes:o,message:a?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${o.join(", ")}].`,mode:r})}if(e==="minimal"){let a=o.filter(l=>l!=="unknown"),c=new Set(a.map(l=>Vn(l))).size<=1;return Po({ok:c,checkId:"profile.minimal",profile:e,runtimes:o,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${a.join(", ")}].`,mode:r})}return Po({ok:true,checkId:`profile.${e}`,profile:e,runtimes:o,message:`${e} profile accepts the detected runtime mix.`,mode:r})}function kt(t){let e=Gn(t.profile),o=vo(t.runtime),r=t.mode??"warn",n=uc[e];if(!n||o==="unknown")return Po({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[o],message:o==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:r});let a=Vn(o)===n;return Po({ok:a,checkId:`profile.${e}`,profile:e,runtimes:a?[o]:Rr([n,o]),message:a?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${Bp[o]}, but workspace profile is "${e}".`,mode:r})}async function qt(t){let e=(await Promise.all(o$1(t,"policies.yml").map(async o=>await I__default.pathExists(o)?o:null))).find(o=>typeof o=="string");if(!e)return "warn";try{return (await I__default.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function zt(t){let e=(await Promise.all(o$1(t,"workspace.json").map(async o=>await I__default.pathExists(o)?o:null))).find(o=>typeof o=="string");if(!e)return "minimal";try{let o=await I__default.readJson(e);return Gn(o.profile)}catch{return "minimal"}}async function xt(t,e={}){let o=new Set,r=[],n=new Set,a=[t];for(;a.length>0;){let i=a.pop();if(!i||n.has(i))continue;n.add(i);let c=[];try{c=await x.promises.readdir(i,{withFileTypes:true});}catch{continue}for(let l of c){if(!l.isDirectory()||l.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(l.name))continue;let p$1=b.join(i,l.name);if(p$1!==t&&f$4(p$1))continue;if((await Promise.all([...p(p$1,"context.json"),...p(p$1,"project.json")].map(async d=>I__default.pathExists(d)))).some(Boolean)){r.push(p$1);continue}a.push(p$1);}}for(let i of r){let c=i$2(i);o.add(vo(i$3(i,c).runtime));}for(let i of await a$y(t))o.add(vo(i.runtime));for(let i of e.additionalRuntimes??[])o.add(vo(i));return Rr(o)}function Ar(t,e={}){let o=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return o?`Recommended: ${o}`:null}function mc(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Qp(t){let e=t.trim();if(!e)return "imported-project";let o=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),r=o[o.length-1]||e,n=r.split(":"),a=(n[n.length-1]||r).replace(/\.git$/i,"");return mc(a)||"imported-project"}function _r(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function Xp(t){return _r(t)?"git-url":"local-folder"}async function Zp(t,e){let o=mc(e)||"imported-project",r=0;for(;;){let n=r===0?o:r===1?`${o}-imported`:`${o}-imported-${r}`,a=b.join(t,n);if(!await I__default.pathExists(a))return a;r+=1;}}function ed(t,e){let o=b.resolve(t),r=b.resolve(e),n=b.relative(o,r);return n===""||n.length>0&&!n.startsWith("..")&&!b.isAbsolute(n)}function td(t,e){if(ed(t,e))throw new Error("Import source must be outside the current workspace root.")}function od(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function rd(t){let e=b.basename(t);return !(await lc(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||od(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function nd(t){await Be(t);for(let e of p(t,"project.json"))if(await I__default.pathExists(e))try{return await I__default.readJson(e)}catch{return null}return null}async function sd(t){await Be(t.projectPath);let e=new Date().toISOString(),o=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),r=ko({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:o}),n=r.contractRelativePath,a=q(t.projectPath,"project.json"),i=q(t.projectPath,"import.json"),c=q(t.projectPath,"import-readiness.json"),l=Sr({existingProjectJson:t.existingProjectJson}),p=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],m=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},d={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:b.basename(t.projectPath),kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:l,modules:p,contracts:m,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:r.relativePath,is_external:r.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},h={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:b.basename(t.projectPath)},project:{name:d.name,slug:d.slug,relative_path:n,kind:t.projectKind,module_support:l},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:l,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},g=Cr({projectName:String(d.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:l,projectPath:t.projectPath,generatedAt:new Date(e)});return await I__default.ensureDir(b.dirname(a)),await I__default.writeJson(a,d,{spaces:2}),await I__default.writeJson(i,h,{spaces:2}),await I__default.writeJson(c,g,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:l}}async function ad(t,e){let o={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,importedAt:new Date().toISOString()};await b$d(t,[o]);}async function id(t){await I__default.pathExists(t)&&(await Be(t),await I__default.remove(t));}async function gc(t){let e=b.resolve(t.workspacePath),o=t.source.trim(),r=t.sourceType??Xp(o),n=t.name??(r==="git-url"?Qp(o):b.basename(o)),a=await Zp(e,n),i=false;try{if(r==="local-folder"){let y=b.resolve(o),f=await I__default.stat(y).catch(()=>null);if(!f||!f.isDirectory())throw new Error("Import source is not a directory.");if(await Be(y),f$4(y))throw new Error("This is a workspace. Import it as a workspace instead.");td(e,y),i=true,await I__default.copy(y,a,{overwrite:false,errorOnExist:true,filter:rd});}else i=true,await execa("git",["clone","--depth","1","--",o,a],{timeout:12e4,env:a$d()});await Be(a);let c=await nd(a),l=i$3(a,c),p=await f$5(a,c),[m,d]=await Promise.all([zt(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):qt(e)]),h=kt({profile:m,runtime:l.runtime,subjectLabel:b.basename(a),mode:d}),g=St({profile:m,runtimes:await xt(e,{additionalRuntimes:[l.runtime]}),mode:d}),k=h.ok?g:h;if(!k.ok&&d==="strict")throw new Error(k.message);let C=await sd({workspacePath:e,projectPath:a,sourceType:r,detection:l,existingProjectJson:c,projectKind:p,profileCompatibility:k}),A=ko({workspacePath:e,projectPath:a,projectName:b.basename(a)}),w={name:b.basename(a),path:a,relativePath:A.contractRelativePath,stack:l.importStack,runtime:l.runtime,framework:l.key,frameworkDisplayName:l.displayName,supportTier:l.supportTier,moduleSupport:C.moduleSupport,confidence:l.confidence,source:r,projectJsonPath:C.projectJsonPath,importJsonPath:C.importJsonPath,importReadinessPath:C.importReadinessPath,profileCompatibility:k};return await ad(e,w),w}catch(c){if(i)try{await id(a);}catch(l){let p=c instanceof Error?c.message:String(c),m=l instanceof Error?l.message:String(l);throw new Error(`Import failed: ${p}. Rollback also failed: ${m}`)}throw c}}function cd(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function ld(t,e){return b.resolve(t)===b.resolve(e)}async function pd(t){await Be(t);for(let e of p(t,"project.json")){if(!await I__default.pathExists(e))continue;let o;try{o=JSON.parse((await I__default.readFile(e)).toString("utf8"));}catch(r){throw new Error(`Authoritative project metadata is malformed: ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return o}return null}async function Un(t,e){let o=b.resolve(t),r=b.resolve(e);await Be(r);let n=[q(r,"project.json"),q(r,"adopt.json"),q(r,"adopt-readiness.json"),l(o,"imported-projects.json")];return {workspacePath:o,projectPath:r,files:await Promise.all(n.map(async a=>({path:a,contents:await I__default.pathExists(a)?await I__default.readFile(a):null})))}}function fc(t,e,o){let r=[q(o,"project.json"),q(o,"adopt.json"),q(o,"adopt-readiness.json"),l(e,"imported-projects.json")].map(n=>b.resolve(n));if(t.workspacePath!==b.resolve(e)||t.projectPath!==b.resolve(o)||t.files.length!==r.length||t.files.some((n,a)=>b.resolve(n.path)!==r[a]))throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function dd(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],o=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:o,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,discovered_relative_path:t.discoveredRelativePath,is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function ud(t,e,o){await Be(e),fc(o,t,e);let r=[];for(let n of o.files)try{n.contents===null?await I__default.remove(n.path):(await I__default.ensureDir(b.dirname(n.path)),await I__default.writeFile(n.path,n.contents));}catch(a){r.push(a);}if(r.length>0)throw new AggregateError(r,"Failed to restore adopt rollback snapshot.")}async function Bn(t){let e=b.resolve(t.workspacePath),o=b.resolve(t.source),r=await I__default.stat(o).catch(()=>null);if(!r||!r.isDirectory())throw new Error("Adopt source is not a directory.");if(await Be(o),ld(e,o))throw new Error("Adopt source cannot be the workspace root itself.");if(f$4(o))throw new Error("This is a workspace. Import it as a workspace instead.");let n=t.rollbackSnapshot??await Un(e,o);fc(n,e,o);let a=await pd(o),i=i$3(o,a),c=await f$5(o,a),l=cd(t.name||(typeof a?.name=="string"?a.name:"")||b.basename(o))||"adopted-project",p=ko({workspacePath:e,projectPath:o,projectName:l}),m=(t.now??new Date).toISOString(),d=q(o,"project.json"),h=q(o,"adopt.json"),g=q(o,"adopt-readiness.json"),k=Sr({existingProjectJson:a}),[C,A]=await Promise.all([zt(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):qt(e)]),w=kt({profile:C,runtime:i.runtime,subjectLabel:l,mode:A}),y=St({profile:C,runtimes:await xt(e,{additionalRuntimes:[i.runtime]}),mode:A}),f=w.ok?y:w;if(!f.ok&&A==="strict")throw new Error(f.message);let v=dd({projectName:l,contractRelativePath:p.contractRelativePath,isExternal:p.isExternal,discoveredRelativePath:p.relativePath,detection:i,existingProjectJson:a,projectKind:c,moduleSupport:k,adoptedAt:m}),u={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:m,managed_by:"workspai",mode:"linked",workspace:{path:e},project:{name:l,path:o,relative_path:p.contractRelativePath,discovered_relative_path:p.relativePath,is_external:p.isExternal,kind:c,module_support:k},detection:{framework:i.key,framework_display_name:i.displayName,runtime:i.runtime,kind:c,confidence:i.confidence,support_tier:i.supportTier,import_stack:i.importStack,source:i.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:k,workspace_contract:"linked-project",profile_compatibility:{ok:f.ok,profile:f.profile,runtimes:f.runtimes,message:f.message,recommended_profile:f.recommendedProfile,recommended_command:f.recommendedCommand}}},j=Cr({projectName:l,relativePath:p.contractRelativePath,projectKind:c,source:"adopted-local",detection:i,moduleSupport:k,projectPath:o,generatedAt:new Date(m)});if(t.dryRun!==true)try{await Be(o),await I__default.ensureDir(b.dirname(d)),await I__default.writeJson(d,v,{spaces:2}),await I__default.writeJson(h,u,{spaces:2}),await I__default.writeJson(g,j,{spaces:2});let P={name:l,path:o,relativePath:p.contractRelativePath,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:k,confidence:i.confidence,source:"adopted-local",importedAt:m};await b$d(e,[P]);}catch(P){try{await ud(e,o,n);}catch(E){throw new AggregateError([P,E],`Adopt failed and rollback was incomplete: ${P instanceof Error?P.message:String(P)}`)}throw P}return {name:l,path:o,relativePath:p.relativePath,contractRelativePath:p.contractRelativePath,isExternal:p.isExternal,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:k,confidence:i.confidence,projectJsonPath:d,adoptJsonPath:h,adoptReadinessPath:g,profileCompatibility:f,wroteFiles:t.dryRun!==true}}var fd=br,hd=vr;function Hn(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 yd(t=process.argv){let e=b.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function Qt(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function wd(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Se(t,e){let o=t.indexOf(e);if(o>=0&&o+1<t.length)return t[o+1];let r=t.find(n=>n.startsWith(`${e}=`));if(r)return r.slice(e.length+1)}function kd(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let o=Number(e);if(!Number.isSafeInteger(o)||o<1||o>16)throw new Error("--max-workers must be an integer between 1 and 16.");return o}function Zn(t){try{return kd(t.raw)}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$2({operation:t.operation,code:"cli.option.max-workers.invalid",message:o,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${o}`)),process.exit(1);}}async function ls(t,e){let o=Se(t,"--port")?.trim(),r=t[3];if(!o||!r||!/^\d+$/.test(o))return;let n=Number.parseInt(o,10);if(n<1||n>65535)return;let a=Se(t,"--output")||".",i=b.resolve(e,a,r),c=p(i,"project.json").find(p=>x.existsSync(p))??q(i,"project.json");if(!await I__default.pathExists(c))return;let l=await I__default.readJson(c);await I__default.writeJson(c,{...l,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function yc(t){let e=le(process.cwd()),o=t.trim().toLowerCase();if(!e||!o)return true;try{let[r,n]=await Promise.all([zt(e),qt(e)]),a=a$2(o),c=j$1(o)?"node":a?.runtime??"python",l=kt({profile:r,runtime:c,subjectLabel:o,mode:n}),p=St({profile:r,runtimes:await xt(e,{additionalRuntimes:[c]}),mode:n}),m=l.ok?p:l;if(m.ok)return true;let d=Ar(m);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${m.message}`)),d&&console.log(s.gray(`\u{1F4A1} ${d}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${m.message}`)),d&&console.log(s.gray(`\u{1F4A1} ${d}`));}catch{}return true}function ps(){return i$6()}function wc(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(b.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=h$3()),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 vd(t){return l$4(b.join(t,".venv"))}async function Pd(t,e){return await se(t,["--version"],e)===0}async function Rt(t){let e=b.join(t,"go.mod");if(await I__default.pathExists(e))return "go";let o=b.join(t,"pom.xml"),r=b.join(t,"build.gradle"),n=b.join(t,"build.gradle.kts");if(await I__default.pathExists(o)||await I__default.pathExists(r)||await I__default.pathExists(n))return "java";if((await I__default.pathExists(t)?await x.promises.readdir(t,{withFileTypes:true}):[]).some(d=>d.isFile()&&d.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=b.join(t,"src");if(await I__default.pathExists(i)&&(await x.promises.readdir(i,{withFileTypes:true})).some(h=>h.isFile()&&h.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=b.join(t,"package.json");if(await I__default.pathExists(c))return "node";let l=b.join(t,"pyproject.toml"),p=b.join(t,"requirements.txt"),m=b.join(t,"poetry.lock");return await I__default.pathExists(l)||await I__default.pathExists(p)||await I__default.pathExists(m)?"python":null}async function bd(t,e={}){let o=e.runCommand??se;for(let r of e.pythonCandidates??ps())if(await o(r,r==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Mc(t,e={}){let o=e.runCommand??se;for(let r of e.pythonCandidates??ps())if(await o(r,r==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function jd(t,e={}){let o=e.runCommand??se,r=l$4(b.join(t,".venv"));if(!await I__default.pathExists(r)){let c=await Mc(t,e);if(c!==0)return c}if(!(await o("poetry",["--version"],t)===0))return 0;let a=await o("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await o("poetry",["env","use",r],t);return i!==0?i:0}async function Cd(t,e={}){let o=e.runCommand??se,r=l$4(b.join(t,".venv"));if(!await I__default.pathExists(r)){let i=await Mc(t,e);if(i!==0)return i}await o(r,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=b.join(t,"requirements.txt");if(await I__default.pathExists(n)&&await o(r,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=b.join(t,"pyproject.toml");return await I__default.pathExists(a)&&(await o(r,["-m","pip","install","-e","."],t)===0||await o(r,["-m","pip","install","."],t)===0)?0:1}async function qn(t,e){return await jd(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 I__default.pathExists(b.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await Cd(t))}async function zn(t){let e=await Et("init",t);if(e===0)return 0;let o=["npm","pnpm","yarn"];for(let r of o){if(!await Pd(r,t))continue;if(await se(r,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${r} install`)),0}return e}function Sd(t,e){let o=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),r=Se([...e],"--port");if(r&&!/^\d+$/.test(r.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Se([...e],"--java-version"),a=Se([...e],"--spring-boot-version"),i=Se([...e],"--springdoc-version"),c=Se([...e],"--group-id"),l=Se([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!o(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!o(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(l&&!/^[A-Za-z0-9_.-]+$/.test(l.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Se([...e],"--target-framework"),a=Se([...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 kc(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||ss(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:r}=await import('./create-7JKJDAQV.js');await r(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b$2()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:o}=await b$4([{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(o==="current"){let{registerWorkspaceAtPath:r}=await import('./create-7JKJDAQV.js');await r(process.cwd(),{skipGit:e,yes:false,userConfig:await b$2()});}else o==="none"&&t.push("--no-workspace");}async function xd(t){await I__default.ensureDir(t);let e=b.join(t,"lifecycle.lock"),o=Date.now();for(;;)try{let r=await x.promises.open(e,"wx");return await r.writeFile(`${JSON.stringify({pid:process.pid})}
154
- `),async()=>{await r.close().catch(()=>{}),await I__default.remove(e).catch(()=>{});}}catch(r){if(r.code!=="EEXIST")throw r;let n=await I__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 I__default.remove(e).catch(()=>{});continue}if(Date.now()-o>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function Or(t,e={}){let o=b.join(p$2(),"transactions"),r=await xd(o),n;try{await b$b(o),n=await a$a({journalDirectory:o});}catch(i){throw await r(),i}let a=new Set([b.join(p$2(),"workspaces.json"),b.join(q$1(),"workspaces.json"),a$b(t,d$6),b$c(t,d$6),a$b(t,a$c),b$c(t,a$c),...o$1(t,"imported-projects.json")]);e.projectPath&&(a.add(q(e.projectPath,"project.json")),a.add(q(e.projectPath,"context.json")),a.add(q(e.projectPath,"file-hashes.json")),a.add(q(e.projectPath,"adopt.json")),a.add(q(e.projectPath,"adopt-readiness.json")));try{for(let c of a)await n.captureFile(c);e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let i=false;return {registerCompensation:c=>n.registerCompensation(c),commit:async()=>{i||(await n.commit(),i=true,await r());},rollback:async()=>{if(!i){i=true;try{await n.rollback();}finally{await r();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await r(),i}}async function Xt(t,e){try{await t.rollback();}catch(o){throw new AggregateError([e,o],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function Mr(t,e,o){if(t.includes("--no-workspace")||t.includes("--dry-run"))return;if(!await I__default.pathExists(e)){f.warn(`Created project path was not found for workspace linking: ${e}`);return}let r=le(e)||le(process.cwd()),n=false,a;if(r)a=await Or(r,{projectPath:e});else {r=k(),a=await Or(r,{projectPath:e,ownedWorkspace:r});try{r=(await us()).workspacePath;}catch(c){await Xt(a,c);}n=true;}let i="managed";try{await o$2(e);let c=b.relative(r,e);(c.startsWith("..")||b.isAbsolute(c))&&(i=(await Bn({source:e,workspacePath:r,name:o})).relationship);let{registerProjectInWorkspaceStrict:p,registerWorkspaceStrict:m}=await import('./workspace-H3QXBFGB.js'),{syncWorkspaceContract:d}=await import('./workspace-contract-RPQQBQXR.js');await m(r,b.basename(r)),await p(r,o,e),await d({workspacePath:r,strict:true}),await a.commit();}catch(c){await Xt(a,c);}return n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${e$2}" (${i}).`)),console.log(s.gray(` Registry: ${b.join(p$2(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${r}`))),r}async function es(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],o=a$2(e),r=t[3];if(!o||o.owner!=="npm")return 1;if(!r)return process.stderr.write(`Usage: ${o.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
155
- `),1;try{h(r);}catch(d){let h=d instanceof Error?d.message:String(d);return process.stderr.write(`${h}
156
- `),1}let n=Sd(o.id,t);if(n)return process.stderr.write(`${n}
149
+ ${o.stderr||""}`);return r?this.isMavenVersionAtLeast(r,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${r.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let o=E.existsSync(b.join(e,"pom.xml")),r=E.existsSync(b.join(e,"mvnw"))||E.existsSync(b.join(e,"mvnw.cmd")),n=E.existsSync(b.join(e,"build.gradle"))||E.existsSync(b.join(e,"build.gradle.kts"))||E.existsSync(b.join(e,"settings.gradle"))||E.existsSync(b.join(e,"settings.gradle.kts")),a=E.existsSync(b.join(e,"gradlew"))||E.existsSync(b.join(e,"gradlew.bat"));return {hasMavenProject:o||r,hasMavenWrapper:r,hasGradleProject:n||a,hasGradleWrapper:a}}findWorkspaceRoot(e){let o=e;for(;;){if(E.existsSync(b.join(o,".workspai-workspace"))||E.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o$1(r,"policies.yml").find(a=>E.existsSync(a));if(!n)return "isolated";try{let c=E.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let o=b.join(e,"mvnw.cmd");if(process.platform==="win32"&&E.existsSync(o))return {command:o,baseArgs:[]};let r=b.join(e,"mvnw");return E.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let o=b.join(e,"gradlew.bat");if(process.platform==="win32"&&E.existsSync(o))return {command:o,baseArgs:[]};let r=b.join(e,"gradlew");return E.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let o=[],r=new Set,n=[e];for(;n.length>0;){let a=n.shift();if(!a||r.has(a))continue;r.add(a);let i=[];try{i=E.readdirSync(a,{withFileTypes:true});}catch{continue}for(let c of i){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let l=b.join(a,c.name),p=this.inspectJavaProject(l);(p.hasMavenProject||p.hasGradleProject)&&o.push(l),n.push(l);}}return o}withJavaCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","m2"):b.join(e,".workspai","cache","java","m2"),i=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","gradle"):b.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,l=process.env.GRADLE_USER_HOME,p=`-Dmaven.repo.local=${a}`;return process.env.MAVEN_OPTS=c?`${c} ${p}`:p,process.env.GRADLE_USER_HOME=i,o().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof l>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=l;})}async runBuildTool(e,o,r=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:a}=this.buildToolCommand(e),i=await this.runCommand(n,[...a,...o],e);if(i===0||!r)return {exitCode:i};let c=E.existsSync(b.join(e,"pom.xml")),l=E.existsSync(b.join(e,"build.gradle"))||E.existsSync(b.join(e,"build.gradle.kts"));return {exitCode:i,message:c||l?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let o=[b.join(e,"target"),b.join(e,"build","libs")];for(let r of o){if(!E.existsSync(r))continue;let a=E.readdirSync(r).filter(i=>i.toLowerCase().endsWith(".jar")).find(i=>!i.toLowerCase().endsWith("-sources.jar")&&!i.toLowerCase().endsWith("-javadoc.jar")&&!i.toLowerCase().endsWith("-plain.jar"));if(a)return b.join(r,a)}return null}commandArgsFor(e,o){if(e==="gradle"){let r=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return o==="init"?[...r,"dependencies"]:o==="dev"?[...r,"bootRun"]:o==="test"?[...r,"test"]:[...r,"bootJar"]}return o==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:o==="dev"?["spring-boot:run"]:o==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),o=this.resolveJavaCommand(e),r=await this.runCommand(o,["-version"],e);if(r!==0)return {exitCode:r,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),l=await this.detectInstalledJavaMajor(o,e);if(l!==null&&l<c)return {exitCode:1,message:`Detected Java ${l}, but project requires Java ${c}+.`};let p=b.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&E.existsSync(p))try{let d=E.readFileSync(p,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),w=this.parseMajorJavaVersion(d?.[1]);if(w!==null&&w<c)return {exitCode:1,message:`Detected JAVA_HOME version ${w}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),l=c==="gradle"?["--version"]:["-version"],p=await this.runBuildTool(e,l);return p.exitCode!==0?p:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):p}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let l=c.reduce((d,w)=>Math.max(d,this.readRequiredJavaMajor(w)),0);if(l>0){let d=await this.detectInstalledJavaMajor(o,e);if(d!==null&&d<l){let w=c.filter(g=>this.readRequiredJavaMajor(g)>d).map(g=>b.relative(e,g)).join(", ");return {exitCode:1,message:`Detected Java ${d}, but workspace project(s) [${w}] require Java ${l}+.`}}}let p=false,m=false;for(let d of c){let w=this.inspectJavaProject(d);w.hasMavenProject&&!w.hasMavenWrapper&&(p=true),w.hasGradleProject&&!w.hasGradleWrapper&&(m=true);}if(p){let d=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(d!==0)return {exitCode:d,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let w=await this.checkSystemMavenVersion(e);if(w.exitCode!==0)return w}if(m){let d=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(d!==0)return {exitCode:d,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(a===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return i===0?{exitCode:0}:{exitCode:a||i||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let o=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return o&&E.mkdirSync(o,{recursive:true}),process.env.GRADLE_USER_HOME&&E.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let o=this.resolveJarPath(e);if(o)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",o],e)};let r=await this.runBuild(e);if(r.exitCode!==0)return r;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(at(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let o=b.join(e,"pom.xml");if(E.existsSync(o)){let r=E.readFileSync(o,"utf-8");if(r.includes("spotless-maven-plugin"))return this.runBuildTool(e,["spotless:check"]);if(r.includes("checkstyle"))return this.runBuildTool(e,["checkstyle:check"])}return {exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){if(at(e,"format"))return {exitCode:await this.runCommand("make",["format"],e)};let o=b.join(e,"pom.xml");return E.existsSync(o)&&E.readFileSync(o,"utf-8").includes("spotless-maven-plugin")?this.runBuildTool(e,["spotless:apply"]):["build.gradle","build.gradle.kts"].map(n=>b.join(e,n)).filter(n=>E.existsSync(n)).some(n=>E.readFileSync(n,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure Spotless in Maven/Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run npx workspai init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var gr=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}findWorkspaceRoot(e){let o=e;for(;;){if(E.existsSync(b.join(o,".workspai-workspace"))||E.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o$1(r,"policies.yml").find(a=>E.existsSync(a));if(!n)return "isolated";try{let c=E.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,o,r){let n=this.resolveDependencyMode(e),a=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=n==="isolated"?b.join(e,".workspai","cache","node"):b.join(a||e,".workspai","cache","node"),c=process.env.npm_config_cache,l=process.env.npm_config_store_dir,p=process.env.RAPIDKIT_DEP_SHARING_MODE,m=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,a&&(process.env.RAPIDKIT_WORKSPACE_PATH=a),o==="pnpm"?(process.env.npm_config_store_dir=b.join(i,"pnpm-store"),process.env.npm_config_cache=b.join(i,"pnpm-cache")):o==="yarn"?process.env.npm_config_cache=b.join(i,"yarn-cache"):process.env.npm_config_cache=b.join(i,"npm-cache"),r().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof l>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=l,typeof p>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=p,typeof m>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=m;})}detectPackageManager(e){if(E.existsSync(b.join(e,"package-lock.json")))return "npm";if(E.existsSync(b.join(e,"pnpm-lock.yaml")))return "pnpm";if(E.existsSync(b.join(e,"yarn.lock")))return "yarn";if(!this.commandAvailable("npm")){if(this.commandAvailable("pnpm"))return "pnpm";if(this.commandAvailable("yarn"))return "yarn"}return "npm"}hasPinnedPackageManager(e){return E.existsSync(b.join(e,"package-lock.json"))||E.existsSync(b.join(e,"pnpm-lock.yaml"))||E.existsSync(b.join(e,"yarn.lock"))}availablePackageManagers(e){let o=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[o]:[o,...["npm","pnpm","yarn"].filter(n=>n!==o&&this.commandAvailable(n))]}commandAvailable(e){let o=e$6(e);return spawnSync(o.command,[...o.prefixArgs,"--version"],{stdio:"ignore",shell:c$b(),env:g$4()}).status===0}scriptArgs(e,o){return e==="npm"?["run-script",o,"--foreground-scripts"]:["run",o]}async runScriptWithFallback(e,o){let r={exitCode:1};for(let n of this.availablePackageManagers(e))if(r=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,o),e)),r.exitCode===0)return r;return r}async runLifecycle(e,o){let r=i$2(e),n=i$3(e,r),a=t(e,o,{framework:n.key});return a?this.runScriptWithFallback(e,a.scriptName):{exitCode:1,message:`No npm script available for \`${o}\`. Add a "${o}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let o=this.detectPackageManager(e);return this.withDependencyEnv(e,o,async()=>{try{return process.env.npm_config_cache&&E.mkdirSync(process.env.npm_config_cache,{recursive:true}),o==="pnpm"&&process.env.npm_config_store_dir&&E.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let o=this.detectPackageManager(e),r=this.resolveDependencyMode(e),n=r==="shared-runtime-caches"||r==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,o,()=>this.run(o,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var hr=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,o){return {exitCode:await this.withPythonCacheEnv(o,()=>this.runCore(e,o))}}findWorkspaceRoot(e){let o=e;for(;;){if(E.existsSync(b.join(o,".workspai-workspace"))||E.existsSync(b.join(o,".rapidkit-workspace")))return o;let r=b.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=o$1(r,"policies.yml").find(a=>E.existsSync(a));if(!n)return "isolated";try{let c=E.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=r==="shared-runtime-caches"?b.join(n||e,".workspai","cache","python"):b.join(e,".workspai","cache","python"),i=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=b.join(a,"pip"),process.env.POETRY_CACHE_DIR=b.join(a,"poetry"),o().finally(()=>{typeof i>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=i,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),o=await this.run(["doctor","check"],e);return o.exitCode===0?o:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx workspai doctor workspace" for a full workspace scan.','Use "npx workspai init" after adding or changing modules.',"Use `npx workspai <command>` from the project root to avoid environment drift."]}};function hp(){let t={...process.env},e=t.PATH||"";if(e){let o=e.split(b.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter);t.PATH=o;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||h$3(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function et(t,e){return t==="go"?new ur((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="node"?new gr((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="java"?new mr((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="dotnet"?new dr((o,r,n)=>e.runCommandInCwd(o,r,n)):new hr((o,r)=>e.runCoreRapidkit(o,{cwd:r,env:hp()}))}var Vi=b.join(pn.homedir(),".workspai","cache"),Gi=1440*60*1e3;function Tn(){let t=a$f("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?b.join(Vi,`vitest-${e}`):Vi}var wr=class t{static instance;memoryCache=new Map;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getCacheKey(e){return createHash("md5").update(e).digest("hex")}getCachePath(e){return b.join(Tn(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let o=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${o}.tmp`}async get(e,o="1.0"){let r=this.memoryCache.get(e);if(r&&r.version===o&&Date.now()-r.timestamp<Gi)return f.debug(`Cache hit (memory): ${e}`),r.data;try{let n=this.getCachePath(e),a=await promises.readFile(n,"utf-8"),i=JSON.parse(a);if(i.version===o&&Date.now()-i.timestamp<Gi)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,i),i.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,o,r="1.0"){let n={data:o,timestamp:Date.now(),version:r};this.memoryCache.set(e,n);try{await promises.mkdir(Tn(),{recursive:true});let a=this.getCachePath(e),i=this.getTempCachePath(a);await promises.writeFile(i,JSON.stringify(n),"utf-8"),await promises.rename(i,a),f.debug(`Cache set: ${e}`);}catch(a){f.debug(`Cache write failed: ${e}`,a);}}async invalidate(e){this.memoryCache.delete(e);try{let o=this.getCachePath(e);await promises.unlink(o),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=Tn(),o=await promises.readdir(e);await Promise.all(o.map(r=>promises.unlink(b.join(e,r)))),f.debug("Cache cleared");}catch{}}};var yo=["list","sync","registry","foundation","intelligence","model","snapshot","diff","impact","verify","graph","watch","context","agent-sync","remediation-plan","explain","why","trace","feedback","eval","mcp","policy","contract","share","export","archive","hydrate","import","run","init"],kr=["intelligence","model","snapshot","diff","impact","contract","verify","graph","watch","context","agent-sync","remediation-plan","explain","why","trace","feedback","eval","mcp"];function Ui(t){return kr.includes(t)}var Bi="workspai-project-entry-capability-v1";var Wn="workspai-cli-runtime-command-inventory-v1",vr=[...e$4,"autopilot","pipeline","import","adopt","snapshot","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands","create","project"],Dn=["bootstrap","setup","cache","mirror"],Pr="create",kp=[...Dn,Pr],vp={bootstrap:"Bootstrap project or workspace dependencies through runtime-aware setup rules.",setup:"Prepare a selected runtime toolchain through the supported adapter boundary.",cache:"Inspect or clear Workspai cache state through the managed cache boundary.",mirror:"Coordinate supported mirror lifecycle operations for the current project.",create:"Create a supported workspace or project through the canonical planner boundary."},br=[["ai","generate-embeddings"],["ai","info"],["ai","recommend"],["ai","update-embeddings"],["config","ai"],["config","remove-api-key"],["config","set-api-key"],["config","show"],["infra","down"],["infra","plan"],["infra","status"],["infra","up"],["product","manifest"],["product","manifest","create"],["product","plan"],["project","commands"],["project","archives"],["project","archive"],["project","restore"],["project","delete"],["snapshot","create"],["snapshot","inspect"],["snapshot","list"],["snapshot","restore"]];function Pp(t,e,o,r){let n=new Set(t),a=new Set(e),i=t.filter(w=>!a.has(w)).sort(),c=e.filter(w=>!n.has(w)).sort(),l=new Set(o),p=new Set(r),m=o.filter(w=>!p.has(w)).sort(),d=r.filter(w=>!l.has(w)).sort();return {ok:i.length===0&&c.length===0&&m.length===0&&d.length===0,registeredButUndeclared:i,declaredButUnregistered:c,registeredScopedButUndeclared:m,declaredScopedButUnregistered:d}}function Hi(t,e=[]){return t.commands.flatMap(o=>{let r=o.name(),n=[...e,r];return [{path:n,command:r,parent:e.length>0?e.join(" "):null,registrationKind:"commander",aliases:o.aliases?.()??[],description:o.description?.()??"",hidden:o._hidden===true,arguments:(o.registeredArguments??[]).map(i=>({name:i.name(),required:i.required,variadic:i.variadic})),options:(o.options??[]).map(i=>({flags:i.flags,attributeName:i.attributeName?.()??null}))},...Hi(o,n)]})}function qi(t){let e=Hi(t),o=e.filter(c=>c.path.length===1).map(c=>c.command),r=new Set(o),n=kp.filter(c=>!r.has(c)).map(c=>({path:[c],command:c,parent:null,registrationKind:"manual-handler",aliases:[],description:vp[c],hidden:false,arguments:[],options:[]})),a=[...e,...n].sort((c,l)=>c.path.join(" ").localeCompare(l.path.join(" "))),i=[...new Set(a.filter(c=>c.path.length===1).map(c=>c.command))].sort();return {schemaVersion:Wn,commands:a,topLevelCommands:i,integrity:Pp(i,vr,e.filter(c=>c.path.length>1).map(c=>c.path.join(" ")),br.map(c=>c.join(" ")))}}function zi(t){return `CLI command surface integrity violation (${[t.registeredButUndeclared.length>0?`registered but undeclared: ${t.registeredButUndeclared.join(", ")}`:null,t.declaredButUnregistered.length>0?`declared but unreachable: ${t.declaredButUnregistered.join(", ")}`:null,t.registeredScopedButUndeclared.length>0?`registered scoped but undeclared: ${t.registeredScopedButUndeclared.join(", ")}`:null,t.declaredScopedButUnregistered.length>0?`declared scoped but unreachable: ${t.declaredScopedButUnregistered.join(", ")}`:null].filter(o=>o!==null).join("; ")})`}var Yi="rapidkit-runtime-command-surface-v1";var Qi="doctor-remediation-plan-v2";var Xi="workspai-workspace-intelligence-architecture-v1";var Zi={autopilotRelease:"autopilot-release-v1",workspaceList:"rapidkit-workspace-list-v1",workspaceSync:"rapidkit-workspace-sync-v1",compatibilityMatrix:"rapidkit.compatibility-matrix.v1",mcpDesign:"workspai-mcp-design.v1",agentHooks:"workspai-agent-hooks.v1",projectArchive:"rapidkit-project-archive-v1",workspaceSnapshot:"rapidkit-workspace-snapshot-v1",workspaceSnapshotV2:"rapidkit-workspace-snapshot-v2",infraPlan:"rapidkit.infra-plan.v1",privateProductManifest:"rapidkit.private-product-manifest.v1",productFactoryPlan:"rapidkit.product-factory-plan.v1",workspaceModelCache:"workspace-model-cache.v1",workspaceWatchEvent:"workspace-watch-event.v1",doctorProjectScan:"doctor-project-scan-v2",doctorWorkspaceCache:"doctor-workspace-cache-v2"};var bp="workspai-published-contract-catalog-v1",jp="workspace-graph-stream.v1";function wo(){return {workspaceContract:1,runtimeCommandSurface:Yi,cliRuntimeCommandInventory:Wn,cliOperationResult:a$x,publishedContractCatalog:bp,workspaceArchiveCapabilities:a$w,workspaceArchiveManifest:b$h,workspaceArchiveOperationResult:c$3,projectEntryCapability:Bi,workspaceIntelligenceArchitecture:Xi,workspaceIntelligenceChain:a$v,workspaceIntelligenceArtifacts:b$8,cliLogEvent:c$a,freshnessMetadata:a$u,factFreshness:a$t,blockerResolution:a$s,workspaceModel:g$1,workspaceImpact:f$6,workspaceVerify:c$9,workspaceContext:c$8,workspaceDependencyGraph:b$g,workspaceKnowledgeGraph:a$r,workspaceGraphStream:jp,workspaceKnowledgeGraphChangeOverlay:a$q,workspaceKnowledgeSearch:a$p,workspaceGraphTokenEfficiency:a$o,modelUsageEvent:a$n,workspaceIntelligenceEvaluation:b$f,workspaceIntelligenceEvaluationComparison:c$7,workspaceIntelligenceHistory:a$m,agentCustomizationPackCapabilities:l$3,agentCustomizationPackReport:b$8.agentCustomizationPack,agentReportsIndex:b$8.agentIndex,workspaceOperationalSkill:a$l,workspaceSkillsIndex:b$e,workspaceExplain:a$k,agentActionOutcome:a$j,doctorRemediationPlan:Qi,artifactRemediationPlan:a$i,doctorFixResult:a$h,...Zi}}function jr(){let t=wo(),e={workspaceContract:"contracts/workspace-contract.v1.json",runtimeCommandSurface:"contracts/runtime-command-surface.v1.json",cliRuntimeCommandInventory:"contracts/cli-runtime-command-inventory.v1.snapshot.json",cliOperationResult:"contracts/cli-operation-result.v1.json",publishedContractCatalog:"contracts/published-contract-catalog.v1.json",workspaceArchiveCapabilities:"contracts/workspace-archive-capabilities.v1.json",workspaceArchiveManifest:"contracts/workspace-archive-manifest.v1.json",workspaceArchiveOperationResult:"contracts/workspace-archive-operation-result.v1.json",projectEntryCapability:"contracts/project-entry-capability.v1.json",workspaceIntelligenceArchitecture:"contracts/workspace-intelligence-architecture.v1.json",workspaceIntelligenceChain:"contracts/workspace-intelligence-chain.v1.json",workspaceIntelligenceArtifacts:null,cliLogEvent:"contracts/cli-log-event.v1.json",freshnessMetadata:null,factFreshness:"contracts/workspace-intelligence/fact-freshness.v1.json",blockerResolution:"contracts/workspace-intelligence/blocker-resolution.v1.json",workspaceModel:"contracts/workspace-intelligence/workspace-model.v1.json",workspaceImpact:"contracts/workspace-intelligence/workspace-impact.v1.json",workspaceVerify:"contracts/workspace-intelligence/workspace-verify.v1.json",workspaceContext:"contracts/workspace-intelligence/workspace-context.v1.json",workspaceDependencyGraph:"contracts/workspace-intelligence/workspace-dependency-graph.v1.json",workspaceKnowledgeGraph:"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json",workspaceGraphStream:"contracts/workspace-intelligence/workspace-graph-stream.v1.json",workspaceKnowledgeGraphChangeOverlay:"contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json",workspaceKnowledgeSearch:"contracts/workspace-intelligence/workspace-knowledge-search.v1.json",workspaceGraphTokenEfficiency:"contracts/workspace-intelligence/workspace-graph-token-efficiency.v1.json",modelUsageEvent:"contracts/workspace-intelligence/model-usage-event.v1.json",workspaceIntelligenceEvaluation:"contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",workspaceIntelligenceEvaluationComparison:"contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",workspaceIntelligenceHistory:"contracts/workspace-intelligence/workspace-intelligence-history.v1.json",agentCustomizationPackCapabilities:"contracts/agent-customization-pack.v1.json",agentCustomizationPackReport:"contracts/workspace-intelligence/agent-customization-pack-report.v1.json",agentReportsIndex:"contracts/workspace-intelligence/agent-reports-index.v1.json",workspaceOperationalSkill:"contracts/workspace-intelligence/workspace-operational-skill.v1.json",workspaceSkillsIndex:"contracts/workspace-intelligence/workspace-skills-index.v1.json",workspaceExplain:"contracts/workspace-intelligence/workspace-explain.v1.json",agentActionOutcome:"contracts/workspace-intelligence/agent-action-outcome.v1.json",doctorRemediationPlan:"contracts/doctor-remediation-plan.v2.json",artifactRemediationPlan:"contracts/artifact-remediation-plan.v1.json",doctorFixResult:"contracts/workspace-intelligence/doctor-fix-result.v1.json",autopilotRelease:"contracts/autopilot-release.v1.json",workspaceList:"contracts/workspace-list.v1.json",workspaceSync:"contracts/workspace-sync.v1.json",compatibilityMatrix:"contracts/compatibility-matrix.v1.json",mcpDesign:"contracts/workspace-intelligence/mcp-design.v1.json",agentHooks:"contracts/workspace-intelligence/agent-hooks.v1.json",projectArchive:"contracts/project-archive.v1.json",workspaceSnapshot:"contracts/workspace-snapshot.v1.json",workspaceSnapshotV2:"contracts/workspace-snapshot.v2.json",infraPlan:"contracts/infra-plan.v1.json",privateProductManifest:"contracts/private-product-manifest.v1.json",productFactoryPlan:"contracts/product-factory-plan.v1.json",workspaceModelCache:"contracts/workspace-model-cache.v1.json",workspaceWatchEvent:"contracts/workspace-watch-event.v1.json",doctorProjectScan:"contracts/doctor-project-scan.v2.json",doctorWorkspaceCache:"contracts/doctor-workspace-cache.v2.json"};return Object.fromEntries(Object.entries(t).map(([o,r])=>{let n=e[o];return [o,{schemaVersion:r,contractPath:n,publication:n?o==="runtimeCommandSurface"||o==="cliRuntimeCommandInventory"||o.endsWith("Capabilities")?"capability-contract":"json-schema":"embedded-type",...o==="workspaceIntelligenceArtifacts"?{artifacts:Object.fromEntries(Object.keys(a$2).map(a=>[a,{path:a$2[a],schemaVersion:b$8[a],contractPath:c$6[a]}]))}:{}}]}))}var Ln="rapidkit-command-capabilities-v1",ec="rapidkit-version-v1";var Cp=["catalog","pulse","nova","orbit","atlas","vertex","summit","beacon","ledger","flux","nexus","apex","harbor","forge","spark","portal","studio","canvas","quantum","vault","zenith","compass","vector","catalyst","saas","commerce","radar","stellar","prism","cedar","momentum","signal","cipher","lumen","trail","ridge"],Sp={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},xp={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"};function Ep(t){return t[Math.floor(Math.random()*t.length)]}function Fn(t){let e=Ep(Cp),o=j$1(t);if(o){let a=xp[o.id]??"app";return `${e}-${a}`}let r=a$3(t),n=r?Sp[r.id]??"service":"app";return `${e}-${n}`}async function Ip(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function $p(t){if(!await O.pathExists(t))return [];let e=[],o=[t];for(;o.length>0;){let r=o.shift();if(r)for(let n of await promises.readdir(r,{withFileTypes:true})){let a=b.join(r,n.name);n.isFile()?e.push(a):n.isDirectory()&&o.push(a);}}return e}async function oc(t,e){await O.outputFile(t,`${JSON.stringify(e,null,2)}
150
+ `,"utf-8");}function tt(t,e){return b.isAbsolute(e)?e:b.join(t,e)}function Op(t,e){if(!e.trim()||b.isAbsolute(e)||/^[a-zA-Z]:[\\/]/.test(e))throw new Error(`Mirror artifact target must be a non-empty relative path: ${e}`);let o=b.resolve(t),r=b.resolve(o,e),n=b.relative(o,r);if(!n||n.startsWith("..")||b.isAbsolute(n))throw new Error(`Mirror artifact target escapes the managed artifact directory: ${e}`);return r}async function rc(t,e){let o=b.relative(t,e),r=t;for(let a of o.split(b.sep).slice(0,-1)){r=b.join(r,a);let i=await promises.lstat(r).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: ${r}`);if(!i.isDirectory())throw new Error(`Mirror artifact target parent is not a directory: ${r}`)}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 Np(t,e){let o=b.resolve(t),r=b.relative(o,b.resolve(e));if(!r||r.startsWith("..")||b.isAbsolute(r))throw new Error("Managed mirror directory escapes the workspace.");let n=o;for(let a of r.split(b.sep)){n=b.join(n,a);let i=await promises.lstat(n);if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Managed mirror path must contain only real directories: ${n}`)}}function Mp(t,e){if(t.target)return t.target;if(t.source)return b.basename(t.source);if(t.url)try{let o=new URL(t.url).pathname,r=b.basename(o);if(r&&r!=="/")return r}catch{}return `${e}.artifact`}async function Tp(t){let e=o$1(t,"trusted-sources.lock").find(r=>existsSync(r)),o=new Set(["localhost","127.0.0.1"]);if(!e)return o;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));for(let a of n)o.add(a.toLowerCase());}catch{}return o}async function Wp(t,e,o){await O.ensureDir(b.dirname(e)),await new Promise((r,n)=>{let i=(t.startsWith("https://")?lc:cc).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let l=createWriteStream(e);c.pipe(l),l.on("finish",()=>{l.close(),r();}),l.on("error",p=>{n(p);});});i.setTimeout(o,()=>{i.destroy(new Error(`Request timeout after ${o}ms`));}),i.on("error",c=>{n(c);});});}async function Dp(t,e,o,r,n){let a=new URL(t),i=JSON.stringify(e),c=a.protocol==="https:"?lc:cc;await new Promise((l,p)=>{let m=c.request({method:"POST",hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:`${a.pathname}${a.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...r?{Authorization:`Bearer ${r}`}:{},...n||{}}},d=>{if(!d.statusCode||d.statusCode<200||d.statusCode>=300){p(new Error(`HTTP ${d.statusCode||"unknown"}`)),d.resume();return}d.resume(),l();});m.setTimeout(o,()=>{m.destroy(new Error(`Request timeout after ${o}ms`));}),m.on("error",d=>{p(d);}),m.write(i),m.end();});}function nc(t){return new Promise(e=>setTimeout(e,t))}async function Lp(t,e,o,r){let n=tt(t,e||".workspai/reports/evidence-export-dead-letter.ndjson");return await O.ensureDir(b.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:r,payload:o})}
151
+ `,"utf-8"),n}function Fp(t,e){if(!e?.enabled)return {headers:{}};let o=process.env[e.hmacKeyEnv];if(!o)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let r=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(r,o).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":r}}}async function Jp(t,e,o){let r=(o.algorithm||"sha256").toLowerCase(),n=tt(t,o.publicKeyPath);if(!await O.pathExists(n))return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(r);c.update(i),c.end();let l=Buffer.from(o.signature,"base64"),p=c.verify(a,l),m=createHash("sha256").update(a).digest("hex");return {verified:p,algorithm:r,publicKeyPath:n,publicKeyFingerprint:m,signature:o.signature,message:p?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Attestation verification error: ${a.message}`}}}async function Kp(t,e,o,r){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};let a=o.signaturePath?tt(t,o.signaturePath):null;if(!a||!await O.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=o.certificatePath?tt(t,o.certificatePath):null;c&&i.push("--certificate",c);let l=o.bundlePath?tt(t,o.bundlePath):null;l&&i.push("--bundle",l);let p=o.keyPath?tt(t,o.keyPath):null;p&&i.push("--key",p),o.identity&&i.push("--certificate-identity",o.identity),o.issuer&&i.push("--certificate-oidc-issuer",o.issuer),o.rekorUrl&&i.push("--rekor-url",o.rekorUrl),r.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let m=await execa("cosign",i,{reject:false});return m.exitCode===0?{verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${m.stderr||m.stdout||"unknown error"}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}catch(m){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${m.message}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}}async function Vp(t,e){let o=e.algorithm||"sha256",r=tt(t,e.policyPath),n=tt(t,e.signaturePath),a=tt(t,e.publicKeyPath);if(!await O.pathExists(r))return {verified:false,message:`Governance policy bundle not found: ${r}`,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(r,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),l=await promises.readFile(a,"utf-8"),p=createVerify(o);return p.update(i),p.end(),p.verify(l,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function Jn(t,e){let o=[],r={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=o$1(t,"mirror-config.json").find(T=>existsSync(T))??l(t,"mirror-config.json"),a=l(t,"mirror.lock"),i=l(t,"mirror","artifacts"),c=l(t,"reports"),l$1=await Tp(t);if(!await O.pathExists(n))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:o,details:r};let p={};try{p=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return o.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:o,details:r}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||p.mode==="offline-only"))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:o,details:r};await O.ensureDir(i);try{await Np(t,i);}catch(T){return o.push({id:"mirror.root.safety",status:"failed",message:T instanceof Error?T.message:String(T)}),{checks:o,details:r}}let d=Math.max(0,p.prefetch?.retries??2),w=Math.max(0,p.prefetch?.backoffMs??250),g=Math.max(1e3,p.prefetch?.timeoutMs??15e3),P=p.security?.requireAttestation===true,j=p.security?.requireSigstore===true,A=p.security?.requireTransparencyLog===true,h=p.security?.requireSignedGovernance===true,y=p.security?.evidenceExport,f=(process.env.RAPIDKIT_ENV||p.security?.governance?.environment||"dev").toLowerCase(),k=p.security?.governance?.policies||{};if(p.security?.governanceBundle){let T=await Vp(t,p.security.governanceBundle);if(o.push({id:"governance.bundle.verify",status:T.verified?"passed":"failed",message:T.message}),T.verified&&T.policies)k=T.policies,r.governanceBundleVerified=true;else if(h)return {checks:o,details:r}}let u=k[f],C=A||u?.requireTransparencyLog===true,x=[],R=Array.isArray(p.artifacts)?p.artifacts:[],v=[];for(let T=0;T<R.length;T+=1){let $=R[T],S=$.id||`artifact-${T+1}`,K=$.source?tt(t,$.source):null,J=Mp($,S),D;try{D=Op(i,J),await rc(i,D);}catch(ve){o.push({id:`mirror.target.${S}`,status:"failed",message:ve instanceof Error?ve.message:String(ve)});continue}let q=false,Q=D,Re=false,de=async()=>{Re&&await promises.rm(Q,{force:true}).catch(()=>{});},ne={sourceType:"path",source:K||$.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(K&&await O.pathExists(K))await O.ensureDir(b.dirname(D)),Q=`${D}.${process.pid}.${randomUUID()}.tmp`,Re=true,await promises.copyFile(K,Q),r.syncedArtifacts+=1,q=true,ne={sourceType:"path",source:K,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},o.push({id:`mirror.sync.${S}`,status:"passed",message:`Mirrored artifact ${S} from source path.`});else if($.url){let ve="";try{ve=new URL($.url).hostname.toLowerCase();}catch{o.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Invalid URL for ${S}: ${$.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||l$1.has(ve))){o.push({id:`mirror.prefetch.trust.${S}`,status:"failed",message:`Untrusted mirror host for ${S}: ${ve}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await O.pathExists(D)?(q=true,ne={sourceType:"url",source:$.url,host:ve,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},o.push({id:`mirror.prefetch.${S}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${S}.`})):o.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${S} without an existing mirrored copy.`}),!q))continue;if(!q){await O.ensureDir(b.dirname(D)),Q=`${D}.${process.pid}.${randomUUID()}.tmp`,Re=true;let Pe=null,M=0;for(let F=1;F<=d+1;F+=1){M=F;try{await promises.rm(Q,{force:true}).catch(()=>{}),await Wp($.url,Q,g),r.syncedArtifacts+=1,q=true,ne={sourceType:"url",source:$.url,host:ve,fetchedAt:new Date().toISOString(),attempts:M,trusted:true},o.push({id:`mirror.prefetch.${S}`,status:"passed",message:M>1?`Prefetched artifact ${S} from ${ve} after ${M} attempts.`:`Prefetched artifact ${S} from ${ve}.`});break}catch(te){if(Pe=te,F<=d){await nc(w*F);continue}}}if(!q){await de(),o.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S} after ${d+1} attempt(s): ${Pe?.message||"unknown error"}`});continue}}if(!q){o.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S}.`});continue}}if(!q){$.required||e.offlineMode?o.push({id:`mirror.sync.${S}`,status:"failed",message:`Mirror source missing for ${S}${K?`: ${K}`:""}`}):o.push({id:`mirror.sync.${S}`,status:"skipped",message:`Mirror source not found for optional artifact ${S}.`});continue}let Ae=await Ip(Q);if($.sha256&&$.sha256.toLowerCase()!==Ae.toLowerCase()){o.push({id:`mirror.verify.${S}`,status:"failed",message:`Checksum mismatch for ${S}.`}),await de();continue}r.verifiedArtifacts+=1,o.push({id:`mirror.verify.${S}`,status:"passed",message:`Checksum verified for ${S}.`});let Oe=$.attestation?await Jp(t,Q,$.attestation):null;if($.attestation){if(o.push({id:`mirror.attest.${S}`,status:Oe?.verified?"passed":"failed",message:Oe?.message||"Attestation verification failed."}),!Oe?.verified){await de();continue}}else if(P){o.push({id:`mirror.attest.${S}`,status:"failed",message:`Attestation is required but missing for ${S}.`}),await de();continue}else o.push({id:`mirror.attest.${S}`,status:"skipped",message:`No attestation provided for ${S}.`});let Me=$.attestation?.sigstore,oe=Me?await Kp(t,Q,Me,{requireTransparencyLog:C}):null;if(Me){if(o.push({id:`mirror.sigstore.${S}`,status:oe?.verified?"passed":"failed",message:oe?.message||"Sigstore verification failed."}),x.push({artifactId:S,verified:!!oe?.verified,tlogVerified:!!oe?.tlogVerified,identity:oe?.identity||null,issuer:oe?.issuer||null,rekorUrl:oe?.rekorUrl||null,timestamp:new Date().toISOString(),environment:f}),!oe?.verified){await de();continue}}else if(j){o.push({id:`mirror.sigstore.${S}`,status:"failed",message:`Sigstore attestation is required but missing for ${S}.`}),await de();continue}else o.push({id:`mirror.sigstore.${S}`,status:"skipped",message:`No Sigstore attestation provided for ${S}.`});if(Me&&oe?.verified&&u){let ve=u.allowedIdentities||[];if(ve.length>0){let Pe=!!oe.identity&&ve.includes(oe.identity);if(o.push({id:`mirror.sigstore.policy.identity.${S}`,status:Pe?"passed":"failed",message:Pe?`Sigstore identity policy passed for ${S} in ${f}.`:`Sigstore identity policy failed for ${S} in ${f}.`}),!Pe){await de();continue}}let Zt=u.allowedIssuers||[];if(Zt.length>0){let Pe=!!oe.issuer&&Zt.includes(oe.issuer);if(o.push({id:`mirror.sigstore.policy.issuer.${S}`,status:Pe?"passed":"failed",message:Pe?`Sigstore issuer policy passed for ${S} in ${f}.`:`Sigstore issuer policy failed for ${S} in ${f}.`}),!Pe){await de();continue}}let _t=u.allowedRekorUrls||[];if(_t.length>0){let Pe=!!oe.rekorUrl&&_t.includes(oe.rekorUrl);if(o.push({id:`mirror.sigstore.policy.rekor.${S}`,status:Pe?"passed":"failed",message:Pe?`Sigstore Rekor policy passed for ${S} in ${f}.`:`Sigstore Rekor policy failed for ${S} in ${f}.`}),!Pe){await de();continue}}}else u&&o.push({id:`mirror.sigstore.policy.${S}`,status:"skipped",message:`Sigstore governance policy configured for ${f} but no verified Sigstore attestation for ${S}.`});Re&&(await rc(i,D),await promises.rename(Q,D),Re=false);let ms=await promises.stat(D);v.push({id:S,path:b.relative(t,D),sha256:Ae,size:ms.size,provenance:ne,attestation:{detached:{provided:!!$.attestation,verified:Oe?.verified||false,algorithm:Oe?.algorithm||null,publicKeyPath:Oe?.publicKeyPath||null,publicKeyFingerprint:Oe?.publicKeyFingerprint||null,signature:Oe?.signature||null,verifiedAt:Oe?.verified?new Date().toISOString():null},sigstore:{provided:!!Me,verified:oe?.verified||false,tlogVerified:oe?.tlogVerified||false,identity:oe?.identity||null,issuer:oe?.issuer||null,rekorUrl:oe?.rekorUrl||null,bundlePath:oe?.bundlePath||null,certificatePath:oe?.certificatePath||null,signaturePath:oe?.signaturePath||null,verifiedAt:oe?.verified?new Date().toISOString():null}}});}let I=p.retention?.keepLast;if(typeof I=="number"&&I>0){let T=new Set(v.map(S=>b.resolve(t,S.path))),$=(await $p(i)).filter(S=>!T.has(b.resolve(S)));if($.length>I){let S=await Promise.all($.map(async J=>({filePath:J,stat:await promises.stat(J)})));S.sort((J,D)=>D.stat.mtimeMs-J.stat.mtimeMs);let K=S.slice(I);for(let J of K)await promises.unlink(J.filePath),r.rotatedFiles+=1;}}o.push({id:"mirror.rotate",status:"passed",message:r.rotatedFiles>0?`Mirror retention rotation removed ${r.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let N={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:p.mode||null,environment:f,artifacts:v};if(await promises.writeFile(a,`${JSON.stringify(N,null,2)}
152
+ `,"utf-8"),r.lockWritten=true,o.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${b.relative(t,a)}.`}),r.transparencyEvidenceRecords=x.length,x.length>0){let T={schemaVersion:"transparency-evidence.v1",generatedAt:new Date().toISOString(),environment:f,records:x},$=new Date().toISOString().replace(/[:.]/g,"-"),S=b.join(c,`transparency-evidence-${$}.json`),K=b.join(c,"transparency-evidence.latest.json");if(b$j(`.workspai/reports/${b.basename(S)}`,T),b$j(".workspai/reports/transparency-evidence.latest.json",T),await O.ensureDir(c),await oc(S,T),await oc(K,T),r.transparencyEvidenceWritten=true,o.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${b.relative(t,K)}.`}),y?.enabled){let J=Math.max(1e3,y.timeoutMs??1e4);if(y.target==="file")if(!y.filePath)o.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let D=tt(t,y.filePath);await O.ensureDir(b.dirname(D)),await promises.appendFile(D,`${JSON.stringify(T)}
153
+ `,"utf-8"),r.evidenceExported=true,r.evidenceExportTarget=D,o.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${D}.`});}catch(D){o.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${D.message}`});}else if(y.target==="http")if(!y.endpoint)o.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let D=Math.max(0,y.retries??0),q=Math.max(0,y.backoffMs??500),Q=Fp(T,y.signing);Q.error&&o.push({id:"sigstore.evidence.export.http",status:"failed",message:Q.error});try{let Re=y.authTokenEnv?process.env[y.authTokenEnv]:void 0,de=false,ne=null;for(let Ae=1;Ae<=D+1;Ae+=1)try{if(Q.error)throw new Error(Q.error);await Dp(y.endpoint,T,J,Re,Q.headers),r.evidenceExported=true,r.evidenceExportTarget=y.endpoint,o.push({id:"sigstore.evidence.export.http",status:"passed",message:Ae>1?`Transparency evidence exported to HTTP endpoint ${y.endpoint} after ${Ae} attempts.`:`Transparency evidence exported to HTTP endpoint ${y.endpoint}.`}),de=true;break}catch(Oe){ne=Oe,Ae<=D&&await nc(q*Ae);}if(!de)throw ne||new Error("unknown evidence export error")}catch(Re){let de=`Evidence HTTP export failed: ${Re.message}`;o.push({id:"sigstore.evidence.export.http",status:"failed",message:de});try{let ne=await Lp(t,y.deadLetterPath,T,de);o.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${ne}.`});}catch(ne){o.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${ne.message}`});}}}if(y.failOnError&&o.some(q=>q.status==="failed"&&(q.id==="sigstore.evidence.export.file"||q.id==="sigstore.evidence.export.http")))return {checks:o,details:r}}else o.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else o.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),o.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:o,details:r}}function Cr(t){let e=f$7(t.detection.runtime),o=u({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),r=[];r.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),r.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),r.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),r.push({id:"lifecycle-commands",status:o.lifecycleCommands.length>1?"pass":"warn",message:o.lifecycleCommands.length>1?`Lifecycle commands available: ${o.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:o.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=r.some(i=>i.status==="fail"),a=r.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:o.lifecycleCommands,unsupportedLifecycleCommands:o.unsupportedLifecycleCommands,moduleCommands:o.moduleCommands},checks:r}}function Gp(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function Sr(t){if(t.existingProjectJson?.module_support===true){let e=Gp(t.existingProjectJson),o=e?a$3(e):void 0;return o?.owner==="core"&&o.moduleSupport===true}return false}function pc(t){return t.replace(/\\/g,"/")}function Up(t,e){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||e}function Bp(t,e){let o=pc(b.relative(t,e));return !o||o.startsWith("..")?true:o.split("/").filter(Boolean).some(r=>r==="..")}function ko(t){let e=pc(b.relative(t.workspacePath,t.projectPath)),o=Bp(t.workspacePath,t.projectPath),r=Up(t.projectName,b.basename(t.projectPath)),n=o?`external/${r}`:e||r;return {relativePath:e||n,contractRelativePath:n,isExternal:o}}var dc=[a$y,b$i];function Hp(t,e){let o=b.relative(t,e);return o===""||o.length>0&&!o.startsWith("..")&&!b.isAbsolute(o)}async function Be(t){let e=await O__default.realpath(t);for(let o of dc){let r=b.join(t,o),n=await O__default.lstat(r).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: ${r}`);let a=await O__default.realpath(r);if(!Hp(e,a))throw new Error(`Project metadata directory resolves outside the project: ${r}`)}}async function uc(t){let e=b.basename(t);return dc.includes(e)?(await O__default.lstat(t)).isSymbolicLink():false}var fc={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},Yp={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"},Qp={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},mc=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function Vn(t){return t==="bun"||t==="deno"?"node":t==="kotlin"||t==="scala"?"java":t}function Gn(t){return typeof t!="string"||t.trim().length===0?"minimal":t.trim().toLowerCase()}function vo(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 Rr(t){let e=new Set;for(let o of t)e.add(vo(o));return [...e].sort((o,r)=>mc.indexOf(o)-mc.indexOf(r))}function Xp(t){let e=Rr(t).filter(o=>o!=="unknown");if(e.length!==0)return e.length===1?Qp[e[0]]:"polyglot"}function gc(t,e={}){return `npx workspai bootstrap --profile ${t}${e.ci?" --ci --json":""}`}function Zp(t,e){return t?"none":e==="strict"?"error":"warning"}function Po(t){let e=t.ok?void 0:Xp(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?gc(e):void 0,ciRecommendedCommand:e?gc(e,{ci:true}):void 0,severity:Zp(t.ok,t.mode)}}function xt(t){let e=Gn(t.profile),o=Rr(t.runtimes),r=t.mode??"warn",n=fc[e];if(n){let a=o.length===0||o.every(i=>Vn(i)===n);return Po({ok:a,checkId:`profile.${e}`,profile:e,runtimes:o,message:a?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${o.join(", ")}].`,mode:r})}if(e==="minimal"){let a=o.filter(l=>l!=="unknown"),c=new Set(a.map(l=>Vn(l))).size<=1;return Po({ok:c,checkId:"profile.minimal",profile:e,runtimes:o,message:c?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${a.join(", ")}].`,mode:r})}return Po({ok:true,checkId:`profile.${e}`,profile:e,runtimes:o,message:`${e} profile accepts the detected runtime mix.`,mode:r})}function kt(t){let e=Gn(t.profile),o=vo(t.runtime),r=t.mode??"warn",n=fc[e];if(!n||o==="unknown")return Po({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[o],message:o==="unknown"?`Project "${t.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${t.subjectLabel}".`,mode:r});let a=Vn(o)===n;return Po({ok:a,checkId:`profile.${e}`,profile:e,runtimes:a?[o]:Rr([n,o]),message:a?`Project "${t.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${t.subjectLabel}" is ${Yp[o]}, but workspace profile is "${e}".`,mode:r})}async function qt(t){let e=(await Promise.all(o$1(t,"policies.yml").map(async o=>await O__default.pathExists(o)?o:null))).find(o=>typeof o=="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 zt(t){let e=(await Promise.all(o$1(t,"workspace.json").map(async o=>await O__default.pathExists(o)?o:null))).find(o=>typeof o=="string");if(!e)return "minimal";try{let o=await O__default.readJson(e);return Gn(o.profile)}catch{return "minimal"}}async function Et(t,e={}){let o=new Set,r=[],n=new Set,a=[t];for(;a.length>0;){let i=a.pop();if(!i||n.has(i))continue;n.add(i);let c=[];try{c=await E.promises.readdir(i,{withFileTypes:true});}catch{continue}for(let l of c){if(!l.isDirectory()||l.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(l.name))continue;let p$1=b.join(i,l.name);if(p$1!==t&&f$4(p$1))continue;if((await Promise.all([...p(p$1,"context.json"),...p(p$1,"project.json")].map(async d=>O__default.pathExists(d)))).some(Boolean)){r.push(p$1);continue}a.push(p$1);}}for(let i of r){let c=i$2(i);o.add(vo(i$3(i,c).runtime));}for(let i of await a$z(t))o.add(vo(i.runtime));for(let i of e.additionalRuntimes??[])o.add(vo(i));return Rr(o)}function Ar(t,e={}){let o=e.ci?t.ciRecommendedCommand:t.recommendedCommand;return o?`Recommended: ${o}`:null}function hc(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function td(t){let e=t.trim();if(!e)return "imported-project";let o=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),r=o[o.length-1]||e,n=r.split(":"),a=(n[n.length-1]||r).replace(/\.git$/i,"");return hc(a)||"imported-project"}function _r(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function od(t){return _r(t)?"git-url":"local-folder"}async function rd(t,e){let o=hc(e)||"imported-project",r=0;for(;;){let n=r===0?o:r===1?`${o}-imported`:`${o}-imported-${r}`,a=b.join(t,n);if(!await O__default.pathExists(a))return a;r+=1;}}function nd(t,e){let o=b.resolve(t),r=b.resolve(e),n=b.relative(o,r);return n===""||n.length>0&&!n.startsWith("..")&&!b.isAbsolute(n)}function sd(t,e){if(nd(t,e))throw new Error("Import source must be outside the current workspace root.")}function ad(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function id(t){let e=b.basename(t);return !(await uc(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||ad(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function cd(t){await Be(t);for(let e of p(t,"project.json"))if(await O__default.pathExists(e))try{return await O__default.readJson(e)}catch{return null}return null}async function ld(t){await Be(t.projectPath);let e=new Date().toISOString(),o=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),r=ko({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:o}),n=r.contractRelativePath,a=q(t.projectPath,"project.json"),i=q(t.projectPath,"import.json"),c=q(t.projectPath,"import-readiness.json"),l=Sr({existingProjectJson:t.existingProjectJson}),p=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],m=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},d={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:b.basename(t.projectPath),kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:l,modules:p,contracts:m,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:r.relativePath,is_external:r.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},w={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:b.basename(t.projectPath)},project:{name:d.name,slug:d.slug,relative_path:n,kind:t.projectKind,module_support:l},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:l,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},g=Cr({projectName:String(d.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:l,projectPath:t.projectPath,generatedAt:new Date(e)});return await O__default.ensureDir(b.dirname(a)),await O__default.writeJson(a,d,{spaces:2}),await O__default.writeJson(i,w,{spaces:2}),await O__default.writeJson(c,g,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:l}}async function pd(t,e){let o={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,importedAt:new Date().toISOString()};await b$d(t,[o]);}async function dd(t){await O__default.pathExists(t)&&(await Be(t),await O__default.remove(t));}async function yc(t){let e=b.resolve(t.workspacePath),o=t.source.trim(),r=t.sourceType??od(o),n=t.name??(r==="git-url"?td(o):b.basename(o)),a=await rd(e,n),i=false;try{if(r==="local-folder"){let y=b.resolve(o),f=await O__default.stat(y).catch(()=>null);if(!f||!f.isDirectory())throw new Error("Import source is not a directory.");if(await Be(y),f$4(y))throw new Error("This is a workspace. Import it as a workspace instead.");sd(e,y),i=true,await O__default.copy(y,a,{overwrite:false,errorOnExist:true,filter:id});}else i=true,await execa("git",["clone","--depth","1","--",o,a],{timeout:12e4,env:a$d()});await Be(a);let c=await cd(a),l=i$3(a,c),p=await f$5(a,c),[m,d]=await Promise.all([zt(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):qt(e)]),w=kt({profile:m,runtime:l.runtime,subjectLabel:b.basename(a),mode:d}),g=xt({profile:m,runtimes:await Et(e,{additionalRuntimes:[l.runtime]}),mode:d}),P=w.ok?g:w;if(!P.ok&&d==="strict")throw new Error(P.message);let j=await ld({workspacePath:e,projectPath:a,sourceType:r,detection:l,existingProjectJson:c,projectKind:p,profileCompatibility:P}),A=ko({workspacePath:e,projectPath:a,projectName:b.basename(a)}),h={name:b.basename(a),path:a,relativePath:A.contractRelativePath,stack:l.importStack,runtime:l.runtime,framework:l.key,frameworkDisplayName:l.displayName,supportTier:l.supportTier,moduleSupport:j.moduleSupport,confidence:l.confidence,source:r,projectJsonPath:j.projectJsonPath,importJsonPath:j.importJsonPath,importReadinessPath:j.importReadinessPath,profileCompatibility:P};return await pd(e,h),h}catch(c){if(i)try{await dd(a);}catch(l){let p=c instanceof Error?c.message:String(c),m=l instanceof Error?l.message:String(l);throw new Error(`Import failed: ${p}. Rollback also failed: ${m}`)}throw c}}function ud(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function md(t,e){return b.resolve(t)===b.resolve(e)}async function gd(t){await Be(t);for(let e of p(t,"project.json")){if(!await O__default.pathExists(e))continue;let o;try{o=JSON.parse((await O__default.readFile(e)).toString("utf8"));}catch(r){throw new Error(`Authoritative project metadata is malformed: ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return o}return null}async function Un(t,e){let o=b.resolve(t),r=b.resolve(e);await Be(r);let n=[q(r,"project.json"),q(r,"adopt.json"),q(r,"adopt-readiness.json"),l(o,"imported-projects.json")];return {workspacePath:o,projectPath:r,files:await Promise.all(n.map(async a=>({path:a,contents:await O__default.pathExists(a)?await O__default.readFile(a):null})))}}function wc(t,e,o){let r=[q(o,"project.json"),q(o,"adopt.json"),q(o,"adopt-readiness.json"),l(e,"imported-projects.json")].map(n=>b.resolve(n));if(t.workspacePath!==b.resolve(e)||t.projectPath!==b.resolve(o)||t.files.length!==r.length||t.files.some((n,a)=>b.resolve(n.path)!==r[a]))throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function fd(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],o=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:o,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,discovered_relative_path:t.discoveredRelativePath,is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function hd(t,e,o){await Be(e),wc(o,t,e);let r=[];for(let n of o.files)try{n.contents===null?await O__default.remove(n.path):(await O__default.ensureDir(b.dirname(n.path)),await O__default.writeFile(n.path,n.contents));}catch(a){r.push(a);}if(r.length>0)throw new AggregateError(r,"Failed to restore adopt rollback snapshot.")}async function Bn(t){let e=b.resolve(t.workspacePath),o=b.resolve(t.source),r=await O__default.stat(o).catch(()=>null);if(!r||!r.isDirectory())throw new Error("Adopt source is not a directory.");if(await Be(o),md(e,o))throw new Error("Adopt source cannot be the workspace root itself.");if(f$4(o))throw new Error("This is a workspace. Import it as a workspace instead.");let n=t.rollbackSnapshot??await Un(e,o);wc(n,e,o);let a=await gd(o),i=i$3(o,a),c=await f$5(o,a),l=ud(t.name||(typeof a?.name=="string"?a.name:"")||b.basename(o))||"adopted-project",p=ko({workspacePath:e,projectPath:o,projectName:l}),m=(t.now??new Date).toISOString(),d=q(o,"project.json"),w=q(o,"adopt.json"),g=q(o,"adopt-readiness.json"),P=Sr({existingProjectJson:a}),[j,A]=await Promise.all([zt(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):qt(e)]),h=kt({profile:j,runtime:i.runtime,subjectLabel:l,mode:A}),y=xt({profile:j,runtimes:await Et(e,{additionalRuntimes:[i.runtime]}),mode:A}),f=h.ok?y:h;if(!f.ok&&A==="strict")throw new Error(f.message);let k=fd({projectName:l,contractRelativePath:p.contractRelativePath,isExternal:p.isExternal,discoveredRelativePath:p.relativePath,detection:i,existingProjectJson:a,projectKind:c,moduleSupport:P,adoptedAt:m}),u={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:m,managed_by:"workspai",mode:"linked",workspace:{path:e},project:{name:l,path:o,relative_path:p.contractRelativePath,discovered_relative_path:p.relativePath,is_external:p.isExternal,kind:c,module_support:P},detection:{framework:i.key,framework_display_name:i.displayName,runtime:i.runtime,kind:c,confidence:i.confidence,support_tier:i.supportTier,import_stack:i.importStack,source:i.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:P,workspace_contract:"linked-project",profile_compatibility:{ok:f.ok,profile:f.profile,runtimes:f.runtimes,message:f.message,recommended_profile:f.recommendedProfile,recommended_command:f.recommendedCommand}}},C=Cr({projectName:l,relativePath:p.contractRelativePath,projectKind:c,source:"adopted-local",detection:i,moduleSupport:P,projectPath:o,generatedAt:new Date(m)});if(t.dryRun!==true)try{await Be(o),await O__default.ensureDir(b.dirname(d)),await O__default.writeJson(d,k,{spaces:2}),await O__default.writeJson(w,u,{spaces:2}),await O__default.writeJson(g,C,{spaces:2});let x={name:l,path:o,relativePath:p.contractRelativePath,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:P,confidence:i.confidence,source:"adopted-local",importedAt:m};await b$d(e,[x]);}catch(x){try{await hd(e,o,n);}catch(R){throw new AggregateError([x,R],`Adopt failed and rollback was incomplete: ${x instanceof Error?x.message:String(x)}`)}throw x}return {name:l,path:o,relativePath:p.relativePath,contractRelativePath:p.contractRelativePath,isExternal:p.isExternal,relationship:"adopted",stack:i.importStack,runtime:i.runtime,framework:i.key,frameworkDisplayName:i.displayName,supportTier:i.supportTier,moduleSupport:P,confidence:i.confidence,projectJsonPath:d,adoptJsonPath:w,adoptReadinessPath:g,profileCompatibility:f,wroteFiles:t.dryRun!==true}}var kd=br,vd=vr;function Hn(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 Pd(t=process.argv){let e=b.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function Qt(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function bd(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Se(t,e){let o=t.indexOf(e);if(o>=0&&o+1<t.length)return t[o+1];let r=t.find(n=>n.startsWith(`${e}=`));if(r)return r.slice(e.length+1)}function jd(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let o=Number(e);if(!Number.isSafeInteger(o)||o<1||o>16)throw new Error("--max-workers must be an integer between 1 and 16.");return o}function Zn(t){try{return jd(t.raw)}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$2({operation:t.operation,code:"cli.option.max-workers.invalid",message:o,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${o}`)),process.exit(1);}}async function ls(t,e){let o=Se(t,"--port")?.trim(),r=t[3];if(!o||!r||!/^\d+$/.test(o))return;let n=Number.parseInt(o,10);if(n<1||n>65535)return;let a=Se(t,"--output")||".",i=b.resolve(e,a,r),c=p(i,"project.json").find(p=>E.existsSync(p))??q(i,"project.json");if(!await O__default.pathExists(c))return;let l=await O__default.readJson(c);await O__default.writeJson(c,{...l,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function vc(t){let e=le(process.cwd()),o=t.trim().toLowerCase();if(!e||!o)return true;try{let[r,n]=await Promise.all([zt(e),qt(e)]),a=a$3(o),c=j$1(o)?"node":a?.runtime??"python",l=kt({profile:r,runtime:c,subjectLabel:o,mode:n}),p=xt({profile:r,runtimes:await Et(e,{additionalRuntimes:[c]}),mode:n}),m=l.ok?p:l;if(m.ok)return true;let d=Ar(m);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${m.message}`)),d&&console.log(s.gray(`\u{1F4A1} ${d}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${m.message}`)),d&&console.log(s.gray(`\u{1F4A1} ${d}`));}catch{}return true}function ps(){return i$6()}function Pc(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(b.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=h$3()),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 Cd(t){return l$4(b.join(t,".venv"))}async function Sd(t,e){return await se(t,["--version"],e)===0}async function At(t){let e=b.join(t,"go.mod");if(await O__default.pathExists(e))return "go";let o=b.join(t,"pom.xml"),r=b.join(t,"build.gradle"),n=b.join(t,"build.gradle.kts");if(await O__default.pathExists(o)||await O__default.pathExists(r)||await O__default.pathExists(n))return "java";if((await O__default.pathExists(t)?await E.promises.readdir(t,{withFileTypes:true}):[]).some(d=>d.isFile()&&d.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=b.join(t,"src");if(await O__default.pathExists(i)&&(await E.promises.readdir(i,{withFileTypes:true})).some(w=>w.isFile()&&w.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=b.join(t,"package.json");if(await O__default.pathExists(c))return "node";let l=b.join(t,"pyproject.toml"),p=b.join(t,"requirements.txt"),m=b.join(t,"poetry.lock");return await O__default.pathExists(l)||await O__default.pathExists(p)||await O__default.pathExists(m)?"python":null}async function xd(t,e={}){let o=e.runCommand??se;for(let r of e.pythonCandidates??ps())if(await o(r,r==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Dc(t,e={}){let o=e.runCommand??se;for(let r of e.pythonCandidates??ps())if(await o(r,r==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function Ed(t,e={}){let o=e.runCommand??se,r=l$4(b.join(t,".venv"));if(!await O__default.pathExists(r)){let c=await Dc(t,e);if(c!==0)return c}if(!(await o("poetry",["--version"],t)===0))return 0;let a=await o("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await o("poetry",["env","use",r],t);return i!==0?i:0}async function Rd(t,e={}){let o=e.runCommand??se,r=l$4(b.join(t,".venv"));if(!await O__default.pathExists(r)){let i=await Dc(t,e);if(i!==0)return i}await o(r,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=b.join(t,"requirements.txt");if(await O__default.pathExists(n)&&await o(r,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=b.join(t,"pyproject.toml");return await O__default.pathExists(a)&&(await o(r,["-m","pip","install","-e","."],t)===0||await o(r,["-m","pip","install","."],t)===0)?0:1}async function qn(t,e){return await Ed(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await O__default.pathExists(b.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await Rd(t))}async function zn(t){let e=await Rt("init",t);if(e===0)return 0;let o=["npm","pnpm","yarn"];for(let r of o){if(!await Sd(r,t))continue;if(await se(r,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${r} install`)),0}return e}function Ad(t,e){let o=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),r=Se([...e],"--port");if(r&&!/^\d+$/.test(r.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Se([...e],"--java-version"),a=Se([...e],"--spring-boot-version"),i=Se([...e],"--springdoc-version"),c=Se([...e],"--group-id"),l=Se([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!o(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!o(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(l&&!/^[A-Za-z0-9_.-]+$/.test(l.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Se([...e],"--target-framework"),a=Se([...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 bc(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||ss(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:r}=await import('./create-S64IWHAP.js');await r(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b$2()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:o}=await b$4([{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(o==="current"){let{registerWorkspaceAtPath:r}=await import('./create-S64IWHAP.js');await r(process.cwd(),{skipGit:e,yes:false,userConfig:await b$2()});}else o==="none"&&t.push("--no-workspace");}async function _d(t){await O__default.ensureDir(t);let e=b.join(t,"lifecycle.lock"),o=Date.now();for(;;)try{let r=await E.promises.open(e,"wx");return await r.writeFile(`${JSON.stringify({pid:process.pid})}
154
+ `),async()=>{await r.close().catch(()=>{}),await O__default.remove(e).catch(()=>{});}}catch(r){if(r.code!=="EEXIST")throw r;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()-o>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function Or(t,e={}){let o=b.join(p$2(),"transactions"),r=await _d(o),n;try{await b$b(o),n=await a$a({journalDirectory:o});}catch(i){throw await r(),i}let a=new Set([b.join(p$2(),"workspaces.json"),b.join(q$1(),"workspaces.json"),a$b(t,d$6),b$c(t,d$6),a$b(t,a$c),b$c(t,a$c),...o$1(t,"imported-projects.json")]);e.projectPath&&(a.add(q(e.projectPath,"project.json")),a.add(q(e.projectPath,"context.json")),a.add(q(e.projectPath,"file-hashes.json")),a.add(q(e.projectPath,"adopt.json")),a.add(q(e.projectPath,"adopt-readiness.json")));try{for(let c of a)await n.captureFile(c);e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let i=false;return {registerCompensation:c=>n.registerCompensation(c),commit:async()=>{i||(await n.commit(),i=true,await r());},rollback:async()=>{if(!i){i=true;try{await n.rollback();}finally{await r();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await r(),i}}async function Xt(t,e){try{await t.rollback();}catch(o){throw new AggregateError([e,o],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function Mr(t,e,o){if(t.includes("--no-workspace")||t.includes("--dry-run"))return;if(!await O__default.pathExists(e)){f.warn(`Created project path was not found for workspace linking: ${e}`);return}let r=le(e)||le(process.cwd()),n=false,a;if(r)a=await Or(r,{projectPath:e});else {r=k(),a=await Or(r,{projectPath:e,ownedWorkspace:r});try{r=(await us()).workspacePath;}catch(c){await Xt(a,c);}n=true;}let i="managed";try{await o$2(e);let c=b.relative(r,e);(c.startsWith("..")||b.isAbsolute(c))&&(i=(await Bn({source:e,workspacePath:r,name:o})).relationship);let{registerProjectInWorkspaceStrict:p,registerWorkspaceStrict:m}=await import('./workspace-PJPRBUMQ.js'),{syncWorkspaceContract:d}=await import('./workspace-contract-TU2I7GC2.js');await m(r,b.basename(r)),await p(r,o,e),await d({workspacePath:r,strict:true}),await a.commit();}catch(c){await Xt(a,c);}return n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${e$2}" (${i}).`)),console.log(s.gray(` Registry: ${b.join(p$2(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${r}`))),r}async function es(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],o=a$3(e),r=t[3];if(!o||o.owner!=="npm")return 1;if(!r)return process.stderr.write(`Usage: ${o.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
155
+ `),1;try{h(r);}catch(d){let w=d instanceof Error?d.message:String(d);return process.stderr.write(`${w}
156
+ `),1}let n=Ad(o.id,t);if(n)return process.stderr.write(`${n}
157
157
  `),1;let a=Se(t,"--output")||process.cwd(),i=b.resolve(a,r),c=t.includes("--skip-git")||t.includes("--no-git"),l=t.includes("--skip-install"),p=t.includes("--dry-run"),m=false;try{let{default:d}=await import('fs-extra');return await d.pathExists(i)?(process.stderr.write(`\u274C Directory "${i}" already exists
158
158
  `),1):p?(console.log(s.bold(`
159
- ${o.label}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` Target: ${i}`)),console.log(s.gray(" Dry run: no files or workspace state will be changed.")),0):(await d.ensureDir(b.dirname(i)),await d.ensureDir(i),m=true,await e$1(o,{projectName:r,projectPath:i,args:t,skipGit:c,skipInstall:l}),await ls(t,process.cwd()),await Mr(t,i,r),0)}catch(d){if(m){let{default:h}=await import('fs-extra');await h.remove(i).catch(()=>{});}return process.stderr.write(`Workspai ${o.id} generator failed: ${d?.message??d}
160
- `),1}}async function vc(t){let e=j$1(t[2]);if(!e)return 1;let o;try{let r=await n$2({args:t});return r.dryRun||(o=r.projectPath,await Mr(t,r.projectPath,r.projectName)),0}catch(r){return o&&await I__default.remove(o).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${r?.message??r}
159
+ ${o.label}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` Target: ${i}`)),console.log(s.gray(" Dry run: no files or workspace state will be changed.")),0):(await d.ensureDir(b.dirname(i)),await d.ensureDir(i),m=true,await e$1(o,{projectName:r,projectPath:i,args:t,skipGit:c,skipInstall:l}),await ls(t,process.cwd()),await Mr(t,i,r),0)}catch(d){if(m){let{default:w}=await import('fs-extra');await w.remove(i).catch(()=>{});}return process.stderr.write(`Workspai ${o.id} generator failed: ${d?.message??d}
160
+ `),1}}async function jc(t){let e=j$1(t[2]);if(!e)return 1;let o;try{let r=await n$2({args:t});return r.dryRun||(o=r.projectPath,await Mr(t,r.projectPath,r.projectName)),0}catch(r){return o&&await O__default.remove(o).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${r?.message??r}
161
161
  `),t[3]||process.stderr.write(`Usage: ${m$1(e.id)}
162
162
  `),1}}async function Ir(t,e){if(t.includes("--json"))return process.stderr.write("Workspai CLI offline fallback does not support --json for `create` commands.\nInstall Python 3.10+ and retry the same command.\n"),1;if(t[0]!=="create")return 1;if(t[1]!=="project")return process.stderr.write(`Workspai CLI could not run the Python core engine for \`create\`.
163
163
  Reason: ${e}.
164
164
  Install Python 3.10+ to use the interactive wizard and full kit catalog.
165
165
  `),1;let n=t[2],a=t[3];if(!n||!a)return process.stderr.write(`Usage: npx workspai create project <kit> <name> [--output <dir>]
166
166
  Tip: offline fallback supports only fastapi* and nestjs* kits.
167
- `),1;let i=wd(n);if(!i)return process.stderr.write(`Workspai CLI could not run the Python core engine to create this kit.
167
+ `),1;let i=bd(n);if(!i)return process.stderr.write(`Workspai CLI could not run the Python core engine to create this kit.
168
168
  Reason: ${e}.
169
169
  Requested kit: ${n}
170
170
  Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
171
171
  Install Python 3.10+ to access all kits.
172
- `),1;let c=Se(t,"--output")||process.cwd(),l=b.resolve(c,a),p=false,m=t.includes("--skip-git")||t.includes("--no-git"),d=t.includes("--skip-install");try{if(await I__default.ensureDir(b.dirname(l)),await I__default.pathExists(l))return process.stderr.write(`\u274C Directory "${l}" already exists
173
- `),1;let h="pip",g=le(process.cwd());if(g)try{let{readWorkspaceMarker:C}=await import('./workspace-marker-SMBC3Z2Q.js'),A=await C(g);A?.metadata?.npm?.installMethod&&(h=A.metadata.npm.installMethod,f.debug(`Detected workspace engine: ${h}`));}catch(C){f.debug("Failed to read workspace marker",C);}else f.debug("No workspace found, using default engine: pip");await I__default.ensureDir(l),p=true;let{generateDemoKit:k}=await import('./demo-kit-DZ7TPG7K.js');return await k(l,{project_name:a,template:i,kit_name:n,skipGit:m,skipInstall:d,engine:h}),await ls(t,process.cwd()),await Mr(t,l,a),0}catch(h){return p&&await I__default.remove(l).catch(()=>{}),process.stderr.write(`Workspai CLI offline fallback failed: ${h?.message??h}
174
- `),1}}function Ed(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("Workspai native create is not available for this request yet.")}
172
+ `),1;let c=Se(t,"--output")||process.cwd(),l=b.resolve(c,a),p=false,m=t.includes("--skip-git")||t.includes("--no-git"),d=t.includes("--skip-install");try{if(await O__default.ensureDir(b.dirname(l)),await O__default.pathExists(l))return process.stderr.write(`\u274C Directory "${l}" already exists
173
+ `),1;let w="pip",g=le(process.cwd());if(g)try{let{readWorkspaceMarker:j}=await import('./workspace-marker-SMBC3Z2Q.js'),A=await j(g);A?.metadata?.npm?.installMethod&&(w=A.metadata.npm.installMethod,f.debug(`Detected workspace engine: ${w}`));}catch(j){f.debug("Failed to read workspace marker",j);}else f.debug("No workspace found, using default engine: pip");await O__default.ensureDir(l),p=true;let{generateDemoKit:P}=await import('./demo-kit-DZ7TPG7K.js');return await P(l,{project_name:a,template:i,kit_name:n,skipGit:m,skipInstall:d,engine:w}),await ls(t,process.cwd()),await Mr(t,l,a),0}catch(w){return p&&await O__default.remove(l).catch(()=>{}),process.stderr.write(`Workspai CLI offline fallback failed: ${w?.message??w}
174
+ `),1}}function Id(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("Workspai native create is not available for this request yet.")}
175
175
  `),process.stderr.write(s.gray(`Requested: ${e}
176
176
  `)),process.stderr.write(s.gray(`Lane: ${t.lane} (${t.status})
177
177
  `)),process.stderr.write(s.gray(`Reason: ${t.reason}
178
178
  `)),t.officialCommands?.length){process.stderr.write(s.gray(`Official generator candidates:
179
179
  `));for(let o of t.officialCommands)process.stderr.write(s.gray(` - ${o}
180
- `));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx workspai adopt <project-path>` to add Workspace Intelligence.\n"));}function Pc(){console.log(`Usage: npx workspai create project <kit> <name> [options]
180
+ `));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx workspai adopt <project-path>` to add Workspace Intelligence.\n"));}function Cc(){console.log(`Usage: npx workspai create project <kit> <name> [options]
181
181
 
182
182
  Scaffold a project and register it with Workspace Intelligence.
183
183
 
@@ -210,7 +210,7 @@ Notes:
210
210
  Outside a workspace, projects are linked to the managed default workspace.
211
211
  Interactive mode can instead turn the current folder into a workspace or opt out.
212
212
  Python-backed kits delegate execution to RapidKit Core when needed, but the
213
- Workspai CLI owns the command UX, workspace registration, and artifacts.`);}function Rd(){console.log(`Usage: npx workspai create workspace [name] [options]
213
+ Workspai CLI owns the command UX, workspace registration, and artifacts.`);}function $d(){console.log(`Usage: npx workspai create workspace [name] [options]
214
214
 
215
215
  Create a Workspai workspace and initialize Workspace Intelligence files.
216
216
 
@@ -234,7 +234,7 @@ Mental model:
234
234
  \u2193
235
235
  Workspace Intelligence
236
236
  \u2193
237
- Developers \xB7 CI \xB7 IDEs \xB7 AI Agents`);}function Ad(){console.log(`Usage: npx workspai create <workspace|project> [options]
237
+ Developers \xB7 CI \xB7 IDEs \xB7 AI Agents`);}function Od(){console.log(`Usage: npx workspai create <workspace|project> [options]
238
238
 
239
239
  Create a workspace or scaffold a project into Workspace Intelligence.
240
240
 
@@ -247,74 +247,74 @@ Shortcuts:
247
247
 
248
248
  Run:
249
249
  npx workspai create workspace --help
250
- npx workspai create project --help`);}function _d(t){let e=t[2]??"<kit>",o=t[3]??"<name>",r=Se(t,"--output")||process.cwd();console.log("Workspai create project dry run (Dry-run mode)"),console.log(` kit: ${e}`),console.log(` name: ${o}`),console.log(` output: ${b.resolve(r)}`),console.log(" execution: RapidKit Core bridge"),console.log(" writes: none"),console.log(""),console.log("Run without --dry-run to scaffold the project.");}async function ts(t){if(t[0]==="create"&&(t.includes("--help")||t.includes("-h")||t.includes("help")))return t[1]==="project"?Pc():t[1]==="workspace"?Rd():Ad(),0;let e$1=t[0]==="create"&&t[1]==="frontend",o=l$2(t);if(o&&(t=o),e$1&&!k$2(t[2]))return process.stderr.write(`Unknown frontend generator: ${t[2]?.replace(/^frontend\./,"")}
250
+ npx workspai create project --help`);}function Nd(t){let e=t[2]??"<kit>",o=t[3]??"<name>",r=Se(t,"--output")||process.cwd();console.log("Workspai create project dry run (Dry-run mode)"),console.log(` kit: ${e}`),console.log(` name: ${o}`),console.log(` output: ${b.resolve(r)}`),console.log(" execution: RapidKit Core bridge"),console.log(" writes: none"),console.log(""),console.log("Run without --dry-run to scaffold the project.");}async function ts(t){if(t[0]==="create"&&(t.includes("--help")||t.includes("-h")||t.includes("help")))return t[1]==="project"?Cc():t[1]==="workspace"?$d():Od(),0;let e$1=t[0]==="create"&&t[1]==="frontend",o=l$2(t);if(o&&(t=o),e$1&&!k$2(t[2]))return process.stderr.write(`Unknown frontend generator: ${t[2]?.replace(/^frontend\./,"")}
251
251
  `),process.stderr.write(`Usage: ${m$1()}
252
- `),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return Ir(t,"PYTHON_NOT_FOUND");let r=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace","--here"]);if(t[0]==="create"&&(!t[1]||t[1].startsWith("-"))){let n=t.includes("--yes")||t.includes("-y"),a$1=t.slice(1),i;!process.stdin.isTTY||n?(i="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."))):(process.stdin.isTTY&&a("create"),i=(await b$4([{type:"rawlist",name:"createTarget",message:"What do you want to create?",choices:[{name:"workspace",value:"workspace"},{name:"project",value:"project"}]}])).createTarget);let c=["create",i,...a$1];return await ts(c)}if(t[0]==="create"&&t[1]==="workspace")try{let n=t.includes("--yes")||t.includes("-y"),a$2=t.includes("--skip-git")||t.includes("--no-git"),i$2=t.includes("--skip-python-engine")||t.includes("--no-python-engine"),c=t.includes("--dry-run"),l=t[2]&&!t[2].startsWith("-")?t[2]:void 0,p=Se(t,"--install-method"),m=p==="poetry"||p==="venv"||p==="pipx"?p:void 0,d=Se(t,"--profile"),h$2=d==="minimal"||d==="java-only"||d==="go-only"||d==="dotnet-only"||d==="python-only"||d==="node-only"||d==="polyglot"||d==="enterprise"?d:void 0,g$1=l;if(g$1||(n?g$1="my-workspace":(process.stdin.isTTY&&a("create workspace"),g$1=(await b$4([{type:"input",name:"workspaceName",message:"Workspace name:",default:"my-workspace"}])).workspaceName)),!g$1||!g$1.trim())return process.stderr.write(`Workspace name is required.
253
- `),1;try{h(g$1);}catch(v){if(v instanceof a$1)return process.stderr.write(`${v.message}
254
- `),1;throw v}let k=await i(t,{hasYes:n}),C=g(g$1.trim(),{argv:t,outputParent:k});c||await I__default.ensureDir(b.dirname(C));let A=i$1(g$1.trim());if(!c&&(h$1(A,C,{outputParent:k})&&A&&await I__default.pathExists(A)||await I__default.pathExists(C)))return process.stderr.write(`\u274C Workspace "${g$1}" already exists
255
- `),A&&A!==C&&process.stderr.write(` Found at: ${A}
256
- `),1;let w=await b$2(),y=w.author||process.env.USER||"Workspai User";if(!n){let v=await b$4([{type:"input",name:"author",message:"Author name:",default:y}]);v.author?.trim()&&(y=v.author.trim());}let{createProject:f}=await import('./create-7JKJDAQV.js');return await f(g$1,{skipGit:a$2,skipPythonEngine:i$2,yes:n,dryRun:c,userConfig:{...w,author:y},installMethod:m,profile:h$2,parentDirectory:b.dirname(C)}),c||(console.log(s.gray(`\u2139\uFE0F Workspace root: ${C}`)),console.log(s.gray(` Next: ${f$2(C)} && npx workspai create project`))),0}catch(n){return process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
257
- `),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return Pc(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitChoice:g}=await b$4([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$g()}]);if(d$1(g)||k$2(g)){let A=Fn(g),{projectName:w}=await b$4([{type:"input",name:"projectName",message:"Project name:",default:A,validate:j=>j.trim().length>0||"Project name is required"}]),y=t.slice(2).filter(j=>j.startsWith("-")),f=["create","project",g,w.trim(),...y];if(!await yc(g))return 1;await kc(f);let v=k$2(g)?await vc(f):await es(f),u=le(process.cwd());return v===0&&u&&await ds(u),v}let k=Fn(g),{projectName:C}=await b$4([{type:"input",name:"projectName",message:"Project name:",default:k,validate:A=>A.trim().length>0||"Project name is required"}]);t.splice(2,0,g,C.trim());}let a$1=t[2],i=d$7({kitId:a$1,framework:a$1,runtime:a$1});if(e$3(i))return Ed(i),1;if(!await yc(t[2]||""))return 1;if(await kc(t),d$1(t[2]))return await es(t);if(k$2(t[2]))return await vc(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 _d(t),0;let l=[...t.filter(g=>{let k=g.split("=")[0];return !r.has(g)&&!r.has(k)})],p=le(process.cwd()),h=t.includes("--skip-install")||!!p?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$8();let g=await e(l,{cwd:process.cwd(),env:h});if(g===0&&p&&!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"))),g===0){await ls(t,process.cwd());let k=t[3],C=Se(t,"--output")||process.cwd(),A=k?b.resolve(C,k):void 0,w=k&&A?await Mr(t,A,k).catch(async y=>{throw await I__default.remove(A).catch(()=>{}),y}):p;if(w)try{if(k&&A){let y=b.join(w,".python-version"),f$1=b.join(A,".python-version");if(x.existsSync(y)&&x.existsSync(A)){let v=x.readFileSync(y,"utf-8");x.writeFileSync(f$1,v.trim()+`
258
- `),f.debug(`Synced Python version ${v.trim()} from workspace to ${k}`);}}}catch(y){f.debug("Could not sync Python version from workspace:",y);}}return g}catch(g){let k=Hn(g);return k?await Ir(t,k):(process.stderr.write(`Workspai failed to run the Python core engine: ${g?.message??g}
259
- `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$8();let n=await e(t,{cwd:process.cwd()});if(n===0){let a=le(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-H3QXBFGB.js');await i(a,true);}}return n}catch(n){let a=Hn(n);return a?await Ir(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
252
+ `),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return Ir(t,"PYTHON_NOT_FOUND");let r=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace","--here"]);if(t[0]==="create"&&(!t[1]||t[1].startsWith("-"))){let n=t.includes("--yes")||t.includes("-y"),a$1=t.slice(1),i;!process.stdin.isTTY||n?(i="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."))):(process.stdin.isTTY&&a("create"),i=(await b$4([{type:"rawlist",name:"createTarget",message:"What do you want to create?",choices:[{name:"workspace",value:"workspace"},{name:"project",value:"project"}]}])).createTarget);let c=["create",i,...a$1];return await ts(c)}if(t[0]==="create"&&t[1]==="workspace")try{let n=t.includes("--yes")||t.includes("-y"),a$2=t.includes("--skip-git")||t.includes("--no-git"),i$2=t.includes("--skip-python-engine")||t.includes("--no-python-engine"),c=t.includes("--dry-run"),l=t[2]&&!t[2].startsWith("-")?t[2]:void 0,p=Se(t,"--install-method"),m=p==="poetry"||p==="venv"||p==="pipx"?p:void 0,d=Se(t,"--profile"),w=d==="minimal"||d==="java-only"||d==="go-only"||d==="dotnet-only"||d==="python-only"||d==="node-only"||d==="polyglot"||d==="enterprise"?d:void 0,g$1=l;if(g$1||(n?g$1="my-workspace":(process.stdin.isTTY&&a("create workspace"),g$1=(await b$4([{type:"input",name:"workspaceName",message:"Workspace name:",default:"my-workspace"}])).workspaceName)),!g$1||!g$1.trim())return process.stderr.write(`Workspace name is required.
253
+ `),1;try{h(g$1);}catch(k){if(k instanceof a$1)return process.stderr.write(`${k.message}
254
+ `),1;throw k}let P=await i(t,{hasYes:n}),j=g(g$1.trim(),{argv:t,outputParent:P});c||await O__default.ensureDir(b.dirname(j));let A=i$1(g$1.trim());if(!c&&(h$1(A,j,{outputParent:P})&&A&&await O__default.pathExists(A)||await O__default.pathExists(j)))return process.stderr.write(`\u274C Workspace "${g$1}" already exists
255
+ `),A&&A!==j&&process.stderr.write(` Found at: ${A}
256
+ `),1;let h$2=await b$2(),y=h$2.author||process.env.USER||"Workspai User";if(!n){let k=await b$4([{type:"input",name:"author",message:"Author name:",default:y}]);k.author?.trim()&&(y=k.author.trim());}let{createProject:f}=await import('./create-S64IWHAP.js');return await f(g$1,{skipGit:a$2,skipPythonEngine:i$2,yes:n,dryRun:c,userConfig:{...h$2,author:y},installMethod:m,profile:w,parentDirectory:b.dirname(j)}),c||(console.log(s.gray(`\u2139\uFE0F Workspace root: ${j}`)),console.log(s.gray(` Next: ${f$2(j)} && npx workspai create project`))),0}catch(n){return process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
257
+ `),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return Cc(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitChoice:g}=await b$4([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$g()}]);if(d$1(g)||k$2(g)){let A=Fn(g),{projectName:h}=await b$4([{type:"input",name:"projectName",message:"Project name:",default:A,validate:C=>C.trim().length>0||"Project name is required"}]),y=t.slice(2).filter(C=>C.startsWith("-")),f=["create","project",g,h.trim(),...y];if(!await vc(g))return 1;await bc(f);let k=k$2(g)?await jc(f):await es(f),u=le(process.cwd());return k===0&&u&&await ds(u),k}let P=Fn(g),{projectName:j}=await b$4([{type:"input",name:"projectName",message:"Project name:",default:P,validate:A=>A.trim().length>0||"Project name is required"}]);t.splice(2,0,g,j.trim());}let a$1=t[2],i=d$7({kitId:a$1,framework:a$1,runtime:a$1});if(e$3(i))return Id(i),1;if(!await vc(t[2]||""))return 1;if(await bc(t),d$1(t[2]))return await es(t);if(k$2(t[2]))return await jc(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 Nd(t),0;let l=[...t.filter(g=>{let P=g.split("=")[0];return !r.has(g)&&!r.has(P)})],p=le(process.cwd()),w=t.includes("--skip-install")||!!p?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$8();let g=await e(l,{cwd:process.cwd(),env:w});if(g===0&&p&&!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"))),g===0){await ls(t,process.cwd());let P=t[3],j=Se(t,"--output")||process.cwd(),A=P?b.resolve(j,P):void 0,h=P&&A?await Mr(t,A,P).catch(async y=>{throw await O__default.remove(A).catch(()=>{}),y}):p;if(h)try{if(P&&A){let y=b.join(h,".python-version"),f$1=b.join(A,".python-version");if(E.existsSync(y)&&E.existsSync(A)){let k=E.readFileSync(y,"utf-8");E.writeFileSync(f$1,k.trim()+`
258
+ `),f.debug(`Synced Python version ${k.trim()} from workspace to ${P}`);}}}catch(y){f.debug("Could not sync Python version from workspace:",y);}}return g}catch(g){let P=Hn(g);return P?await Ir(t,P):(process.stderr.write(`Workspai failed to run the Python core engine: ${g?.message??g}
259
+ `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$8();let n=await e(t,{cwd:process.cwd()});if(n===0){let a=le(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-PJPRBUMQ.js');await i(a,true);}}return n}catch(n){let a=Hn(n);return a?await Ir(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
260
260
  `),1)}return await d$8(),await e(t,{cwd:process.cwd()})}catch(n){let a=Hn(n);return a?await Ir(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
261
- `),1)}}var bc=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],Id=[...e$4,"autopilot","pipeline","import","adopt","snapshot","ai","config","product","infra","shell","commands"],$d=["init"],Od=q$2,jc=[...Od,...r$1];function Nd(t){return !!t&&hd.includes(t)}function os(t){let e=t[0],o=t[1];return e==="project"&&(o==="--help"||o==="-h"||o==="help")?true:fd.some(([r,n])=>e!==r?false:o?o===n:true)}function Co(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?os(t):Nd(t[0])||os(t)}function Md(t){return !!t&&Id.includes(t)}function Cc(t){return Md(t[0])||os(t)}function Sc(t){return !!t&&Dn.includes(t)}async function xc(t,e){switch(t){case "bootstrap":return tu(e);case "setup":return ou(e);case "cache":return nu(e);case "mirror":return au(e);default:{let o=t;throw new Error(`Unreachable npm-only manual command: ${String(o)}`)}}}function Td(t=process.env){let e=t.npm_config_user_agent||"",o=t.npm_execpath||"",r=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(o)||r==="exec"||r==="x"}function Tc(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 Wd(){return {schemaVersion:Qi,cli:"workspai",version:c(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:Ln,contracts:wo(),contractCatalog:jr()}}function Dd(){let t=Ui(ce),e=[...t.topLevelCommands],o=[...a$9].filter(i=>!e.includes(i)),r=["init","dev","start","build","test","lint","format","help"],n=[...yo],a=[...kr];return {schemaVersion:Ln,scope:"global",cli:"workspai",version:c(),cwd:process.cwd(),contracts:wo(),contractCatalog:jr(),commands:{npmOwned:e,coreBacked:o,projectScoped:r},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...o.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...r.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function Ld(t={}){let e=Dd();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(Bi(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 rs(t){return y(t)?(Tc({json:t.includes("--json")||t.includes("--ci")}),true):false}function ns(t){let e=w(process.cwd());if(!e.projectRoot)return false;let o=x$1(t,process.cwd());if(!o||o.status!=="unsupported")return false;console.error(s.red(z(o,e))),process.exit(1);}function qe(t){return x.existsSync(b.join(t,".workspai-workspace"))||x.existsSync(b.join(t,".workspai","workspace.json"))||x.existsSync(b.join(t,".rapidkit-workspace"))||x.existsSync(b.join(t,".rapidkit","workspace.json"))}function Wc(t){let e=t;for(;;){let o=p(e,"context.json").find(n=>x.existsSync(n));if(o)return o;let r=b.dirname(e);if(r===e)break;e=r;}return null}function ss(t){let e=t,o=b.resolve(tmpdir());for(;;){let r=[b.join(e,".workspai-workspace"),b.join(e,".rapidkit-workspace")].find(a=>x.existsSync(a));if(r&&b.resolve(e)!==o)return r;let n=b.dirname(e);if(n===e)break;e=n;}return null}function le(t){let e=t,o=b.resolve(tmpdir());for(;;){if((x.existsSync(b.join(e,".workspai-workspace"))||x.existsSync(b.join(e,".workspai","workspace.json"))||x.existsSync(b.join(e,".rapidkit-workspace"))||x.existsSync(b.join(e,".rapidkit","workspace.json")))&&b.resolve(e)!==o)return e;let n=b.dirname(e);if(n===e)break;e=n;}return null}async function ds(t,e){try{let{syncWorkspaceContract:o}=await import('./workspace-contract-RPQQBQXR.js'),r=await o({workspacePath:t});if(!e?.silent&&(r.addedProjects.length>0||r.updatedProjects.length>0)&&console.log(s.gray(`\u2139\uFE0F Workspace contract synced (${r.contract.projects.length} project(s)).`)),!e?.silent&&r.verification.status!=="passed"){console.log(s.yellow("\u26A0\uFE0F Workspace contract verification failed after project sync."));for(let n of r.verification.violations)console.log(s.gray(` Violation: ${n}`));console.log(s.white(" Next: npx workspai workspace contract inspect"));}}catch(o){e?.silent||console.log(s.yellow(`\u26A0\uFE0F Workspace contract sync skipped: ${o.message}`));}}async function Fd(t,e=process.cwd(),o$1=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$1(o$1))return {detected:false};let n=o(e,o$1);for(let a of n){if(!await I__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 Jd(t){let e=t;for(;;){let o=b.join(e,".rapidkit-workspace"),r=b.join(e,".rapidkit","workspace.json");if(!x.existsSync(o)&&x.existsSync(r))return e;let n=b.dirname(e);if(n===e)break;e=n;}return null}var Dc={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function Kd(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function jo(t,e){let o=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return o?o[1]==="true":Dc[e]}function Ec(t){let e=t??"";return {mode:Kd(e),dependency_sharing_mode:Lc(e),rules:{enforce_workspace_marker:jo(e,"enforce_workspace_marker"),enforce_toolchain_lock:jo(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:jo(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:jo(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:jo(e,"require_mirror_lock_for_offline")}}}function Rc(t,e,o){let r=`${e}: ${o}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,r);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${r}
261
+ `),1)}}var Sc=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],Md=[...e$4,"autopilot","pipeline","import","adopt","snapshot","ai","config","product","infra","shell","commands"],Td=["init"],Wd=q$2,xc=[...Wd,...r$1];function Dd(t){return !!t&&vd.includes(t)}function os(t){let e=t[0],o=t[1];return e==="project"&&(o==="--help"||o==="-h"||o==="help")?true:kd.some(([r,n])=>e!==r?false:o?o===n:true)}function Co(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?os(t):Dd(t[0])||os(t)}function Ld(t){return !!t&&Md.includes(t)}function Ec(t){return Ld(t[0])||os(t)}function Rc(t){return !!t&&Dn.includes(t)}async function Ac(t,e){switch(t){case "bootstrap":return su(e);case "setup":return au(e);case "cache":return cu(e);case "mirror":return pu(e);default:{let o=t;throw new Error(`Unreachable npm-only manual command: ${String(o)}`)}}}function Fd(t=process.env){let e=t.npm_config_user_agent||"",o=t.npm_execpath||"",r=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(o)||r==="exec"||r==="x"}function Lc(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 Jd(){return {schemaVersion:ec,cli:"workspai",version:c(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:Ln,contracts:wo(),contractCatalog:jr()}}function Kd(){let t=qi(ce),e=[...t.topLevelCommands],o=[...a$9].filter(i=>!e.includes(i)),r=["init","dev","start","build","test","lint","format","help"],n=[...yo],a=[...kr];return {schemaVersion:Ln,scope:"global",cli:"workspai",version:c(),cwd:process.cwd(),contracts:wo(),contractCatalog:jr(),commands:{npmOwned:e,coreBacked:o,projectScoped:r},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...o.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...r.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function Vd(t={}){let e=Kd();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(zi(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 rs(t){return y(t)?(Lc({json:t.includes("--json")||t.includes("--ci")}),true):false}function ns(t){let e=w(process.cwd());if(!e.projectRoot)return false;let o=x(t,process.cwd());if(!o||o.status!=="unsupported")return false;console.error(s.red(z(o,e))),process.exit(1);}function qe(t){return E.existsSync(b.join(t,".workspai-workspace"))||E.existsSync(b.join(t,".workspai","workspace.json"))||E.existsSync(b.join(t,".rapidkit-workspace"))||E.existsSync(b.join(t,".rapidkit","workspace.json"))}function Fc(t){let e=t;for(;;){let o=p(e,"context.json").find(n=>E.existsSync(n));if(o)return o;let r=b.dirname(e);if(r===e)break;e=r;}return null}function ss(t){let e=t,o=b.resolve(tmpdir());for(;;){let r=[b.join(e,".workspai-workspace"),b.join(e,".rapidkit-workspace")].find(a=>E.existsSync(a));if(r&&b.resolve(e)!==o)return r;let n=b.dirname(e);if(n===e)break;e=n;}return null}function le(t){let e=t,o=b.resolve(tmpdir());for(;;){if((E.existsSync(b.join(e,".workspai-workspace"))||E.existsSync(b.join(e,".workspai","workspace.json"))||E.existsSync(b.join(e,".rapidkit-workspace"))||E.existsSync(b.join(e,".rapidkit","workspace.json")))&&b.resolve(e)!==o)return e;let n=b.dirname(e);if(n===e)break;e=n;}return null}async function ds(t,e){try{let{syncWorkspaceContract:o}=await import('./workspace-contract-TU2I7GC2.js'),r=await o({workspacePath:t});if(!e?.silent&&(r.addedProjects.length>0||r.updatedProjects.length>0)&&console.log(s.gray(`\u2139\uFE0F Workspace contract synced (${r.contract.projects.length} project(s)).`)),!e?.silent&&r.verification.status!=="passed"){console.log(s.yellow("\u26A0\uFE0F Workspace contract verification failed after project sync."));for(let n of r.verification.violations)console.log(s.gray(` Violation: ${n}`));console.log(s.white(" Next: npx workspai workspace contract inspect"));}}catch(o){e?.silent||console.log(s.yellow(`\u26A0\uFE0F Workspace contract sync skipped: ${o.message}`));}}async function Gd(t,e=process.cwd(),o$1=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$1(o$1))return {detected:false};let n=o(e,o$1);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 Ud(t){let e=t;for(;;){let o=b.join(e,".rapidkit-workspace"),r=b.join(e,".rapidkit","workspace.json");if(!E.existsSync(o)&&E.existsSync(r))return e;let n=b.dirname(e);if(n===e)break;e=n;}return null}var Jc={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function Bd(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function jo(t,e){let o=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return o?o[1]==="true":Jc[e]}function _c(t){let e=t??"";return {mode:Bd(e),dependency_sharing_mode:Kc(e),rules:{enforce_workspace_marker:jo(e,"enforce_workspace_marker"),enforce_toolchain_lock:jo(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:jo(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:jo(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:jo(e,"require_mirror_lock_for_offline")}}}function Ic(t,e,o){let r=`${e}: ${o}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,r);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${r}
262
262
  rules:`):`${t.endsWith(`
263
263
  `)?t:`${t}
264
264
  `}${r}
265
- `}function Vd(t,e,o){let r=` ${e}: ${o?"true":"false"}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]+${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,r);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`rules:
265
+ `}function Hd(t,e,o){let r=` ${e}: ${o?"true":"false"}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]+${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,r);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`rules:
266
266
  ${r}`):`${t.endsWith(`
267
267
  `)?t:`${t}
268
268
  `}rules:
269
269
  ${r}
270
- `}function Gd(){return ['version: "1.0"','mode: warn # "warn" or "strict"','dependency_sharing_mode: isolated # "isolated" or "shared-runtime-caches" or "shared-node-deps"',"# change profile (recommended): npx workspai bootstrap --profile polyglot","# change mode/dependency manually: edit this file and rerun npx workspai init","rules:"," enforce_workspace_marker: true"," enforce_toolchain_lock: false"," disallow_untrusted_tool_sources: false"," enforce_compatibility_matrix: false"," require_mirror_lock_for_offline: true",""].join(`
271
- `)}async function Ac(t){for(let e of o$1(t,"policies.yml"))if(await I__default.pathExists(e))return x.promises.readFile(e,"utf-8");return Gd()}async function Ud(t,e){let o=l(t,"policies.yml");await I__default.ensureDir(b.dirname(o));let r=e.endsWith(`
270
+ `}function qd(){return ['version: "1.0"','mode: warn # "warn" or "strict"','dependency_sharing_mode: isolated # "isolated" or "shared-runtime-caches" or "shared-node-deps"',"# change profile (recommended): npx workspai bootstrap --profile polyglot","# change mode/dependency manually: edit this file and rerun npx workspai init","rules:"," enforce_workspace_marker: true"," enforce_toolchain_lock: false"," disallow_untrusted_tool_sources: false"," enforce_compatibility_matrix: false"," require_mirror_lock_for_offline: true",""].join(`
271
+ `)}async function $c(t){for(let e of o$1(t,"policies.yml"))if(await O__default.pathExists(e))return E.promises.readFile(e,"utf-8");return qd()}async function zd(t,e){let o=l(t,"policies.yml");await O__default.ensureDir(b.dirname(o));let r=e.endsWith(`
272
272
  `)?e:`${e}
273
- `;await x.promises.writeFile(o,r,"utf-8");}function Bd(t){let e=t.trim().toLowerCase();return e==="true"||e==="1"||e==="on"?true:e==="false"||e==="0"||e==="off"?false:null}function Lc(t){if(!t)return "isolated";let o=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated"?o:"isolated"}function Fc(t){if(!t)return {mode:"isolated",status:"skipped",message:"No policies.yml found; dependency_sharing_mode defaults to isolated."};let e=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m);if(!e)return {mode:"isolated",status:"skipped",message:"dependency_sharing_mode is not set; defaulting to isolated."};let o=e[1].toLowerCase();return o==="isolated"||o==="shared-runtime-caches"||o==="shared-node-deps"?{mode:o,status:"passed",message:`dependency_sharing_mode is valid: ${o}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${o}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function Jc(t,e){let o=le(t),r=o?o$1(o,"policies.yml").find(c=>x.existsSync(c)):null,n="isolated";if(r&&await I__default.pathExists(r))try{let c=await x.promises.readFile(r,"utf-8"),l=Fc(c);if(l.status==="failed")return console.log(s.red(`\u274C ${l.message}`)),{ok:false,code:1};n=l.mode;}catch{return console.log(s.red("\u274C Failed to read workspace policy file (.workspai/policies.yml).")),{ok:false,code:1}}let a=process.env.RAPIDKIT_DEP_SHARING_MODE,i=process.env.RAPIDKIT_WORKSPACE_PATH;process.env.RAPIDKIT_DEP_SHARING_MODE=n,o&&(process.env.RAPIDKIT_WORKSPACE_PATH=o);try{return {ok:true,value:await e()}}finally{typeof a>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=a,typeof i>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=i;}}async function se(t,e,o,r={}){let{buildPackageRunnerSubprocessEnv:n,resolvePackageRunnerInvocation:a}=await import('./platform-capabilities-2B4QMZXE.js'),i=Hd(t,e,o),c=i?{command:process.execPath,prefixArgs:["-e",i]}:a(t),l=c.command,p=i?c.prefixArgs:[...c.prefixArgs,...e],m=n();if(i){Qt()&&process.stderr.write(`[workspai-cli] runCommandInCwd.nodeEval=${JSON.stringify({cwd:o,scriptBytes:i.length})}
274
- `);try{return gd.runInThisContext(i,{filename:b.join(o,"package.json#script")}),0}catch(A){return process.stderr.write(`${A instanceof Error?A.stack||A.message:String(A)}
275
- `),1}}let h=!(process.argv.includes("--json")||process.env.RAPIDKIT_WORKSPACE_RUN_CHILD==="1"||process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT==="1")&&t==="npm"&&(e[0]==="run"||e[0]==="run-script"||e[0]==="install"),g=()=>{let A=m.npm_config_cache;if(!A)return "";let w=b.join(A,"_logs");try{let f=x.readdirSync(w).filter(u=>u.endsWith(".log")).map(u=>{let j=b.join(w,u);return {filePath:j,mtimeMs:x.statSync(j).mtimeMs}}).sort((u,j)=>j.mtimeMs-u.mtimeMs)[0]?.filePath;return f?x.readFileSync(f,"utf-8").split(/\r?\n/).map(u=>u.trim()).filter(u=>/(?:^|\s)(?:npm\s+)?(?:error|verbose\s+(?:stack|cwd|os|node|npm|exit|code))\b/i.test(u)).slice(0,12).join(`
276
- `):""}catch{return ""}},k=Number.parseInt(process.env.RAPIDKIT_CHILD_COMMAND_TIMEOUT_MS||"",10),C=r.timeoutMs&&r.timeoutMs>0?r.timeoutMs:Number.isFinite(k)&&k>0?k:void 0;return await new Promise(A=>{let w=[],y=[],f=false,v=null,u=null,j=()=>{try{u?.stdout?.destroy();}catch{}try{u?.stderr?.destroy();}catch{}try{u?.stdin?.destroy();}catch{}try{u?.removeAllListeners("close"),u?.removeAllListeners("error"),u?.unref();}catch{}};Qt()&&process.stderr.write(`[workspai-cli] runCommandInCwd=${JSON.stringify({executable:l,args:p,cwd:o,directNodeEvalScript:i!==null,npmEnv:Object.fromEntries(Object.entries(m).filter(([E])=>["npm_config_if_present","npm_config_ignore_scripts","npm_config_loglevel","npm_config_silent","npm_config_json","npm_lifecycle_event","npm_lifecycle_script"].includes(E)))})}
277
- `);let P=b$1()&&/\.(?:cmd|bat)$/i.test(l);u=spawn(l,p,{stdio:h?"inherit":["ignore","pipe","pipe"],cwd:o,shell:P,env:m,detached:!b$1()}),C&&C>0&&(v=setTimeout(()=>{if(!f){if(f=true,!b$1()&&u.pid)try{process.kill(-u.pid,"SIGTERM");}catch{u.kill("SIGTERM");}else u.kill("SIGTERM");j(),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`RapidKit command timed out after ${C}ms: ${l} ${p.join(" ")}
278
- `),A(124);}},C)),h||(u.stdout?.on("data",E=>{w.push(E);}),u.stderr?.on("data",E=>{y.push(E);})),u.on("close",E=>{if(f)return;f=true,v&&clearTimeout(v);let S=Buffer.concat(w),$=Buffer.concat(y),L=E&&E!==0&&S.length===0&&$.length===0&&t==="npm"?g():"";Qt()&&process.stderr.write(`[workspai-cli] runCommandInCwd.close=${JSON.stringify({code:E,stdoutBytes:S.length,stderrBytes:$.length,npmFailureExcerptBytes:L.length})}
279
- `),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(S.length>0&&process.stdout.write(S),$.length>0?process.stderr.write($):L&&process.stderr.write(`${L}
280
- `)),A(E??1);}),u.on("error",()=>{f||(f=true,v&&clearTimeout(v),A(1));});})}function Hd(t,e,o){if(t!=="npm")return null;let r=e[0];if(r!=="run"&&r!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=b.join(o,"package.json");if(!x.existsSync(a))return null;try{let c=JSON.parse(x.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:qd(c)}catch{return null}}function qd(t){let e=t.trim(),o=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(o)return o[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let r=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return r?r[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function Nr(t,e){await I__default.outputFile(t,`${JSON.stringify(e,null,2)}
281
- `,"utf-8");}function zd(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function Yd(t,e,o){let r=_r(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":b.basename(e),n=zd(o||r)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=b.join(t,i);if(!await I__default.pathExists(c))return c;a+=1;}}async function Qd(t,e,o){let r=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?b.resolve(e.workspace):null,a=n??le(process.cwd()),i=false,c=false,l=false;if(n){if(!qe(n)){let d=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:d},null,2)):console.log(s.red(`\u274C ${d}`)),1}}else (!a||!qe(a))&&(a=k(),i=true,l=true);if(!a||!qe(a)&&!l){let d="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:d},null,2)):(console.log(s.red(`\u274C ${d}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let p=`cd ${a}`,m;try{let d=await Yd(a,t,e.name);if(m=await Or(a,{ownedDestination:d,ownedWorkspace:l?a:void 0}),l){let g=await us({silent:e.json});a=g.workspacePath,c=g.created;}let h=await gc({workspacePath:a,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0});h.path!==d&&m.registerCompensation(()=>I__default.remove(h.path));try{if(o?.syncWorkspaceProjects)await o.syncWorkspaceProjects(a);else {if(r)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:g,registerWorkspaceStrict:k}=await import('./workspace-H3QXBFGB.js'),{syncWorkspaceContract:C}=await import('./workspace-contract-RPQQBQXR.js');await k(a,b.basename(a)),await g(a,h.name,h.path),await C({workspacePath:a,strict:true});}await m.commit();}catch(g){try{await Xt(m,g);}catch(k){if(k!==g)throw k}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${g instanceof Error?g.message:String(g)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:a,workspaceResolution:i?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:i?c:false,suggestedCdCommand:p,importedProject:h},null,2)),0;if(i&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${a}`)),console.log(s.green(`\u2714 Imported project: ${h.name}`)),console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Destination: ${h.path}`)),console.log(s.gray(` Stack: ${h.stack} (${h.confidence})`)),console.log(s.gray(` Source: ${e.git===true||_r(t)?"git-url":"local-folder"}`)),!h.profileCompatibility.ok){let g=Ar(h.profileCompatibility);console.log(s.yellow(` Profile warning: ${h.profileCompatibility.message}`)),g&&console.log(s.gray(` ${g}`));}return console.log(s.gray(` Next shell step: ${p}`)),0}catch(d){if(m)try{await Xt(m,d);}catch(g){g!==d&&(d=g);}let h=d instanceof Error?d.message:String(d);return e.json?console.log(JSON.stringify({error:h},null,2)):console.log(s.red(`\u274C Import failed: ${h}`)),1}}async function Xd(t,e,o){let r=b.resolve(t||process.cwd()),n=e.workspace?b.resolve(e.workspace):null,a=n??le(process.cwd()),i=false,c=false,l=false;if(n){if(!qe(n)){let h=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:h},null,2)):console.log(s.red(`\u274C ${h}`)),1}}else (!a||!qe(a))&&(a=k(),i=true,l=e.dryRun!==true);let p=i&&a!==null&&(e.dryRun===true||l);if(!a||!qe(a)&&!p){let h="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:h},null,2)):(console.log(s.red(`\u274C ${h}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let m=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),d;try{if(e.dryRun!==true&&(d=await Or(a,{projectPath:r,ownedWorkspace:l?a:void 0}),l)){let k=await us({silent:e.json});a=k.workspacePath,c=k.created;}let h=await Un(a,r),g=await Bn({workspacePath:a,source:r,name:e.name,dryRun:e.dryRun===true,rollbackSnapshot:h});if(e.dryRun!==true)try{if(o?.registerWorkspace||o?.registerProjectInWorkspace||o?.syncWorkspaceProjects)o.registerWorkspace&&await o.registerWorkspace(a,b.basename(a)),o.registerProjectInWorkspace&&await o.registerProjectInWorkspace(a,g.name,g.path),o.syncWorkspaceProjects&&await o.syncWorkspaceProjects(a);else {let{registerProjectInWorkspaceStrict:k,registerWorkspaceStrict:C}=await import('./workspace-H3QXBFGB.js'),{syncWorkspaceContract:A}=await import('./workspace-contract-RPQQBQXR.js');if(await C(a,b.basename(a)),await k(a,g.name,g.path),m)throw new Error("forced sync failure for command-level adopt rollback test");await A({workspacePath:a,strict:true});}await d?.commit();}catch(k){if(d)try{await Xt(d,k);}catch(C){if(C!==k)throw C}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${k instanceof Error?k.message:String(k)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:a,workspaceResolution:i?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:i?c:false,wouldCreateDefaultWorkspace:i&&e.dryRun===true?!qe(a):false,dryRun:e.dryRun===true,adoptedProject:g},null,2)),0;if(i&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${a}`)),e.dryRun===true&&console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.green(`\u2714 Adopted project: ${g.name}`)),console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Project: ${g.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${g.stack} (${g.confidence})`)),!g.profileCompatibility.ok){let k=Ar(g.profileCompatibility);console.log(s.yellow(` Profile warning: ${g.profileCompatibility.message}`)),k&&console.log(s.gray(` ${k}`));}return console.log(s.gray(` Report: ${g.adoptReadinessPath}`)),console.log(s.gray(" Next: npx workspai workspace model --json")),0}catch(h){if(d)try{await Xt(d,h);}catch(k){k!==h&&(h=k);}let g=h instanceof Error?h.message:String(h);return e.json?console.log(JSON.stringify({error:g},null,2)):console.log(s.red(`\u274C Adopt failed: ${g}`)),1}}async function as(t){let e=new Set(["python-only","polyglot","enterprise"]),o=Zd(),r="minimal",n=false;try{let l$1=o$1(t,"workspace.json").find(m=>x.existsSync(m))??l(t,"workspace.json"),p=JSON.parse(await x.promises.readFile(l$1,"utf-8"));r=p.profile??"minimal",n=p.bootstrap_note==="python-engine-skipped"||p.engine?.python_core?.status==="skipped";}catch{r="minimal";}if(!await(async()=>{if(!n&&e.has(r))return true;let l=await is(t);if(l.length===0)return false;for(let p of l){let m$1=i$2(p),d=m$1?.module_support,h=p$1(p);if(n){if(h?.moduleSupport===true)return true;continue}if(!(j(m$1,p)||l$1(m$1,p)||m(m$1,p))&&d!==false)return n$1(m$1,p)||k$1(m$1,p),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:l}=await import('./workspace-marker-SMBC3Z2Q.js'),m=(await l(t))?.metadata?.npm?.installMethod;(m==="poetry"||m==="venv"||m==="pipx"||m==="pip")&&(i=m);}catch{}let c=async()=>{let l=vd(t);if(!await I__default.pathExists(l)){let h=await bd(t);if(h!==0)return h}let p=a$f("DEV_PATH"),d=(p?await I__default.pathExists(p):false)&&p?["-m","pip","install",p,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await se(l,d,t,{timeoutMs:o})};if(i==="venv"){let l=await c();if(l!==0)return l}else if(i==="poetry"){let l=b.join(t,"pyproject.toml"),p=false;try{p=(await x.promises.readFile(l,"utf-8")).includes("rapidkit-core");}catch{p=false;}if(p){let m=await c();if(m!==0)return m}else {let m=await se("poetry",["install","--no-root"],t,{timeoutMs:o});if(m!==0)return m;let d=await se("poetry",["add","rapidkit-core"],t,{timeoutMs:o});if(d!==0)return d}}else return 0;try{let{writeWorkspaceLauncher:l}=await import('./create-7JKJDAQV.js');await l(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:l}=await import('./workspace-python-engine-state-2MLKJYQG.js');await l(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function Zd(){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 is(t){let e=[],o=new Set,r=[t];for(;r.length>0;){let n=r.pop();if(!n||o.has(n))continue;o.add(n);let a=[];try{a=await x.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){if(!i.isDirectory()||i.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(i.name))continue;let c=b.join(n,i.name);if((await Promise.all([...p(c,"context.json"),...p(c,"project.json")].map(p=>I__default.pathExists(p)))).some(Boolean)){e.push(c);continue}r.push(c);}}return e}function eu(t){return j$2(t)}async function us(t={}){let e=k(),o=b.basename(e),r=qe(e);if(!r){let{createProject:n}=await import('./create-7JKJDAQV.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(o,{parentDirectory:b.dirname(e),profile:"polyglot",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b$2()});}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:!r}}async function Yn(t){let o=await Ze("go",{runCommandInCwd:se,runCoreRapidkit:e}).initProject(t);return ae(o)}function ae(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Et(t,e$1){let o=Ze("node",{runCommandInCwd:se,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return ae(n)}if(t==="dev"){let n=await o.runDev(e$1);return ae(n)}if(t==="test"){let n=await o.runTest(e$1);return ae(n)}if(t==="build"){let n=await o.runBuild(e$1);return ae(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return ae(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return ae(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return ae(r)}async function lt(t,e$1){let o=Ze("java",{runCommandInCwd:se,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return ae(n)}if(t==="dev"){let n=await o.runDev(e$1);return ae(n)}if(t==="test"){let n=await o.runTest(e$1);return ae(n)}if(t==="build"){let n=await o.runBuild(e$1);return ae(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return ae(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return ae(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return ae(r)}function Qn(t,e,o){let r=o.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$8(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:r,runId:e$5()})}async function tu(t,e=cs){if(t.includes("--help")||t.includes("-h")||t.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let o=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(O){if(!O)return null;let F=O.trim().toLowerCase();return F==="minimal"||F==="java-only"||F==="go-only"||F==="dotnet-only"||F==="python-only"||F==="node-only"||F==="polyglot"||F==="enterprise"?F:null},i=function(O){let Le=O.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",_e=(ue,Me)=>{let ze=O.match(new RegExp(`^\\s*${ue}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return ze?ze[1].toLowerCase()==="true":Me};return {mode:Le,dependency_sharing_mode:Lc(O),rules:{enforce_workspace_marker:_e("enforce_workspace_marker",true),enforce_toolchain_lock:_e("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:_e("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:_e("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:_e("require_mirror_lock_for_offline",true)}}};let c=["init"],l$2,p=false,m$1=false,d=false,h=false;for(let O=1;O<t.length;O+=1){let F=t[O];if(F==="--ci"){p=true;continue}if(F==="--offline"){m$1=true;continue}if(F==="--json"){d=true;continue}if(F==="--compliance-only"){h=true;continue}if(F==="--profile"){let te=t[O+1];if(!te||te.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;l$2=te,O+=1;continue}if(F.startsWith("--profile=")){l$2=F.slice(10);continue}c.push(F);}let g=a(l$2);if(l$2&&!g)return console.log(s.red(`Invalid profile: ${l$2}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let k=process.cwd(),C=c.slice(1).filter(O=>!O.startsWith("-"));if(C.length>0){let O=b.resolve(k,C[0]),F=i$2(O),te=x.existsSync(O)?await Rt(O):"unknown";if(!qe(O)&&(j(F,O)||l$1(F,O)||m(F,O)||k$1(F,O)||n$1(F,O)||te!=="unknown"))return await e(c)}let A=b.join(k,".rapidkit-workspace"),w=b.join(k,".rapidkit","workspace.json"),y;!x.existsSync(A)&&x.existsSync(w)?y=k:(y=le(k),y||(y=Jd(k)));let f=[],v=null,u=null;if(y)try{let O=o$1(y,"workspace.json").find(Le=>x.existsSync(Le))??l(y,"workspace.json"),F=await x.promises.readFile(O,"utf-8"),te=JSON.parse(F);u=a(te.profile);}catch{u=null;}let j$1=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],P={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},E=g;if(!!y&&!g&&!p&&!d&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let O=u||"minimal",{chosenProfile:F}=await b$4([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${O})`,choices:j$1.map(te=>({name:te===O?`${P[te]} \u2190 current`:P[te],value:te})),default:j$1.indexOf(O)}]);E=F;}let $=E||u||"minimal";if(y&&!h)try{let F=$==="python-only"||$==="polyglot"||$==="enterprise"?"poetry":"venv",te;try{let Me=(await x.promises.readFile(b.join(y,".python-version"),"utf-8")).trim();Me&&(te=Me);}catch{}let{syncWorkspaceFoundationFiles:Le}=await import('./create-7JKJDAQV.js'),_e=await Le(y,{workspaceName:b.basename(y),installMethod:F,pythonVersion:te,profile:$,writeMarker:true,writeGitignore:true,onlyIfMissing:true});f.push({id:"workspace.foundation.sync",status:_e.length>0?"passed":"skipped",message:_e.length>0?`Workspace foundation synchronized: ${_e.join(", ")}`:"Workspace foundation files are already up to date."});}catch(O){f.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${O.message}`});}else y&&f.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(y&&!h&&E&&E!==u)try{let O=l(y,"workspace.json"),F=await x.promises.readFile(O,"utf-8"),te=JSON.parse(F);te.profile=E,await I__default.ensureDir(b.dirname(O)),await x.promises.writeFile(O,JSON.stringify(te,null,2)+`
282
- `,"utf-8");}catch{}let L={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}},W=null;if(y)try{let O=o$1(y,"policies.yml").find(te=>x.existsSync(te));if(!O)throw new Error("policy file missing");let F=await x.promises.readFile(O,"utf-8");W=F,L=i(F);}catch{f.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else f.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(y){let O=Fc(W);L.dependency_sharing_mode=O.mode,f.push({id:"policy.schema.dependency_sharing_mode",status:O.status,message:O.message}),f.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:L.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":L.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 F=x.existsSync(b.join(y,".workspai-workspace"))||x.existsSync(b.join(y,".rapidkit-workspace"));f.push({id:"policy.enforce_workspace_marker",status:!L.rules.enforce_workspace_marker||F?"passed":"failed",message:!L.rules.enforce_workspace_marker||F?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let te=o$1(y,"toolchain.lock").some(ke=>x.existsSync(ke));f.push({id:"policy.enforce_toolchain_lock",status:!L.rules.enforce_toolchain_lock||te?"passed":"failed",message:!L.rules.enforce_toolchain_lock||te?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let Le=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||o$1(y,"trusted-sources.lock").some(ke=>x.existsSync(ke));f.push({id:"policy.disallow_untrusted_tool_sources",status:!L.rules.disallow_untrusted_tool_sources||Le?"passed":"failed",message:!L.rules.disallow_untrusted_tool_sources||Le?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let _e=o$1(y,"compatibility-matrix.json").find(ke=>x.existsSync(ke))??l(y,"compatibility-matrix.json"),ue=x.existsSync(_e),Me=L.rules.enforce_compatibility_matrix;if(f.push({id:"policy.enforce_compatibility_matrix",status:!Me||ue?"passed":"failed",message:!Me||ue?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),ue)try{let ke=await x.promises.readFile(_e,"utf-8"),at=JSON.parse(ke),fs=!!at&&typeof at=="object";f.push({id:"compatibility.matrix.parse",status:fs?"passed":"failed",message:fs?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{f.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let ze=o$1(y,"mirror-config.json").find(ke=>x.existsSync(ke))??l(y,"mirror-config.json"),eo=o$1(y,"mirror.lock").find(ke=>x.existsSync(ke))??l(y,"mirror.lock"),Wr=x.existsSync(ze),Dr=x.existsSync(eo),gs={};if(Wr)try{gs=JSON.parse(await x.promises.readFile(ze,"utf-8")),f.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{f.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(h)f.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let ke=await Jn(y,{ciMode:p,offlineMode:m$1});f.push(...ke.checks.map(at=>({id:at.id,status:at.status,message:at.message}))),v=ke.details,ke.details.lockWritten&&(Dr=true);}if(m$1){let ke=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||gs.enabled===true;f.push({id:"offline.mirror.enabled",status:ke?"passed":"failed",message:ke?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let at=L.rules.require_mirror_lock_for_offline;f.push({id:"offline.mirror.lock",status:!at||Dr?"passed":"failed",message:!at||Dr?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else f.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let xo=St({profile:$,runtimes:await xt(y),mode:L.mode});xo.profile!=="enterprise"?f.push({id:xo.checkId,status:xo.status,message:xo.message}):(f.push({id:"profile.enterprise.ci",status:p?"passed":h?"skipped":"failed",message:p?"enterprise profile running with --ci.":h?"Enterprise runtime execution skipped by --compliance-only; --ci is not required.":"enterprise profile expects --ci for deterministic non-interactive mode."}),f.push({id:"profile.enterprise.compatibility-matrix",status:ue?"passed":"failed",message:ue?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),f.push({id:"profile.enterprise.mirror-config",status:Wr?"passed":"failed",message:Wr?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}p&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),m$1&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let R=f.some(O=>O.id.startsWith("policy.schema.")&&O.status==="failed")||L.mode==="strict"&&f.some(O=>O.status==="failed"),G=l(y||k,"reports"),D=new Date().toISOString().replace(/[:.]/g,"-"),q=b.join(G,`bootstrap-compliance-${D}.json`),ee=b.join(G,"bootstrap-compliance.latest.json"),Re={schemaVersion:"bootstrap-compliance.v1",command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:y,profile:$,options:{ci:p,offline:m$1,strict:L.mode==="strict",complianceOnly:h},policyMode:L.mode,policyRules:L.rules,mirrorLifecycle:v,checks:f},de=async O=>{b$i(`.workspai/reports/${b.basename(q)}`,O),b$i(".workspai/reports/bootstrap-compliance.latest.json",O),await I__default.ensureDir(G),await Nr(q,O),await Nr(ee,O);};if(R){let O=Qn({...Re,result:"blocked",initExitCode:null},1,f);return await de(O),d?process.stdout.write(`${JSON.stringify(O,null,2)}
283
- `):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${q}`))),1}if(d&&$==="enterprise"&&!p&&!h){let O=Qn({...Re,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,f);return await de(O),process.stdout.write(`${JSON.stringify(O,null,2)}
284
- `),1}let Ae=async O=>{let F=process.stdout.write.bind(process.stdout),te=process.stderr.write.bind(process.stderr),Le=[],_e=[];process.stdout.write=((ue,Me,ze)=>{let eo=typeof Me=="function"?Me:typeof ze=="function"?ze:void 0;return Le.push(typeof ue=="string"?ue:ue instanceof Uint8Array?Buffer.from(ue).toString("utf8"):String(ue)),eo?.(),true}),process.stderr.write=((ue,Me,ze)=>{let eo=typeof Me=="function"?Me:typeof ze=="function"?ze:void 0;return _e.push(typeof ue=="string"?ue:ue instanceof Uint8Array?Buffer.from(ue).toString("utf8"):String(ue)),eo?.(),true});try{return {exitCode:await O(),stdout:Le.join(""),stderr:_e.join("")}}finally{process.stdout.write=F,process.stderr.write=te;}},Oe=O=>{let F=O.split(/\r?\n/).map(te=>te.trim()).filter(Boolean);return {bytes:Buffer.byteLength(O),excerpt:F.slice(0,12)}},Ne=0,oe;if(!h)if(d){let O=await Ae(()=>e(c));Ne=O.exitCode,oe={captured:true,stdout:Oe(O.stdout),stderr:Oe(O.stderr)};}else Ne=await e(c);let ve=f.filter(O=>O.status==="failed").length,Zt=Ne!==0?"failed":ve>0?"ok_with_warnings":"ok",At=Ne!==0?Ne:ve>0?1:0,Pe=Qn({...Re,result:Zt,initExitCode:Ne,complianceOnly:h,...oe?{initOutput:oe}:{}},At,f);if(await de(Pe),y&&!h&&Ne===0)try{let{syncWorkspaceProjects:O}=await import('./workspace-H3QXBFGB.js');await O(y,d),await ds(y,{silent:d});}catch{}if(d)process.stdout.write(`${JSON.stringify(Pe,null,2)}
285
- `);else {let O=f.filter(F=>F.status==="failed").length;O>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${O} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${q}`));}return At}finally{typeof o>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=o;}}async function ou(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]")),0;let e$1=(t[1]||"").toLowerCase(),o=t.includes("--json"),r=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!e$1||!["python","node","go","java","dotnet"].includes(e$1))return o?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]"},null,2)}
286
- `):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]")),1;let n=async(h,g)=>{if(h==="node"){if(!x.existsSync(b.join(g,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let C=x.existsSync(b.join(g,"pnpm-lock.yaml")),A=x.existsSync(b.join(g,"yarn.lock"));return C?{exitCode:await se("pnpm",["install","--lockfile-only","--ignore-scripts"],g)}:A?{exitCode:await se("yarn",["install","--ignore-scripts"],g)}:{exitCode:await se("npm",["install","--package-lock-only","--ignore-scripts"],g)}}if(h==="go")return x.existsSync(b.join(g,"go.mod"))?{exitCode:await se("go",["mod","download"],g)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(h==="java"){let k=x.existsSync(b.join(g,"pom.xml")),C=x.existsSync(b.join(g,"build.gradle"))||x.existsSync(b.join(g,"build.gradle.kts")),A=b.join(g,process.platform==="win32"?"gradlew.bat":"gradlew"),w=x.existsSync(A);return !k&&!C?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:k?{exitCode:await se("mvn",["-B","-q","-DskipTests","dependency:go-offline"],g)}:{exitCode:await se(w?A:"gradle",["--no-daemon","dependencies"],g)}}return h==="dotnet"?(()=>{let C=[{dir:g,depth:0}],A=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;C.length>0;){let w=C.shift();if(!w||w.depth>3)continue;let y=[];try{y=x.readdirSync(w.dir,{withFileTypes:true});}catch{continue}for(let f of y)if(f.isFile()){let v=f.name.toLowerCase();if(v.endsWith(".sln")||v.endsWith(".csproj"))return true}else f.isDirectory()&&!A.has(f.name)&&C.push({dir:b.join(w.dir,f.name),depth:w.depth+1});}return false})()?{exitCode:await se("dotnet",["restore"],g)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:{exitCode:0,message:"Dependency warm-up currently applies to node/go/java/dotnet runtimes."}};if(o){let h=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let k=await Ze(e$1,{runCommandInCwd:se,runCoreRapidkit:async(f,v)=>(await g$3(f,{...v,cwd:void 0})).exitCode}).checkPrereqs(),C=le(process.cwd()),A=C||process.cwd(),w=null;if(e$1==="node"&&k.exitCode===0&&(w=process.version),C&&w){let f=o$1(C,"toolchain.lock").find(j=>x.existsSync(j))??l(C,"toolchain.lock"),v=l(C,"toolchain.lock"),u={};try{u=JSON.parse(await x.promises.readFile(f,"utf-8"));}catch{}(!u.runtime||typeof u.runtime!="object")&&(u.runtime={}),u.runtime[e$1]={version:w,detectedAt:new Date().toISOString()},await I__default.ensureDir(b.dirname(v)),await x.promises.writeFile(v,JSON.stringify(u,null,2)+`
287
- `,"utf-8");}let y={requested:r,status:"not-requested",exitCode:null,targets:0,messages:[]};if(r&&k.exitCode===0){let f=[A];if(e$1==="java"&&C){let E=(await is(C)).filter(S=>{let $=i$2(S);return l$1($,S)});E.length>0&&(f=E);}let v=[];for(let P of f)v.push(await n(e$1,P));let u=v.filter(P=>P.exitCode!==0),j=v.filter(P=>P.exitCode===0&&!/skipped/i.test(P.message||""));y.status=u.length>0?"failed":j.length>0?"passed":"skipped",y.exitCode=u[0]?.exitCode??0,y.targets=f.length,y.messages=v.map(P=>P.message).filter(P=>typeof P=="string");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:e$1,result:k.exitCode===0?"ok":"failed",exitCode:k.exitCode,workspacePath:C,version:w,warmDeps:r,warmDependencies:y},null,2)}
288
- `),k.exitCode}finally{typeof h>"u"?delete process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT:process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT=h;}}let a=Ze(e$1,{runCommandInCwd:se,runCoreRapidkit:(h,g)=>e(h,{...g,cwd:void 0})}),i=await a.checkPrereqs(),c=await a.doctorHints(process.cwd()),l$2=le(process.cwd()),p=l$2||process.cwd(),m=null,d=async()=>e$1!=="java"||!l$2?[]:m||(m=(await is(l$2)).filter(g=>{let k=i$2(g);return l$1(k,g)}),m);if(i.exitCode===0){console.log(s.green(`\u2705 ${e$1} prerequisites look good.`));let h=["python","node","go","java","dotnet"].filter(g=>g!==e$1).join("/");if(console.log(s.gray(` Scope: validated ${e$1} runtime only. ${h} checks are optional unless your workspace profile uses them.`)),e$1==="python"&&console.log(s.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),a.warmSetupCache&&((await a.warmSetupCache(p)).exitCode===0?console.log(s.gray(` ${e$1} cache warm-up completed.`)):console.log(s.yellow(` ${e$1} cache warm-up skipped (non-fatal).`))),r)if(e$1==="java"&&l$2){let g=await d();if(g.length>0){let k=0,C=0,A=0;for(let w of g){let y=await n("java",w),f=/skipped/i.test(y.message||""),v=b.relative(l$2,w)||b.basename(w);y.message&&console.log(s.gray(` [${v}] ${y.message}`)),y.exitCode===0&&!f?k+=1:y.exitCode===0&&f?A+=1:C+=1;}k>0&&console.log(s.gray(` java dependency warm-up completed for ${k} project(s) (--warm-deps).`)),C>0&&console.log(s.yellow(` java dependency warm-up failed for ${C} project(s) (non-fatal).`)),k===0&&C===0&&A>0&&console.log(s.gray(" java dependency warm-up skipped for discovered workspace projects."));}else {let k=await n("java",p),C=/skipped/i.test(k.message||"");k.message&&console.log(s.gray(` ${k.message}`)),k.exitCode===0&&!C?console.log(s.gray(` ${e$1} dependency warm-up completed (--warm-deps).`)):k.exitCode!==0&&console.log(s.yellow(` ${e$1} dependency warm-up failed (non-fatal).`));}}else {let g=await n(e$1,p),k=/skipped/i.test(g.message||"");g.message&&console.log(s.gray(` ${g.message}`)),g.exitCode===0&&!k?console.log(s.gray(` ${e$1} dependency warm-up completed (--warm-deps).`)):g.exitCode!==0&&console.log(s.yellow(` ${e$1} dependency warm-up failed (non-fatal).`));}if(l$2)try{let g=o$1(l$2,"toolchain.lock").find(w=>x.existsSync(w))??l(l$2,"toolchain.lock"),k=l(l$2,"toolchain.lock"),C={};try{C=JSON.parse(await x.promises.readFile(g,"utf-8"));}catch{}(!C.runtime||typeof C.runtime!="object")&&(C.runtime={});let A=C.runtime;if(e$1==="python"){let w=null;try{let{execa:y}=await import('execa');for(let f of ps()){let u=await y(f,f==="py"?["-3","--version"]:["--version"],{cwd:l$2,stdio:"pipe",reject:false,timeout:3e3});if(u.exitCode===0){let P=(u.stdout||u.stderr||"").match(/Python\s+(\S+)/);if(w=P?P[1]:null,w)break}}}catch{}A.python={...A.python||{},version:w,last_setup:new Date().toISOString()};}else if(e$1==="node")A.node={...A.node||{},version:process.version,last_setup:new Date().toISOString()};else if(e$1==="go"){let w=null;try{let{execa:y}=await import('execa'),v=((await y("go",["version"],{cwd:l$2,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);w=v?v[1]:null;}catch{}A.go={...A.go||{},version:w,last_setup:new Date().toISOString()};}else if(e$1==="java"){let w=null,y=null,f=null,v=await d(),j=x.existsSync(b.join(p,"pom.xml"))||x.existsSync(b.join(p,"build.gradle"))||x.existsSync(b.join(p,"build.gradle.kts"))?p:v[0]||p;try{let{execa:P}=await import('execa'),E=await P("java",["-version"],{cwd:l$2,stdio:"pipe",reject:false,timeout:3e3}),$=`${E.stdout||""}
289
- ${E.stderr||""}`.match(/version\s+"([^"]+)"/i);w=$?$[1]:null;let L=x.existsSync(b.join(j,"pom.xml")),W=x.existsSync(b.join(j,"build.gradle"))||x.existsSync(b.join(j,"build.gradle.kts"));if(L){y="maven";let N=(()=>{let D=b.join(j,"mvnw.cmd");if(process.platform==="win32"&&x.existsSync(D))return D;let q=b.join(j,"mvnw");return x.existsSync(q)?q:"mvn"})(),R=await P(N,["-version"],{cwd:j,stdio:"pipe",reject:false,timeout:3e3}),G=`${R.stdout||""}
290
- ${R.stderr||""}`.match(/Apache Maven\s+(\S+)/i);f=G?G[1]:null;}else if(W){y="gradle";let N=(()=>{let D=b.join(j,"gradlew.bat");if(process.platform==="win32"&&x.existsSync(D))return D;let q=b.join(j,"gradlew");return x.existsSync(q)?q:"gradle"})(),R=await P(N,["--version"],{cwd:j,stdio:"pipe",reject:false,timeout:3e3}),G=`${R.stdout||""}
291
- ${R.stderr||""}`.match(/Gradle\s+(\S+)/i);f=G?G[1]:null;}}catch{}A.java={...A.java||{},version:w,build_tool:y,build_tool_version:f,last_setup:new Date().toISOString()};}else if(e$1==="dotnet"){let w=null;try{let{execa:y}=await import('execa'),v=((await y("dotnet",["--version"],{cwd:l$2,stdio:"pipe",reject:false,timeout:3e3})).stdout||"").trim();w=v.length>0?v:null;}catch{}A.dotnet={...A.dotnet||{},version:w,sdk:w,last_setup:new Date().toISOString()};}C.updated_at=new Date().toISOString(),await x.promises.writeFile(k,JSON.stringify(C,null,2)+`
273
+ `;await E.promises.writeFile(o,r,"utf-8");}function Yd(t){let e=t.trim().toLowerCase();return e==="true"||e==="1"||e==="on"?true:e==="false"||e==="0"||e==="off"?false:null}function Kc(t){if(!t)return "isolated";let o=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated"?o:"isolated"}function Vc(t){if(!t)return {mode:"isolated",status:"skipped",message:"No policies.yml found; dependency_sharing_mode defaults to isolated."};let e=t.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m);if(!e)return {mode:"isolated",status:"skipped",message:"dependency_sharing_mode is not set; defaulting to isolated."};let o=e[1].toLowerCase();return o==="isolated"||o==="shared-runtime-caches"||o==="shared-node-deps"?{mode:o,status:"passed",message:`dependency_sharing_mode is valid: ${o}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${o}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function Gc(t,e){let o=le(t),r=o?o$1(o,"policies.yml").find(c=>E.existsSync(c)):null,n="isolated";if(r&&await O__default.pathExists(r))try{let c=await E.promises.readFile(r,"utf-8"),l=Vc(c);if(l.status==="failed")return console.log(s.red(`\u274C ${l.message}`)),{ok:false,code:1};n=l.mode;}catch{return console.log(s.red("\u274C Failed to read workspace policy file (.workspai/policies.yml).")),{ok:false,code:1}}let a=process.env.RAPIDKIT_DEP_SHARING_MODE,i=process.env.RAPIDKIT_WORKSPACE_PATH;process.env.RAPIDKIT_DEP_SHARING_MODE=n,o&&(process.env.RAPIDKIT_WORKSPACE_PATH=o);try{return {ok:true,value:await e()}}finally{typeof a>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=a,typeof i>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=i;}}async function se(t,e,o,r={}){let{buildPackageRunnerSubprocessEnv:n,resolvePackageRunnerInvocation:a}=await import('./platform-capabilities-2B4QMZXE.js'),i=Qd(t,e,o),c=i?{command:process.execPath,prefixArgs:["-e",i]}:a(t),l=c.command,p=i?c.prefixArgs:[...c.prefixArgs,...e],m=n();if(i){Qt()&&process.stderr.write(`[workspai-cli] runCommandInCwd.nodeEval=${JSON.stringify({cwd:o,scriptBytes:i.length})}
274
+ `);try{return wd.runInThisContext(i,{filename:b.join(o,"package.json#script")}),0}catch(A){return process.stderr.write(`${A instanceof Error?A.stack||A.message:String(A)}
275
+ `),1}}let w=!(process.argv.includes("--json")||process.env.RAPIDKIT_WORKSPACE_RUN_CHILD==="1"||process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT==="1")&&t==="npm"&&(e[0]==="run"||e[0]==="run-script"||e[0]==="install"),g=()=>{let A=m.npm_config_cache;if(!A)return "";let h=b.join(A,"_logs");try{let f=E.readdirSync(h).filter(u=>u.endsWith(".log")).map(u=>{let C=b.join(h,u);return {filePath:C,mtimeMs:E.statSync(C).mtimeMs}}).sort((u,C)=>C.mtimeMs-u.mtimeMs)[0]?.filePath;return f?E.readFileSync(f,"utf-8").split(/\r?\n/).map(u=>u.trim()).filter(u=>/(?:^|\s)(?:npm\s+)?(?:error|verbose\s+(?:stack|cwd|os|node|npm|exit|code))\b/i.test(u)).slice(0,12).join(`
276
+ `):""}catch{return ""}},P=Number.parseInt(process.env.RAPIDKIT_CHILD_COMMAND_TIMEOUT_MS||"",10),j=r.timeoutMs&&r.timeoutMs>0?r.timeoutMs:Number.isFinite(P)&&P>0?P:void 0;return await new Promise(A=>{let h=[],y=[],f=false,k=null,u=null,C=()=>{try{u?.stdout?.destroy();}catch{}try{u?.stderr?.destroy();}catch{}try{u?.stdin?.destroy();}catch{}try{u?.removeAllListeners("close"),u?.removeAllListeners("error"),u?.unref();}catch{}};Qt()&&process.stderr.write(`[workspai-cli] runCommandInCwd=${JSON.stringify({executable:l,args:p,cwd:o,directNodeEvalScript:i!==null,npmEnv:Object.fromEntries(Object.entries(m).filter(([R])=>["npm_config_if_present","npm_config_ignore_scripts","npm_config_loglevel","npm_config_silent","npm_config_json","npm_lifecycle_event","npm_lifecycle_script"].includes(R)))})}
277
+ `);let x=b$1()&&/\.(?:cmd|bat)$/i.test(l);u=spawn(l,p,{stdio:w?"inherit":["ignore","pipe","pipe"],cwd:o,shell:x,env:m,detached:!b$1()}),j&&j>0&&(k=setTimeout(()=>{if(!f){if(f=true,!b$1()&&u.pid)try{process.kill(-u.pid,"SIGTERM");}catch{u.kill("SIGTERM");}else u.kill("SIGTERM");C(),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`RapidKit command timed out after ${j}ms: ${l} ${p.join(" ")}
278
+ `),A(124);}},j)),w||(u.stdout?.on("data",R=>{h.push(R);}),u.stderr?.on("data",R=>{y.push(R);})),u.on("close",R=>{if(f)return;f=true,k&&clearTimeout(k);let v=Buffer.concat(h),I=Buffer.concat(y),N=R&&R!==0&&v.length===0&&I.length===0&&t==="npm"?g():"";Qt()&&process.stderr.write(`[workspai-cli] runCommandInCwd.close=${JSON.stringify({code:R,stdoutBytes:v.length,stderrBytes:I.length,npmFailureExcerptBytes:N.length})}
279
+ `),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(v.length>0&&process.stdout.write(v),I.length>0?process.stderr.write(I):N&&process.stderr.write(`${N}
280
+ `)),A(R??1);}),u.on("error",()=>{f||(f=true,k&&clearTimeout(k),A(1));});})}function Qd(t,e,o){if(t!=="npm")return null;let r=e[0];if(r!=="run"&&r!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=b.join(o,"package.json");if(!E.existsSync(a))return null;try{let c=JSON.parse(E.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:Xd(c)}catch{return null}}function Xd(t){let e=t.trim(),o=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(o)return o[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let r=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return r?r[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function Nr(t,e){await O__default.outputFile(t,`${JSON.stringify(e,null,2)}
281
+ `,"utf-8");}function Zd(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function eu(t,e,o){let r=_r(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":b.basename(e),n=Zd(o||r)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=b.join(t,i);if(!await O__default.pathExists(c))return c;a+=1;}}async function tu(t,e,o){let r=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?b.resolve(e.workspace):null,a=n??le(process.cwd()),i=false,c=false,l=false;if(n){if(!qe(n)){let d=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:d},null,2)):console.log(s.red(`\u274C ${d}`)),1}}else (!a||!qe(a))&&(a=k(),i=true,l=true);if(!a||!qe(a)&&!l){let d="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:d},null,2)):(console.log(s.red(`\u274C ${d}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let p=`cd ${a}`,m;try{let d=await eu(a,t,e.name);if(m=await Or(a,{ownedDestination:d,ownedWorkspace:l?a:void 0}),l){let g=await us({silent:e.json});a=g.workspacePath,c=g.created;}let w=await yc({workspacePath:a,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0});w.path!==d&&m.registerCompensation(()=>O__default.remove(w.path));try{if(o?.syncWorkspaceProjects)await o.syncWorkspaceProjects(a);else {if(r)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:g,registerWorkspaceStrict:P}=await import('./workspace-PJPRBUMQ.js'),{syncWorkspaceContract:j}=await import('./workspace-contract-TU2I7GC2.js');await P(a,b.basename(a)),await g(a,w.name,w.path),await j({workspacePath:a,strict:true});}await m.commit();}catch(g){try{await Xt(m,g);}catch(P){if(P!==g)throw P}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${g instanceof Error?g.message:String(g)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:a,workspaceResolution:i?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:i?c:false,suggestedCdCommand:p,importedProject:w},null,2)),0;if(i&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${a}`)),console.log(s.green(`\u2714 Imported project: ${w.name}`)),console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Destination: ${w.path}`)),console.log(s.gray(` Stack: ${w.stack} (${w.confidence})`)),console.log(s.gray(` Source: ${e.git===true||_r(t)?"git-url":"local-folder"}`)),!w.profileCompatibility.ok){let g=Ar(w.profileCompatibility);console.log(s.yellow(` Profile warning: ${w.profileCompatibility.message}`)),g&&console.log(s.gray(` ${g}`));}return console.log(s.gray(` Next shell step: ${p}`)),0}catch(d){if(m)try{await Xt(m,d);}catch(g){g!==d&&(d=g);}let w=d instanceof Error?d.message:String(d);return e.json?console.log(JSON.stringify({error:w},null,2)):console.log(s.red(`\u274C Import failed: ${w}`)),1}}async function ou(t,e,o){let r=b.resolve(t||process.cwd()),n=e.workspace?b.resolve(e.workspace):null,a=n??le(process.cwd()),i=false,c=false,l=false;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 (!a||!qe(a))&&(a=k(),i=true,l=e.dryRun!==true);let p=i&&a!==null&&(e.dryRun===true||l);if(!a||!qe(a)&&!p){let w="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:w},null,2)):(console.log(s.red(`\u274C ${w}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let m=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),d;try{if(e.dryRun!==true&&(d=await Or(a,{projectPath:r,ownedWorkspace:l?a:void 0}),l)){let j=await us({silent:e.json});a=j.workspacePath,c=j.created;}let w=await Un(a,r),g=await Bn({workspacePath:a,source:r,name:e.name,dryRun:e.dryRun===true,rollbackSnapshot:w}),P=`cd ${a}`;if(e.dryRun!==true)try{if(o?.registerWorkspace||o?.registerProjectInWorkspace||o?.syncWorkspaceProjects)o.registerWorkspace&&await o.registerWorkspace(a,b.basename(a)),o.registerProjectInWorkspace&&await o.registerProjectInWorkspace(a,g.name,g.path),o.syncWorkspaceProjects&&await o.syncWorkspaceProjects(a);else {let{registerProjectInWorkspaceStrict:j,registerWorkspaceStrict:A}=await import('./workspace-PJPRBUMQ.js'),{syncWorkspaceContract:h}=await import('./workspace-contract-TU2I7GC2.js');if(await A(a,b.basename(a)),await j(a,g.name,g.path),m)throw new Error("forced sync failure for command-level adopt rollback test");await h({workspacePath:a,strict:true});}await d?.commit();}catch(j){if(d)try{await Xt(d,j);}catch(A){if(A!==j)throw A}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${j instanceof Error?j.message:String(j)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:a,workspaceResolution:i?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:i?c:false,wouldCreateDefaultWorkspace:i&&e.dryRun===true?!qe(a):false,suggestedCdCommand:P,dryRun:e.dryRun===true,adoptedProject:g},null,2)),0;if(i&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${a}`)),e.dryRun===true&&console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.green(`\u2714 Adopted project: ${g.name}`)),console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Project: ${g.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${g.stack} (${g.confidence})`)),!g.profileCompatibility.ok){let j=Ar(g.profileCompatibility);console.log(s.yellow(` Profile warning: ${g.profileCompatibility.message}`)),j&&console.log(s.gray(` ${j}`));}return console.log(s.gray(` Report: ${g.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(` Next shell step: ${P}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(w){if(d)try{await Xt(d,w);}catch(P){P!==w&&(w=P);}let g=w instanceof Error?w.message:String(w);return e.json?console.log(JSON.stringify({error:g},null,2)):console.log(s.red(`\u274C Adopt failed: ${g}`)),1}}async function as(t){let e=new Set(["python-only","polyglot","enterprise"]),o=ru(),r="minimal",n=false;try{let l$1=o$1(t,"workspace.json").find(m=>E.existsSync(m))??l(t,"workspace.json"),p=JSON.parse(await E.promises.readFile(l$1,"utf-8"));r=p.profile??"minimal",n=p.bootstrap_note==="python-engine-skipped"||p.engine?.python_core?.status==="skipped";}catch{r="minimal";}if(!await(async()=>{if(!n&&e.has(r))return true;let l=await is(t);if(l.length===0)return false;for(let p of l){let m$1=i$2(p),d=m$1?.module_support,w=p$1(p);if(n){if(w?.moduleSupport===true)return true;continue}if(!(j(m$1,p)||l$1(m$1,p)||m(m$1,p))&&d!==false)return n$1(m$1,p)||k$1(m$1,p),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:l}=await import('./workspace-marker-SMBC3Z2Q.js'),m=(await l(t))?.metadata?.npm?.installMethod;(m==="poetry"||m==="venv"||m==="pipx"||m==="pip")&&(i=m);}catch{}let c=async()=>{let l=Cd(t);if(!await O__default.pathExists(l)){let w=await xd(t);if(w!==0)return w}let p=a$f("DEV_PATH"),d=(p?await O__default.pathExists(p):false)&&p?["-m","pip","install",p,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await se(l,d,t,{timeoutMs:o})};if(i==="venv"){let l=await c();if(l!==0)return l}else if(i==="poetry"){let l=b.join(t,"pyproject.toml"),p=false;try{p=(await E.promises.readFile(l,"utf-8")).includes("rapidkit-core");}catch{p=false;}if(p){let m=await c();if(m!==0)return m}else {let m=await se("poetry",["install","--no-root"],t,{timeoutMs:o});if(m!==0)return m;let d=await se("poetry",["add","rapidkit-core"],t,{timeoutMs:o});if(d!==0)return d}}else return 0;try{let{writeWorkspaceLauncher:l}=await import('./create-S64IWHAP.js');await l(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:l}=await import('./workspace-python-engine-state-2MLKJYQG.js');await l(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function ru(){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 is(t){let e=[],o=new Set,r=[t];for(;r.length>0;){let n=r.pop();if(!n||o.has(n))continue;o.add(n);let a=[];try{a=await E.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){if(!i.isDirectory()||i.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(i.name))continue;let c=b.join(n,i.name);if((await Promise.all([...p(c,"context.json"),...p(c,"project.json")].map(p=>O__default.pathExists(p)))).some(Boolean)){e.push(c);continue}r.push(c);}}return e}function nu(t){return j$2(t)}async function us(t={}){let e=k(),o=b.basename(e),r=qe(e);if(!r){let{createProject:n}=await import('./create-S64IWHAP.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(o,{parentDirectory:b.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b$2()});}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:!r}}async function Yn(t){let o=await et("go",{runCommandInCwd:se,runCoreRapidkit:e}).initProject(t);return ae(o)}function ae(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Rt(t,e$1){let o=et("node",{runCommandInCwd:se,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return ae(n)}if(t==="dev"){let n=await o.runDev(e$1);return ae(n)}if(t==="test"){let n=await o.runTest(e$1);return ae(n)}if(t==="build"){let n=await o.runBuild(e$1);return ae(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return ae(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return ae(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return ae(r)}async function pt(t,e$1){let o=et("java",{runCommandInCwd:se,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return ae(n)}if(t==="dev"){let n=await o.runDev(e$1);return ae(n)}if(t==="test"){let n=await o.runTest(e$1);return ae(n)}if(t==="build"){let n=await o.runBuild(e$1);return ae(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return ae(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return ae(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return ae(r)}function Qn(t,e,o){let r=o.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$8(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:r,runId:e$5()})}async function su(t,e=cs){if(t.includes("--help")||t.includes("-h")||t.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let o=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(M){if(!M)return null;let F=M.trim().toLowerCase();return F==="minimal"||F==="java-only"||F==="go-only"||F==="dotnet-only"||F==="python-only"||F==="node-only"||F==="polyglot"||F==="enterprise"?F:null},i=function(M){let Le=M.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",_e=(ue,Te)=>{let ze=M.match(new RegExp(`^\\s*${ue}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return ze?ze[1].toLowerCase()==="true":Te};return {mode:Le,dependency_sharing_mode:Kc(M),rules:{enforce_workspace_marker:_e("enforce_workspace_marker",true),enforce_toolchain_lock:_e("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:_e("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:_e("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:_e("require_mirror_lock_for_offline",true)}}};let c=["init"],l$2,p=false,m$1=false,d=false,w=false;for(let M=1;M<t.length;M+=1){let F=t[M];if(F==="--ci"){p=true;continue}if(F==="--offline"){m$1=true;continue}if(F==="--json"){d=true;continue}if(F==="--compliance-only"){w=true;continue}if(F==="--profile"){let te=t[M+1];if(!te||te.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;l$2=te,M+=1;continue}if(F.startsWith("--profile=")){l$2=F.slice(10);continue}c.push(F);}let g=a(l$2);if(l$2&&!g)return console.log(s.red(`Invalid profile: ${l$2}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let P=process.cwd(),j$1=c.slice(1).filter(M=>!M.startsWith("-"));if(j$1.length>0){let M=b.resolve(P,j$1[0]),F=i$2(M),te=E.existsSync(M)?await At(M):"unknown";if(!qe(M)&&(j(F,M)||l$1(F,M)||m(F,M)||k$1(F,M)||n$1(F,M)||te!=="unknown"))return await e(c)}let A=b.join(P,".rapidkit-workspace"),h=b.join(P,".rapidkit","workspace.json"),y;!E.existsSync(A)&&E.existsSync(h)?y=P:(y=le(P),y||(y=Ud(P)));let f=[],k=null,u=null;if(y)try{let M=o$1(y,"workspace.json").find(Le=>E.existsSync(Le))??l(y,"workspace.json"),F=await E.promises.readFile(M,"utf-8"),te=JSON.parse(F);u=a(te.profile);}catch{u=null;}let C=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],x={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},R=g;if(!!y&&!g&&!p&&!d&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let M=u||"minimal",{chosenProfile:F}=await b$4([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${M})`,choices:C.map(te=>({name:te===M?`${x[te]} \u2190 current`:x[te],value:te})),default:C.indexOf(M)}]);R=F;}let I=R||u||"minimal";if(y&&!w)try{let F=I==="python-only"||I==="polyglot"||I==="enterprise"?"poetry":"venv",te;try{let Te=(await E.promises.readFile(b.join(y,".python-version"),"utf-8")).trim();Te&&(te=Te);}catch{}let{syncWorkspaceFoundationFiles:Le}=await import('./create-S64IWHAP.js'),_e=await Le(y,{workspaceName:b.basename(y),installMethod:F,pythonVersion:te,profile:I,writeMarker:true,writeGitignore:true,onlyIfMissing:true});f.push({id:"workspace.foundation.sync",status:_e.length>0?"passed":"skipped",message:_e.length>0?`Workspace foundation synchronized: ${_e.join(", ")}`:"Workspace foundation files are already up to date."});}catch(M){f.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${M.message}`});}else y&&f.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(y&&!w&&R&&R!==u)try{let M=l(y,"workspace.json"),F=await E.promises.readFile(M,"utf-8"),te=JSON.parse(F);te.profile=R,await O__default.ensureDir(b.dirname(M)),await E.promises.writeFile(M,JSON.stringify(te,null,2)+`
282
+ `,"utf-8");}catch{}let N={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},T=null;if(y)try{let M=o$1(y,"policies.yml").find(te=>E.existsSync(te));if(!M)throw new Error("policy file missing");let F=await E.promises.readFile(M,"utf-8");T=F,N=i(F);}catch{f.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else f.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(y){let M=Vc(T);N.dependency_sharing_mode=M.mode,f.push({id:"policy.schema.dependency_sharing_mode",status:M.status,message:M.message}),f.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:N.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":N.dependency_sharing_mode==="shared-node-deps"?"Effective dependency mode: shared-node-deps (Node projects share workspace-level caches).":"Effective dependency mode: shared-runtime-caches (Node/Python/Go share workspace-level caches)."});let F=E.existsSync(b.join(y,".workspai-workspace"))||E.existsSync(b.join(y,".rapidkit-workspace"));f.push({id:"policy.enforce_workspace_marker",status:!N.rules.enforce_workspace_marker||F?"passed":"failed",message:!N.rules.enforce_workspace_marker||F?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let te=o$1(y,"toolchain.lock").some(ke=>E.existsSync(ke));f.push({id:"policy.enforce_toolchain_lock",status:!N.rules.enforce_toolchain_lock||te?"passed":"failed",message:!N.rules.enforce_toolchain_lock||te?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let Le=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||o$1(y,"trusted-sources.lock").some(ke=>E.existsSync(ke));f.push({id:"policy.disallow_untrusted_tool_sources",status:!N.rules.disallow_untrusted_tool_sources||Le?"passed":"failed",message:!N.rules.disallow_untrusted_tool_sources||Le?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let _e=o$1(y,"compatibility-matrix.json").find(ke=>E.existsSync(ke))??l(y,"compatibility-matrix.json"),ue=E.existsSync(_e),Te=N.rules.enforce_compatibility_matrix;if(f.push({id:"policy.enforce_compatibility_matrix",status:!Te||ue?"passed":"failed",message:!Te||ue?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),ue)try{let ke=await E.promises.readFile(_e,"utf-8"),it=JSON.parse(ke),fs=!!it&&typeof it=="object";f.push({id:"compatibility.matrix.parse",status:fs?"passed":"failed",message:fs?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{f.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let ze=o$1(y,"mirror-config.json").find(ke=>E.existsSync(ke))??l(y,"mirror-config.json"),eo=o$1(y,"mirror.lock").find(ke=>E.existsSync(ke))??l(y,"mirror.lock"),Wr=E.existsSync(ze),Dr=E.existsSync(eo),gs={};if(Wr)try{gs=JSON.parse(await E.promises.readFile(ze,"utf-8")),f.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{f.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(w)f.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let ke=await Jn(y,{ciMode:p,offlineMode:m$1});f.push(...ke.checks.map(it=>({id:it.id,status:it.status,message:it.message}))),k=ke.details,ke.details.lockWritten&&(Dr=true);}if(m$1){let ke=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||gs.enabled===true;f.push({id:"offline.mirror.enabled",status:ke?"passed":"failed",message:ke?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let it=N.rules.require_mirror_lock_for_offline;f.push({id:"offline.mirror.lock",status:!it||Dr?"passed":"failed",message:!it||Dr?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else f.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let xo=xt({profile:I,runtimes:await Et(y),mode:N.mode});xo.profile!=="enterprise"?f.push({id:xo.checkId,status:xo.status,message:xo.message}):(f.push({id:"profile.enterprise.ci",status:p?"passed":w?"skipped":"failed",message:p?"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."}),f.push({id:"profile.enterprise.compatibility-matrix",status:ue?"passed":"failed",message:ue?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),f.push({id:"profile.enterprise.mirror-config",status:Wr?"passed":"failed",message:Wr?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}p&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),m$1&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let S=f.some(M=>M.id.startsWith("policy.schema.")&&M.status==="failed")||N.mode==="strict"&&f.some(M=>M.status==="failed"),J=l(y||P,"reports"),D=new Date().toISOString().replace(/[:.]/g,"-"),q=b.join(J,`bootstrap-compliance-${D}.json`),Q=b.join(J,"bootstrap-compliance.latest.json"),Re={schemaVersion:"bootstrap-compliance.v1",command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:y,profile:I,options:{ci:p,offline:m$1,strict:N.mode==="strict",complianceOnly:w},policyMode:N.mode,policyRules:N.rules,mirrorLifecycle:k,checks:f},de=async M=>{b$j(`.workspai/reports/${b.basename(q)}`,M),b$j(".workspai/reports/bootstrap-compliance.latest.json",M),await O__default.ensureDir(J),await Nr(q,M),await Nr(Q,M);};if(S){let M=Qn({...Re,result:"blocked",initExitCode:null},1,f);return await de(M),d?process.stdout.write(`${JSON.stringify(M,null,2)}
283
+ `):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${q}`))),1}if(d&&I==="enterprise"&&!p&&!w){let M=Qn({...Re,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,f);return await de(M),process.stdout.write(`${JSON.stringify(M,null,2)}
284
+ `),1}let Ae=async M=>{let F=process.stdout.write.bind(process.stdout),te=process.stderr.write.bind(process.stderr),Le=[],_e=[];process.stdout.write=((ue,Te,ze)=>{let eo=typeof Te=="function"?Te:typeof ze=="function"?ze:void 0;return Le.push(typeof ue=="string"?ue:ue instanceof Uint8Array?Buffer.from(ue).toString("utf8"):String(ue)),eo?.(),true}),process.stderr.write=((ue,Te,ze)=>{let eo=typeof Te=="function"?Te:typeof ze=="function"?ze:void 0;return _e.push(typeof ue=="string"?ue:ue instanceof Uint8Array?Buffer.from(ue).toString("utf8"):String(ue)),eo?.(),true});try{return {exitCode:await M(),stdout:Le.join(""),stderr:_e.join("")}}finally{process.stdout.write=F,process.stderr.write=te;}},Oe=M=>{let F=M.split(/\r?\n/).map(te=>te.trim()).filter(Boolean);return {bytes:Buffer.byteLength(M),excerpt:F.slice(0,12)}},Me=0,oe;if(!w)if(d){let M=await Ae(()=>e(c));Me=M.exitCode,oe={captured:true,stdout:Oe(M.stdout),stderr:Oe(M.stderr)};}else Me=await e(c);let ve=f.filter(M=>M.status==="failed").length,Zt=Me!==0?"failed":ve>0?"ok_with_warnings":"ok",_t=Me!==0?Me:ve>0?1:0,Pe=Qn({...Re,result:Zt,initExitCode:Me,complianceOnly:w,...oe?{initOutput:oe}:{}},_t,f);if(await de(Pe),y&&!w&&Me===0)try{let{syncWorkspaceProjects:M}=await import('./workspace-PJPRBUMQ.js');await M(y,d),await ds(y,{silent:d});}catch{}if(d)process.stdout.write(`${JSON.stringify(Pe,null,2)}
285
+ `);else {let M=f.filter(F=>F.status==="failed").length;M>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${M} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${q}`));}return _t}finally{typeof o>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=o;}}async function au(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]")),0;let e$1=(t[1]||"").toLowerCase(),o=t.includes("--json"),r=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!e$1||!["python","node","go","java","dotnet"].includes(e$1))return o?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]"},null,2)}
286
+ `):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet> [--warm-deps]")),1;let n=async(w,g)=>{if(w==="node"){if(!E.existsSync(b.join(g,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let j=E.existsSync(b.join(g,"pnpm-lock.yaml")),A=E.existsSync(b.join(g,"yarn.lock"));return j?{exitCode:await se("pnpm",["install","--lockfile-only","--ignore-scripts"],g)}:A?{exitCode:await se("yarn",["install","--ignore-scripts"],g)}:{exitCode:await se("npm",["install","--package-lock-only","--ignore-scripts"],g)}}if(w==="go")return E.existsSync(b.join(g,"go.mod"))?{exitCode:await se("go",["mod","download"],g)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(w==="java"){let P=E.existsSync(b.join(g,"pom.xml")),j=E.existsSync(b.join(g,"build.gradle"))||E.existsSync(b.join(g,"build.gradle.kts")),A=b.join(g,process.platform==="win32"?"gradlew.bat":"gradlew"),h=E.existsSync(A);return !P&&!j?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:P?{exitCode:await se("mvn",["-B","-q","-DskipTests","dependency:go-offline"],g)}:{exitCode:await se(h?A:"gradle",["--no-daemon","dependencies"],g)}}return w==="dotnet"?(()=>{let j=[{dir:g,depth:0}],A=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;j.length>0;){let h=j.shift();if(!h||h.depth>3)continue;let y=[];try{y=E.readdirSync(h.dir,{withFileTypes:true});}catch{continue}for(let f of y)if(f.isFile()){let k=f.name.toLowerCase();if(k.endsWith(".sln")||k.endsWith(".csproj"))return true}else f.isDirectory()&&!A.has(f.name)&&j.push({dir:b.join(h.dir,f.name),depth:h.depth+1});}return false})()?{exitCode:await se("dotnet",["restore"],g)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:{exitCode:0,message:"Dependency warm-up currently applies to node/go/java/dotnet runtimes."}};if(o){let w=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let P=await et(e$1,{runCommandInCwd:se,runCoreRapidkit:async(f,k)=>(await g$3(f,{...k,cwd:void 0})).exitCode}).checkPrereqs(),j=le(process.cwd()),A=j||process.cwd(),h=null;if(e$1==="node"&&P.exitCode===0&&(h=process.version),j&&h){let f=o$1(j,"toolchain.lock").find(C=>E.existsSync(C))??l(j,"toolchain.lock"),k=l(j,"toolchain.lock"),u={};try{u=JSON.parse(await E.promises.readFile(f,"utf-8"));}catch{}(!u.runtime||typeof u.runtime!="object")&&(u.runtime={}),u.runtime[e$1]={version:h,detectedAt:new Date().toISOString()},await O__default.ensureDir(b.dirname(k)),await E.promises.writeFile(k,JSON.stringify(u,null,2)+`
287
+ `,"utf-8");}let y={requested:r,status:"not-requested",exitCode:null,targets:0,messages:[]};if(r&&P.exitCode===0){let f=[A];if(e$1==="java"&&j){let R=(await is(j)).filter(v=>{let I=i$2(v);return l$1(I,v)});R.length>0&&(f=R);}let k=[];for(let x of f)k.push(await n(e$1,x));let u=k.filter(x=>x.exitCode!==0),C=k.filter(x=>x.exitCode===0&&!/skipped/i.test(x.message||""));y.status=u.length>0?"failed":C.length>0?"passed":"skipped",y.exitCode=u[0]?.exitCode??0,y.targets=f.length,y.messages=k.map(x=>x.message).filter(x=>typeof x=="string");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:e$1,result:P.exitCode===0?"ok":"failed",exitCode:P.exitCode,workspacePath:j,version:h,warmDeps:r,warmDependencies:y},null,2)}
288
+ `),P.exitCode}finally{typeof w>"u"?delete process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT:process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT=w;}}let a=et(e$1,{runCommandInCwd:se,runCoreRapidkit:(w,g)=>e(w,{...g,cwd:void 0})}),i=await a.checkPrereqs(),c=await a.doctorHints(process.cwd()),l$2=le(process.cwd()),p=l$2||process.cwd(),m=null,d=async()=>e$1!=="java"||!l$2?[]:m||(m=(await is(l$2)).filter(g=>{let P=i$2(g);return l$1(P,g)}),m);if(i.exitCode===0){console.log(s.green(`\u2705 ${e$1} prerequisites look good.`));let w=["python","node","go","java","dotnet"].filter(g=>g!==e$1).join("/");if(console.log(s.gray(` Scope: validated ${e$1} runtime only. ${w} checks are optional unless your workspace profile uses them.`)),e$1==="python"&&console.log(s.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),a.warmSetupCache&&((await a.warmSetupCache(p)).exitCode===0?console.log(s.gray(` ${e$1} cache warm-up completed.`)):console.log(s.yellow(` ${e$1} cache warm-up skipped (non-fatal).`))),r)if(e$1==="java"&&l$2){let g=await d();if(g.length>0){let P=0,j=0,A=0;for(let h of g){let y=await n("java",h),f=/skipped/i.test(y.message||""),k=b.relative(l$2,h)||b.basename(h);y.message&&console.log(s.gray(` [${k}] ${y.message}`)),y.exitCode===0&&!f?P+=1:y.exitCode===0&&f?A+=1:j+=1;}P>0&&console.log(s.gray(` java dependency warm-up completed for ${P} project(s) (--warm-deps).`)),j>0&&console.log(s.yellow(` java dependency warm-up failed for ${j} project(s) (non-fatal).`)),P===0&&j===0&&A>0&&console.log(s.gray(" java dependency warm-up skipped for discovered workspace projects."));}else {let P=await n("java",p),j=/skipped/i.test(P.message||"");P.message&&console.log(s.gray(` ${P.message}`)),P.exitCode===0&&!j?console.log(s.gray(` ${e$1} dependency warm-up completed (--warm-deps).`)):P.exitCode!==0&&console.log(s.yellow(` ${e$1} dependency warm-up failed (non-fatal).`));}}else {let g=await n(e$1,p),P=/skipped/i.test(g.message||"");g.message&&console.log(s.gray(` ${g.message}`)),g.exitCode===0&&!P?console.log(s.gray(` ${e$1} dependency warm-up completed (--warm-deps).`)):g.exitCode!==0&&console.log(s.yellow(` ${e$1} dependency warm-up failed (non-fatal).`));}if(l$2)try{let g=o$1(l$2,"toolchain.lock").find(h=>E.existsSync(h))??l(l$2,"toolchain.lock"),P=l(l$2,"toolchain.lock"),j={};try{j=JSON.parse(await E.promises.readFile(g,"utf-8"));}catch{}(!j.runtime||typeof j.runtime!="object")&&(j.runtime={});let A=j.runtime;if(e$1==="python"){let h=null;try{let{execa:y}=await import('execa');for(let f of ps()){let u=await y(f,f==="py"?["-3","--version"]:["--version"],{cwd:l$2,stdio:"pipe",reject:false,timeout:3e3});if(u.exitCode===0){let x=(u.stdout||u.stderr||"").match(/Python\s+(\S+)/);if(h=x?x[1]:null,h)break}}}catch{}A.python={...A.python||{},version:h,last_setup:new Date().toISOString()};}else if(e$1==="node")A.node={...A.node||{},version:process.version,last_setup:new Date().toISOString()};else if(e$1==="go"){let h=null;try{let{execa:y}=await import('execa'),k=((await y("go",["version"],{cwd:l$2,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);h=k?k[1]:null;}catch{}A.go={...A.go||{},version:h,last_setup:new Date().toISOString()};}else if(e$1==="java"){let h=null,y=null,f=null,k=await d(),C=E.existsSync(b.join(p,"pom.xml"))||E.existsSync(b.join(p,"build.gradle"))||E.existsSync(b.join(p,"build.gradle.kts"))?p:k[0]||p;try{let{execa:x}=await import('execa'),R=await x("java",["-version"],{cwd:l$2,stdio:"pipe",reject:false,timeout:3e3}),I=`${R.stdout||""}
289
+ ${R.stderr||""}`.match(/version\s+"([^"]+)"/i);h=I?I[1]:null;let N=E.existsSync(b.join(C,"pom.xml")),T=E.existsSync(b.join(C,"build.gradle"))||E.existsSync(b.join(C,"build.gradle.kts"));if(N){y="maven";let $=(()=>{let D=b.join(C,"mvnw.cmd");if(process.platform==="win32"&&E.existsSync(D))return D;let q=b.join(C,"mvnw");return E.existsSync(q)?q:"mvn"})(),S=await x($,["-version"],{cwd:C,stdio:"pipe",reject:false,timeout:3e3}),J=`${S.stdout||""}
290
+ ${S.stderr||""}`.match(/Apache Maven\s+(\S+)/i);f=J?J[1]:null;}else if(T){y="gradle";let $=(()=>{let D=b.join(C,"gradlew.bat");if(process.platform==="win32"&&E.existsSync(D))return D;let q=b.join(C,"gradlew");return E.existsSync(q)?q:"gradle"})(),S=await x($,["--version"],{cwd:C,stdio:"pipe",reject:false,timeout:3e3}),J=`${S.stdout||""}
291
+ ${S.stderr||""}`.match(/Gradle\s+(\S+)/i);f=J?J[1]:null;}}catch{}A.java={...A.java||{},version:h,build_tool:y,build_tool_version:f,last_setup:new Date().toISOString()};}else if(e$1==="dotnet"){let h=null;try{let{execa:y}=await import('execa'),k=((await y("dotnet",["--version"],{cwd:l$2,stdio:"pipe",reject:false,timeout:3e3})).stdout||"").trim();h=k.length>0?k:null;}catch{}A.dotnet={...A.dotnet||{},version:h,sdk:h,last_setup:new Date().toISOString()};}j.updated_at=new Date().toISOString(),await E.promises.writeFile(P,JSON.stringify(j,null,2)+`
292
292
  `,"utf-8"),console.log(s.gray(" toolchain.lock updated (.workspai/toolchain.lock)"));}catch{}}else console.log(s.red(`\u274C ${e$1} prerequisites check failed.`));if(c.length>0){console.log(s.gray(`
293
- Hints:`));for(let h of c)console.log(s.gray(`- ${h}`));}return i.exitCode}function ru(t){let e={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let o of t.split(`
294
- `)){let r=o.trim(),n=r.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]/g,""));let a=r.match(/^prune_on_bootstrap:\s*(true|false)/);a&&(e.prune_on_bootstrap=a[1]==="true");let i=r.match(/^self_heal:\s*(true|false)/);i&&(e.self_heal=i[1]==="true");let c=r.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function nu(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),0;let e=(t[1]||"status").toLowerCase(),o=t.includes("--json"),r=t.includes("--dry-run"),n=wr.getInstance(),a=le(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(a)try{let c=o$1(a,"cache-config.yml").find(p=>x.existsSync(p));if(!c)throw new Error("cache config missing");let l=await x.promises.readFile(c,"utf-8");i=ru(l);}catch{}if(e==="status"){let c={command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{enabled:true,strategy:i.strategy,selfHeal:i.self_heal,pruneOnBootstrap:i.prune_on_bootstrap,verifyIntegrity:i.verify_integrity,inMemory:true}};return o?(process.stdout.write(`${JSON.stringify(c,null,2)}
293
+ Hints:`));for(let w of c)console.log(s.gray(`- ${w}`));}return i.exitCode}function iu(t){let e={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let o of t.split(`
294
+ `)){let r=o.trim(),n=r.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]/g,""));let a=r.match(/^prune_on_bootstrap:\s*(true|false)/);a&&(e.prune_on_bootstrap=a[1]==="true");let i=r.match(/^self_heal:\s*(true|false)/);i&&(e.self_heal=i[1]==="true");let c=r.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function cu(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),0;let e=(t[1]||"status").toLowerCase(),o=t.includes("--json"),r=t.includes("--dry-run"),n=wr.getInstance(),a=le(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(a)try{let c=o$1(a,"cache-config.yml").find(p=>E.existsSync(p));if(!c)throw new Error("cache config missing");let l=await E.promises.readFile(c,"utf-8");i=iu(l);}catch{}if(e==="status"){let c={command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{enabled:true,strategy:i.strategy,selfHeal:i.self_heal,pruneOnBootstrap:i.prune_on_bootstrap,verifyIntegrity:i.verify_integrity,inMemory:true}};return o?(process.stdout.write(`${JSON.stringify(c,null,2)}
295
295
  `),0):(console.log(s.cyan("Workspai cache is enabled")),console.log(s.cyan("Workspai cache status")),a?(console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Strategy: ${i.strategy}`)),console.log(s.gray(` Self-heal: ${i.self_heal}`)),console.log(s.gray(` Prune on bootstrap:${i.prune_on_bootstrap}`)),console.log(s.gray(` Verify integrity: ${i.verify_integrity}`))):console.log(s.gray(" (not inside a workspace \u2014 showing in-memory cache only)")),console.log(s.gray(" In-memory cache: enabled")),console.log(s.gray(" Use: workspai cache clear|prune|repair")),0)}return e==="clear"?(await n.clear(),o?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{cleared:true,strategy:i.strategy}},null,2)}
296
296
  `),0):(console.log(s.green("Cache clear completed")),console.log(s.green("\u2705 Cache cleared (all entries removed).")),0)):e==="prune"?(r||await n.clear(),o?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,dryRun:r,cache:{pruned:!r,strategy:i.strategy,pruneOnBootstrap:i.prune_on_bootstrap},nextActions:i.prune_on_bootstrap?[]:["Set prune_on_bootstrap: true in .workspai/cache-config.yml to auto-prune on bootstrap."]},null,2)}
297
297
  `),0):r?(console.log(s.green("Cache prune dry run completed")),console.log(s.gray(" No cache entries were removed.")),0):(console.log(s.green("\u2705 Cache pruned (stale entries removed).")),i.prune_on_bootstrap||console.log(s.gray(" Tip: set prune_on_bootstrap: true in .workspai/cache-config.yml to auto-prune on every bootstrap.")),0)):e==="repair"?i.self_heal?(await n.clear(),o?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{repaired:true,selfHeal:i.self_heal,verifyIntegrity:i.verify_integrity}},null,2)}
298
298
  `),0):(console.log(s.green("\u2705 Cache repaired (self-heal applied, stale entries evicted).")),i.verify_integrity&&console.log(s.gray(" Integrity verification is enabled in cache-config.yml.")),0)):o?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"skipped",timestamp:new Date().toISOString(),workspacePath:a,reason:"self_heal is disabled in .workspai/cache-config.yml",cache:{selfHeal:i.self_heal,verifyIntegrity:i.verify_integrity}},null,2)}
299
- `),0):(console.log(s.yellow("\u26A0\uFE0F self_heal is disabled in .workspai/cache-config.yml \u2014 skipping repair.")),0):(console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),1)}async function su(t,e,o,r,n=false){let a=(e||"show").toLowerCase(),i=l(t,"policies.yml");if(a==="show"||a==="status"||a==="get"){let d=await Ac(t),h=Ec(d);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,policy:h},null,2)}
300
- `),0):(console.log(s.cyan(`Policy file: ${i}`)),console.log(s.gray(` mode: ${h.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${h.dependency_sharing_mode}`)),console.log(s.gray(" rules:")),console.log(s.gray(` enforce_workspace_marker: ${h.rules.enforce_workspace_marker}`)),console.log(s.gray(` enforce_toolchain_lock: ${h.rules.enforce_toolchain_lock}`)),console.log(s.gray(` disallow_untrusted_tool_sources: ${h.rules.disallow_untrusted_tool_sources}`)),console.log(s.gray(` enforce_compatibility_matrix: ${h.rules.enforce_compatibility_matrix}`)),console.log(s.gray(` require_mirror_lock_for_offline: ${h.rules.require_mirror_lock_for_offline}`)),console.log(s.gray("Examples:")),console.log(s.gray(" npx workspai workspace policy set mode strict")),console.log(s.gray(" npx workspai workspace policy set dependency_sharing_mode shared-runtime-caches")),console.log(s.gray(" npx workspai workspace policy set rules.enforce_toolchain_lock true")),0)}if(a!=="set")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_action",message:`Unknown workspace policy action: ${e||""}`},allowedActions:["show","status","get","set"]},null,2)}
299
+ `),0):(console.log(s.yellow("\u26A0\uFE0F self_heal is disabled in .workspai/cache-config.yml \u2014 skipping repair.")),0):(console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),1)}async function lu(t,e,o,r,n=false){let a=(e||"show").toLowerCase(),i=l(t,"policies.yml");if(a==="show"||a==="status"||a==="get"){let d=await $c(t),w=_c(d);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,policy:w},null,2)}
300
+ `),0):(console.log(s.cyan(`Policy file: ${i}`)),console.log(s.gray(` mode: ${w.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${w.dependency_sharing_mode}`)),console.log(s.gray(" rules:")),console.log(s.gray(` enforce_workspace_marker: ${w.rules.enforce_workspace_marker}`)),console.log(s.gray(` enforce_toolchain_lock: ${w.rules.enforce_toolchain_lock}`)),console.log(s.gray(` disallow_untrusted_tool_sources: ${w.rules.disallow_untrusted_tool_sources}`)),console.log(s.gray(` enforce_compatibility_matrix: ${w.rules.enforce_compatibility_matrix}`)),console.log(s.gray(` require_mirror_lock_for_offline: ${w.rules.require_mirror_lock_for_offline}`)),console.log(s.gray("Examples:")),console.log(s.gray(" npx workspai workspace policy set mode strict")),console.log(s.gray(" npx workspai workspace policy set dependency_sharing_mode shared-runtime-caches")),console.log(s.gray(" npx workspai workspace policy set rules.enforce_toolchain_lock true")),0)}if(a!=="set")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_action",message:`Unknown workspace policy action: ${e||""}`},allowedActions:["show","status","get","set"]},null,2)}
301
301
  `),1):(console.log(s.red(`Unknown workspace policy action: ${e||""}`)),console.log(s.gray("Available: show, set")),1);if(!o||typeof r>"u")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.missing_arguments",message:"Usage: workspai workspace policy set <key> <value>"},allowedKeys:["mode","dependency_sharing_mode","rules.enforce_workspace_marker","rules.enforce_toolchain_lock","rules.disallow_untrusted_tool_sources","rules.enforce_compatibility_matrix","rules.require_mirror_lock_for_offline"]},null,2)}
302
- `),1):(console.log(s.yellow("Usage: workspai workspace policy set <key> <value>")),console.log(s.gray("Allowed keys:")),console.log(s.gray(" mode (warn|strict)")),console.log(s.gray(" dependency_sharing_mode (isolated|shared-runtime-caches|shared-node-deps)")),console.log(s.gray(" rules.enforce_workspace_marker (true|false)")),console.log(s.gray(" rules.enforce_toolchain_lock (true|false)")),console.log(s.gray(" rules.disallow_untrusted_tool_sources (true|false)")),console.log(s.gray(" rules.enforce_compatibility_matrix (true|false)")),console.log(s.gray(" rules.require_mirror_lock_for_offline (true|false)")),1);let c=o.trim(),p=await Ac(t);if(c==="mode"){let d=r.trim().toLowerCase();if(d!=="warn"&&d!=="strict")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_mode",message:"Invalid mode. Use: warn | strict"}},null,2)}
303
- `),1):(console.log(s.red("\u274C Invalid mode. Use: warn | strict")),1);p=Rc(p,"mode",`${d} # "warn" or "strict"`);}else if(c==="dependency_sharing_mode"){let d=r.trim().toLowerCase();if(d!=="isolated"&&d!=="shared-runtime-caches"&&d!=="shared-node-deps")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_dependency_sharing_mode",message:"Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps"}},null,2)}
304
- `),1):(console.log(s.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1);p=Rc(p,"dependency_sharing_mode",`${d} # "isolated" or "shared-runtime-caches" or "shared-node-deps"`);}else if(c.startsWith("rules.")){let d=c.slice(6);if(!(d in Dc))return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_rule",message:`Unknown policy rule: ${d}`}},null,2)}
305
- `),1):(console.log(s.red(`\u274C Unknown policy rule: ${d}`)),1);let h=Bd(r);if(h===null)return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_boolean",message:"Rule values must be boolean: true | false"}},null,2)}
306
- `),1):(console.log(s.red("\u274C Rule values must be boolean: true | false")),1);p=Vd(p,d,h);}else return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_key",message:`Unknown policy key: ${c}`}},null,2)}
307
- `),1):(console.log(s.red(`\u274C Unknown policy key: ${c}`)),1);await Ud(t,p);let m=Ec(p);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,updatedKey:c,policy:m},null,2)}
308
- `),0):(console.log(s.green(`\u2705 Updated ${c} in .workspai/policies.yml`)),console.log(s.gray(` mode: ${m.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${m.dependency_sharing_mode}`)),console.log(s.gray(" Tip: run `npx workspai workspace policy show` to inspect all values.")),0)}async function au(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),0;let e=(t[1]||"status").toLowerCase(),o=t.includes("--json"),r=le(process.cwd());if(!r)return console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let n=o$1(r,"mirror-config.json").find(d=>x.existsSync(d))??l(r,"mirror-config.json"),a=o$1(r,"mirror.lock").find(d=>x.existsSync(d))??l(r,"mirror.lock"),i=l(r,"mirror","artifacts"),c=l(r,"reports");async function l$1(d){if(!await I__default.pathExists(d))return 0;let h=0,g=[d];for(;g.length>0;){let k=g.shift();if(!k)continue;let C=await x.promises.readdir(k,{withFileTypes:true});for(let A of C)A.isFile()?h+=1:A.isDirectory()&&g.push(b.join(k,A.name));}return h}async function p(d){let h=new Date().toISOString().replace(/[:.]/g,"-"),g=b.join(c,`mirror-ops-${h}.json`),k=b.join(c,"mirror-ops.latest.json"),C={schemaVersion:"mirror-ops.v1",...d};b$i(`.workspai/reports/${b.basename(g)}`,C),b$i(".workspai/reports/mirror-ops.latest.json",C),await I__default.ensureDir(c),await Nr(g,C),await Nr(k,C);}async function m(){let d=await I__default.pathExists(n),h=await I__default.pathExists(a),g=await l$1(i);return {configExists:d,lockExists:h,artifactsCount:g}}if(e==="status"){let d=await I__default.pathExists(n),h=await I__default.pathExists(a),g=await l$1(i),k={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:{configExists:d,lockExists:h,artifactsCount:g}};return await p(k),o?(process.stdout.write(`${JSON.stringify(k,null,2)}
309
- `),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Config: ${d?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${h?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${g}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let d=await Jn(r,{ciMode:true,offlineMode:e==="verify",forceRun:true}),h=d.checks.filter(C=>C.status==="failed"),g=d.checks.some(C=>C.id.startsWith("mirror.verify.")&&C.status==="failed");if(e==="verify"&&g){let C={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:d.details,checks:d.checks};if(await p(C),o)return process.stdout.write(`${JSON.stringify(C,null,2)}
310
- `),1;console.log(s.red("\u274C Mirror verify failed."));for(let A of d.checks.filter(w=>w.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${A.id}: ${A.message}`));return 1}if(h.length>0){let C={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:d.details,checks:d.checks};if(await p(C),o)return process.stdout.write(`${JSON.stringify(C,null,2)}
311
- `),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${h.length} issue(s).`));for(let A of h)console.log(s.gray(`- ${A.id}: ${A.message}`));return 1}let k={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:d.details,checks:d.checks};return await p(k),o?(process.stdout.write(`${JSON.stringify(k,null,2)}
312
- `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${d.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${d.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${d.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function cs(t){let e$1=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$1>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let o=process.cwd(),r=await Jc(o,async()=>{let n=le(o),a=Ze("python",{runCommandInCwd:se,runCoreRapidkit:e}),i=Ze("dotnet",{runCommandInCwd:se,runCoreRapidkit:e}),c=t.slice(1).filter(k=>!k.startsWith("-"));if(c.length>0){let k=b.resolve(o,c[0]),C=i$2(k),A=await Rt(k);return j(C,k)||A==="go"?await Yn(k):l$1(C,k)||A==="java"?await lt("init",k):m(C,k)||A==="dotnet"?ae(await i.initProject(k)):k$1(C,k)||A==="node"?await zn(k):n$1(C,k)||A==="python"?await qn(k,a):await e(t,{cwd:o})}let l=i$2(o),p=!!le(o)&&o===le(o);if(!p&&j(l,o))return await Yn(o);let m$1=await Rt(o);if(!p&&(l$1(l,o)||m$1==="java"))return await lt("init",o);if(!p&&(m(l,o)||m$1==="dotnet"))return ae(await i.initProject(o));if(!p&&(k$1(l,o)||m$1==="node"))return await zn(o);if(!p&&(n$1(l,o)||m$1==="python"))return await qn(o,a);let d=n||le(o),h=Wc(o),g=h?b.dirname(b.dirname(h)):null;if(g&&g!==d){let k=i$2(g),C=await Rt(g);return j(k,g)||C==="go"?await Yn(g):l$1(k,g)||C==="java"?await lt("init",g):m(k,g)||C==="dotnet"?ae(await i.initProject(g)):k$1(k,g)||C==="node"?await zn(g):n$1(k,g)||C==="python"?await qn(g,a):await e(["init"],{cwd:g})}if(d&&o===d){console.log(s.yellow("\u26A0\uFE0F Running `npx workspai init` at workspace root.")),console.log(s.gray(" Root `init`, `workspace init`, and `workspace run init` now share the same full-init flow:\n workspace-profile dependencies first, then project dependency initialization.\n"));let k=await as(d);if(k!==0)return k;let{runWorkspaceStage:C}=await import('./workspace-run-M4LNJILC.js');return (await C({workspacePath:d,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!d){let k=await b$2(),C=g$2(),{name:A}=eu(C);await I__default.ensureDir(C);let{createProject:w}=await import('./create-7JKJDAQV.js');return await w(A,{yes:true,userConfig:k,parentDirectory:C}),0}return await e(t,{cwd:o})});return r.ok?r.value:r.code}finally{typeof e$1>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$1;}}async function _c(t){let e=le(t);if(!e)return [];let o="warn";try{let l=o$1(e,"policies.yml").find(d=>x.existsSync(d));if(!l)return [];let p=await x.promises.readFile(l,"utf-8");(p.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??p.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(o="strict");}catch{return []}if(o!=="strict")return [];let r=[],n=o$1(e,"toolchain.lock").find(l=>x.existsSync(l));if(!n||!x.existsSync(n))return r.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),r;let a={};try{a=JSON.parse(await x.promises.readFile(n,"utf-8"));}catch{return r.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),r}let i=a.runtime??{},c=i$2(t);j(c,t)&&!i.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):k$1(c,t)&&!i.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):l$1(c,t)&&!i.java?.version?r.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):m(c,t)&&!i.dotnet?.version?r.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):n$1(c,t)&&!i.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let l=o$1(e,"workspace.json").find(g=>x.existsSync(g));if(!l)throw new Error("workspace manifest missing");let m=JSON.parse(await x.promises.readFile(l,"utf-8")).profile??"",d=i$3(t,c),h=kt({profile:m,runtime:d.runtime,subjectLabel:b.basename(t),mode:"strict"});h.ok||r.push(`${h.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return r}async function iu(){let t=async f=>{if(!b$1()||!f.toLowerCase().endsWith(".cmd"))return false;try{let u=(await I__default.readFile(f,"utf8")).replace(/\r\n/g,`
313
- `).toLowerCase(),j=u.includes("\\.rapidkit\\rapidkit"),P=u.includes("\\.rapidkit\\rapidkit.cmd")||u.includes("\\.rapidkit\\rapidkit.exe")||u.includes("\\.venv\\scripts\\rapidkit.exe");return j&&!P}catch{return false}},e$1=process.cwd(),o$1=process.argv.slice(2),r=o$1[0],n=r==="init",a=new Set(q$2),i=!r||r==="--help"||r==="-h"||r==="help",c=qe(e$1),l=p(e$1,"project.json").some(f=>x.existsSync(f)),p$1=i$2(e$1),m$1=await Rt(e$1),d=j(p$1,e$1)||k$1(p$1,e$1)||n$1(p$1,e$1)||l$1(p$1,e$1)||m(p$1,e$1)||h$2(m$1??void 0),h=!!r&&a.has(r)&&d,g=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Co(o$1)||o$1[0]==="create")return false;if(rs(o$1))return true;if(o$1[0]==="init"&&c&&!l)return false;if(ns(o$1))return true;try{let f=r==="shell"&&o$1[1]==="activate",v=r==="create",u=await Ra(e$1,{cwd:e$1,timeoutMs:1200});if(u.ok&&u.data?.isRapidkitProject&&u.data.engine==="python"){let j=v||Co(o$1);if(!i&&!f&&!j&&!n&&!h&&an(o$1)){if(r&&jc.includes(r)){let E=await _c(e$1).catch(()=>[]);if(E.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
314
- `);for(let S of E)process.stderr.write(s.red(` \u2022 ${S}`)+`
315
- `);process.exit(1);}}let P=await e(process.argv.slice(2),{cwd:e$1});process.exit(P);}}}catch{}let k=Wc(e$1),C=b$1(),A=g?[]:o(e$1),w=null;for(let f$1 of A)if(await I__default.pathExists(f$1)){if(await t(f$1)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${f$1}. Falling back to core bridge.`);continue}w=f$1;break}let y=r==="create";if(r==="init"&&c&&!l)return false;if(r&&jc.includes(r)){let f=await _c(e$1);if(f.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
316
- `);for(let v of f)process.stderr.write(s.red(` \u2022 ${v}`)+`
317
- `);process.exit(1);}}if(w&&r&&bc.includes(r)&&!y&&!n&&!h){f.debug(`Delegating to local CLI: ${w} ${o$1.join(" ")}`);let f$1=r==="init"?wc():process.env,v=spawn(w,o$1,{stdio:"inherit",cwd:e$1,shell:C,env:f$1});return v.on("close",u=>{process.exit(u??0);}),v.on("error",u=>{f.error(`Failed to run local rapidkit: ${u.message}`),process.exit(1);}),true}if(k&&await I__default.pathExists(k))try{let f$1=await I__default.readJson(k);if(_a(f$1.engine)){let v=o$1[0],u=g?[]:o(e$1),j=null;for(let P of u)if(await I__default.pathExists(P)){if(await t(P)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${P}. Falling back to core bridge.`);continue}j=P;break}if(j&&v&&bc.includes(v)&&v!=="init"&&!h){f.debug(`Delegating to local CLI (early detection): ${j} ${o$1.join(" ")}`);let P=v==="init"?wc():process.env,E=spawn(j,o$1,{stdio:"inherit",cwd:e$1,shell:C,env:P});return E.on("close",S=>process.exit(S??0)),E.on("error",S=>{f.error(`Failed to run local rapidkit: ${S.message}`),process.exit(1);}),true}if(v==="shell"&&o$1[1]==="activate"){let P=b$1()?`# RapidKit Core activation snippet (PowerShell)
302
+ `),1):(console.log(s.yellow("Usage: workspai workspace policy set <key> <value>")),console.log(s.gray("Allowed keys:")),console.log(s.gray(" mode (warn|strict)")),console.log(s.gray(" dependency_sharing_mode (isolated|shared-runtime-caches|shared-node-deps)")),console.log(s.gray(" rules.enforce_workspace_marker (true|false)")),console.log(s.gray(" rules.enforce_toolchain_lock (true|false)")),console.log(s.gray(" rules.disallow_untrusted_tool_sources (true|false)")),console.log(s.gray(" rules.enforce_compatibility_matrix (true|false)")),console.log(s.gray(" rules.require_mirror_lock_for_offline (true|false)")),1);let c=o.trim(),p=await $c(t);if(c==="mode"){let d=r.trim().toLowerCase();if(d!=="warn"&&d!=="strict")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_mode",message:"Invalid mode. Use: warn | strict"}},null,2)}
303
+ `),1):(console.log(s.red("\u274C Invalid mode. Use: warn | strict")),1);p=Ic(p,"mode",`${d} # "warn" or "strict"`);}else if(c==="dependency_sharing_mode"){let d=r.trim().toLowerCase();if(d!=="isolated"&&d!=="shared-runtime-caches"&&d!=="shared-node-deps")return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_dependency_sharing_mode",message:"Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps"}},null,2)}
304
+ `),1):(console.log(s.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1);p=Ic(p,"dependency_sharing_mode",`${d} # "isolated" or "shared-runtime-caches" or "shared-node-deps"`);}else if(c.startsWith("rules.")){let d=c.slice(6);if(!(d in Jc))return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_rule",message:`Unknown policy rule: ${d}`}},null,2)}
305
+ `),1):(console.log(s.red(`\u274C Unknown policy rule: ${d}`)),1);let w=Yd(r);if(w===null)return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_boolean",message:"Rule values must be boolean: true | false"}},null,2)}
306
+ `),1):(console.log(s.red("\u274C Rule values must be boolean: true | false")),1);p=Hd(p,d,w);}else return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_key",message:`Unknown policy key: ${c}`}},null,2)}
307
+ `),1):(console.log(s.red(`\u274C Unknown policy key: ${c}`)),1);await zd(t,p);let m=_c(p);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,updatedKey:c,policy:m},null,2)}
308
+ `),0):(console.log(s.green(`\u2705 Updated ${c} in .workspai/policies.yml`)),console.log(s.gray(` mode: ${m.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${m.dependency_sharing_mode}`)),console.log(s.gray(" Tip: run `npx workspai workspace policy show` to inspect all values.")),0)}async function pu(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),0;let e=(t[1]||"status").toLowerCase(),o=t.includes("--json"),r=le(process.cwd());if(!r)return console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let n=o$1(r,"mirror-config.json").find(d=>E.existsSync(d))??l(r,"mirror-config.json"),a=o$1(r,"mirror.lock").find(d=>E.existsSync(d))??l(r,"mirror.lock"),i=l(r,"mirror","artifacts"),c=l(r,"reports");async function l$1(d){if(!await O__default.pathExists(d))return 0;let w=0,g=[d];for(;g.length>0;){let P=g.shift();if(!P)continue;let j=await E.promises.readdir(P,{withFileTypes:true});for(let A of j)A.isFile()?w+=1:A.isDirectory()&&g.push(b.join(P,A.name));}return w}async function p(d){let w=new Date().toISOString().replace(/[:.]/g,"-"),g=b.join(c,`mirror-ops-${w}.json`),P=b.join(c,"mirror-ops.latest.json"),j={schemaVersion:"mirror-ops.v1",...d};b$j(`.workspai/reports/${b.basename(g)}`,j),b$j(".workspai/reports/mirror-ops.latest.json",j),await O__default.ensureDir(c),await Nr(g,j),await Nr(P,j);}async function m(){let d=await O__default.pathExists(n),w=await O__default.pathExists(a),g=await l$1(i);return {configExists:d,lockExists:w,artifactsCount:g}}if(e==="status"){let d=await O__default.pathExists(n),w=await O__default.pathExists(a),g=await l$1(i),P={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:{configExists:d,lockExists:w,artifactsCount:g}};return await p(P),o?(process.stdout.write(`${JSON.stringify(P,null,2)}
309
+ `),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Config: ${d?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${w?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${g}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let d=await Jn(r,{ciMode:true,offlineMode:e==="verify",forceRun:true}),w=d.checks.filter(j=>j.status==="failed"),g=d.checks.some(j=>j.id.startsWith("mirror.verify.")&&j.status==="failed");if(e==="verify"&&g){let j={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:d.details,checks:d.checks};if(await p(j),o)return process.stdout.write(`${JSON.stringify(j,null,2)}
310
+ `),1;console.log(s.red("\u274C Mirror verify failed."));for(let A of d.checks.filter(h=>h.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${A.id}: ${A.message}`));return 1}if(w.length>0){let j={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:d.details,checks:d.checks};if(await p(j),o)return process.stdout.write(`${JSON.stringify(j,null,2)}
311
+ `),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${w.length} issue(s).`));for(let A of w)console.log(s.gray(`- ${A.id}: ${A.message}`));return 1}let P={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:d.details,checks:d.checks};return await p(P),o?(process.stdout.write(`${JSON.stringify(P,null,2)}
312
+ `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${d.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${d.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${d.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function cs(t){let e$1=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$1>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let o=process.cwd(),r=await Gc(o,async()=>{let n=le(o),a=et("python",{runCommandInCwd:se,runCoreRapidkit:e}),i=et("dotnet",{runCommandInCwd:se,runCoreRapidkit:e}),c=t.slice(1).filter(P=>!P.startsWith("-"));if(c.length>0){let P=b.resolve(o,c[0]),j$1=i$2(P),A=await At(P);return j(j$1,P)||A==="go"?await Yn(P):l$1(j$1,P)||A==="java"?await pt("init",P):m(j$1,P)||A==="dotnet"?ae(await i.initProject(P)):k$1(j$1,P)||A==="node"?await zn(P):n$1(j$1,P)||A==="python"?await qn(P,a):await e(t,{cwd:o})}let l=i$2(o),p=!!le(o)&&o===le(o);if(!p&&j(l,o))return await Yn(o);let m$1=await At(o);if(!p&&(l$1(l,o)||m$1==="java"))return await pt("init",o);if(!p&&(m(l,o)||m$1==="dotnet"))return ae(await i.initProject(o));if(!p&&(k$1(l,o)||m$1==="node"))return await zn(o);if(!p&&(n$1(l,o)||m$1==="python"))return await qn(o,a);let d=n||le(o),w=Fc(o),g=w?b.dirname(b.dirname(w)):null;if(g&&g!==d){let P=i$2(g),j$1=await At(g);return j(P,g)||j$1==="go"?await Yn(g):l$1(P,g)||j$1==="java"?await pt("init",g):m(P,g)||j$1==="dotnet"?ae(await i.initProject(g)):k$1(P,g)||j$1==="node"?await zn(g):n$1(P,g)||j$1==="python"?await qn(g,a):await e(["init"],{cwd:g})}if(d&&o===d){console.log(s.yellow("\u26A0\uFE0F Running `npx workspai init` at workspace root.")),console.log(s.gray(" Root `init`, `workspace init`, and `workspace run init` now share the same full-init flow:\n workspace-profile dependencies first, then project dependency initialization.\n"));let P=await as(d);if(P!==0)return P;let{runWorkspaceStage:j}=await import('./workspace-run-QND2SIYA.js');return (await j({workspacePath:d,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!d){let P=await b$2(),j=g$2(),{name:A}=nu(j);await O__default.ensureDir(j);let{createProject:h}=await import('./create-S64IWHAP.js');return await h(A,{yes:true,userConfig:P,parentDirectory:j}),0}return await e(t,{cwd:o})});return r.ok?r.value:r.code}finally{typeof e$1>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$1;}}async function Oc(t){let e=le(t);if(!e)return [];let o="warn";try{let l=o$1(e,"policies.yml").find(d=>E.existsSync(d));if(!l)return [];let p=await E.promises.readFile(l,"utf-8");(p.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??p.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(o="strict");}catch{return []}if(o!=="strict")return [];let r=[],n=o$1(e,"toolchain.lock").find(l=>E.existsSync(l));if(!n||!E.existsSync(n))return r.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),r;let a={};try{a=JSON.parse(await E.promises.readFile(n,"utf-8"));}catch{return r.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),r}let i=a.runtime??{},c=i$2(t);j(c,t)&&!i.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):k$1(c,t)&&!i.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):l$1(c,t)&&!i.java?.version?r.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):m(c,t)&&!i.dotnet?.version?r.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):n$1(c,t)&&!i.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let l=o$1(e,"workspace.json").find(g=>E.existsSync(g));if(!l)throw new Error("workspace manifest missing");let m=JSON.parse(await E.promises.readFile(l,"utf-8")).profile??"",d=i$3(t,c),w=kt({profile:m,runtime:d.runtime,subjectLabel:b.basename(t),mode:"strict"});w.ok||r.push(`${w.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return r}async function du(){let t=async f=>{if(!b$1()||!f.toLowerCase().endsWith(".cmd"))return false;try{let u=(await O__default.readFile(f,"utf8")).replace(/\r\n/g,`
313
+ `).toLowerCase(),C=u.includes("\\.rapidkit\\rapidkit"),x=u.includes("\\.rapidkit\\rapidkit.cmd")||u.includes("\\.rapidkit\\rapidkit.exe")||u.includes("\\.venv\\scripts\\rapidkit.exe");return C&&!x}catch{return false}},e$1=process.cwd(),o$1=process.argv.slice(2),r=o$1[0],n=r==="init",a=new Set(q$2),i=!r||r==="--help"||r==="-h"||r==="help",c=qe(e$1),l=p(e$1,"project.json").some(f=>E.existsSync(f)),p$1=i$2(e$1),m$1=await At(e$1),d=j(p$1,e$1)||k$1(p$1,e$1)||n$1(p$1,e$1)||l$1(p$1,e$1)||m(p$1,e$1)||h$2(m$1??void 0),w=!!r&&a.has(r)&&d,g=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Co(o$1)||o$1[0]==="create")return false;if(rs(o$1))return true;if(o$1[0]==="init"&&c&&!l)return false;if(ns(o$1))return true;try{let f=r==="shell"&&o$1[1]==="activate",k=r==="create",u=await Ia(e$1,{cwd:e$1,timeoutMs:1200});if(u.ok&&u.data?.isRapidkitProject&&u.data.engine==="python"){let C=k||Co(o$1);if(!i&&!f&&!C&&!n&&!w&&an(o$1)){if(r&&xc.includes(r)){let R=await Oc(e$1).catch(()=>[]);if(R.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
314
+ `);for(let v of R)process.stderr.write(s.red(` \u2022 ${v}`)+`
315
+ `);process.exit(1);}}let x=await e(process.argv.slice(2),{cwd:e$1});process.exit(x);}}}catch{}let P=Fc(e$1),j$1=b$1(),A=g?[]:o(e$1),h=null;for(let f$1 of A)if(await O__default.pathExists(f$1)){if(await t(f$1)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${f$1}. Falling back to core bridge.`);continue}h=f$1;break}let y=r==="create";if(r==="init"&&c&&!l)return false;if(r&&xc.includes(r)){let f=await Oc(e$1);if(f.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
316
+ `);for(let k of f)process.stderr.write(s.red(` \u2022 ${k}`)+`
317
+ `);process.exit(1);}}if(h&&r&&Sc.includes(r)&&!y&&!n&&!w){f.debug(`Delegating to local CLI: ${h} ${o$1.join(" ")}`);let f$1=r==="init"?Pc():process.env,k=spawn(h,o$1,{stdio:"inherit",cwd:e$1,shell:j$1,env:f$1});return k.on("close",u=>{process.exit(u??0);}),k.on("error",u=>{f.error(`Failed to run local rapidkit: ${u.message}`),process.exit(1);}),true}if(P&&await O__default.pathExists(P))try{let f$1=await O__default.readJson(P);if(Oa(f$1.engine)){let k=o$1[0],u=g?[]:o(e$1),C=null;for(let x of u)if(await O__default.pathExists(x)){if(await t(x)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${x}. Falling back to core bridge.`);continue}C=x;break}if(C&&k&&Sc.includes(k)&&k!=="init"&&!w){f.debug(`Delegating to local CLI (early detection): ${C} ${o$1.join(" ")}`);let x=k==="init"?Pc():process.env,R=spawn(C,o$1,{stdio:"inherit",cwd:e$1,shell:j$1,env:x});return R.on("close",v=>process.exit(v??0)),R.on("error",v=>{f.error(`Failed to run local rapidkit: ${v.message}`),process.exit(1);}),true}if(k==="shell"&&o$1[1]==="activate"){let x=b$1()?`# RapidKit Core activation snippet (PowerShell)
318
318
  $venv = ".venv"
319
319
  if (Test-Path "$venv\\Scripts\\Activate.ps1") { . "$venv\\Scripts\\Activate.ps1" }
320
320
  $env:RAPIDKIT_PROJECT_ROOT = (Get-Location).Path
@@ -334,9 +334,9 @@ export RAPIDKIT_PROJECT_ROOT="$(pwd)"
334
334
  export PATH="$(pwd)/.workspai:$(pwd)/.rapidkit:$(pwd):$PATH"
335
335
  `;console.log(s.green.bold(`
336
336
  \u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
337
- `)),console.log(P),console.log(s.gray(`
337
+ `)),console.log(x),console.log(s.gray(`
338
338
  \u{1F4A1} After activation you can run: workspai dev
339
- `)),process.exit(0);}if(!i&&!Co(o$1)&&v!=="init"&&!h&&an(o$1)){let P=await e(o$1,{cwd:e$1});process.exit(P);}}}catch{}return false}var vt=null,$r=false,cu=yd(),we="workspai",Ce="npx workspai",ce=new Command,lu=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function pu(t$1){if(t$1.length===0)return false;let e=t$1[0],o=t$1[1];if(y(t$1)||$d.includes(e))return false;if(r$1.includes(e)){if(e==="lint"||e==="format"){let n=i$2(process.cwd()),a=await Rt(process.cwd());if(k$1(n,process.cwd())||a==="node"){let i=i$3(process.cwd(),n);if(t(process.cwd(),e,{framework:i.key})!==null)return false}if(n$1(n,process.cwd())||a==="python")return true;if(v(process.cwd()))return false}return true}if(Co(t$1)||e==="shell"&&o==="activate")return false;if(t$1.includes("--tui"))return true;if(e==="--help"||e==="-h"||e==="help"||e==="--version"||e==="-V"||e==="-v"||t$1.includes("--template")||t$1.includes("-t"))return false;let r=await i$4();return sn(e,r)?true:t$1.some(n=>nn.has(n))?false:r?r.has(e):!!(a$9.has(e)||t$1.length>1)}ce.name(we).description("Workspai workspace intelligence CLI").version(c());var du=b$1()?`${Ce} init; ${Ce} dev`:`${Ce} init && ${Ce} dev`,uu="~/.workspai/workspaces/my-workspace";ce.addHelpText("beforeAll",`Workspai CLI
339
+ `)),process.exit(0);}if(!i&&!Co(o$1)&&k!=="init"&&!w&&an(o$1)){let x=await e(o$1,{cwd:e$1});process.exit(x);}}}catch{}return false}var vt=null,$r=false,uu=Pd(),we="workspai",Ce="npx workspai",ce=new Command,mu=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function gu(t$1){if(t$1.length===0)return false;let e=t$1[0],o=t$1[1];if(y(t$1)||Td.includes(e))return false;if(r$1.includes(e)){if(e==="lint"||e==="format"){let n=i$2(process.cwd()),a=await At(process.cwd());if(k$1(n,process.cwd())||a==="node"){let i=i$3(process.cwd(),n);if(t(process.cwd(),e,{framework:i.key})!==null)return false}if(n$1(n,process.cwd())||a==="python")return true;if(v(process.cwd()))return false}return true}if(Co(t$1)||e==="shell"&&o==="activate")return false;if(t$1.includes("--tui"))return true;if(e==="--help"||e==="-h"||e==="help"||e==="--version"||e==="-V"||e==="-v"||t$1.includes("--template")||t$1.includes("-t"))return false;let r=await i$4();return sn(e,r)?true:t$1.some(n=>nn.has(n))?false:r?r.has(e):!!(a$9.has(e)||t$1.length>1)}ce.name(we).description("Workspai workspace intelligence CLI").version(c());var fu=b$1()?`${Ce} init; ${Ce} dev`:`${Ce} init && ${Ce} dev`,hu="~/.workspai/workspaces/my-workspace";ce.addHelpText("beforeAll",`Workspai CLI
340
340
 
341
341
  Create workspaces, scaffold projects, and manage your development toolchain.
342
342
  `);ce.addHelpText("afterAll",`
@@ -369,9 +369,9 @@ Quick start:
369
369
  ${Ce} my-workspace # Create workspace in ~/.workspai/workspaces
370
370
  ${Ce} my-workspace --here # Create workspace in the current directory
371
371
  ${Ce} create workspace --output .
372
- cd ${uu} # Or cd my-workspace when using --here
372
+ cd ${hu} # Or cd my-workspace when using --here
373
373
  ${Ce} create project # Interactive kit picker
374
- ${du} # Install deps + run
374
+ ${fu} # Install deps + run
375
375
 
376
376
  Notes:
377
377
  --here Create workspace in the current directory (alias for --output .)
@@ -380,56 +380,58 @@ Notes:
380
380
  It is different from core --skip-essentials (essential module installation).
381
381
 
382
382
  Use "${we} help <command>" for more information.
383
- `);ce.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-python-engine","Create a Python-aware workspace without installing rapidkit-core now").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, java-only, python-only, node-only, go-only, dotnet-only, polyglot, enterprise").choices(["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not link it to any workspace").hideHelp()).option("--no-update-check","Skip checking for updates").option("--trust-config","Trust and execute workspai.config.js/mjs/cjs discovered in this tree").action(async(t,e$1)=>{try{e$1.debug&&(f.setDebug(true),f.debug("Debug mode enabled"));let o=await b$2();f.debug("User config loaded",{...o,openaiApiKey:o.openaiApiKey?"[REDACTED]":void 0});let r=await c$1(process.cwd(),{trustExecutableConfig:e$1.trustConfig===true||process.env.WORKSPAI_TRUST_CONFIG==="1"});f.debug("Workspai config loaded",r);let n=d(o,r,{author:e$1.author,pythonVersion:void 0,skipGit:e$1.skipGit});f.debug("Merged config",n),e$1.updateCheck!==false&&await b$3(),a("workspace"),t||(Kc(),process.exit(0));try{h(t);}catch(l){throw l instanceof a$1&&(f.error(`
383
+ `);ce.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-python-engine","Create a Python-aware workspace without installing rapidkit-core now").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, java-only, python-only, node-only, go-only, dotnet-only, polyglot, enterprise").choices(["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not link it to any workspace").hideHelp()).option("--no-update-check","Skip checking for updates").option("--trust-config","Trust and execute workspai.config.js/mjs/cjs discovered in this tree").action(async(t,e$1)=>{try{e$1.debug&&(f.setDebug(true),f.debug("Debug mode enabled"));let o=await b$2();f.debug("User config loaded",{...o,openaiApiKey:o.openaiApiKey?"[REDACTED]":void 0});let r=await c$1(process.cwd(),{trustExecutableConfig:e$1.trustConfig===true||process.env.WORKSPAI_TRUST_CONFIG==="1"});f.debug("Workspai config loaded",r);let n=d(o,r,{author:e$1.author,pythonVersion:void 0,skipGit:e$1.skipGit});f.debug("Merged config",n),e$1.updateCheck!==false&&await b$3(),a("workspace"),t||(Uc(),process.exit(0));try{h(t);}catch(l){throw l instanceof a$1&&(f.error(`
384
384
  \u274C ${l.message}`),l.details&&f.warn(`\u{1F4A1} ${l.details}
385
- `),process.exit(1)),l}let a$2=!!e$1.template,i$2;a$2||(e$1.here?i$2=process.cwd():e$1.output?i$2=b.resolve(e$1.output):i$2=await i([],{hasYes:e$1.yes}));let c=a$2?b.resolve(process.cwd(),t):g(t,{outputParent:i$2});if(vt=c,!e$1.dryRun){a$2||await I__default.ensureDir(b.dirname(c));let l=a$2?void 0:i$1(t);(!a$2&&h$1(l,c,{outputParent:i$2})&&l&&await I__default.pathExists(l)||await I__default.pathExists(c))&&(f.error(`
385
+ `),process.exit(1)),l}let a$2=!!e$1.template,i$2;a$2||(e$1.here?i$2=process.cwd():e$1.output?i$2=b.resolve(e$1.output):i$2=await i([],{hasYes:e$1.yes}));let c=a$2?b.resolve(process.cwd(),t):g(t,{outputParent:i$2});if(vt=c,!e$1.dryRun){a$2||await O__default.ensureDir(b.dirname(c));let l=a$2?void 0:i$1(t);(!a$2&&h$1(l,c,{outputParent:i$2})&&l&&await O__default.pathExists(l)||await O__default.pathExists(c))&&(f.error(`
386
386
  \u274C Directory "${t}" already exists`),l&&l!==c&&console.log(s.gray(` Found at: ${l}`)),console.log(s.cyan(`
387
387
  \u{1F4A1} Choose a different name or delete the existing directory.
388
388
  `)),process.exit(1));}if(e$1.dryRun){console.log(s.cyan(`
389
389
  \u{1F50D} Dry-run mode - showing what would be created:
390
390
  `)),console.log(s.white("\u{1F4C2} Path:"),c),console.log(s.white("\u{1F4E6} Type:"),a$2?`Project (${e$1.template})`:"Workspace"),console.log();return}if(!e$1.yes&&!a$2?await b$4([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"Workspai User"}]):e$1.yes&&console.log(s.gray(`Using default values (--yes flag)
391
- `)),a$2){let l=String(e$1.template||"").trim(),p=b$5(l);if(d$1(p)){let y=await es(["create","project",p,t,...e$1.skipGit?["--skip-git"]:[]]);y!==0&&process.exit(y);return}if(!!!ss(process.cwd())){let{registerWorkspaceAtPath:y}=await import('./create-7JKJDAQV.js');if(e$1.createWorkspace)await y(process.cwd(),{skipGit:e$1.skipGit,yes:e$1.yes,userConfig:o});else if(!e$1.noWorkspace)if(e$1.yes)await y(process.cwd(),{skipGit:e$1.skipGit,yes:true,userConfig:o});else {let{createWs:f}=await b$4([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);f&&await y(process.cwd(),{skipGit:e$1.skipGit,yes:false,userConfig:o});}}let d=["create","project",p,t,"--output",process.cwd()];e$1.yes&&d.push("--yes");let h=le(process.cwd()),g=!!e$1.skipInstall,k=g||!!h;g&&d.push("--skip-essentials");let C=k?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,A=await f$1(d,{cwd:process.cwd(),env:C});A!==0&&process.exit(A),h&&!e$1.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init")));let w=ss(process.cwd());if(w){let y=b.dirname(w),f$1=b.join(y,".python-version"),v=b.join(c,".python-version");try{if(await I__default.pathExists(f$1)){let u=x.readFileSync(f$1,"utf-8");x.writeFileSync(v,u.trim()+`
392
- `),f.debug(`Synced Python version ${u.trim()} from workspace to project`);}}catch(u){f.debug("Could not sync Python version from workspace:",u);}}if(!e$1.skipInstall){let y=await e(["init",c],{cwd:process.cwd()});if(y!==0&&process.exit(y),w){let f$1=b.dirname(w),v=b.join(f$1,".python-version"),u=b.join(c,".python-version");try{if(await I__default.pathExists(v)){let j=x.readFileSync(v,"utf-8");x.writeFileSync(u,j.trim()+`
393
- `),f.debug(`Re-synced Python version ${j.trim()} after init`);}}catch(j){f.debug("Could not re-sync Python version after init:",j);}}}}else {let{createProject:l}=await import('./create-7JKJDAQV.js');await l(t,{skipGit:e$1.skipGit,skipPythonEngine:e$1.skipPythonEngine,dryRun:e$1.dryRun,yes:e$1.yes,userConfig:n,installMethod:e$1.installMethod,profile:e$1.profile,parentDirectory:b.dirname(c)}),console.log(s.gray(`\u2139\uFE0F Workspace root: ${c}`)),console.log(s.gray(` Next: ${f$2(c)} && npx workspai create project`));}}catch(o){o instanceof a$1?(f.error(`
391
+ `)),a$2){let l=String(e$1.template||"").trim(),p=b$5(l);if(d$1(p)){let y=await es(["create","project",p,t,...e$1.skipGit?["--skip-git"]:[]]);y!==0&&process.exit(y);return}if(!!!ss(process.cwd())){let{registerWorkspaceAtPath:y}=await import('./create-S64IWHAP.js');if(e$1.createWorkspace)await y(process.cwd(),{skipGit:e$1.skipGit,yes:e$1.yes,userConfig:o});else if(!e$1.noWorkspace)if(e$1.yes)await y(process.cwd(),{skipGit:e$1.skipGit,yes:true,userConfig:o});else {let{createWs:f}=await b$4([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);f&&await y(process.cwd(),{skipGit:e$1.skipGit,yes:false,userConfig:o});}}let d=["create","project",p,t,"--output",process.cwd()];e$1.yes&&d.push("--yes");let w=le(process.cwd()),g=!!e$1.skipInstall,P=g||!!w;g&&d.push("--skip-essentials");let j=P?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,A=await f$1(d,{cwd:process.cwd(),env:j});A!==0&&process.exit(A),w&&!e$1.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init")));let h=ss(process.cwd());if(h){let y=b.dirname(h),f$1=b.join(y,".python-version"),k=b.join(c,".python-version");try{if(await O__default.pathExists(f$1)){let u=E.readFileSync(f$1,"utf-8");E.writeFileSync(k,u.trim()+`
392
+ `),f.debug(`Synced Python version ${u.trim()} from workspace to project`);}}catch(u){f.debug("Could not sync Python version from workspace:",u);}}if(!e$1.skipInstall){let y=await e(["init",c],{cwd:process.cwd()});if(y!==0&&process.exit(y),h){let f$1=b.dirname(h),k=b.join(f$1,".python-version"),u=b.join(c,".python-version");try{if(await O__default.pathExists(k)){let C=E.readFileSync(k,"utf-8");E.writeFileSync(u,C.trim()+`
393
+ `),f.debug(`Re-synced Python version ${C.trim()} after init`);}}catch(C){f.debug("Could not re-sync Python version after init:",C);}}}}else {let{createProject:l}=await import('./create-S64IWHAP.js');await l(t,{skipGit:e$1.skipGit,skipPythonEngine:e$1.skipPythonEngine,dryRun:e$1.dryRun,yes:e$1.yes,userConfig:n,installMethod:e$1.installMethod,profile:e$1.profile,parentDirectory:b.dirname(c)}),console.log(s.gray(`\u2139\uFE0F Workspace root: ${c}`)),console.log(s.gray(` Next: ${f$2(c)} && npx workspai create project`));}}catch(o){o instanceof a$1?(f.error(`
394
394
  \u274C ${o.message}`),o.details&&f.warn(`\u{1F4A1} ${o.details}`),f.debug("Error code:",o.code)):(f.error(`
395
- \u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{vt=null;}});Ya(ce);oi(ce);Ti(ce);ce.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{Ld({json:t.json});});ce.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:o}=await import('./analyze-UVXPRGYZ.js'),r=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(r,null,2)):o(r),r.summary.verdict==="blocked"&&process.exit(2);}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$2({operation:"analyze",code:"analyze.failed",message:o}),null,2)):console.error(s.red(`Analyze failed: ${o}`)),process.exit(1);}});$a(ce);ce.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(l){let p$1=l;for(;;){let m=p(p$1,"context.json").find(h=>x.existsSync(h));if(m)return m;let d=b.dirname(p$1);if(d===p$1)break;p$1=d;}return null}let r=o(e);function n$1(l){let p=l;for(;;){let m=b.join(p,".venv"),d=[b.join(p,".workspai","activate"),b.join(p,".rapidkit","activate")].find(g=>x.existsSync(g))??b.join(p,".workspai","activate");if(x.existsSync(d)||x.existsSync(m))return {venv:m,activateFile:d};let h=b.dirname(p);if(h===p)break;p=h;}return null}let a=n$1(e);!r&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&x.existsSync(a.activateFile)?i=a.activateFile:a&&x.existsSync(a.venv)?i=n(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$1();console.log(c?`call "${i}"`:`. "${i}"`);});ce.command(d$2.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$6({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});ce.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:o}=await import('./pipeline-IB6ILJSV.js');await o({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});ce.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let o=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(o)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let r=Zn({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-5BQ6F5L2.js'),a;try{a=await n({workspacePath:process.cwd(),mode:o,since:e.since,parallel:e.parallel===true,maxWorkers:r,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});ce.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await Qd(t,e);o!==0&&process.exit(o);});ce.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await Xd(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});o!==0&&process.exit(o);});var Tr=ce.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");Tr.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await sr({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot create failed: ${o.message}`)),process.exit(1);}});Tr.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 di({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let o of e)console.log(s.cyan(o.name)),console.log(s.gray(` ${o.createdAt} | ${o.mode} | ${o.projects.length} project(s)`)),console.log(s.gray(` ${o.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});Tr.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await pi({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.cyan(`Snapshot: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Created: ${o.manifest.createdAt}`)),console.log(s.gray(` Projects: ${o.manifest.projects.length}`)),console.log(s.gray(` Files: ${o.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${o.estimatedBytes}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot inspect failed: ${o.message}`)),process.exit(1);}});Tr.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await mi({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(o,null,2));return}o.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${o.snapshotPath}`)),console.log(s.gray(` Restored paths: ${o.restoredPaths.join(", ")}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot restore failed: ${o.message}`)),process.exit(1);}});var So=ce.command("project").description("Safe workspace project lifecycle operations");So.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{Tc({json:t.json});});So.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 jn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let o of e)console.log(s.cyan(o.projectName)),console.log(s.gray(` Archived: ${o.archivedAt}`)),console.log(s.gray(` Path: ${o.archivePath}`)),o.reason&&console.log(s.gray(` Reason: ${o.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});So.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Cn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project archive dry-run: ${o.projectName}`):s.green(`\u2714 Project archived: ${o.projectName}`)),console.log(s.gray(` From: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` To: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){let r=o.message;e.json?console.log(JSON.stringify(c$2({operation:"project archive",code:"project.archive.failed",message:r}),null,2)):console.log(s.red(`\u274C Project archive failed: ${r}`)),process.exit(1);}});So.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await ki({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project restore dry-run: ${o.projectName}`):s.green(`\u2714 Project restored: ${o.projectName}`)),console.log(s.gray(` From: ${o.archivePath}`)),console.log(s.gray(` To: ${o.projectPath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){let r=o.message;e.json?console.log(JSON.stringify(c$2({operation:"project restore",code:"project.restore.failed",message:r}),null,2)):console.log(s.red(`\u274C Project restore failed: ${r}`)),process.exit(1);}});So.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await wi({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}let r=o.action==="archive"?"archived":"deleted";console.log(o.dryRun?s.cyan(`Project ${r} dry-run: ${o.projectName}`):s.green(`\u2714 Project ${r}: ${o.projectName}`)),console.log(s.gray(` Path: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` Archive: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){let r=o.message;e.json?console.log(JSON.stringify(c$2({operation:"project delete",code:"project.delete.failed",message:r}),null,2)):console.log(s.red(`\u274C Project delete failed: ${r}`)),process.exit(1);}});ce.command(d$2.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let o=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!o.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let r=await Fd({scope:t,workspaceFlag:e.workspace});r.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),r.candidatePath&&console.log(s.gray(` Candidate: ${r.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-PGPNIS76.js'),a=await n({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});ce.command(d$2.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
395
+ \u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{vt=null;}});Za(ce);si(ce);Li(ce);ce.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{Vd({json:t.json});});ce.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:o}=await import('./analyze-EEEU3MIF.js'),r=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(r,null,2)):o(r),r.summary.verdict==="blocked"&&process.exit(2);}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$2({operation:"analyze",code:"analyze.failed",message:o}),null,2)):console.error(s.red(`Analyze failed: ${o}`)),process.exit(1);}});Ma(ce);ce.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(l){let p$1=l;for(;;){let m=p(p$1,"context.json").find(w=>E.existsSync(w));if(m)return m;let d=b.dirname(p$1);if(d===p$1)break;p$1=d;}return null}let r=o(e);function n$1(l){let p=l;for(;;){let m=b.join(p,".venv"),d=[b.join(p,".workspai","activate"),b.join(p,".rapidkit","activate")].find(g=>E.existsSync(g))??b.join(p,".workspai","activate");if(E.existsSync(d)||E.existsSync(m))return {venv:m,activateFile:d};let w=b.dirname(p);if(w===p)break;p=w;}return null}let a=n$1(e);!r&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&E.existsSync(a.activateFile)?i=a.activateFile:a&&E.existsSync(a.venv)?i=n(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$1();console.log(c?`call "${i}"`:`. "${i}"`);});ce.command(d$2.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$6({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});ce.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:o}=await import('./pipeline-LHTPE3DR.js');await o({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});ce.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let o=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(o)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let r=Zn({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-R4XRTWEM.js'),a;try{a=await n({workspacePath:process.cwd(),mode:o,since:e.since,parallel:e.parallel===true,maxWorkers:r,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});ce.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await tu(t,e);o!==0&&process.exit(o);});ce.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await ou(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});o!==0&&process.exit(o);});var Tr=ce.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");Tr.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await sr({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot create failed: ${o.message}`)),process.exit(1);}});Tr.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 gi({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let o of e)console.log(s.cyan(o.name)),console.log(s.gray(` ${o.createdAt} | ${o.mode} | ${o.projects.length} project(s)`)),console.log(s.gray(` ${o.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});Tr.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await mi({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.cyan(`Snapshot: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Created: ${o.manifest.createdAt}`)),console.log(s.gray(` Projects: ${o.manifest.projects.length}`)),console.log(s.gray(` Files: ${o.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${o.estimatedBytes}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot inspect failed: ${o.message}`)),process.exit(1);}});Tr.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await hi({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(o,null,2));return}o.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${o.snapshotPath}`)),console.log(s.gray(` Restored paths: ${o.restoredPaths.join(", ")}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot restore failed: ${o.message}`)),process.exit(1);}});var So=ce.command("project").description("Safe workspace project lifecycle operations");So.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{Lc({json:t.json});});So.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 jn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let o of e)console.log(s.cyan(o.projectName)),console.log(s.gray(` Archived: ${o.archivedAt}`)),console.log(s.gray(` Path: ${o.archivePath}`)),o.reason&&console.log(s.gray(` Reason: ${o.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});So.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Cn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project archive dry-run: ${o.projectName}`):s.green(`\u2714 Project archived: ${o.projectName}`)),console.log(s.gray(` From: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` To: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){let r=o.message;e.json?console.log(JSON.stringify(c$2({operation:"project archive",code:"project.archive.failed",message:r}),null,2)):console.log(s.red(`\u274C Project archive failed: ${r}`)),process.exit(1);}});So.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await bi({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project restore dry-run: ${o.projectName}`):s.green(`\u2714 Project restored: ${o.projectName}`)),console.log(s.gray(` From: ${o.archivePath}`)),console.log(s.gray(` To: ${o.projectPath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){let r=o.message;e.json?console.log(JSON.stringify(c$2({operation:"project restore",code:"project.restore.failed",message:r}),null,2)):console.log(s.red(`\u274C Project restore failed: ${r}`)),process.exit(1);}});So.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Pi({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}let r=o.action==="archive"?"archived":"deleted";console.log(o.dryRun?s.cyan(`Project ${r} dry-run: ${o.projectName}`):s.green(`\u2714 Project ${r}: ${o.projectName}`)),console.log(s.gray(` Path: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` Archive: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){let r=o.message;e.json?console.log(JSON.stringify(c$2({operation:"project delete",code:"project.delete.failed",message:r}),null,2)):console.log(s.red(`\u274C Project delete failed: ${r}`)),process.exit(1);}});ce.command(d$2.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let o=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!o.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let r=await Gd({scope:t,workspaceFlag:e.workspace});r.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),r.candidatePath&&console.log(s.gray(` Candidate: ${r.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-4NNUDNGZ.js'),a=await n({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});ce.command(d$2.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
396
396
  workspace run <stage> \u2014 fleet stage execution across discovered projects
397
397
  stages: init | test | build | start | <custom-from-context>
398
398
  workspace explain|why \u2014 blocker/project narrative (--write for artifact)
399
399
  workspace trace \u2014 diff \u2192 blast radius \u2192 gates narrative (--from <diff>)
400
- workspace mcp serve \u2014 read-mostly stdio MCP bridge over workspace evidence`).option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--output <file>","Output file path for workspace share/export artifacts").option("--from <file>","Input workspace model snapshot/report for workspace diff").option("--from-impact <file>","Input workspace impact report for workspace verify (defaults to last-run impact)").option("--include-paths","Include absolute paths in workspace share bundle").option("--write","Write workspace intelligence artifact to .workspai/reports").option("--include-evidence","Read status metadata from referenced evidence reports").option("--scan-depth <count>","Observable project discovery depth for large monorepos").option("--limit <count>","Bound graph search results (default 12, maximum 100)").option("--cache","Reuse cached workspace model when inputs are unchanged (keyed by inputsHash)").option("--incremental","Rebuild only changed projects and re-infer only their incident graph edges (graph-aware)").option("--once","For workspace watch: do the initial in-memory build and exit (no watcher)").option("--for-agent [agent]","Build an agent-ready workspace context pack").option("--agent-sync","After --write on context, sync cross-tool agent grounding files (AGENTS.md, Copilot, Cursor, Claude)").option("--no-agent-sync","Skip automatic agent grounding sync after context --write").option("--target <targets>","Agent customization targets for agent-sync (all|vscode|agents,copilot,cursor,claude,codex,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").option("--refresh-context","Rebuild workspace-context-agent.json during agent-sync").option("--experimental-hooks","Generate advisory VS Code agent hook design files during enterprise agent-sync").option("--hydrate-prompts","Hydrate matching Copilot prompt files with workspace-specific verification steps during agent-sync").option("--scope <scope>","Scope workspace intelligence output, e.g. project:<name>").option("--no-doctor","Exclude doctor evidence in workspace share bundle").option("--no-blueprint","Exclude reproducibility blueprint from workspace share bundle").option("--include-env","Include .env/private key files in workspace export archive").option(f$3.archiveCompression.signature,f$3.archiveCompression.description).option(f$3.maxDownloadSize.signature,f$3.maxDownloadSize.description).option(f$3.maxExpandedSize.signature,f$3.maxExpandedSize.description).option(f$3.downloadTimeoutMs.signature,f$3.downloadTimeoutMs.description).option(f$3.allowPrivateNetwork.signature,f$3.allowPrivateNetwork.description).option("--force","Overwrite an existing hydrate output directory").option("--refresh","Publish workspace registry summary before reading status").option("--dry-run","Preview hydrate without writing files").option("--affected","Run only affected projects (requires git diff context)").option("--blast-radius","Include downstream dependents from workspace dependency graph").option("--since <ref>","Git ref for affected calculation (default: HEAD~1)").option("--parallel","Run project stages in parallel").option("--max-workers <count>","Maximum parallel workers (default: min(4, selected))").option("--continue-on-error","Continue running remaining projects after a failure").option("--reuse-passed","Skip projects that already passed this stage in workspace-run-last.json").option("--json","Emit machine-readable JSON output").option("--ci","Build CI-oriented command plans where supported").option("--strict","Return non-zero exit on warn/fail gate outcomes").option("--no-gates","Skip doctor/readiness pre-run gates").addHelpText("after",`
400
+ workspace mcp serve \u2014 read-mostly stdio MCP bridge over workspace evidence`).option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--output <file>","Output file path for workspace share/export artifacts").option("--from <file>","Input workspace model snapshot/report for workspace diff").option("--from-impact <file>","Input workspace impact report for workspace verify (defaults to last-run impact)").option("--include-paths","Include absolute paths in workspace share bundle").option("--write","Write workspace intelligence artifact to .workspai/reports").option("--include-evidence","Read status metadata from referenced evidence reports").option("--scan-depth <count>","Observable project discovery depth for large monorepos").option("--limit <count>","Bound graph search results (default 12, maximum 100)").option("--cache","Reuse cached workspace model when inputs are unchanged (keyed by inputsHash)").option("--incremental","Rebuild only changed projects and re-infer only their incident graph edges (graph-aware)").option("--once","For workspace watch: do the initial in-memory build and exit (no watcher)").option("--graph-stream","For workspace watch: emit workspace-graph-stream.v1 snapshot/delta NDJSON").option("--for-agent [agent]","Build an agent-ready workspace context pack").option("--agent-sync","After --write on context, sync cross-tool agent grounding files (AGENTS.md, Copilot, Cursor, Claude)").option("--no-agent-sync","Skip automatic agent grounding sync after context --write").option("--target <targets>","Agent customization targets for agent-sync (all|vscode|agents,copilot,cursor,claude,codex,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").option("--refresh-context","Rebuild workspace-context-agent.json during agent-sync").option("--experimental-hooks","Generate advisory VS Code agent hook design files during enterprise agent-sync").option("--hydrate-prompts","Hydrate matching Copilot prompt files with workspace-specific verification steps during agent-sync").option("--scope <scope>","Scope workspace intelligence output, e.g. project:<name>").option("--no-doctor","Exclude doctor evidence in workspace share bundle").option("--no-blueprint","Exclude reproducibility blueprint from workspace share bundle").option("--include-env","Include .env/private key files in workspace export archive").option(f$3.archiveCompression.signature,f$3.archiveCompression.description).option(f$3.maxDownloadSize.signature,f$3.maxDownloadSize.description).option(f$3.maxExpandedSize.signature,f$3.maxExpandedSize.description).option(f$3.downloadTimeoutMs.signature,f$3.downloadTimeoutMs.description).option(f$3.allowPrivateNetwork.signature,f$3.allowPrivateNetwork.description).option("--force","Overwrite an existing hydrate output directory").option("--refresh","Publish workspace registry summary before reading status").option("--dry-run","Preview hydrate without writing files").option("--affected","Run only affected projects (requires git diff context)").option("--blast-radius","Include downstream dependents from workspace dependency graph").option("--since <ref>","Git ref for affected calculation (default: HEAD~1)").option("--parallel","Run project stages in parallel").option("--max-workers <count>","Maximum parallel workers (default: min(4, selected))").option("--continue-on-error","Continue running remaining projects after a failure").option("--reuse-passed","Skip projects that already passed this stage in workspace-run-last.json").option("--json","Emit machine-readable JSON output").option("--ci","Build CI-oriented command plans where supported").option("--strict","Return non-zero exit on warn/fail gate outcomes").option("--no-gates","Skip doctor/readiness pre-run gates").addHelpText("after",`
401
401
  Workspace Actions:
402
402
  Discovery & registry list | sync | registry | foundation
403
403
  Intelligence loop model | snapshot | diff | impact | verify | context
404
- Intelligence consumers agent-sync | remediation-plan | explain | why | trace | feedback | mcp
404
+ Intelligence consumers agent-sync | remediation-plan | explain | why | trace | feedback | eval | mcp
405
405
  Graph & observation graph | watch
406
406
  Contracts & policy contract | policy
407
407
  Portability share | export | archive | hydrate | import
408
408
  Fleet lifecycle run | init
409
409
 
410
410
  Use "workspai commands --json" for the contract-backed runtime inventory.
411
- See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,o,r){let n=this.opts(),a=w=>{let y=n.workspace?b.resolve(n.workspace):null,f=y??a$4(process.cwd())??le(process.cwd());(!f||!qe(f))&&((n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$2({operation:`workspace ${w}`,code:"workspace.root.required",message:"Not inside a Workspai workspace. Run from a workspace directory or pass --workspace <path>.",context:{cwd:b.resolve(process.cwd()),...y?{requestedWorkspace:y}:{}}}),null,2)),process.exit(1)),console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run from a workspace directory or pass --workspace <path>.")),process.exit(1));let v=b.resolve(process.cwd()),u=b.resolve(f);return v!==u&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${f} for "${w}" (current directory: ${v}).`)),f},i=w=>process.argv.includes(w),c=w=>Se(process.argv,w),l=()=>n.output||c("--output"),p=()=>{if(!n.scanDepth)return;let w=Number.parseInt(n.scanDepth,10);return Number.isFinite(w)?w:void 0},m=(w,y)=>{if(!w)return;let f=w.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!f)throw new Error(`${y} must be a byte size such as 500gb or 2tb.`);let v={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},u=Number(f[1])*v[f[2]||"b"];if(!Number.isSafeInteger(Math.floor(u))||u<=0)throw new Error(`${y} is outside the supported numeric range.`);return Math.floor(u)},d=()=>{let w=n.downloadTimeoutMs,y=w===void 0?void 0:Number.parseInt(w,10);if(y!==void 0&&(!Number.isFinite(y)||y<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:m(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:m(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:y,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},h={list:["--json"],intelligence:["--workspace","--json","--strict","--for-agent"],model:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--cache","--incremental","--write","--strict"],"agent-sync":["--workspace","--json","--scope","--for-agent","--write","--dry-run","--strict","--preset","--refresh-context","--refresh","--target","--experimental-hooks","--hydrate-prompts"],"remediation-plan":["--workspace","--json","--include-paths","--ci","--write"],context:["--workspace","--json","--for-agent","--scope","--include-evidence","--scan-depth","--write","--agent-sync","--no-agent-sync","--preset","--target","--strict"],snapshot:["--workspace","--json","--include-paths","--include-evidence","--scan-depth"],diff:["--workspace","--json","--from","--include-paths","--include-evidence","--scan-depth","--strict"],impact:["--workspace","--json","--from","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],verify:["--workspace","--json","--from-impact","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],graph:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--scope"],watch:["--workspace","--json","--once","--scan-depth"],sync:["--workspace","--json"],registry:["--workspace","--json","--refresh"],foundation:["--workspace","--json","--force"],policy:["--workspace","--json"],contract:["--workspace","--json","--output","--force","--strict"],share:["--workspace","--json","--output","--include-paths","--no-doctor","--no-blueprint"],export:["--workspace","--json","--output","--include-env","--archive-compression"],archive:["--json","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],hydrate:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],import:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],run:["--workspace","--json","--scope","--affected","--blast-radius","--since","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],explain:["--workspace","--json","--scope","--write"],why:["--workspace","--json","--scope","--write"],trace:["--workspace","--json","--from","--write"],feedback:["--workspace","--json"],mcp:["--workspace","--json"],init:["--workspace","--json","--scope","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"]},g=new Set(Object.values(h).flatMap(w=>[...w])),k=new Set(process.argv.slice(2).filter(w=>w.startsWith("--")).map(w=>w.split("=",1)[0]).filter(w=>g.has(w))),C=h[t],A=C?[...k].filter(w=>!C.includes(w)):[];if(A.length>0){let w=`${A.join(", ")} ${A.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||k.has("--json")?console.log(JSON.stringify(c$2({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:w,exitCode:2,context:{action:t,unsupportedFlags:A,allowedFlags:C}}),null,2)):(console.log(s.red(`\u274C ${w}`)),console.log(s.gray(` Allowed flags: ${C.join(", ")||"none"}`))),process.exit(2);}if((Ki(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$3({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:w}=await import('./workspace-H3QXBFGB.js');await w({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 w=a("intelligence"),{runWorkspaceIntelligenceChain:y}=await import('./workspace-intelligence-runner-LVALAZY7.js'),f=await y({workspacePath:w,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(f,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${f.status}`));for(let v of f.stages)console.log(s.gray(` ${v.id}: ${v.status} \u2014 ${v.message}`));console.log(s.gray(` Evidence: ${f.artifactPath}`));}f.exitCode!==0&&process.exit(f.exitCode);}else if(t==="model"){let w=a("model"),{buildWorkspaceModelCached:y,buildWorkspaceModelIncremental:f,writeWorkspaceModel:v}=await import('./workspace-model-S33CIB2R.js'),u=n.incremental===true||i("--incremental"),j=n.cache===true||i("--cache")||u,P={workspacePath:w,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p(),strict:n.strict===true||i("--strict")},E,S;if(u){let W=await f(P);E=W.model,S=W.mode;}else {let W=await y({...P,cache:j});E=W.model,S=W.cache;}let $;(n.write===true||i("--write"))&&($=await v(E,w));let L=(n.strict===true||i("--strict"))&&E.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...E,...$?{outputPath:$}:{}},null,2)),L&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${E.workspace.name}`)),u?console.log(s.gray(` Build: ${S} (incremental)`)):j&&console.log(s.gray(` Cache: ${S}`)),console.log(s.gray(` Projects: ${E.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${E.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${E.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${E.identity.workspaceType}`)),console.log(s.gray(` Validation: ${E.validation?.status??"unknown"} (${E.validation?.errors??0} error, ${E.validation?.warnings??0} warning)`)),console.log($?s.gray(` Written: ${$}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),L&&process.exit(1);}else if(t==="agent-sync"){let w=a("agent-sync"),{syncWorkspaceAgentGrounding:y,parseAgentGroundingTargets:f}=await import('./workspace-agent-sync-C7SG2Z5W.js'),v=n.strict===true||i("--strict"),u=n.write===true||i("--write"),j=i("--dry-run"),P=await y({workspacePath:w,scope:n.scope,agent:n.forAgent,write:u&&!j,dryRun:j,strict:v,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:f(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),staleAfterHours:24});if(n.json)console.log(JSON.stringify(P,null,2));else {console.log(s.green(`\u2714 Agent grounding ${u&&!j?"synced":"planned"}`)),console.log(s.gray(` Index: ${P.indexPath}`)),P.contextPath&&console.log(s.gray(` Context: ${P.contextPath}`)),P.blockers.length>0&&console.log(s.yellow(` Blockers: ${P.blockers.slice(0,3).join(" \xB7 ")}`));let E=u&&!j?P.writtenFiles:P.skippedFiles;if(E.length>0&&console.log(s.gray(` Files: ${E.join(", ")}`)),P.strictViolations.length>0)for(let S of P.strictViolations)console.log(s.red(`\u274C ${S}`));}v&&P.strictViolations.length>0&&process.exit(1);}else if(t==="remediation-plan"){let w=a("remediation-plan"),{buildArtifactRemediationPlan:y,writeArtifactRemediationPlan:f}=await import('./artifact-remediation-plan-EPALZ2LC.js'),v=await y({workspacePath:w,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),u;if((n.write===true||i("--write"))&&(u=await f(v,w)),n.json===true||i("--json")){console.log(JSON.stringify(b$7("workspace remediation-plan",v,u),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${v.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${v.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${v.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${v.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${v.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${v.summary.risk.safe}, guarded=${v.summary.risk.guarded}, invasive=${v.summary.risk.invasive}`));for(let j of v.actions.slice(0,8))console.log(s.gray(` \u2022 ${j.cardId}: ${j.title} (${j.mode}, ${j.risk})`));v.actions.length>8&&console.log(s.gray(` \u2026 ${v.actions.length-8} more action(s)`)),console.log(u?s.gray(` Written: ${u}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let w=a("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:y,writeWorkspaceAgentContext:f}=await import('./workspace-context-BKQBKA4C.js'),v=n.strict===true||i("--strict"),u=await y({workspacePath:w,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p(),strict:false}),j,P;if((n.write===true||i("--write"))&&(j=await f(u,w),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:$,parseAgentGroundingTargets:L}=await import('./workspace-agent-sync-C7SG2Z5W.js');if(P=await $({workspacePath:w,scope:n.scope,agent:u.agent,write:true,refreshContext:false,strict:v,preset:n.preset==="minimal"?"minimal":"enterprise",targets:L(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${P.writtenFiles.length} file(s) updated`)),v&&P.strictViolations.length>0){for(let W of P.strictViolations)console.log(s.red(`\u274C ${W}`));process.exit(1);}}let E=v&&u.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...u,...j?{outputPath:j}:{},...P?{agentGroundingSync:P}:{}},null,2)),E&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${u.workspace.name}`)),console.log(s.gray(` Agent: ${u.agent}`)),console.log(s.gray(` Scope: ${u.scope.activeProject??u.scope.requested}`)),console.log(s.gray(` Projects included: ${u.projects.length}`)),console.log(s.gray(` Safe commands: ${u.safeCommands.length}`)),console.log(s.gray(` Validation: ${u.validation.status} (${u.validation.errors} error, ${u.validation.warnings} warning)`)),console.log(j?s.gray(` Written: ${j}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),E){for(let S of u.validation.issues)console.log(s.red(`\u274C ${S.severity}:${S.code}:${S.target}`));process.exit(1);}}else if(t==="snapshot"){let w=a("snapshot"),{buildWorkspaceModelSnapshot:y,writeWorkspaceModelSnapshot:f}=await import('./workspace-intelligence-VKDL3H2J.js'),v=await y({workspacePath:w,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()}),u=await f(v,w);if(n.json){console.log(JSON.stringify(b$7("workspace snapshot",v,u),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${v.model.workspace.name}`)),console.log(s.gray(` Hash: ${v.modelHash}`)),console.log(s.gray(` Projects: ${v.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${v.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${u}`));}else if(t==="diff"){let w=a("diff"),y=n.from||e;y||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:w},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:f,writeWorkspaceModelDiff:v}=await import('./workspace-intelligence-VKDL3H2J.js'),u;try{u=await f({workspacePath:w,fromPath:y,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()});}catch(E){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:E.message,context:{workspacePath:w,fromPath:y},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),E}let j=await v(u,w);if(n.json){console.log(JSON.stringify(b$7("workspace diff",u,j),null,2));return}let P=u.summary.changed?s.yellow:s.green;console.log(P(`\u2714 Workspace model diff: ${u.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${u.fromRef}`)),console.log(s.gray(` Added projects: ${u.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${u.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${u.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${u.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${u.summary.validationChanges}`)),u.git?.available&&console.log(s.gray(` Git: ${u.git.dirty?"dirty":"clean"} (${u.summary.gitChangedFiles} mapped change(s))`));for(let E of u.changes.slice(0,12))console.log(s.gray(` \u2022 ${E.type} ${E.target}: ${E.message}`));u.changes.length>12&&console.log(s.gray(` \u2026 ${u.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${j}`));}else if(t==="impact"){let w=a("impact"),y=n.from||e;y||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:w},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:f,writeWorkspaceImpact:v}=await import('./workspace-intelligence-VKDL3H2J.js'),u;try{u=await f({workspacePath:w,fromPath:y,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()});}catch(E){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:E.message,context:{workspacePath:w,fromPath:y},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)),E}let j=await v(u,w);if(n.json){console.log(JSON.stringify(b$7("workspace impact",u,j),null,2));return}let P=u.summary.risk==="critical"||u.summary.risk==="high"?s.red:u.summary.risk==="medium"?s.yellow:s.green;console.log(P(`\u2714 Workspace impact: ${u.summary.risk}`)),console.log(s.gray(` From: ${u.fromRef}`)),console.log(s.gray(` Affected projects: ${u.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${u.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${u.summary.recommendedCommands}`));for(let E of u.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${E.title}: ${E.summary}`));u.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${u.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${j}`));}else if(t==="verify"){let w=a("verify"),{buildWorkspaceVerify:y,writeWorkspaceVerify:f,evaluateWorkspaceVerifyGate:v}=await import('./workspace-verify-ZGH3NXAH.js'),u=await y({workspacePath:w,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()}),j=await f(u,w),P=v(u,{strict:n.strict===true||i("--strict")}),E=P.exitCode,{recordWorkspaceHistory:S,historyEntryFromVerify:$}=await import('./workspace-history-C6OP3IAQ.js');if(await S(w,$(u,P.passed)),n.json){console.log(JSON.stringify(b$7("workspace verify",{...u,gate:P},j),null,2)),E!==0&&process.exit(E);return}let L=u.summary.verdict==="ready"?s.green:u.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(L(`\u2714 Workspace verify: ${u.summary.verdict}`)),console.log(s.gray(` Freshness: ${u.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${u.impact.risk}`)),console.log(s.gray(` Steps: ${u.steps.length}`)),console.log(s.gray(` Passed ${u.summary.stepsPassed}, warn ${u.summary.stepsWarn}, failed ${u.summary.stepsFailed}, missing ${u.summary.stepsMissing}`));for(let W of u.steps.slice(0,10))console.log(s.gray(` \u2022 ${W.id}: ${W.status} \u2014 ${W.message}`));if(u.steps.length>10&&console.log(s.gray(` \u2026 ${u.steps.length-10} more step(s)`)),u.policyViolations.length>0){console.log(s.gray(` Policy (${u.policyMode}): ${u.policyViolations.length} violation(s)`));for(let W of u.policyViolations.slice(0,5)){let N=W.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${N} [${W.source}] ${W.code}: ${W.message}`);}}console.log(s.gray(` Gate (${P.mode}): ${P.passed?"passed":"blocked"}`));for(let W of P.reasons.slice(0,5))console.log(s.red(` \u2717 ${W}`));console.log(s.gray(` Written: ${j}`)),E!==0&&process.exit(E);}else if(t==="graph"){let w=a("graph"),{buildWorkspaceModel:y}=await import('./workspace-model-S33CIB2R.js'),{buildGraphEmit:f,renderGraphDot:v,renderGraphMermaid:u,explainGraphNode:j}=await import('./workspace-graph-2A5THUCI.js'),P=await y({workspacePath:w,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()}),E=P.graph,S=(e||"emit").toLowerCase();E||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:S,result:"error",workspacePath:w,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let $=async()=>{let{buildWorkspaceKnowledgeGraph:N}=await import('./workspace-knowledge-graph-FE2NTZKV.js'),{hashWorkspaceModel:R}=await import('./workspace-model-hash-MHXK5MEI.js'),{readWorkspaceContract:H}=await import('./workspace-contract-RPQQBQXR.js'),G=null;try{G=(await H({workspacePath:w})).contract;}catch{}return N({workspacePath:w,workspace:{name:P.workspace.name,...P.workspace.profile?{profile:P.workspace.profile}:{}},projects:P.projects.map(D=>({id:D.name,path:D.path,...D.absolutePath?{absolutePath:D.absolutePath}:{},runtime:D.runtime,framework:D.framework,...D.kit?{kit:D.kit}:{}})),projectTopology:E,contract:G,now:new Date(P.generatedAt),source:{kind:"workspace-model",artifact:a$5.model,hashAlgorithm:"sha256",hash:R(P)}})};if(S==="dot"){console.log(v(E));return}if(S==="mermaid"){console.log(u(E));return}if(S==="explain"){let N=(n.scope?.replace(/^project:/,"")||o||"").trim();N||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:w,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let R=j(E,N);if(n.json){console.log(JSON.stringify(R,null,2)),R.found||process.exit(1);return}R.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${N}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${R.project}`)),R.centrality&&console.log(s.gray(` Centrality: fanIn ${R.centrality.fanIn}, fanOut ${R.centrality.fanOut}, reach ${R.centrality.reach}, betweenness ${R.centrality.betweenness}${R.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${R.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${R.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${R.transitiveDependents.length}`));for(let H of R.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${H.id} (d${H.distance}, via ${H.via??"\u2014"})`));return}if(S==="entities"){let N=await $(),{queryKnowledgeEntities:R}=await import('./workspace-knowledge-graph-query-VOSPPH4W.js'),H=R(N,o);if(n.json){console.log(JSON.stringify({schemaVersion:N.schemaVersion,generatedAt:N.generatedAt,kind:o??null,count:H.length,entities:H},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${o?`: ${o}`:""}`)),console.log(s.gray(` Count: ${H.length}`));for(let G of H)console.log(s.gray(` \u2022 ${G.kind}: ${G.label} [${G.id}]`));return}if(S==="search"||S==="benchmark"){let N=(o||"").trim();N||(console.log(s.red(`\u274C workspace graph ${S} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${S} "authentication endpoint" --json`)),process.exit(1));let R=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(R)||R<1||R>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let H=await $();if(S==="benchmark"){let{buildWorkspaceGraphTokenEfficiencyReport:q}=await import('./workspace-graph-token-efficiency-CFGFCJ5V.js'),ee=await q({workspacePath:w,graph:H,query:N,limit:R});n.json?console.log(JSON.stringify(ee,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${N}`)),console.log(s.gray(` Estimated tokens: ${ee.corpus.estimatedTokens} corpus \u2192 ${ee.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${ee.savings.reductionRatio}\xD7 (${ee.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${ee.retrieval.matchCount}`)),console.log(s.yellow(` ${ee.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:G}=await import('./workspace-knowledge-graph-query-VOSPPH4W.js'),D=G(H,{query:N,limit:R});if(n.json)console.log(JSON.stringify(D,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${N}`)),console.log(s.gray(` ${D.entities.length}/${D.totalMatches} match(es)${D.truncated?" (bounded)":""}`));for(let q of D.entities)console.log(s.gray(` \u2022 ${q.kind}: ${q.label} [${q.id}]`));}return}if(S==="evidence"){let N=(o||"").trim();N||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let R=await $(),{queryKnowledgeEvidence:H}=await import('./workspace-knowledge-graph-query-VOSPPH4W.js'),G=H(R,N);if(n.json)console.log(JSON.stringify(G,null,2));else if(G.found){console.log(s.green(`\u2714 Graph evidence: ${N}`));for(let D of G.proofs)console.log(s.gray(` \u2022 ${D.artifact}${D.pointer?`#${D.pointer}`:""} [${D.provider}/${D.trust}/${D.confidence}]`));}else {console.log(s.red(G.candidates.length>0?`\u274C Graph query is ambiguous: ${N}`:`\u274C Graph entity or relation not found: ${N}`));for(let D of G.candidates.slice(0,10))console.log(s.gray(` \u2022 ${D}`));}G.found||process.exit(1);return}if(S==="path"){let N=(o||"").trim(),R=(r||"").trim();(!N||!R)&&(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 H=await $(),{queryKnowledgePath:G}=await import('./workspace-knowledge-graph-query-VOSPPH4W.js'),D=G(H,N,R);if(n.json)console.log(JSON.stringify(D,null,2));else if(D.found){console.log(s.green(`\u2714 Graph proof path: ${N} \u2192 ${R}`));for(let q of D.hops)console.log(s.gray(` \u2022 ${q.from} ${q.direction==="forward"?"\u2192":"\u2190"} ${q.to} [${q.kind}]`));console.log(s.gray(` Proofs: ${D.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${N} and ${R}.`));D.found||process.exit(1);return}if(S==="overlay"){let N=(n.from||o||"").trim();N||(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 R=b.resolve(w,N),H;try{H=JSON.parse(await I__default.readFile(R,"utf8"));}catch(Ae){console.log(s.red(`\u274C Could not read the base knowledge graph: ${Ae instanceof Error?Ae.message:String(Ae)}`)),process.exit(1);}let G=H&&typeof H=="object"?H:{},D=G.graph,q=D&&typeof D=="object"?D:{},ee=G.schemaVersion===b$8.knowledgeGraph?G:G.knowledgeGraph??q.knowledgeGraph;(!ee||typeof ee!="object"||ee.schemaVersion!==b$8.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${b$8.knowledgeGraph} document.`)),process.exit(1));let Re=await $(),{buildWorkspaceKnowledgeGraphChangeOverlay:de}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),ne=de(ee,Re);if(n.json){console.log(JSON.stringify(ne,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${N}`)),console.log(s.gray(` Risk: ${ne.summary.risk}`)),console.log(s.gray(` Entities: +${ne.summary.entityAdds} -${ne.summary.entityRemovals} ~${ne.summary.entityChanges}`)),console.log(s.gray(` Relations: +${ne.summary.relationAdds} -${ne.summary.relationRemovals} ~${ne.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${ne.summary.proofAdds} -${ne.summary.proofRemovals} ~${ne.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${ne.summary.impactedEntities} entities \xB7 ${ne.summary.changedArtifacts} proof artifacts`));return}let L=f(E),W=await $();if(n.json){console.log(JSON.stringify({...L,knowledgeGraph:W},null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${L.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${L.graph.stats.edgeCount} (inferred ${L.graph.stats.inferredEdges}, contract ${L.graph.stats.contractEdges}, manual ${L.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${L.integrity.ok?"ok":"issues"} (cycles ${L.integrity.stats.cycleCount}, dangling ${L.integrity.stats.danglingCount}, orphans ${L.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${L.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${W.quality.entityCount} entities \xB7 ${W.quality.relationCount} relations \xB7 ${W.quality.proofCount} proofs \xB7 ${W.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 | workspace graph mermaid"));}else if(t==="watch"){let w=a("watch"),{runWorkspaceWatch:y}=await import('./workspace-watch-EVBJTMV7.js'),f=n.once===true||i("--once"),v=n.json===true,u=new AbortController,j=()=>u.abort();process.once("SIGINT",j),process.once("SIGTERM",j),v||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await y({workspacePath:w,once:f,signal:u.signal,buildOptions:{workspacePath:w,observableScanDepth:p()},onProgress:P=>{v||console.error(s.gray(` ${P}`));},emit:P=>{if(v){console.log(JSON.stringify(P));return}if(P.kind==="ready"){console.log(s.gray(` Ready: ${P.graph.nodeCount} nodes, ${P.graph.edgeCount} edges (hash ${P.modelHash.slice(0,12)})`));return}if(P.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${P.error??"unknown error"}`));return}if(P.kind==="unchanged"){console.log(s.gray(` No structural change (${P.mode}, ${P.durationMs}ms)`));return}let E=[];P.changedProjects.length>0&&E.push(`changed: ${P.changedProjects.join(", ")}`),P.addedProjects.length>0&&E.push(`added: ${P.addedProjects.join(", ")}`),P.removedProjects.length>0&&E.push(`removed: ${P.removedProjects.join(", ")}`),P.graph.edgesAdded.length>0&&E.push(`+${P.graph.edgesAdded.length} edges`),P.graph.edgesRemoved.length>0&&E.push(`-${P.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${P.mode}, ${P.durationMs}ms): ${E.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",j),process.removeListener("SIGTERM",j),!v&&!f&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let w=a("sync"),{syncWorkspaceProjects:y}=await import('./workspace-H3QXBFGB.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${b.basename(w)}`));let f=await y(w,n.json===true);await ds(w,{silent:n.json===true});let{readWorkspaceRegistrySummary:v}=await import('./workspace-registry-summary-A3YDL63D.js'),u=await v(w);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:w,registry:f,contractSynced:true,registrySummary:u},null,2));}else if(t==="registry"){let w=a("registry"),y=e||"status";y!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${y}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:f,resolveWorkspaceRegisteredProjects:v}=await import('./workspace-registry-summary-A3YDL63D.js'),u=await f(w);if(n.json){console.log(JSON.stringify(u,null,2));return}let j=await v(w);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${u.authority}`)),console.log(s.gray(` Projects: ${u.projectCount}`)),console.log(s.gray(` Summary: ${u.registrySummaryPath}`)),j.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let w=a("foundation"),y=e||"ensure";y!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${y}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:f}=await import('./workspace-foundation-5OOJEO2D.js'),v=await f(w,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(v,null,2));return}v.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${v.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let w=a("policy"),y=await su(w,e,o,r,n.json===true||i("--json"));y!==0&&process.exit(y);}else if(t==="contract"){let w=a("contract"),{buildWorkspaceContractGraph:y,readWorkspaceContract:f,verifyWorkspaceContract:v,writeWorkspaceContract:u,WORKSPACE_CONTRACT_PATH:j}=await import('./workspace-contract-RPQQBQXR.js'),P=e||"inspect",E=l();try{if(P==="init"){let S=await u({workspacePath:w,outputPath:E,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(S,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${S.contractPath}`)),console.log(s.gray(` Projects: ${S.contract.projects.length}`));return}if(P==="inspect"){let S=await f({workspacePath:w,contractPath:E});if(n.json){console.log(JSON.stringify(S,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${S.contractPath}`)),console.log(s.gray(` Workspace: ${S.contract.workspace.name}`)),console.log(s.gray(` Projects: ${S.contract.projects.length}`)),console.log(s.gray(` Schema: v${S.contract.schemaVersion}`));return}if(P==="verify"){let S=await v({workspacePath:w,contractPath:E,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:$}=await import('./workspace-contract-RPQQBQXR.js'),L=await $({workspacePath:w,result:S});if(n.json)console.log(JSON.stringify({...S,evidencePath:L},null,2));else {let W=S.status==="passed"?s.green:s.red;console.log(W(`\u2714 Workspace contract verification ${S.status}: ${S.contractPath}`)),console.log(s.gray(` Projects: ${S.projectCount}`));for(let N of S.checks){let R=N.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${R} ${N.id}: ${N.message}`));}for(let N of S.violations)console.log(s.gray(` Violation: ${N}`));}(S.status==="failed"||S.status!=="passed"&&n.strict)&&process.exit(1);return}if(P==="graph"){let S=await y({workspacePath:w,contractPath:E});if(n.json){console.log(JSON.stringify(S,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${S.contractPath}`)),console.log(s.gray(` Workspace: ${S.graph.workspace.name}`)),console.log(s.gray(` Projects: ${S.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${S.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${S.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${S.graph.summary.relationshipEdges} (${S.graph.summary.inferredEdges} inferred, ${S.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${S.graph.summary.connectedProjects}/${S.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(S.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(S.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${S.graph.summary.orphanProjects} \xB7 Hotspots: ${S.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${S.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${S.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${S.graph.summary.entityCount} entities \xB7 ${S.graph.summary.knowledgeRelations} relations \xB7 ${S.graph.summary.proofCount} proofs \xB7 ${S.graph.summary.providerCount} providers \xB7 ${S.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${S.graph.summary.portCount}`));for(let $ of S.graph.nodes){let L=$.ports.map(N=>`${N.name}:${N.port}`).join(", ")||"none",W=$.operationalProfile?` risk=${$.operationalProfile.weight}/${$.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${$.id} (${$.runtime||"unknown"}${$.framework?`/${$.framework}`:""}) ports=${L} manifests=${$.files.manifests.length}${W}`));}for(let $ of S.graph.edges){let L=$.type==="event"?`event:${$.label}`:$.label;console.log(s.gray(` ${$.from} -> ${$.to} [${L}]`));}if(S.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let $ of S.graph.dependencyGraph.edges)console.log(s.gray(` ${$.from} -> ${$.to} [${$.kind}/${$.source}/${$.confidence}] evidence=${$.evidence.length}`));}for(let $ of S.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${$.severity}: ${$.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${P}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${j}]`)),process.exit(1);}catch(S){n.json&&(console.log(JSON.stringify({command:`workspace contract ${P}`,result:"error",workspacePath:w,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${P}.failed`,message:S.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${P} failed: ${S.message}`)),process.exit(1);}}else if(t==="share"){let w=a("share"),y=l()||e,{createWorkspaceShareBundle:f}=await import('./workspace-H3QXBFGB.js'),v=await f(w,{outputPath:y,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:w,bundlePath:v,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${v}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let w=a("export");try{let{exportWorkspaceArchive:y}=await import('./workspace-archive-P76EDIUG.js'),f=n.archiveCompression?.trim().toLowerCase()??"store";if(f!=="store"&&f!=="deflate")throw new Error("--archive-compression must be store or deflate.");let v=await y({workspacePath:w,outputPath:l()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:f});if(n.json){console.log(JSON.stringify(v,null,2));return}let u=(v.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${v.archivePath}`)),console.log(s.gray(` Files: ${v.manifest.files.length}`)),console.log(s.gray(` Size: ${u} MB`)),v.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(y){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:y.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${y.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let w=o;w||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:y,inspectWorkspaceArchive:f,verifyWorkspaceArchive:v}=await import('./workspace-archive-P76EDIUG.js');try{if(e==="inspect"){let j=await f({archivePathOrUrl:w,safety:d()});if(n.json){console.log(JSON.stringify(j,null,2));return}let P=(j.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${j.archivePath}`)),console.log(s.gray(` Workspace: ${j.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${j.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${j.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${j.fileCount}`)),console.log(s.gray(` Payload: ${P} MB`));return}if(e==="doctor"){let j=await y({archivePathOrUrl:w,strict:n.strict===true||i("--strict"),safety:d()});if(n.json)console.log(JSON.stringify(j,null,2));else {let P=j.status==="passed"?s.green:j.status==="warning"?s.yellow:s.red;console.log(P(`\u2714 Workspace archive doctor ${j.status}: ${j.archivePath}`)),console.log(s.gray(` Workspace: ${j.workspaceName}`)),console.log(s.gray(` Files: ${j.fileCount}`));for(let E of j.checks){let S=E.status==="passed"?"\u2714":E.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${S} ${E.id}: ${E.message}`));}for(let E of j.recommendedActions)console.log(s.gray(` Next: ${E}`));}(j.status==="failed"||j.status==="warning"&&n.strict)&&process.exit(1);return}let u=await v({archivePathOrUrl:w,requireChecksums:n.strict===true||i("--strict"),safety:d()});if(n.json)console.log(JSON.stringify(u,null,2));else if(u.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${u.archivePath}`)),console.log(s.gray(` Files: ${u.verifiedFiles}/${u.fileCount}`));else {let j=u.status==="failed"?s.red:s.yellow;console.log(j(`\u274C Workspace archive verification ${u.status}: ${u.archivePath}`)),u.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${u.missingArchiveEntries.join(", ")}`)),u.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${u.extraArchiveEntries.join(", ")}`)),u.mismatches.length&&console.log(s.gray(` Mismatches: ${u.mismatches.map(P=>P.path).join(", ")}`)),u.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${u.missingChecksumFiles.join(", ")}`));}(u.status==="failed"||u.status==="warning"&&n.strict)&&process.exit(1);}catch(u){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:w,error:{code:`workspace.archive.${e}.failed`,message:u.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${u.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let w=e;w||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.${t}.input-required`,message:`workspace ${t} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));let{hydrateWorkspaceArchive:y}=await import('./workspace-archive-P76EDIUG.js');try{let f=await y({archivePathOrUrl:w,outputPath:l(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:d()});if(n.json){console.log(JSON.stringify(f,null,2));return}console.log(s.green(f.dryRun?`\u2714 Workspace archive hydrate preview: ${f.outputPath}`:`\u2714 Workspace archive hydrated: ${f.outputPath}`)),console.log(s.gray(` Files: ${f.files.length}`)),f.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${f.manifest.workspaceName}`));}catch(f){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:w,...l()?{outputPath:l()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:f.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${f.message}`)),process.exit(1);}}else if(t==="run"){let w=a(`run ${e||""}`.trim()),y=new Set(["init","test","build","start"]),f=e?.trim()??"";f||(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)),y.has(f)||(!/^[a-z][a-z0-9_-]*$/i.test(f)||f==="dev"||f==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${f}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),process.exit(2));let v=Zn({raw:n.maxWorkers,operation:`workspace run ${f}`,json:n.json===true||i("--json")});if(f==="init"&&n.json!==true){let P=await as(w);P!==0&&process.exit(P);}let{runWorkspaceStage:u}=await import('./workspace-run-M4LNJILC.js'),j=await u({workspacePath:w,stage:f,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:v,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(j,null,2)),j.summary.exitCode!==0&&process.exit(j.summary.exitCode);}else if(t==="explain"||t==="why"){let w=a(t),{parseWorkspaceExplainTarget:y}=await import('./workspace-explain-contract-SEFTVF6J.js'),{buildWorkspaceExplain:f,writeWorkspaceExplainReport:v}=await import('./workspace-explain-WVN7JH3U.js'),u=(e??o??"").trim();!u&&n.scope&&(u=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),u||(console.log(s.red(`\u274C workspace ${t} requires a target.`)),console.log(s.gray(" npx workspai workspace explain project:<name>|release-blocked [--json] [--write]")),console.log(s.gray(" npx workspai workspace why <project>|release-blocked [--json]")),process.exit(1));let j=y(u);j||(console.log(s.red(`\u274C Invalid explain target: ${u}`)),process.exit(1));let P=await f({workspacePath:w,target:j}),E=n.write===true||i("--write"),S;if(E&&(S=await v(P,w,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$7(`workspace ${t}`,P,S),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${P.summary}`));for(let $ of P.sections)console.log(s.bold(`
412
- ${$.title}`)),console.log($.body);S&&console.log(s.gray(`
413
- Written: ${S}`));}else if(t==="trace"){let w=a("trace"),y=n.from||e;y||(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:f}=await import('./workspace-explain-contract-SEFTVF6J.js'),{buildWorkspaceExplain:v,writeWorkspaceExplainReport:u}=await import('./workspace-explain-WVN7JH3U.js'),j=f(y);(!j||j.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${y}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.workspai/reports/workspace-model-diff-last-run.json")),process.exit(1));let P=await v({workspacePath:w,target:j}),E=n.write===true||i("--write"),S;if(E&&(S=await u(P,w,"trace")),n.json){console.log(JSON.stringify(b$7("workspace trace",P,S),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${P.summary}`));for(let $ of P.sections)console.log(s.bold(`
414
- ${$.title}`)),console.log($.body);S&&console.log(s.gray(`
415
- Written: ${S}`));}else if(t==="feedback"){let w=a("feedback"),y=(e||"record").toLowerCase();y!=="record"&&(console.log(s.red(`Unknown feedback action: ${y}`)),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:f,parseFeedbackStdinPayload:v,readStdinAll:u}=await import('./workspace-feedback-WAID3IOE.js'),j=await u(),P=v(j);P||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let E=await f({workspacePath:w,payload:P});n.json?console.log(JSON.stringify(E,null,2)):E.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${E.historyPath}`))):console.log(s.red(`\u274C ${E.error??"Failed to record feedback"}`)),E.ok||process.exit(1);}else if(t==="mcp"){let w=a("mcp"),y=(e||"serve").toLowerCase();y!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:y,result:"error",workspacePath:w,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${y}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${y}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:f}=await import('./workspace-mcp-serve-KT2I676Z.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await f({workspacePath:w});}else if(t==="init"){n.json||(console.log(s.yellow("\u2139 workspace init is an alias of: npx workspai workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
411
+ See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,o,r){let n=this.opts(),a=h=>{let y=n.workspace?b.resolve(n.workspace):null,f=y??a$5(process.cwd())??le(process.cwd());(!f||!qe(f))&&((n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$2({operation:`workspace ${h}`,code:"workspace.root.required",message:"Not inside a Workspai workspace. Run from a workspace directory or pass --workspace <path>.",context:{cwd:b.resolve(process.cwd()),...y?{requestedWorkspace:y}:{}}}),null,2)),process.exit(1)),console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run from a workspace directory or pass --workspace <path>.")),process.exit(1));let k=b.resolve(process.cwd()),u=b.resolve(f);return k!==u&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${f} for "${h}" (current directory: ${k}).`)),f},i=h=>process.argv.includes(h),c=h=>Se(process.argv,h),l=()=>n.output||c("--output"),p=()=>{if(!n.scanDepth)return;let h=Number.parseInt(n.scanDepth,10);return Number.isFinite(h)?h:void 0},m=(h,y)=>{if(!h)return;let f=h.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!f)throw new Error(`${y} must be a byte size such as 500gb or 2tb.`);let k={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},u=Number(f[1])*k[f[2]||"b"];if(!Number.isSafeInteger(Math.floor(u))||u<=0)throw new Error(`${y} is outside the supported numeric range.`);return Math.floor(u)},d=()=>{let h=n.downloadTimeoutMs,y=h===void 0?void 0:Number.parseInt(h,10);if(y!==void 0&&(!Number.isFinite(y)||y<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:m(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:m(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:y,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},w={list:["--json"],intelligence:["--workspace","--json","--strict","--for-agent"],model:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--cache","--incremental","--write","--strict"],"agent-sync":["--workspace","--json","--scope","--for-agent","--write","--dry-run","--strict","--preset","--refresh-context","--refresh","--target","--experimental-hooks","--hydrate-prompts"],"remediation-plan":["--workspace","--json","--include-paths","--ci","--write"],context:["--workspace","--json","--for-agent","--scope","--include-evidence","--scan-depth","--write","--agent-sync","--no-agent-sync","--preset","--target","--strict"],snapshot:["--workspace","--json","--include-paths","--include-evidence","--scan-depth"],diff:["--workspace","--json","--from","--include-paths","--include-evidence","--scan-depth","--strict"],impact:["--workspace","--json","--from","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],verify:["--workspace","--json","--from-impact","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],graph:["--workspace","--json","--output","--from","--limit","--include-paths","--include-evidence","--scan-depth","--scope"],watch:["--workspace","--json","--once","--scan-depth"],sync:["--workspace","--json"],registry:["--workspace","--json","--refresh"],foundation:["--workspace","--json","--force"],policy:["--workspace","--json"],contract:["--workspace","--json","--output","--force","--strict"],share:["--workspace","--json","--output","--include-paths","--no-doctor","--no-blueprint"],export:["--workspace","--json","--output","--include-env","--archive-compression"],archive:["--json","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],hydrate:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],import:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],run:["--workspace","--json","--scope","--affected","--blast-radius","--since","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],explain:["--workspace","--json","--scope","--write"],why:["--workspace","--json","--scope","--write"],trace:["--workspace","--json","--from","--write"],feedback:["--workspace","--json"],eval:["--workspace","--json","--from","--output"],mcp:["--workspace","--json"],init:["--workspace","--json","--scope","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"]},g=new Set(Object.values(w).flatMap(h=>[...h])),P=new Set(process.argv.slice(2).filter(h=>h.startsWith("--")).map(h=>h.split("=",1)[0]).filter(h=>g.has(h))),j=w[t],A=j?[...P].filter(h=>!j.includes(h)):[];if(A.length>0){let h=`${A.join(", ")} ${A.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||P.has("--json")?console.log(JSON.stringify(c$2({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:h,exitCode:2,context:{action:t,unsupportedFlags:A,allowedFlags:j}}),null,2)):(console.log(s.red(`\u274C ${h}`)),console.log(s.gray(` Allowed flags: ${j.join(", ")||"none"}`))),process.exit(2);}if((Ui(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$3({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:h}=await import('./workspace-PJPRBUMQ.js');await h({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 h=a("intelligence"),{runWorkspaceIntelligenceChain:y}=await import('./workspace-intelligence-runner-OTYTHV6B.js'),f=await y({workspacePath:h,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(f,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${f.status}`));for(let k of f.stages)console.log(s.gray(` ${k.id}: ${k.status} \u2014 ${k.message}`));console.log(s.gray(` Evidence: ${f.artifactPath}`));}f.exitCode!==0&&process.exit(f.exitCode);}else if(t==="model"){let h=a("model"),{buildWorkspaceModelCached:y,buildWorkspaceModelIncremental:f,writeWorkspaceModel:k}=await import('./workspace-model-7OU2M3LE.js'),u=n.incremental===true||i("--incremental"),C=n.cache===true||i("--cache")||u,x={workspacePath:h,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p(),strict:n.strict===true||i("--strict")},R,v;if(u){let T=await f(x);R=T.model,v=T.mode;}else {let T=await y({...x,cache:C});R=T.model,v=T.cache;}let I;(n.write===true||i("--write"))&&(I=await k(R,h));let N=(n.strict===true||i("--strict"))&&R.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...R,...I?{outputPath:I}:{}},null,2)),N&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${R.workspace.name}`)),u?console.log(s.gray(` Build: ${v} (incremental)`)):C&&console.log(s.gray(` Cache: ${v}`)),console.log(s.gray(` Projects: ${R.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${R.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${R.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${R.identity.workspaceType}`)),console.log(s.gray(` Validation: ${R.validation?.status??"unknown"} (${R.validation?.errors??0} error, ${R.validation?.warnings??0} warning)`)),console.log(I?s.gray(` Written: ${I}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),N&&process.exit(1);}else if(t==="agent-sync"){let h=a("agent-sync"),{syncWorkspaceAgentGrounding:y,parseAgentGroundingTargets:f}=await import('./workspace-agent-sync-662QHXGF.js'),k=n.strict===true||i("--strict"),u=n.write===true||i("--write"),C=i("--dry-run"),x=await y({workspacePath:h,scope:n.scope,agent:n.forAgent,write:u&&!C,dryRun:C,strict:k,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:f(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),staleAfterHours:24});if(n.json)console.log(JSON.stringify(x,null,2));else {console.log(s.green(`\u2714 Agent grounding ${u&&!C?"synced":"planned"}`)),console.log(s.gray(` Index: ${x.indexPath}`)),x.contextPath&&console.log(s.gray(` Context: ${x.contextPath}`)),x.blockers.length>0&&console.log(s.yellow(` Blockers: ${x.blockers.slice(0,3).join(" \xB7 ")}`));let R=u&&!C?x.writtenFiles:x.skippedFiles;if(R.length>0&&console.log(s.gray(` Files: ${R.join(", ")}`)),x.strictViolations.length>0)for(let v of x.strictViolations)console.log(s.red(`\u274C ${v}`));}k&&x.strictViolations.length>0&&process.exit(1);}else if(t==="remediation-plan"){let h=a("remediation-plan"),{buildArtifactRemediationPlan:y,writeArtifactRemediationPlan:f}=await import('./artifact-remediation-plan-SPOUHMK5.js'),k=await y({workspacePath:h,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),u;if((n.write===true||i("--write"))&&(u=await f(k,h)),n.json===true||i("--json")){console.log(JSON.stringify(b$7("workspace remediation-plan",k,u),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${k.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${k.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${k.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${k.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${k.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${k.summary.risk.safe}, guarded=${k.summary.risk.guarded}, invasive=${k.summary.risk.invasive}`));for(let C of k.actions.slice(0,8))console.log(s.gray(` \u2022 ${C.cardId}: ${C.title} (${C.mode}, ${C.risk})`));k.actions.length>8&&console.log(s.gray(` \u2026 ${k.actions.length-8} more action(s)`)),console.log(u?s.gray(` Written: ${u}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let h=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:y,writeWorkspaceAgentContext:f}=await import('./workspace-context-23YYCUCP.js'),k=n.strict===true||i("--strict"),u=await y({workspacePath:h,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p(),strict:false}),C,x;if((n.write===true||i("--write"))&&(C=await f(u,h),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:I,parseAgentGroundingTargets:N}=await import('./workspace-agent-sync-662QHXGF.js');if(x=await I({workspacePath:h,scope:n.scope,agent:u.agent,write:true,refreshContext:false,strict:k,preset:n.preset==="minimal"?"minimal":"enterprise",targets:N(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${x.writtenFiles.length} file(s) updated`)),k&&x.strictViolations.length>0){for(let T of x.strictViolations)console.log(s.red(`\u274C ${T}`));process.exit(1);}}let R=k&&u.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...u,...C?{outputPath:C}:{},...x?{agentGroundingSync:x}:{}},null,2)),R&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${u.workspace.name}`)),console.log(s.gray(` Agent: ${u.agent}`)),console.log(s.gray(` Scope: ${u.scope.activeProject??u.scope.requested}`)),console.log(s.gray(` Projects included: ${u.projects.length}`)),console.log(s.gray(` Safe commands: ${u.safeCommands.length}`)),console.log(s.gray(` Validation: ${u.validation.status} (${u.validation.errors} error, ${u.validation.warnings} warning)`)),console.log(C?s.gray(` Written: ${C}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),R){for(let v of u.validation.issues)console.log(s.red(`\u274C ${v.severity}:${v.code}:${v.target}`));process.exit(1);}}else if(t==="snapshot"){let h=a("snapshot"),{buildWorkspaceModelSnapshot:y,writeWorkspaceModelSnapshot:f}=await import('./workspace-intelligence-MFJE7W67.js'),k=await y({workspacePath:h,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()}),u=await f(k,h);if(n.json){console.log(JSON.stringify(b$7("workspace snapshot",k,u),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${k.model.workspace.name}`)),console.log(s.gray(` Hash: ${k.modelHash}`)),console.log(s.gray(` Projects: ${k.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${k.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${u}`));}else if(t==="diff"){let h=a("diff"),y=n.from||e;y||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:h},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:f,writeWorkspaceModelDiff:k}=await import('./workspace-intelligence-MFJE7W67.js'),u;try{u=await f({workspacePath:h,fromPath:y,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:R.message,context:{workspacePath:h,fromPath:y},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),R}let C=await k(u,h);if(n.json){console.log(JSON.stringify(b$7("workspace diff",u,C),null,2));return}let x=u.summary.changed?s.yellow:s.green;console.log(x(`\u2714 Workspace model diff: ${u.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${u.fromRef}`)),console.log(s.gray(` Added projects: ${u.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${u.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${u.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${u.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${u.summary.validationChanges}`)),u.git?.available&&console.log(s.gray(` Git: ${u.git.dirty?"dirty":"clean"} (${u.summary.gitChangedFiles} mapped change(s))`));for(let R of u.changes.slice(0,12))console.log(s.gray(` \u2022 ${R.type} ${R.target}: ${R.message}`));u.changes.length>12&&console.log(s.gray(` \u2026 ${u.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${C}`));}else if(t==="impact"){let h=a("impact"),y=n.from||e;y||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:h},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:f,writeWorkspaceImpact:k}=await import('./workspace-intelligence-MFJE7W67.js'),u;try{u=await f({workspacePath:h,fromPath:y,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:R.message,context:{workspacePath:h,fromPath:y},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),R}let C=await k(u,h);if(n.json){console.log(JSON.stringify(b$7("workspace impact",u,C),null,2));return}let x=u.summary.risk==="critical"||u.summary.risk==="high"?s.red:u.summary.risk==="medium"?s.yellow:s.green;console.log(x(`\u2714 Workspace impact: ${u.summary.risk}`)),console.log(s.gray(` From: ${u.fromRef}`)),console.log(s.gray(` Affected projects: ${u.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${u.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${u.summary.recommendedCommands}`));for(let R of u.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${R.title}: ${R.summary}`));u.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${u.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${C}`));}else if(t==="verify"){let h=a("verify"),{buildWorkspaceVerify:y,writeWorkspaceVerify:f,evaluateWorkspaceVerifyGate:k}=await import('./workspace-verify-EBVL7FWT.js'),u=await y({workspacePath:h,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()}),C=await f(u,h),x=k(u,{strict:n.strict===true||i("--strict")}),R=x.exitCode,{recordWorkspaceHistory:v,historyEntryFromVerify:I}=await import('./workspace-history-BANOJRQ2.js');if(await v(h,I(u,x.passed)),n.json){console.log(JSON.stringify(b$7("workspace verify",{...u,gate:x},C),null,2)),R!==0&&process.exit(R);return}let N=u.summary.verdict==="ready"?s.green:u.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(N(`\u2714 Workspace verify: ${u.summary.verdict}`)),console.log(s.gray(` Freshness: ${u.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${u.impact.risk}`)),console.log(s.gray(` Steps: ${u.steps.length}`)),console.log(s.gray(` Passed ${u.summary.stepsPassed}, warn ${u.summary.stepsWarn}, failed ${u.summary.stepsFailed}, missing ${u.summary.stepsMissing}`));for(let T of u.steps.slice(0,10))console.log(s.gray(` \u2022 ${T.id}: ${T.status} \u2014 ${T.message}`));if(u.steps.length>10&&console.log(s.gray(` \u2026 ${u.steps.length-10} more step(s)`)),u.policyViolations.length>0){console.log(s.gray(` Policy (${u.policyMode}): ${u.policyViolations.length} violation(s)`));for(let T of u.policyViolations.slice(0,5)){let $=T.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${$} [${T.source}] ${T.code}: ${T.message}`);}}console.log(s.gray(` Gate (${x.mode}): ${x.passed?"passed":"blocked"}`));for(let T of x.reasons.slice(0,5))console.log(s.red(` \u2717 ${T}`));console.log(s.gray(` Written: ${C}`)),R!==0&&process.exit(R);}else if(t==="graph"){let h=a("graph"),{buildWorkspaceModel:y}=await import('./workspace-model-7OU2M3LE.js'),{buildGraphEmit:f,renderGraphDot:k,renderGraphMermaid:u,explainGraphNode:C}=await import('./workspace-graph-2A5THUCI.js'),x=await y({workspacePath:h,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p()}),R=x.graph,v=(e||"emit").toLowerCase();R||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:v,result:"error",workspacePath:h,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 I=async()=>{let{buildWorkspaceKnowledgeGraph:$}=await import('./workspace-knowledge-graph-ARDC6HHG.js'),{hashWorkspaceModel:S}=await import('./workspace-model-hash-MHXK5MEI.js'),{readWorkspaceContract:K}=await import('./workspace-contract-TU2I7GC2.js'),J=null;try{J=(await K({workspacePath:h})).contract;}catch{}return $({workspacePath:h,workspace:{name:x.workspace.name,...x.workspace.profile?{profile:x.workspace.profile}:{}},projects:x.projects.map(D=>({id:D.name,path:D.path,...D.absolutePath?{absolutePath:D.absolutePath}:{},runtime:D.runtime,framework:D.framework,...D.kit?{kit:D.kit}:{}})),projectTopology:R,contract:J,now:new Date(x.generatedAt),source:{kind:"workspace-model",artifact:a$2.model,hashAlgorithm:"sha256",hash:S(x)}})};if(v==="dot"){console.log(k(R));return}if(v==="mermaid"){console.log(u(R));return}if(v==="jsonld"||v==="graphml"||v==="gexf"){let $=await I(),{renderWorkspaceKnowledgeGraphGexf:S,renderWorkspaceKnowledgeGraphGraphMl:K,renderWorkspaceKnowledgeGraphJsonLd:J}=await import('./workspace-knowledge-graph-export-UYAYFTWX.js'),D=v==="jsonld"?J($):v==="graphml"?K($):S($),q=l();if(q){let Q=b.resolve(h,q);await O__default.outputFile(Q,`${D}
412
+ `,"utf8"),n.json?console.log(JSON.stringify(b$7(`workspace graph ${v}`,{format:v,entityCount:$.entities.length,relationCount:$.relations.length,proofCount:$.proofs.length},Q),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${v}`)),console.log(s.gray(` Written: ${Q}`)));return}console.log(D);return}if(v==="explain"){let $=(n.scope?.replace(/^project:/,"")||o||"").trim();$||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:h,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let S=C(R,$);if(n.json){console.log(JSON.stringify(S,null,2)),S.found||process.exit(1);return}S.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${$}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${S.project}`)),S.centrality&&console.log(s.gray(` Centrality: fanIn ${S.centrality.fanIn}, fanOut ${S.centrality.fanOut}, reach ${S.centrality.reach}, betweenness ${S.centrality.betweenness}${S.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${S.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${S.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${S.transitiveDependents.length}`));for(let K of S.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${K.id} (d${K.distance}, via ${K.via??"\u2014"})`));return}if(v==="entities"){let $=await I(),{queryKnowledgeEntities:S}=await import('./workspace-knowledge-graph-query-VOSPPH4W.js'),K=S($,o);if(n.json){console.log(JSON.stringify({schemaVersion:$.schemaVersion,generatedAt:$.generatedAt,kind:o??null,count:K.length,entities:K},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${o?`: ${o}`:""}`)),console.log(s.gray(` Count: ${K.length}`));for(let J of K)console.log(s.gray(` \u2022 ${J.kind}: ${J.label} [${J.id}]`));return}if(v==="search"||v==="benchmark"){let $=(o||"").trim();$||(console.log(s.red(`\u274C workspace graph ${v} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${v} "authentication endpoint" --json`)),process.exit(1));let S=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(S)||S<1||S>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let K=await I();if(v==="benchmark"){let{buildWorkspaceGraphTokenEfficiencyReport:q}=await import('./workspace-graph-token-efficiency-CFGFCJ5V.js'),Q=await q({workspacePath:h,graph:K,query:$,limit:S});n.json?console.log(JSON.stringify(Q,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${$}`)),console.log(s.gray(` Estimated tokens: ${Q.corpus.estimatedTokens} corpus \u2192 ${Q.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${Q.savings.reductionRatio}\xD7 (${Q.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${Q.retrieval.matchCount}`)),console.log(s.yellow(` ${Q.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:J}=await import('./workspace-knowledge-graph-query-VOSPPH4W.js'),D=J(K,{query:$,limit:S});if(n.json)console.log(JSON.stringify(D,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${$}`)),console.log(s.gray(` ${D.entities.length}/${D.totalMatches} match(es)${D.truncated?" (bounded)":""}`));for(let q of D.entities)console.log(s.gray(` \u2022 ${q.kind}: ${q.label} [${q.id}]`));}return}if(v==="evidence"){let $=(o||"").trim();$||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let S=await I(),{queryKnowledgeEvidence:K}=await import('./workspace-knowledge-graph-query-VOSPPH4W.js'),J=K(S,$);if(n.json)console.log(JSON.stringify(J,null,2));else if(J.found){console.log(s.green(`\u2714 Graph evidence: ${$}`));for(let D of J.proofs)console.log(s.gray(` \u2022 ${D.artifact}${D.pointer?`#${D.pointer}`:""} [${D.provider}/${D.trust}/${D.confidence}]`));}else {console.log(s.red(J.candidates.length>0?`\u274C Graph query is ambiguous: ${$}`:`\u274C Graph entity or relation not found: ${$}`));for(let D of J.candidates.slice(0,10))console.log(s.gray(` \u2022 ${D}`));}J.found||process.exit(1);return}if(v==="path"){let $=(o||"").trim(),S=(r||"").trim();(!$||!S)&&(console.log(s.red("\u274C workspace graph path requires <from> and <to>.")),console.log(s.gray(" npx workspai workspace graph path <from> <to> --json")),process.exit(1));let K=await I(),{queryKnowledgePath:J}=await import('./workspace-knowledge-graph-query-VOSPPH4W.js'),D=J(K,$,S);if(n.json)console.log(JSON.stringify(D,null,2));else if(D.found){console.log(s.green(`\u2714 Graph proof path: ${$} \u2192 ${S}`));for(let q of D.hops)console.log(s.gray(` \u2022 ${q.from} ${q.direction==="forward"?"\u2192":"\u2190"} ${q.to} [${q.kind}]`));console.log(s.gray(` Proofs: ${D.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${$} and ${S}.`));D.found||process.exit(1);return}if(v==="overlay"){let $=(n.from||o||"").trim();$||(console.log(s.red("\u274C workspace graph overlay requires --from <graph.json>.")),console.log(s.gray(" npx workspai workspace graph overlay --from <graph.json> --json")),process.exit(1));let S=b.resolve(h,$),K;try{K=JSON.parse(await O__default.readFile(S,"utf8"));}catch(Ae){console.log(s.red(`\u274C Could not read the base knowledge graph: ${Ae instanceof Error?Ae.message:String(Ae)}`)),process.exit(1);}let J=K&&typeof K=="object"?K:{},D=J.graph,q=D&&typeof D=="object"?D:{},Q=J.schemaVersion===b$8.knowledgeGraph?J:J.knowledgeGraph??q.knowledgeGraph;(!Q||typeof Q!="object"||Q.schemaVersion!==b$8.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${b$8.knowledgeGraph} document.`)),process.exit(1));let Re=await I(),{buildWorkspaceKnowledgeGraphChangeOverlay:de}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),ne=de(Q,Re);if(n.json){console.log(JSON.stringify(ne,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${$}`)),console.log(s.gray(` Risk: ${ne.summary.risk}`)),console.log(s.gray(` Entities: +${ne.summary.entityAdds} -${ne.summary.entityRemovals} ~${ne.summary.entityChanges}`)),console.log(s.gray(` Relations: +${ne.summary.relationAdds} -${ne.summary.relationRemovals} ~${ne.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${ne.summary.proofAdds} -${ne.summary.proofRemovals} ~${ne.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${ne.summary.impactedEntities} entities \xB7 ${ne.summary.changedArtifacts} proof artifacts`));return}let N=f(R),T=await I();if(n.json){console.log(JSON.stringify({...N,knowledgeGraph:T},null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${N.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${N.graph.stats.edgeCount} (inferred ${N.graph.stats.inferredEdges}, contract ${N.graph.stats.contractEdges}, manual ${N.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${N.integrity.ok?"ok":"issues"} (cycles ${N.integrity.stats.cycleCount}, dangling ${N.integrity.stats.danglingCount}, orphans ${N.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${N.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${T.quality.entityCount} entities \xB7 ${T.quality.relationCount} relations \xB7 ${T.quality.proofCount} proofs \xB7 ${T.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 h=a("watch"),{runWorkspaceWatch:y}=await import('./workspace-watch-7HWGA5TF.js'),f=n.once===true||i("--once"),k=n.json===true,u=n.graphStream===true||i("--graph-stream");if(u&&!k)throw new Error("workspace watch --graph-stream requires --json.");let C=u?new(await import('./workspace-graph-stream-KAGGQPJT.js')).WorkspaceGraphStreamPublisher({workspacePath:h}):null,x=new AbortController,R=()=>x.abort();process.once("SIGINT",R),process.once("SIGTERM",R),k||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await y({workspacePath:h,once:f,signal:x.signal,buildOptions:{workspacePath:h,observableScanDepth:p()},onProgress:v=>{k||console.error(s.gray(` ${v}`));},onModel:C?async v=>{if(!v.graph)return;let{buildWorkspaceKnowledgeGraph:I}=await import('./workspace-knowledge-graph-ARDC6HHG.js'),{readWorkspaceContract:N}=await import('./workspace-contract-TU2I7GC2.js'),T=null;try{T=(await N({workspacePath:h})).contract;}catch{}let $=await I({workspacePath:h,workspace:{name:v.workspace.name,...v.workspace.profile?{profile:v.workspace.profile}:{}},projects:v.projects.map(S=>({id:S.name,path:S.path,...S.absolutePath?{absolutePath:S.absolutePath}:{},runtime:S.runtime,framework:S.framework,...S.kit?{kit:S.kit}:{}})),projectTopology:v.graph,contract:T,now:new Date(v.generatedAt),source:{kind:"workspace-model",artifact:a$2.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-MHXK5MEI.js')).hashWorkspaceModel(v)}});console.log(JSON.stringify(C.publish(v,$)));}:void 0,emit:v=>{if(u)return;if(k){console.log(JSON.stringify(v));return}if(v.kind==="ready"){console.log(s.gray(` Ready: ${v.graph.nodeCount} nodes, ${v.graph.edgeCount} edges (hash ${v.modelHash.slice(0,12)})`));return}if(v.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${v.error??"unknown error"}`));return}if(v.kind==="unchanged"){console.log(s.gray(` No structural change (${v.mode}, ${v.durationMs}ms)`));return}let I=[];v.changedProjects.length>0&&I.push(`changed: ${v.changedProjects.join(", ")}`),v.addedProjects.length>0&&I.push(`added: ${v.addedProjects.join(", ")}`),v.removedProjects.length>0&&I.push(`removed: ${v.removedProjects.join(", ")}`),v.graph.edgesAdded.length>0&&I.push(`+${v.graph.edgesAdded.length} edges`),v.graph.edgesRemoved.length>0&&I.push(`-${v.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${v.mode}, ${v.durationMs}ms): ${I.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R),!k&&!f&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let h=a("sync"),{syncWorkspaceProjects:y}=await import('./workspace-PJPRBUMQ.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${b.basename(h)}`));let f=await y(h,n.json===true);await ds(h,{silent:n.json===true});let{readWorkspaceRegistrySummary:k}=await import('./workspace-registry-summary-ORDK7A36.js'),u=await k(h);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:h,registry:f,contractSynced:true,registrySummary:u},null,2));}else if(t==="registry"){let h=a("registry"),y=e||"status";y!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${y}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:f,resolveWorkspaceRegisteredProjects:k}=await import('./workspace-registry-summary-ORDK7A36.js'),u=await f(h);if(n.json){console.log(JSON.stringify(u,null,2));return}let C=await k(h);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${u.authority}`)),console.log(s.gray(` Projects: ${u.projectCount}`)),console.log(s.gray(` Summary: ${u.registrySummaryPath}`)),C.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let h=a("foundation"),y=e||"ensure";y!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${y}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:f}=await import('./workspace-foundation-WPLD7OEO.js'),k=await f(h,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(k,null,2));return}k.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${k.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let h=a("policy"),y=await lu(h,e,o,r,n.json===true||i("--json"));y!==0&&process.exit(y);}else if(t==="contract"){let h=a("contract"),{buildWorkspaceContractGraph:y,readWorkspaceContract:f,verifyWorkspaceContract:k,writeWorkspaceContract:u,WORKSPACE_CONTRACT_PATH:C}=await import('./workspace-contract-TU2I7GC2.js'),x=e||"inspect",R=l();try{if(x==="init"){let v=await u({workspacePath:h,outputPath:R,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${v.contractPath}`)),console.log(s.gray(` Projects: ${v.contract.projects.length}`));return}if(x==="inspect"){let v=await f({workspacePath:h,contractPath:R});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${v.contractPath}`)),console.log(s.gray(` Workspace: ${v.contract.workspace.name}`)),console.log(s.gray(` Projects: ${v.contract.projects.length}`)),console.log(s.gray(` Schema: v${v.contract.schemaVersion}`));return}if(x==="verify"){let v=await k({workspacePath:h,contractPath:R,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:I}=await import('./workspace-contract-TU2I7GC2.js'),N=await I({workspacePath:h,result:v});if(n.json)console.log(JSON.stringify({...v,evidencePath:N},null,2));else {let T=v.status==="passed"?s.green:s.red;console.log(T(`\u2714 Workspace contract verification ${v.status}: ${v.contractPath}`)),console.log(s.gray(` Projects: ${v.projectCount}`));for(let $ of v.checks){let S=$.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${S} ${$.id}: ${$.message}`));}for(let $ of v.violations)console.log(s.gray(` Violation: ${$}`));}(v.status==="failed"||v.status!=="passed"&&n.strict)&&process.exit(1);return}if(x==="graph"){let v=await y({workspacePath:h,contractPath:R});if(n.json){console.log(JSON.stringify(v,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${v.contractPath}`)),console.log(s.gray(` Workspace: ${v.graph.workspace.name}`)),console.log(s.gray(` Projects: ${v.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${v.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${v.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${v.graph.summary.relationshipEdges} (${v.graph.summary.inferredEdges} inferred, ${v.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${v.graph.summary.connectedProjects}/${v.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(v.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(v.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${v.graph.summary.orphanProjects} \xB7 Hotspots: ${v.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${v.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${v.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${v.graph.summary.entityCount} entities \xB7 ${v.graph.summary.knowledgeRelations} relations \xB7 ${v.graph.summary.proofCount} proofs \xB7 ${v.graph.summary.providerCount} providers \xB7 ${v.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${v.graph.summary.portCount}`));for(let I of v.graph.nodes){let N=I.ports.map($=>`${$.name}:${$.port}`).join(", ")||"none",T=I.operationalProfile?` risk=${I.operationalProfile.weight}/${I.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${I.id} (${I.runtime||"unknown"}${I.framework?`/${I.framework}`:""}) ports=${N} manifests=${I.files.manifests.length}${T}`));}for(let I of v.graph.edges){let N=I.type==="event"?`event:${I.label}`:I.label;console.log(s.gray(` ${I.from} -> ${I.to} [${N}]`));}if(v.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let I of v.graph.dependencyGraph.edges)console.log(s.gray(` ${I.from} -> ${I.to} [${I.kind}/${I.source}/${I.confidence}] evidence=${I.evidence.length}`));}for(let I of v.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${I.severity}: ${I.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${x}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${C}]`)),process.exit(1);}catch(v){n.json&&(console.log(JSON.stringify({command:`workspace contract ${x}`,result:"error",workspacePath:h,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${x}.failed`,message:v.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${x} failed: ${v.message}`)),process.exit(1);}}else if(t==="share"){let h=a("share"),y=l()||e,{createWorkspaceShareBundle:f}=await import('./workspace-PJPRBUMQ.js'),k=await f(h,{outputPath:y,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:h,bundlePath:k,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: ${k}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let h=a("export");try{let{exportWorkspaceArchive:y}=await import('./workspace-archive-P76EDIUG.js'),f=n.archiveCompression?.trim().toLowerCase()??"store";if(f!=="store"&&f!=="deflate")throw new Error("--archive-compression must be store or deflate.");let k=await y({workspacePath:h,outputPath:l()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:f});if(n.json){console.log(JSON.stringify(k,null,2));return}let u=(k.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${k.archivePath}`)),console.log(s.gray(` Files: ${k.manifest.files.length}`)),console.log(s.gray(` Size: ${u} MB`)),k.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(y){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:y.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${y.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let h=o;h||(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:y,inspectWorkspaceArchive:f,verifyWorkspaceArchive:k}=await import('./workspace-archive-P76EDIUG.js');try{if(e==="inspect"){let C=await f({archivePathOrUrl:h,safety:d()});if(n.json){console.log(JSON.stringify(C,null,2));return}let x=(C.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${C.archivePath}`)),console.log(s.gray(` Workspace: ${C.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${C.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${C.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${C.fileCount}`)),console.log(s.gray(` Payload: ${x} MB`));return}if(e==="doctor"){let C=await y({archivePathOrUrl:h,strict:n.strict===true||i("--strict"),safety:d()});if(n.json)console.log(JSON.stringify(C,null,2));else {let x=C.status==="passed"?s.green:C.status==="warning"?s.yellow:s.red;console.log(x(`\u2714 Workspace archive doctor ${C.status}: ${C.archivePath}`)),console.log(s.gray(` Workspace: ${C.workspaceName}`)),console.log(s.gray(` Files: ${C.fileCount}`));for(let R of C.checks){let v=R.status==="passed"?"\u2714":R.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${v} ${R.id}: ${R.message}`));}for(let R of C.recommendedActions)console.log(s.gray(` Next: ${R}`));}(C.status==="failed"||C.status==="warning"&&n.strict)&&process.exit(1);return}let u=await k({archivePathOrUrl:h,requireChecksums:n.strict===true||i("--strict"),safety:d()});if(n.json)console.log(JSON.stringify(u,null,2));else if(u.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${u.archivePath}`)),console.log(s.gray(` Files: ${u.verifiedFiles}/${u.fileCount}`));else {let C=u.status==="failed"?s.red:s.yellow;console.log(C(`\u274C Workspace archive verification ${u.status}: ${u.archivePath}`)),u.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${u.missingArchiveEntries.join(", ")}`)),u.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${u.extraArchiveEntries.join(", ")}`)),u.mismatches.length&&console.log(s.gray(` Mismatches: ${u.mismatches.map(x=>x.path).join(", ")}`)),u.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${u.missingChecksumFiles.join(", ")}`));}(u.status==="failed"||u.status==="warning"&&n.strict)&&process.exit(1);}catch(u){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:h,error:{code:`workspace.archive.${e}.failed`,message:u.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${u.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let h=e;h||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.${t}.input-required`,message:`workspace ${t} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));let{hydrateWorkspaceArchive:y}=await import('./workspace-archive-P76EDIUG.js');try{let f=await y({archivePathOrUrl:h,outputPath:l(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:d()});if(n.json){console.log(JSON.stringify(f,null,2));return}console.log(s.green(f.dryRun?`\u2714 Workspace archive hydrate preview: ${f.outputPath}`:`\u2714 Workspace archive hydrated: ${f.outputPath}`)),console.log(s.gray(` Files: ${f.files.length}`)),f.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${f.manifest.workspaceName}`));}catch(f){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:h,...l()?{outputPath:l()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:f.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${f.message}`)),process.exit(1);}}else if(t==="run"){let h=a(`run ${e||""}`.trim()),y=new Set(["init","test","build","start"]),f=e?.trim()??"";f||(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)),y.has(f)||(!/^[a-z][a-z0-9_-]*$/i.test(f)||f==="dev"||f==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${f}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),process.exit(2));let k=Zn({raw:n.maxWorkers,operation:`workspace run ${f}`,json:n.json===true||i("--json")});if(f==="init"&&n.json!==true){let x=await as(h);x!==0&&process.exit(x);}let{runWorkspaceStage:u}=await import('./workspace-run-QND2SIYA.js'),C=await u({workspacePath:h,stage:f,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:k,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(C,null,2)),C.summary.exitCode!==0&&process.exit(C.summary.exitCode);}else if(t==="explain"||t==="why"){let h=a(t),{parseWorkspaceExplainTarget:y}=await import('./workspace-explain-contract-ZPI3JXJU.js'),{buildWorkspaceExplain:f,writeWorkspaceExplainReport:k}=await import('./workspace-explain-MWUEN643.js'),u=(e??o??"").trim();!u&&n.scope&&(u=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),u||(console.log(s.red(`\u274C workspace ${t} requires a target.`)),console.log(s.gray(" npx workspai workspace explain project:<name>|release-blocked [--json] [--write]")),console.log(s.gray(" npx workspai workspace why <project>|release-blocked [--json]")),process.exit(1));let C=y(u);C||(console.log(s.red(`\u274C Invalid explain target: ${u}`)),process.exit(1));let x=await f({workspacePath:h,target:C}),R=n.write===true||i("--write"),v;if(R&&(v=await k(x,h,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$7(`workspace ${t}`,x,v),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${x.summary}`));for(let I of x.sections)console.log(s.bold(`
413
+ ${I.title}`)),console.log(I.body);v&&console.log(s.gray(`
414
+ Written: ${v}`));}else if(t==="trace"){let h=a("trace"),y=n.from||e;y||(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:f}=await import('./workspace-explain-contract-ZPI3JXJU.js'),{buildWorkspaceExplain:k,writeWorkspaceExplainReport:u}=await import('./workspace-explain-MWUEN643.js'),C=f(y);(!C||C.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${y}`)),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 x=await k({workspacePath:h,target:C}),R=n.write===true||i("--write"),v;if(R&&(v=await u(x,h,"trace")),n.json){console.log(JSON.stringify(b$7("workspace trace",x,v),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${x.summary}`));for(let I of x.sections)console.log(s.bold(`
415
+ ${I.title}`)),console.log(I.body);v&&console.log(s.gray(`
416
+ Written: ${v}`));}else if(t==="eval"){let h=a("eval"),y=(e||"status").toLowerCase(),{WORKSPACE_EVALUATION_LAST_RUN_PATH:f,WORKSPACE_EVALUATION_LIVE_PATH:k,appendWorkspaceEvaluationEvent:u,compareWorkspaceEvaluations:C,createWorkspaceEvaluation:x,finalizeWorkspaceEvaluation:R,readWorkspaceEvaluation:v,writeWorkspaceEvaluation:I}=await import('./workspace-intelligence-evaluation-IPH7M3WV.js');if(y==="init"){let N=(o||"").trim(),T=(r||"workspace-intelligence").trim(),$=["full-corpus","grep","vector","graph","workspace-intelligence","custom"];(!N||!$.includes(T))&&(console.log(s.red("\u274C workspace eval init requires <task> and an optional valid strategy.")),console.log(s.gray(` Strategies: ${$.join(" | ")}
417
+ npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:S}=await import('./workspace-marker-SMBC3Z2Q.js'),K=await S(h),J=x({workspacePath:h,workspaceName:K?.name,taskId:N,strategy:T}),D=await I(h,J);if(n.json){console.log(JSON.stringify(b$7("workspace eval init",J,D),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${N}`)),console.log(s.gray(` Run: ${J.runId}`)),console.log(s.gray(` Strategy: ${J.configuration.strategy}`)),console.log(s.gray(` Live: ${D}`));return}if(y==="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:N,readStdinAll:T}=await import('./workspace-feedback-SUVH2LUJ.js'),$=N(await T());$||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let S=await u({workspacePath:h,payload:$});console.log(JSON.stringify(S,null,2));}catch(S){console.log(JSON.stringify(c$2({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:S instanceof Error?S.message:String(S),context:{workspacePath:h}}),null,2)),process.exit(1);}return}if(y==="report"){let N=await R({workspacePath:h});if(n.output&&await O__default.copy(N.outputPath,b.resolve(h,n.output)),n.json){console.log(JSON.stringify(b$7("workspace eval report",N.report,N.outputPath),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${N.report.runId}`)),console.log(s.gray(` Tokens: ${N.report.summary.tokens.observedTotal} \xB7 model calls ${N.report.summary.modelCalls} \xB7 tool calls ${N.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${N.report.summary.outcome.status}${N.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${N.outputPath}`));return}if(y==="compare"){let N=(n.from||o||"").trim();N||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let T=await v(h,f),$=await v(h,N),S=C(T,$);if(n.json){console.log(JSON.stringify(S,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${S.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${S.delta.tokens}`)),console.log(s.gray(` Reduction: ${S.delta.reductionPercent===null?"unavailable":`${S.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${S.comparableOutcome?"yes":"no"}`));return}if(y==="status"){let N;try{N=await v(h,k);}catch{N=await v(h,f);}if(n.json){console.log(JSON.stringify(N,null,2));return}console.log(s.green(`\u2714 Evaluation ${N.status}: ${N.configuration.taskId}`)),console.log(s.gray(` Run: ${N.runId}`)),console.log(s.gray(` Events: ${N.events.length}`)),console.log(s.gray(` Tokens: ${N.summary.tokens.observedTotal} (${N.summary.tokenSources.providerReported} provider-reported calls, ${N.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${y}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let h=a("feedback"),y=(e||"record").toLowerCase();y!=="record"&&(console.log(s.red(`Unknown feedback action: ${y}`)),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:f,parseFeedbackStdinPayload:k,readStdinAll:u}=await import('./workspace-feedback-SUVH2LUJ.js'),C=await u(),x=k(C);x||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let R=await f({workspacePath:h,payload:x});n.json?console.log(JSON.stringify(R,null,2)):R.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${R.historyPath}`))):console.log(s.red(`\u274C ${R.error??"Failed to record feedback"}`)),R.ok||process.exit(1);}else if(t==="mcp"){let h=a("mcp"),y=(e||"serve").toLowerCase();y!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:y,result:"error",workspacePath:h,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${y}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${y}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:f}=await import('./workspace-mcp-serve-EZR6O76D.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await f({workspacePath:h});}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:
416
418
  npx workspai init | npx workspai workspace init | npx workspai workspace run init
417
- `)));let w=a("init"),y=Zn({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let u=await as(w);u!==0&&process.exit(u);}let{runWorkspaceStage:f}=await import('./workspace-run-M4LNJILC.js'),v=await f({workspacePath:w,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:y,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(v,null,2)),v.summary.exitCode!==0&&process.exit(v.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:yo}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${yo.join(", ")}`)),process.exit(1);});function Yt(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function Kc(){let t=n=>n.replace(/\bnpx (?:rapidkit|workspai)\b/g,Ce),e=n=>s.gray(t(n)),o=n=>s.cyan(t(n)),r=b$1()?`${Ce} init; ${Ce} dev`:`${Ce} init && ${Ce} dev`;console.log(s.white(`Usage:
418
- `)),console.log(s.cyan(` ${Ce} <command> [options]`)),console.log(s.gray(` ${Ce} <workspace-name> [options] # shortcut: create workspace`)),cu==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${Ce}.
419
+ `)));let h=a("init"),y=Zn({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let u=await as(h);u!==0&&process.exit(u);}let{runWorkspaceStage:f}=await import('./workspace-run-QND2SIYA.js'),k=await f({workspacePath:h,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:y,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(k,null,2)),k.summary.exitCode!==0&&process.exit(k.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$2({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:yo}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${yo.join(", ")}`)),process.exit(1);});function Yt(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function Uc(){let t=n=>n.replace(/\bnpx (?:rapidkit|workspai)\b/g,Ce),e=n=>s.gray(t(n)),o=n=>s.cyan(t(n)),r=b$1()?`${Ce} init; ${Ce} dev`:`${Ce} init && ${Ce} dev`;console.log(s.white(`Usage:
420
+ `)),console.log(s.cyan(` ${Ce} <command> [options]`)),console.log(s.gray(` ${Ce} <workspace-name> [options] # shortcut: create workspace`)),uu==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${Ce}.
419
421
  `)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems
420
422
  `)),console.log(s.white("Most AI tools understand files.")),console.log(s.white("Workspai helps developers, CI pipelines, IDEs, and AI agents share the same understanding of a software system.")),console.log(s.dim(`One workspace. One truth. Humans and AI aligned.
421
423
  `)),Yt("Workspace Lifecycle"),console.log(s.white(`
422
424
  1. Create or adopt a workspace
423
425
  `)),console.log(s.cyan(t(" npx workspai my-workspace"))),console.log(s.cyan(t(" npx workspai adopt /path/to/project"))),console.log(s.cyan(t(` npx workspai import <path|git-url>
424
426
  `))),console.log(s.white(`2. Run the contract-backed intelligence chain
425
- `)),console.log(s.cyan(t(` npx workspai workspace intelligence run --for-agent codex --json
427
+ `)),console.log(s.cyan(t(` npx workspai workspace intelligence run --for-agent generic --json
426
428
  `))),console.log(s.white(`3. Enforce enterprise gates in CI or before release
427
- `)),console.log(s.cyan(t(` npx workspai workspace intelligence run --for-agent codex --strict --json
429
+ `)),console.log(s.cyan(t(` npx workspai workspace intelligence run --for-agent generic --strict --json
428
430
  `))),console.log(s.white(`4. Explain blockers and trace change impact
429
431
  `)),console.log(s.cyan(t(" npx workspai workspace explain release-blocked --json --write"))),console.log(s.cyan(t(` npx workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --json --write
430
432
  `))),Yt("Workspace Intelligence"),console.log(s.white(`
431
433
  Run the complete canonical chain?
432
- `)),console.log(s.cyan(t(` npx workspai workspace intelligence run --for-agent codex --strict --json
434
+ `)),console.log(s.cyan(t(` npx workspai workspace intelligence run --for-agent generic --strict --json
433
435
  `))),console.log(s.white(`What projects exist?
434
436
  `)),console.log(s.cyan(t(` npx workspai workspace model --json
435
437
  `))),console.log(s.white(`What should AI agents know?
@@ -485,20 +487,20 @@ Generate context pack
485
487
  `)),console.log(s.bold("Installed command:")),console.log(s.gray(" npm install -g workspai")),console.log(s.gray(" workspai create project Scaffold a new project")),console.log(s.gray(" workspai init Install project dependencies")),console.log(s.gray(" workspai dev Start dev server")),console.log(s.gray(" workspai workspace list List registered workspaces")),console.log(s.gray(" workspai import <path|git-url> Copy or clone a project")),console.log(s.gray(` workspai adopt [path] Link an existing local project
486
488
  `)),console.log(s.bold("Workspace profiles (asked during creation):")),console.log(s.gray(" minimal Foundation files only \u2014 fastest bootstrap (default)")),console.log(s.gray(" java-only Java runtime (Spring Boot services)")),console.log(s.gray(" python-only Python + Poetry (FastAPI, Django, ML)")),console.log(s.gray(" node-only Node.js runtime (NestJS, Express, Next.js)")),console.log(s.gray(" go-only Go runtime (Fiber, Gin, gRPC)")),console.log(s.gray(" dotnet-only .NET runtime (ASP.NET Core services)")),console.log(s.gray(" polyglot Python + Node.js + Go + Java + .NET multi-runtime")),console.log(s.gray(` enterprise Polyglot + governance + Sigstore
487
489
  `)),console.log(s.gray(` Tip: use --skip-python-engine for a Python-aware Workspace Intelligence shell first; after creating a RapidKit Core module-enabled project, run workspace run init to install the local Python engine.
488
- `)),console.log(s.bold("Workspace commands (inside a workspace):")),console.log(e(" npx workspai bootstrap [--profile <p>] Re-bootstrap toolchains")),console.log(e(" npx workspai analyze [--json --strict] Analyze workspace health and gaps")),console.log(e(" npx workspai pipeline [--json --strict --no-agent-sync] Governance loop: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot")),console.log(e(" npx workspai readiness [--workspace <path>] [--json --strict] Release readiness gates (env/doctor/analyze/verify/deps)")),console.log(e(" npx workspai doctor workspace [--ci] Workspace health with CI exit codes")),console.log(e(" npx workspai workspace list List registered workspaces")),console.log(e(" npx workspai workspace model --json Build workspace intelligence model")),console.log(e(" npx workspai workspace intelligence run [--strict] --json Run the canonical contract-backed chain")),console.log(e(" npx workspai workspace context --for-agent --json --write Build agent context + sync grounding")),console.log(e(" npx workspai workspace agent-sync --write --refresh-context Sync the Agent Customization Pack")),console.log(e(" npx workspai workspace snapshot --json Persist workspace intelligence snapshot")),console.log(e(" npx workspai workspace diff --from <file|git[:ref]> --json Diff current model against a snapshot")),console.log(e(" npx workspai workspace impact --from <diff> --json Build blast radius from model diff")),console.log(e(" npx workspai workspace verify [--strict] --json Evaluate impact verification evidence")),console.log(e(" npx workspai workspace explain <target> [--write] --json Narrative for blockers/projects (alias: why)")),console.log(e(" npx workspai workspace trace --from <diff> [--write] --json Diff \u2192 blast radius \u2192 gates narrative")),console.log(e(" npx workspai workspace feedback record --json Append agent action outcome to intelligence history")),console.log(e(" npx workspai workspace mcp serve Read-mostly stdio MCP over workspace evidence")),console.log(e(" npx workspai workspace graph [emit|explain|search|benchmark|entities|evidence|path|overlay|dot|mermaid] Query evidence graph")),console.log(e(" npx workspai workspace watch [--once] [--json] Keep model+graph in memory; stream change events")),console.log(e(" npx workspai workspace run <stage> [--scope project:<name>] [--reuse-passed] Fleet init/test/build/start or custom stage")),console.log(e(" npx workspai workspace sync [--json] Sync registry + contract from projects")),console.log(e(" npx workspai workspace registry status [--refresh] [--json] Canonical project registry summary")),console.log(e(" npx workspai import <path|git-url> Copy or clone a project into this workspace")),console.log(e(" npx workspai adopt [path] Link an existing local project to a workspace")),console.log(e(" npx workspai snapshot create [name] Create a recoverable workspace snapshot")),console.log(e(" npx workspai snapshot restore <name> Restore snapshot metadata with safety guard")),console.log(e(" npx workspai snapshot inspect <name> Inspect snapshot manifest and size")),console.log(e(" npx workspai project archive <name> Archive a project with a safety snapshot")),console.log(e(" npx workspai project restore <archive> Restore an archived project safely")),console.log(e(" npx workspai workspace share [--output <file>] Export collaboration bundle")),console.log(e(" npx workspai workspace foundation ensure Ensure workspace.json/policies/toolchain files")),console.log(e(" npx workspai workspace contract init Create workspace service contract")),console.log(e(" npx workspai workspace contract verify Verify service ports/dependencies")),console.log(e(" npx workspai workspace contract graph Show service dependency graph")),console.log(e(" npx workspai workspace export --output <file> Export portable workspace archive")),console.log(e(" npx workspai workspace archive verify <file> Verify archive integrity")),console.log(e(" npx workspai workspace archive doctor <file> Diagnose archive readiness")),console.log(e(" npx workspai workspace hydrate <archive> --output <dir> Hydrate workspace archive")),console.log(e(" npx workspai workspace policy show Show effective workspace policies")),console.log(e(" npx workspai workspace policy set <k> <v> Update workspace policy values")),console.log(e(" npx workspai setup python|node|go|java|dotnet [--warm-deps] Set up runtime (+ optional deps warm-up)")),console.log(e(" npx workspai mirror [status|sync|verify|rotate] Registry mirror management")),console.log(e(" npx workspai cache [status|clear|prune|repair] Package cache management")),console.log(e(" npx workspai infra plan Discover and generate infra compose")),console.log(e(` npx workspai infra up|down|status Manage Docker sidecar infrastructure
490
+ `)),console.log(s.bold("Workspace commands (inside a workspace):")),console.log(e(" npx workspai bootstrap [--profile <p>] Re-bootstrap toolchains")),console.log(e(" npx workspai analyze [--json --strict] Analyze workspace health and gaps")),console.log(e(" npx workspai pipeline [--json --strict --no-agent-sync] Governance loop: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot")),console.log(e(" npx workspai readiness [--workspace <path>] [--json --strict] Release readiness gates (env/doctor/analyze/verify/deps)")),console.log(e(" npx workspai doctor workspace [--ci] Workspace health with CI exit codes")),console.log(e(" npx workspai workspace list List registered workspaces")),console.log(e(" npx workspai workspace model --json Build workspace intelligence model")),console.log(e(" npx workspai workspace intelligence run [--strict] --json Run the canonical contract-backed chain")),console.log(e(" npx workspai workspace context --for-agent --json --write Build agent context + sync grounding")),console.log(e(" npx workspai workspace agent-sync --write --refresh-context Sync the Agent Customization Pack")),console.log(e(" npx workspai workspace snapshot --json Persist workspace intelligence snapshot")),console.log(e(" npx workspai workspace diff --from <file|git[:ref]> --json Diff current model against a snapshot")),console.log(e(" npx workspai workspace impact --from <diff> --json Build blast radius from model diff")),console.log(e(" npx workspai workspace verify [--strict] --json Evaluate impact verification evidence")),console.log(e(" npx workspai workspace explain <target> [--write] --json Narrative for blockers/projects (alias: why)")),console.log(e(" npx workspai workspace trace --from <diff> [--write] --json Diff \u2192 blast radius \u2192 gates narrative")),console.log(e(" npx workspai workspace feedback record --json Append agent action outcome to intelligence history")),console.log(e(" npx workspai workspace eval [init|record|status|report|compare] Measure model usage and verified outcomes")),console.log(e(" npx workspai workspace mcp serve Read-mostly stdio MCP over workspace evidence")),console.log(e(" npx workspai workspace graph [emit|explain|search|benchmark|entities|evidence|path|overlay|dot|mermaid|jsonld|graphml|gexf] Query or export evidence graph")),console.log(e(" npx workspai workspace watch [--once] [--json] Keep model+graph in memory; stream change events")),console.log(e(" npx workspai workspace run <stage> [--scope project:<name>] [--reuse-passed] Fleet init/test/build/start or custom stage")),console.log(e(" npx workspai workspace sync [--json] Sync registry + contract from projects")),console.log(e(" npx workspai workspace registry status [--refresh] [--json] Canonical project registry summary")),console.log(e(" npx workspai import <path|git-url> Copy or clone a project into this workspace")),console.log(e(" npx workspai adopt [path] Link an existing local project to a workspace")),console.log(e(" npx workspai snapshot create [name] Create a recoverable workspace snapshot")),console.log(e(" npx workspai snapshot restore <name> Restore snapshot metadata with safety guard")),console.log(e(" npx workspai snapshot inspect <name> Inspect snapshot manifest and size")),console.log(e(" npx workspai project archive <name> Archive a project with a safety snapshot")),console.log(e(" npx workspai project restore <archive> Restore an archived project safely")),console.log(e(" npx workspai workspace share [--output <file>] Export collaboration bundle")),console.log(e(" npx workspai workspace foundation ensure Ensure workspace.json/policies/toolchain files")),console.log(e(" npx workspai workspace contract init Create workspace service contract")),console.log(e(" npx workspai workspace contract verify Verify service ports/dependencies")),console.log(e(" npx workspai workspace contract graph Show service dependency graph")),console.log(e(" npx workspai workspace export --output <file> Export portable workspace archive")),console.log(e(" npx workspai workspace archive verify <file> Verify archive integrity")),console.log(e(" npx workspai workspace archive doctor <file> Diagnose archive readiness")),console.log(e(" npx workspai workspace hydrate <archive> --output <dir> Hydrate workspace archive")),console.log(e(" npx workspai workspace policy show Show effective workspace policies")),console.log(e(" npx workspai workspace policy set <k> <v> Update workspace policy values")),console.log(e(" npx workspai setup python|node|go|java|dotnet [--warm-deps] Set up runtime (+ optional deps warm-up)")),console.log(e(" npx workspai mirror [status|sync|verify|rotate] Registry mirror management")),console.log(e(" npx workspai cache [status|clear|prune|repair] Package cache management")),console.log(e(" npx workspai infra plan Discover and generate infra compose")),console.log(e(` npx workspai infra up|down|status Manage Docker sidecar infrastructure
489
491
  `)),console.log(s.bold("Options (workspace creation):")),console.log(s.gray(" -y, --yes Skip prompts and use defaults")),console.log(s.gray(" --author <name> Author/team name for workspace metadata")),console.log(s.gray(" --skip-git Skip git initialization")),console.log(s.gray(" --debug Enable debug logging")),console.log(s.gray(" --dry-run Show what would be created")),console.log(s.gray(" --create-workspace When creating a project outside a workspace: create and register a workspace in the current directory")),console.log(s.gray(" --no-workspace When creating a project outside a workspace: do not link it to any workspace")),console.log(s.gray(` --no-update-check Skip checking for updates
490
492
  `)),console.log(s.bold("Project commands (inside a project):")),console.log(e(" npx workspai create project Scaffold a new project")),console.log(s.gray(" cd my-project Change directory to the new project")),console.log(e(" npx workspai init Install project dependencies")),console.log(e(" npx workspai dev Start dev server")),console.log(e(" npx workspai build Build for production")),console.log(e(` npx workspai test Run tests
491
493
  `)),console.log(s.bold("Flags clarification:")),console.log(s.gray(" --skip-install npm fast-path for lock/dependency steps")),console.log(s.gray(` --skip-essentials core flag for skipping essential module installation
492
- `)),lu?(console.log(s.bold("Legacy (shown because RAPIDKIT_SHOW_LEGACY=1):")),console.log(s.gray(" npx workspai my-project --template fastapi")),console.log(s.gray(" npx workspai my-project --template nestjs")),console.log(s.gray(" npx workspai my-project --template springboot")),console.log(s.gray(" npx workspai my-project --template gofiber")),console.log(s.gray(" npx workspai my-project --template gogin")),console.log(s.gray(" npx workspai my-project --template dotnet")),console.log(s.gray(` --skip-install Fast-path lock/deps (legacy template mode) \u2014 not same as --skip-essentials
494
+ `)),mu?(console.log(s.bold("Legacy (shown because RAPIDKIT_SHOW_LEGACY=1):")),console.log(s.gray(" npx workspai my-project --template fastapi")),console.log(s.gray(" npx workspai my-project --template nestjs")),console.log(s.gray(" npx workspai my-project --template springboot")),console.log(s.gray(" npx workspai my-project --template gofiber")),console.log(s.gray(" npx workspai my-project --template gogin")),console.log(s.gray(" npx workspai my-project --template dotnet")),console.log(s.gray(` --skip-install Fast-path lock/deps (legacy template mode) \u2014 not same as --skip-essentials
493
495
  `))):console.log(s.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
494
- `));}var Ic="__rapidkit_signal_handlers_registered__",$c=globalThis;$c[Ic]||($c[Ic]=true,process.on("SIGINT",async()=>{if(!$r){if($r=true,console.log(s.yellow(`
496
+ `));}var Nc="__rapidkit_signal_handlers_registered__",Mc=globalThis;Mc[Nc]||(Mc[Nc]=true,process.on("SIGINT",async()=>{if(!$r){if($r=true,console.log(s.yellow(`
495
497
 
496
- \u26A0\uFE0F Interrupted by user`)),vt&&await I__default.pathExists(vt)){console.log(s.gray("Cleaning up partial installation..."));try{await I__default.remove(vt),console.log(s.green("\u2713 Cleanup complete"));}catch(t){f.debug("Cleanup failed:",t);}}b$9(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!$r){if($r=true,f.debug("Received SIGTERM"),vt&&await I__default.pathExists(vt))try{await I__default.remove(vt);}catch(t){f.debug("Cleanup failed:",t);}b$9(143,"Terminated"),process.exit(143);}}));var mu=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",gu=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),o=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return x.realpathSync(t)===x.realpathSync(fileURLToPath(import.meta.url))||o}catch{return b.resolve(t)===b.resolve(fileURLToPath(import.meta.url))||o}})(),fu=!mu||gu;function hu(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}function yu(){for(let t of [process.stdout,process.stderr]){if(t.isTTY)continue;let e=t;if(e.__rapidkitSyncWriteInstalled)continue;let o=t.fd;if(typeof o!="number")continue;let r=t.write.bind(t);e.write=((n,a,i)=>{let c=typeof a=="string"?a:"utf8",l=typeof a=="function"?a:typeof i=="function"?i:void 0;try{let p=typeof n=="string"?Buffer.from(n,c):n instanceof Uint8Array?Buffer.from(n):Buffer.from(String(n),c);return x.writeSync(o,p),l?.(),true}catch{return r(n,c,l)}}),e.__rapidkitSyncWriteInstalled=true;}}async function je(t){b$9(t),await new Promise(e=>setImmediate(e)),await new Promise(e=>setTimeout(e,25)),await Promise.all([process.stdout,process.stderr].map(e=>new Promise(o=>{e.write("",()=>o());}))),process.exit(t);}async function Oc(t,e=0){return x.writeSync(process.stdout.fd??1,t),je(e)}async function wu(){hu(),yu(),d$4(),a$6({argv:process.argv,cwd:process.cwd(),rapidkitVersion:c()}),c$5(process.argv);let t=process.argv.slice(2),e$1=t[0],o=process.cwd(),r=qe(o),n=p(o,"project.json").some(m=>x.existsSync(m)),a$1=Td(),i=Cc(t),c$1=a$1&&Co(t),l=e$1==="init"&&r&&!n;(t.length===0||t.length===1&&(e$1==="--help"||e$1==="-h"||e$1==="help"))&&(a("npm cli"),Kc(),await je(0)),t.some(m=>m==="--version"||m==="-V"||m==="-v")&&!t.some(m=>m==="--help"||m==="-h"||m==="help")&&(t.includes("--json")?await Oc(`${JSON.stringify(Wd(),null,2)}
497
- `):await Oc(`${c()}
498
+ \u26A0\uFE0F Interrupted by user`)),vt&&await O__default.pathExists(vt)){console.log(s.gray("Cleaning up partial installation..."));try{await O__default.remove(vt),console.log(s.green("\u2713 Cleanup complete"));}catch(t){f.debug("Cleanup failed:",t);}}b$9(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!$r){if($r=true,f.debug("Received SIGTERM"),vt&&await O__default.pathExists(vt))try{await O__default.remove(vt);}catch(t){f.debug("Cleanup failed:",t);}b$9(143,"Terminated"),process.exit(143);}}));var yu=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",wu=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),o=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return E.realpathSync(t)===E.realpathSync(fileURLToPath(import.meta.url))||o}catch{return b.resolve(t)===b.resolve(fileURLToPath(import.meta.url))||o}})(),ku=!yu||wu;function vu(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}function Pu(){for(let t of [process.stdout,process.stderr]){if(t.isTTY)continue;let e=t;if(e.__rapidkitSyncWriteInstalled)continue;let o=t.fd;if(typeof o!="number")continue;let r=t.write.bind(t);e.write=((n,a,i)=>{let c=typeof a=="string"?a:"utf8",l=typeof a=="function"?a:typeof i=="function"?i:void 0;try{let p=typeof n=="string"?Buffer.from(n,c):n instanceof Uint8Array?Buffer.from(n):Buffer.from(String(n),c);return E.writeSync(o,p),l?.(),true}catch{return r(n,c,l)}}),e.__rapidkitSyncWriteInstalled=true;}}async function je(t){b$9(t),await new Promise(e=>setImmediate(e)),await new Promise(e=>setTimeout(e,25)),await Promise.all([process.stdout,process.stderr].map(e=>new Promise(o=>{e.write("",()=>o());}))),process.exit(t);}async function Tc(t,e=0){return E.writeSync(process.stdout.fd??1,t),je(e)}async function bu(){vu(),Pu(),d$4(),a$6({argv:process.argv,cwd:process.cwd(),rapidkitVersion:c()}),c$5(process.argv);let t=process.argv.slice(2),e$1=t[0],o=process.cwd(),r=qe(o),n=p(o,"project.json").some(m=>E.existsSync(m)),a$1=Fd(),i=Ec(t),c$1=a$1&&Co(t),l=e$1==="init"&&r&&!n;(t.length===0||t.length===1&&(e$1==="--help"||e$1==="-h"||e$1==="help"))&&(a("npm cli"),Uc(),await je(0)),t.some(m=>m==="--version"||m==="-V"||m==="-v")&&!t.some(m=>m==="--help"||m==="-h"||m==="help")&&(t.includes("--json")?await Tc(`${JSON.stringify(Jd(),null,2)}
499
+ `):await Tc(`${c()}
498
500
  `)),rs(t)&&await je(0),c$1&&e$1===Pr?(async()=>{await je(await ts(t));})().catch(m=>{process.stderr.write(`Workspai CLI failed to run create: ${m?.message??m}
499
- `),process.exit(1);}):c$1&&Sc(e$1)?(async()=>{await je(await xc(e$1,t));})().catch(m=>{process.stderr.write(`Workspai CLI failed to run ${e$1}: ${m?.message??m}
501
+ `),process.exit(1);}):c$1&&Rc(e$1)?(async()=>{await je(await Ac(e$1,t));})().catch(m=>{process.stderr.write(`Workspai CLI failed to run ${e$1}: ${m?.message??m}
500
502
  `),process.exit(1);}):i||c$1?ce.parseAsync().then(()=>je(0)).catch(m=>{let d=Qt()&&m instanceof Error&&m.stack?m.stack:m?.message??m;process.stderr.write(`Workspai CLI failed: ${d}
501
503
  `),process.exit(1);}):l?cs(t).then(m=>je(m)).catch(m=>{process.stderr.write(`Workspai CLI failed to run workspace init: ${m?.message??m}
502
- `),process.exit(1);}):iu().then(async m$1=>{if(!m$1){let d=process.argv.slice(2);if(Qt()&&process.stderr.write(`[workspai-cli] argv=${JSON.stringify(d)}
503
- `),Cc(d)){await ce.parseAsync();return}if(rs(d)&&await je(0),d[0]===Pr){let g=await ts(d);await je(g);}if(d[0]==="init"){let g=await cs(d);await je(g);}if(Sc(d[0])){let g=await xc(d[0],d);await je(g);}if(s$1(d[0])){if(ns(d))return;let g=d[0],k=i$2(process.cwd()),C=await Rt(process.cwd()),A=le(process.cwd()),w=false;if(A){let u=o$1(A,"policies.yml").find(j=>x.existsSync(j));if(u&&await I__default.pathExists(u))try{let j$1=await x.promises.readFile(u,"utf-8");if(w=((j$1.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??j$1.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict",w){let S=o$1(A,"toolchain.lock").find(W=>x.existsSync(W)),$=[];if(!S||!await I__default.pathExists(S))$.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain).");else try{let N=JSON.parse(await x.promises.readFile(S,"utf-8")).runtime??{};j(k,process.cwd())&&!N.go?.version&&$.push("Go runtime version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."),k$1(k,process.cwd())&&!N.node?.version&&$.push("Node runtime version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."),l$1(k,process.cwd())&&!N.java?.version&&$.push("Java runtime version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."),m(k,process.cwd())&&!N.dotnet?.version&&$.push(".NET runtime version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."),n$1(k,process.cwd())&&!N.python?.version&&$.push("Python runtime version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");}catch{$.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode.");}let L=o$1(A,"workspace.json").find(W=>x.existsSync(W));if(L&&await I__default.pathExists(L))try{let N=JSON.parse(await x.promises.readFile(L,"utf-8")).profile??"",R=i$3(process.cwd(),k),H=kt({profile:N,runtime:R.runtime,subjectLabel:b.basename(process.cwd()),mode:"strict"});H.ok||$.push(`${H.message} Update the workspace profile or use a polyglot workspace.`);}catch{}if($.length>0){console.log(s.red(`\u274C Strict policy violations block \`${g}\`:`));for(let W of $)console.log(s.red(` \u2022 ${W}`));console.log(s.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .workspai/policies.yml")),await je(1);}}}catch{}}let y=await a$7({startPath:process.cwd(),action:g,writeReport:true}),f=w||process.env.RAPIDKIT_LIFECYCLE_ENFORCE_READINESS==="1"||process.env.RAPIDKIT_ENFORCE_READINESS==="1";if(y.blocking&&f){console.log(s.red(`\u274C Release readiness blocks \`${g}\`:`));for(let u of y.blockingReasons)console.log(s.red(` \u2022 ${u}`));y.evidencePath&&console.log(s.gray(`\u2139\uFE0F Readiness evidence: ${y.evidencePath}`)),await je(1);}y.overallStatus!=="pass"&&!f&&(console.log(s.yellow(`\u26A0\uFE0F Release readiness is ${y.overallStatus}. Command continues in warn mode.`)),y.evidencePath&&console.log(s.gray(` Evidence: ${y.evidencePath} (set RAPIDKIT_LIFECYCLE_ENFORCE_READINESS=1 to block)`)));let v=await Jc(process.cwd(),async()=>{if(j(k,process.cwd())||C==="go"){let u=Ze("go",{runCommandInCwd:se,runCoreRapidkit:e});if(g==="lint")return ae(await u.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(g==="format")return ae(await u.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let j=g==="dev"?await u.runDev(process.cwd()):g==="test"?await u.runTest(process.cwd()):g==="build"?await u.runBuild(process.cwd()):await u.runStart(process.cwd());return j.message&&console.log(s.red(`\u274C ${j.message}`)),j.exitCode}if(l$1(k,process.cwd())||C==="java")return g==="dev"?await lt("dev",process.cwd()):g==="test"?await lt("test",process.cwd()):g==="build"?await lt("build",process.cwd()):g==="lint"?await lt("lint",process.cwd()):g==="format"?await lt("format",process.cwd()):await lt("start",process.cwd());if(m(k,process.cwd())||C==="dotnet"){let u=Ze("dotnet",{runCommandInCwd:se,runCoreRapidkit:e});if(g==="lint")return ae(await u.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(g==="format")return ae(await u.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let j=g==="dev"?await u.runDev(process.cwd()):g==="test"?await u.runTest(process.cwd()):g==="build"?await u.runBuild(process.cwd()):await u.runStart(process.cwd());return j.message&&console.log(s.red(`\u274C ${j.message}`)),j.exitCode}if(k$1(k,process.cwd())||C==="node")return g==="dev"?await Et("dev",process.cwd()):g==="test"?await Et("test",process.cwd()):g==="build"?await Et("build",process.cwd()):g==="lint"?await Et("lint",process.cwd()):g==="format"?await Et("format",process.cwd()):await Et("start",process.cwd());if(n$1(k,process.cwd())||C==="python"){if(g==="lint"||g==="format")return await e([g],{cwd:process.cwd()});let u=Ze("python",{runCommandInCwd:se,runCoreRapidkit:e});return ae(g==="dev"?await u.runDev(process.cwd()):g==="test"?await u.runTest(process.cwd()):g==="build"?await u.runBuild(process.cwd()):await u.runStart(process.cwd()))}return -1});if(!v.ok){await je(v.code);return}if(v.ok&&v.value>=0){await je(v.value);return}if(v.ok&&v.value===-1){console.error(s.red(`\u274C Workspai cannot run \`${g}\` for this project runtime.`)),console.error(s.gray("Run `workspai project commands` to inspect supported commands.")),await je(1);return}}if(ns(d))return;let h=await pu(d);if(Qt()&&process.stderr.write(`[workspai-cli] shouldForwardToCore=${h}
504
- `),h){let g=await e(d,{cwd:process.cwd()});await je(g);}await ce.parseAsync();}});}fu&&await wu();export{Ln as COMMAND_CAPABILITIES_SCHEMA_VERSION,fd as NPM_ONLY_SCOPED_COMMANDS,hd as NPM_ONLY_TOP_LEVEL_COMMANDS,Qi as VERSION_CONTRACT_SCHEMA_VERSION,$d as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,wu as bootstrapCli,Hn as bridgeFailureCode,wc as buildDelegationEnvForInit,_c as checkStrictPolicyPreflightForDelegation,Pd as commandAvailable,Mc as createProjectVenv,bd as createWorkspaceVenv,Gd as defaultWorkspacePolicyYaml,Fd as detectWindowsDoctorWorkspaceShadow,jd as ensurePythonProjectUsesLocalVenv,Wc as findContextFileUp,Jd as findLegacyWorkspaceUp,ss as findWorkspaceMarkerUp,le as findWorkspaceUp,Dd as getGlobalCommandCapabilities,jr as getPublishedContractCatalog,wo as getPublishedContractVersions,Wd as getVersionContract,Xd as handleAdoptCommand,tu as handleBootstrapCommand,nu as handleCacheCommand,ts as handleCreateOrFallback,Yn as handleGoInit,Qd as handleImportCommand,cs as handleInitCommand,lt as handleJavaCommand,au as handleMirrorCommand,Et as handleNodeCommand,ou as handleSetupCommand,qe as hasWorkspaceRootMarkers,ps as hostPythonCandidates,Rt as inferRuntimeByFiles,Cd as installPythonDependenciesWithPipFallback,as as installWorkspaceDependencies,Td as isNpmExecInvocation,Co as isNpmOnlyInvocation,Sc as isNpmOnlyManualHandlerCommand,Md as isNpmOnlyParseDirectCommand,Cc as isNpmOnlyParseDirectInvocation,os as isNpmOnlyScopedCommand,Nd as isNpmOnlyTopLevelCommand,wd as normalizeFallbackTemplate,ru as parseCacheConfig,kd as parseMaxWorkersOption,qd as parseNodeEvalScript,Bd as parsePolicyBooleanLiteral,Kc as printHelp,ce as program,Se as readFlagValue,Vd as replaceOrInsertRulePolicyLine,Rc as replaceOrInsertTopLevelPolicyLine,yd as resolveInvokedCliName,se as runCommandInCwd,Ir as runCreateFallback,pu as shouldForwardToCore,Sd as validateNpmKitFlags};
504
+ `),process.exit(1);}):du().then(async m$1=>{if(!m$1){let d=process.argv.slice(2);if(Qt()&&process.stderr.write(`[workspai-cli] argv=${JSON.stringify(d)}
505
+ `),Ec(d)){await ce.parseAsync();return}if(rs(d)&&await je(0),d[0]===Pr){let g=await ts(d);await je(g);}if(d[0]==="init"){let g=await cs(d);await je(g);}if(Rc(d[0])){let g=await Ac(d[0],d);await je(g);}if(s$1(d[0])){if(ns(d))return;let g=d[0],P=i$2(process.cwd()),j$1=await At(process.cwd()),A=le(process.cwd()),h=false;if(A){let u=o$1(A,"policies.yml").find(C=>E.existsSync(C));if(u&&await O__default.pathExists(u))try{let C=await E.promises.readFile(u,"utf-8");if(h=((C.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??C.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict",h){let v=o$1(A,"toolchain.lock").find(T=>E.existsSync(T)),I=[];if(!v||!await O__default.pathExists(v))I.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain).");else try{let $=JSON.parse(await E.promises.readFile(v,"utf-8")).runtime??{};j(P,process.cwd())&&!$.go?.version&&I.push("Go runtime version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."),k$1(P,process.cwd())&&!$.node?.version&&I.push("Node runtime version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."),l$1(P,process.cwd())&&!$.java?.version&&I.push("Java runtime version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."),m(P,process.cwd())&&!$.dotnet?.version&&I.push(".NET runtime version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."),n$1(P,process.cwd())&&!$.python?.version&&I.push("Python runtime version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");}catch{I.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode.");}let N=o$1(A,"workspace.json").find(T=>E.existsSync(T));if(N&&await O__default.pathExists(N))try{let $=JSON.parse(await E.promises.readFile(N,"utf-8")).profile??"",S=i$3(process.cwd(),P),K=kt({profile:$,runtime:S.runtime,subjectLabel:b.basename(process.cwd()),mode:"strict"});K.ok||I.push(`${K.message} Update the workspace profile or use a polyglot workspace.`);}catch{}if(I.length>0){console.log(s.red(`\u274C Strict policy violations block \`${g}\`:`));for(let T of I)console.log(s.red(` \u2022 ${T}`));console.log(s.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .workspai/policies.yml")),await je(1);}}}catch{}}let y=await a$7({startPath:process.cwd(),action:g,writeReport:true}),f=h||process.env.RAPIDKIT_LIFECYCLE_ENFORCE_READINESS==="1"||process.env.RAPIDKIT_ENFORCE_READINESS==="1";if(y.blocking&&f){console.log(s.red(`\u274C Release readiness blocks \`${g}\`:`));for(let u of y.blockingReasons)console.log(s.red(` \u2022 ${u}`));y.evidencePath&&console.log(s.gray(`\u2139\uFE0F Readiness evidence: ${y.evidencePath}`)),await je(1);}y.overallStatus!=="pass"&&!f&&(console.log(s.yellow(`\u26A0\uFE0F Release readiness is ${y.overallStatus}. Command continues in warn mode.`)),y.evidencePath&&console.log(s.gray(` Evidence: ${y.evidencePath} (set RAPIDKIT_LIFECYCLE_ENFORCE_READINESS=1 to block)`)));let k=await Gc(process.cwd(),async()=>{if(j(P,process.cwd())||j$1==="go"){let u=et("go",{runCommandInCwd:se,runCoreRapidkit:e});if(g==="lint")return ae(await u.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(g==="format")return ae(await u.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let C=g==="dev"?await u.runDev(process.cwd()):g==="test"?await u.runTest(process.cwd()):g==="build"?await u.runBuild(process.cwd()):await u.runStart(process.cwd());return C.message&&console.log(s.red(`\u274C ${C.message}`)),C.exitCode}if(l$1(P,process.cwd())||j$1==="java")return g==="dev"?await pt("dev",process.cwd()):g==="test"?await pt("test",process.cwd()):g==="build"?await pt("build",process.cwd()):g==="lint"?await pt("lint",process.cwd()):g==="format"?await pt("format",process.cwd()):await pt("start",process.cwd());if(m(P,process.cwd())||j$1==="dotnet"){let u=et("dotnet",{runCommandInCwd:se,runCoreRapidkit:e});if(g==="lint")return ae(await u.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(g==="format")return ae(await u.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let C=g==="dev"?await u.runDev(process.cwd()):g==="test"?await u.runTest(process.cwd()):g==="build"?await u.runBuild(process.cwd()):await u.runStart(process.cwd());return C.message&&console.log(s.red(`\u274C ${C.message}`)),C.exitCode}if(k$1(P,process.cwd())||j$1==="node")return g==="dev"?await Rt("dev",process.cwd()):g==="test"?await Rt("test",process.cwd()):g==="build"?await Rt("build",process.cwd()):g==="lint"?await Rt("lint",process.cwd()):g==="format"?await Rt("format",process.cwd()):await Rt("start",process.cwd());if(n$1(P,process.cwd())||j$1==="python"){if(g==="lint"||g==="format")return await e([g],{cwd:process.cwd()});let u=et("python",{runCommandInCwd:se,runCoreRapidkit:e});return ae(g==="dev"?await u.runDev(process.cwd()):g==="test"?await u.runTest(process.cwd()):g==="build"?await u.runBuild(process.cwd()):await u.runStart(process.cwd()))}return -1});if(!k.ok){await je(k.code);return}if(k.ok&&k.value>=0){await je(k.value);return}if(k.ok&&k.value===-1){console.error(s.red(`\u274C Workspai cannot run \`${g}\` for this project runtime.`)),console.error(s.gray("Run `workspai project commands` to inspect supported commands.")),await je(1);return}}if(ns(d))return;let w=await gu(d);if(Qt()&&process.stderr.write(`[workspai-cli] shouldForwardToCore=${w}
506
+ `),w){let g=await e(d,{cwd:process.cwd()});await je(g);}await ce.parseAsync();}});}ku&&await bu();export{Ln as COMMAND_CAPABILITIES_SCHEMA_VERSION,kd as NPM_ONLY_SCOPED_COMMANDS,vd as NPM_ONLY_TOP_LEVEL_COMMANDS,ec as VERSION_CONTRACT_SCHEMA_VERSION,Td as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,bu as bootstrapCli,Hn as bridgeFailureCode,Pc as buildDelegationEnvForInit,Oc as checkStrictPolicyPreflightForDelegation,Sd as commandAvailable,Dc as createProjectVenv,xd as createWorkspaceVenv,qd as defaultWorkspacePolicyYaml,Gd as detectWindowsDoctorWorkspaceShadow,Ed as ensurePythonProjectUsesLocalVenv,Fc as findContextFileUp,Ud as findLegacyWorkspaceUp,ss as findWorkspaceMarkerUp,le as findWorkspaceUp,Kd as getGlobalCommandCapabilities,jr as getPublishedContractCatalog,wo as getPublishedContractVersions,Jd as getVersionContract,ou as handleAdoptCommand,su as handleBootstrapCommand,cu as handleCacheCommand,ts as handleCreateOrFallback,Yn as handleGoInit,tu as handleImportCommand,cs as handleInitCommand,pt as handleJavaCommand,pu as handleMirrorCommand,Rt as handleNodeCommand,au as handleSetupCommand,qe as hasWorkspaceRootMarkers,ps as hostPythonCandidates,At as inferRuntimeByFiles,Rd as installPythonDependenciesWithPipFallback,as as installWorkspaceDependencies,Fd as isNpmExecInvocation,Co as isNpmOnlyInvocation,Rc as isNpmOnlyManualHandlerCommand,Ld as isNpmOnlyParseDirectCommand,Ec as isNpmOnlyParseDirectInvocation,os as isNpmOnlyScopedCommand,Dd as isNpmOnlyTopLevelCommand,bd as normalizeFallbackTemplate,iu as parseCacheConfig,jd as parseMaxWorkersOption,Xd as parseNodeEvalScript,Yd as parsePolicyBooleanLiteral,Uc as printHelp,ce as program,Se as readFlagValue,Hd as replaceOrInsertRulePolicyLine,Ic as replaceOrInsertTopLevelPolicyLine,Pd as resolveInvokedCliName,se as runCommandInCwd,Ir as runCreateFallback,gu as shouldForwardToCore,Ad as validateNpmKitFlags};