workspai 0.67.0 → 0.68.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 (107) hide show
  1. package/contracts/workspace-activity-board.v1.json +6 -0
  2. package/contracts/workspace-activity-event.v1.json +31 -1
  3. package/contracts/workspace-activity-monitor-snapshot.v1.json +35 -2
  4. package/contracts/workspace-intelligence/workspace-knowledge-search.v1.json +1 -0
  5. package/dist/analyze-JDEWUBC6.js +1 -0
  6. package/dist/{artifact-remediation-plan-GFFHC2ZU.js → artifact-remediation-plan-I7IKC5MR.js} +1 -1
  7. package/dist/autopilot-release-OELUFNLL.js +1 -0
  8. package/dist/capabilities-command-RAAYENQ6.js +1 -0
  9. package/dist/chunk-25AWHAB5.js +2 -0
  10. package/dist/{chunk-KQ2TMI26.js → chunk-2C5XJBYI.js} +1 -1
  11. package/dist/{chunk-TP7VKEUF.js → chunk-2KX6KHEC.js} +1 -1
  12. package/dist/{chunk-2RPFCBS4.js → chunk-3BMYMZQB.js} +1 -1
  13. package/dist/{chunk-BRYJTW6S.js → chunk-3KU3YUWD.js} +1 -1
  14. package/dist/{chunk-ENZPM52J.js → chunk-3NF3M3RE.js} +1 -1
  15. package/dist/{chunk-HQLBO23O.js → chunk-3XF7O66C.js} +3 -3
  16. package/dist/{chunk-H77ZNH5O.js → chunk-3Z4SVBMR.js} +1 -1
  17. package/dist/{chunk-NVND4727.js → chunk-46QH3ZVI.js} +1 -1
  18. package/dist/{chunk-VI4ZRAY6.js → chunk-5OV2WXAR.js} +1 -1
  19. package/dist/{chunk-Y35VLVF6.js → chunk-5XUAAQSV.js} +2 -2
  20. package/dist/{chunk-BHFRP7TV.js → chunk-5YZ2W57R.js} +1 -1
  21. package/dist/{chunk-B4IVVTMQ.js → chunk-64XWHDZ3.js} +1 -1
  22. package/dist/{chunk-KENOAC2Q.js → chunk-7DDEMDG2.js} +1 -1
  23. package/dist/{chunk-IQQMFRWM.js → chunk-7DZNZ3GM.js} +1 -1
  24. package/dist/{chunk-N4QFNOAI.js → chunk-BG6IX6HA.js} +1 -1
  25. package/dist/{chunk-2MVIRJJR.js → chunk-BMAFHX6A.js} +1 -1
  26. package/dist/{chunk-XDPTAV2T.js → chunk-C2VTO5WT.js} +1 -1
  27. package/dist/{chunk-JCGSIDMC.js → chunk-CSZPE637.js} +1 -1
  28. package/dist/{chunk-5OA33JH2.js → chunk-D5LLTUTY.js} +1 -1
  29. package/dist/{chunk-4RV4JVGR.js → chunk-DFVG4DDZ.js} +1 -1
  30. package/dist/{chunk-OCNPOYMA.js → chunk-EHLGPLIU.js} +1 -1
  31. package/dist/{chunk-6254CWUY.js → chunk-GVQKAINC.js} +1 -1
  32. package/dist/{chunk-HYE5UHPV.js → chunk-IXXQMD34.js} +1 -1
  33. package/dist/{chunk-GIQ4SDRJ.js → chunk-JYMO7QXQ.js} +1 -1
  34. package/dist/{chunk-THIG2YQP.js → chunk-KDY4X7SQ.js} +1 -1
  35. package/dist/{chunk-L5Q2S5GY.js → chunk-KFTJVVJR.js} +1 -1
  36. package/dist/{chunk-SX6A656X.js → chunk-KY2GOSO5.js} +1 -1
  37. package/dist/chunk-LDBULT2T.js +4 -0
  38. package/dist/{chunk-PSYQ6IJA.js → chunk-LEOFD3W5.js} +1 -1
  39. package/dist/{chunk-5EVDW7JM.js → chunk-N5HPMATQ.js} +1 -1
  40. package/dist/{chunk-CZVT7T2X.js → chunk-OFYY4725.js} +1 -1
  41. package/dist/{chunk-3O7LZPKA.js → chunk-P3622IM5.js} +1 -1
  42. package/dist/{chunk-TABXSDTR.js → chunk-PKKSRXUS.js} +1 -1
  43. package/dist/{chunk-ARUFY5W3.js → chunk-Q7UGDNSM.js} +1 -1
  44. package/dist/{chunk-2M62CU3O.js → chunk-RVAOJOXA.js} +1 -1
  45. package/dist/{chunk-EHCKITR4.js → chunk-TCLKGPXF.js} +1 -1
  46. package/dist/{chunk-SRLWHOLF.js → chunk-TMRCPT7S.js} +1 -1
  47. package/dist/{chunk-VWBMDGPY.js → chunk-VIN7NJW3.js} +1 -1
  48. package/dist/chunk-W37NOQVG.js +1 -0
  49. package/dist/{chunk-SVYY55IS.js → chunk-W5VKBDSD.js} +1 -1
  50. package/dist/{chunk-YYY2WXOH.js → chunk-WRZSQDZV.js} +1 -1
  51. package/dist/{create-72ITVZXV.js → create-U5PQHOZ4.js} +1 -1
  52. package/dist/{demo-kit-5UQH2OXC.js → demo-kit-RKTHTXHJ.js} +1 -1
  53. package/dist/{doctor-CVYUESRQ.js → doctor-D7YI7LSA.js} +1 -1
  54. package/dist/{dotnet-webapi-clean-YEHYIGOT.js → dotnet-webapi-clean-XL4IBUQV.js} +1 -1
  55. package/dist/{goal-lifecycle-H55AGFCB.js → goal-lifecycle-BMS6GSIU.js} +1 -1
  56. package/dist/{goal-pack-6OBZOPCD.js → goal-pack-RBSVQMMX.js} +1 -1
  57. package/dist/{gofiber-standard-C44IIQYH.js → gofiber-standard-OHHMCNMJ.js} +1 -1
  58. package/dist/{gogin-standard-X7VKACVR.js → gogin-standard-BAZXPOKL.js} +1 -1
  59. package/dist/index.js +23 -23
  60. package/dist/{live-command-5VXPR43F.js → live-command-GNAASZ7U.js} +1 -1
  61. package/dist/{pipeline-SKYOXWHW.js → pipeline-QOMXH2EK.js} +1 -1
  62. package/dist/{project-agent-entry-5IUBEREI.js → project-agent-entry-MH7364BE.js} +1 -1
  63. package/dist/{project-intelligence-lens-LQCN65P2.js → project-intelligence-lens-ZCCHUKVI.js} +1 -1
  64. package/dist/{project-test-coverage-KD4LLFGV.js → project-test-coverage-JPWTBSSJ.js} +1 -1
  65. package/dist/{rust-axum-JKZTZDRZ.js → rust-axum-CCJ6UCBW.js} +1 -1
  66. package/dist/{springboot-standard-PI4FLTAN.js → springboot-standard-M5JQEJML.js} +1 -1
  67. package/dist/{verified-goal-HN7G532B.js → verified-goal-XUXU2X5H.js} +1 -1
  68. package/dist/{workspace-5W7FYGDQ.js → workspace-B33BFZZ3.js} +1 -1
  69. package/dist/{workspace-agent-sync-OZCDQORK.js → workspace-agent-sync-T3MJO2MX.js} +1 -1
  70. package/dist/{workspace-context-L65BR5L6.js → workspace-context-KOCEP4MJ.js} +1 -1
  71. package/dist/{workspace-contract-JYHNEJPV.js → workspace-contract-MQ3QE52V.js} +1 -1
  72. package/dist/{workspace-explain-SUBK6FLO.js → workspace-explain-DTFCKYXK.js} +1 -1
  73. package/dist/{workspace-feedback-MWGCT5R2.js → workspace-feedback-3YLIUFQ7.js} +1 -1
  74. package/dist/{workspace-foundation-VIB3PXNH.js → workspace-foundation-O7O3QIS4.js} +1 -1
  75. package/dist/{workspace-graph-stream-45JHE4MG.js → workspace-graph-stream-XTGGBD7D.js} +1 -1
  76. package/dist/workspace-graph-token-efficiency-5LJKQU2J.js +1 -0
  77. package/dist/{workspace-history-JKW3VJO3.js → workspace-history-7HDZZ4G5.js} +1 -1
  78. package/dist/{workspace-intelligence-3C47PK4L.js → workspace-intelligence-TFEQBPUP.js} +1 -1
  79. package/dist/{workspace-intelligence-benchmark-SRDIHX3X.js → workspace-intelligence-benchmark-PLVUBGWO.js} +1 -1
  80. package/dist/{workspace-intelligence-runner-OWN5ZI6W.js → workspace-intelligence-runner-6ZAV6RO4.js} +1 -1
  81. package/dist/{workspace-knowledge-graph-AKG5NUU6.js → workspace-knowledge-graph-AUXYL3L6.js} +1 -1
  82. package/dist/{workspace-knowledge-graph-query-DXA4CROE.js → workspace-knowledge-graph-query-A7TKONWY.js} +1 -1
  83. package/dist/workspace-knowledge-graph-snapshot-GPBDAKAU.js +1 -0
  84. package/dist/{workspace-mcp-serve-PK226GMV.js → workspace-mcp-serve-TDUXJUAA.js} +1 -1
  85. package/dist/{workspace-model-R4ISKDB2.js → workspace-model-GVXNLSQM.js} +1 -1
  86. package/dist/{workspace-onboarding-Y5RPEFUD.js → workspace-onboarding-ECZ2KJ2A.js} +1 -1
  87. package/dist/{workspace-readme-PL5V3UDH.js → workspace-readme-6N5Y2ZSJ.js} +1 -1
  88. package/dist/{workspace-registry-summary-STGUGROG.js → workspace-registry-summary-5SFBTRGQ.js} +1 -1
  89. package/dist/{workspace-repair-engine-FNLL5ZDK.js → workspace-repair-engine-CKJCTWKX.js} +1 -1
  90. package/dist/workspace-run-ZZ5WHL7W.js +1 -0
  91. package/dist/{workspace-verify-AXVX3PF3.js → workspace-verify-D3QTMAUI.js} +1 -1
  92. package/dist/{workspace-watch-RLBEJKXE.js → workspace-watch-XYJEW2Z2.js} +1 -1
  93. package/docs/ci-workflows.md +1 -1
  94. package/docs/commands-reference.md +3 -1
  95. package/docs/contracts/README.md +1 -1
  96. package/docs/workspace-knowledge-graph.md +1 -0
  97. package/docs/workspace-live-activity.md +18 -4
  98. package/package.json +1 -1
  99. package/dist/analyze-IC2KRVCG.js +0 -1
  100. package/dist/autopilot-release-RECEZAZI.js +0 -1
  101. package/dist/capabilities-command-X4WZIJNR.js +0 -1
  102. package/dist/chunk-5TY74LLW.js +0 -2
  103. package/dist/chunk-UTV4DTNM.js +0 -1
  104. package/dist/chunk-ZI2E7P6O.js +0 -4
  105. package/dist/workspace-graph-token-efficiency-NPECU6Y5.js +0 -1
  106. package/dist/workspace-knowledge-graph-snapshot-SNI5K2RL.js +0 -1
  107. package/dist/workspace-run-GFBFGUFM.js +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$v}from'./chunk-FB7SCXAZ.js';import {a as a$n}from'./chunk-ICGWHIMK.js';import {h as h$4,b as b$h,a as a$z}from'./chunk-ZI2E7P6O.js';import {b,c,d,j as j$1,h as h$1,i,r,l,n as n$2,p as p$4,o as o$2,m as m$2,q as q$2,a as a$K,k as k$5}from'./chunk-HYE5UHPV.js';import {a as a$j}from'./chunk-VI4ZRAY6.js';import {a as a$s}from'./chunk-SRLWHOLF.js';import {a as a$t}from'./chunk-2RPFCBS4.js';import {c as c$9,b as b$g,a as a$r}from'./chunk-CPR2CMOY.js';import {d as d$3,c as c$3,p as p$2,b as b$k,a as a$I}from'./chunk-BHM6RHTA.js';import {a as a$l,f as f$4,d as d$8,i as i$3}from'./chunk-4WVOAX2V.js';import {c as c$1,b as b$6,a as a$J}from'./chunk-LPCWROQ3.js';import {b as b$4,a as a$7}from'./chunk-3O7LZPKA.js';import {b as b$f,a as a$p,c as c$8}from'./chunk-6254CWUY.js';import {b as b$8,a as a$a}from'./chunk-5OA33JH2.js';import {c as c$5,d as d$5,e as e$5,b as b$e,g as g$4}from'./chunk-HQLBO23O.js';import {j as j$4,a as a$d,k as k$3}from'./chunk-SVYY55IS.js';import {b as b$a,g as g$3,c as c$e,a as a$H}from'./chunk-2M62CU3O.js';import {g as g$6,e as e$9,c as c$c,b as b$i,a as a$D}from'./chunk-GIQ4SDRJ.js';import {a as a$k,e as e$a,d as d$9}from'./chunk-5ME4W4LN.js';import {a,b as b$1}from'./chunk-B6FJ6RG6.js';import {a as a$q}from'./chunk-5EVDW7JM.js';import {a as a$u}from'./chunk-2MVIRJJR.js';import {b as b$7,d as d$6,c as c$6,a as a$6,f as f$7,e as e$b}from'./chunk-SX6A656X.js';import {b as b$5,a as a$2,d as d$2}from'./chunk-FPDH3N3A.js';import {a as a$o}from'./chunk-FX5J6JCK.js';import {e as e$3,d as d$4}from'./chunk-SLFOUSRW.js';import {a as a$x}from'./chunk-JCGSIDMC.js';import {a as a$C}from'./chunk-3OGPTLI2.js';import {c as c$a,a as a$y}from'./chunk-YYY2WXOH.js';import {a as a$G,b as b$j}from'./chunk-BUYLM6QV.js';import {a as a$F}from'./chunk-NS53IPAC.js';import {f as f$5}from'./chunk-BRYJTW6S.js';import {b as b$c,a as a$m}from'./chunk-Y4Z6CEII.js';import {a as a$c}from'./chunk-ARUFY5W3.js';import {a as a$9}from'./chunk-A5FBGRJA.js';import {a as a$w}from'./chunk-6E2Y3XGT.js';import {k as k$4,e as e$8,c as c$b,a as a$L,b as b$l}from'./chunk-TP7VKEUF.js';import {j,a as a$1,n as n$3,m as m$3,o as o$3,s as s$1,l as l$5,r as r$3,p as p$5,u as u$2,t as t$2}from'./chunk-NVND4727.js';import {b as b$b,a as a$f}from'./chunk-2MTJWPQ4.js';import {a as a$h}from'./chunk-NMXGSVMD.js';import {c as c$4,g as g$1,b as b$d,a as a$i,e as e$7,l as l$3}from'./chunk-EHCKITR4.js';import {b as b$2,d as d$1,a as a$3,e as e$4,z,y,j as j$2,k as k$2,m,n as n$1,o as o$1,l as l$1,t as t$1,p as p$3,B,r as r$2,h as h$5,s as s$2,A,C,u as u$1,f as f$6,x,w as w$1,v as v$1}from'./chunk-L5Q2S5GY.js';export{s as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-L5Q2S5GY.js';import {m as m$1,j as j$5,l as l$2}from'./chunk-U5ENEDJA.js';import {a as a$g}from'./chunk-GR6442P7.js';import {d as d$7,a as a$b,b as b$9}from'./chunk-XDPTAV2T.js';import {b as b$n}from'./chunk-IKUFNK46.js';import {a as a$4}from'./chunk-AFIFZTOY.js';import {k,i as i$1,e as e$2,f as f$2,h as h$2,g as g$5,c as c$d,a as a$E,l as l$4}from'./chunk-ZGHJIQXL.js';import {h,e,g,c as c$2,a as a$8,f as f$3}from'./chunk-TABXSDTR.js';import {a as a$e}from'./chunk-TQEMLBAG.js';import {a as a$B}from'./chunk-B4IVVTMQ.js';import {c as c$7}from'./chunk-5TY74LLW.js';import {a as a$A}from'./chunk-UTV4DTNM.js';import {f,e as e$1,a as a$5,d as d$a,i as i$4,g as g$7}from'./chunk-FY4X2VOE.js';import {o,b as b$3,p as p$1,q as q$1,r as r$1,m as m$4,i as i$5,j as j$6,e as e$c,g as g$8,c as c$f}from'./chunk-RGNCL5OB.js';import {c as c$g}from'./chunk-2FIX2MDC.js';import {n,f as f$1,u,p,w,q,k as k$1,t,v,j as j$3,g as g$2,h as h$3,i as i$2,e as e$6,a as a$M,b as b$m,l as l$6,o as o$4}from'./chunk-VQZ5PI5J.js';import {Command,Option}from'commander';import s from'chalk';import P from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import zu from'vm';import*as M from'fs-extra';import M__default from'fs-extra';import I,{existsSync,promises,createWriteStream}from'fs';import Dn,{tmpdir,homedir}from'os';import {execa}from'execa';import St,{randomUUID,createVerify,createHash,createHmac}from'crypto';import Il from'http';import Ol from'https';function bp(){return j$6()}function jp(t,e){return t==="py"?["-3",...e]:e}function Cp(t){return typeof t=="object"&&t!==null}async function Sp(t,e,r,o=c$g()){try{let n=await execa(t,e,{cwd:r,timeout:o,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function Ep(t,e){let r=["-m","rapidkit",...t],o=bp();for(let n of o){let a=await Sp(n,jp(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return Cp(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 qi(t,e){let r=await Ep(["project","detect","--path",t,"--json"],e);return !r.ok||!r.data||r.data.schema_version!==1?{ok:false,command:r.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:r}var zi=new Set(["create"]),$n=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),xp=new Set(["pip","poetry","venv","pipx","python"]);function Yi(t){return typeof t=="string"&&xp.has(t)}function Nn(t,e){return !t||zi.has(t)?false:a$5.has(t)?true:e?.has(t)??false}function Tn(t,e=null){let r=t[0];return !r||r.startsWith("-")||zi.has(r)||r==="init"?false:Nn(r,e)?true:t.filter(n=>!n.startsWith("-")&&!$n.has(n)).length<=1?false:t.length>1}var zt=P.join(Dn.homedir(),".workspairc.json"),Rp=P.join(Dn.homedir(),".rapidkitrc.json"),Ap=P.join(Dn.homedir(),".rapidkit","config.json");function Mn(t){try{if(!I.existsSync(t))return {};let e=I.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Xi(t){if(process.platform!=="win32")try{I.chmodSync(t,384);}catch{}}function Yt(){let t=Mn(zt),e=Mn(Rp),r=Mn(Ap);return I.existsSync(zt)&&Xi(zt),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function vo(t){let r={...Yt(),...t};I.writeFileSync(zt,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Xi(zt);}function Ar(){return process.env.OPENAI_API_KEY||Yt().openaiApiKey||null}function Ln(){return Yt().aiEnabled!==false}function Fn(){return zt}function Zi(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async r=>{let o=r.key;o?o.startsWith("sk-")||(console.log(s.red(`
2
+ import {a as a$v}from'./chunk-FB7SCXAZ.js';import {a as a$n}from'./chunk-ICGWHIMK.js';import {h as h$4,b as b$h,a as a$z}from'./chunk-LDBULT2T.js';import {b,c,d,j as j$1,h as h$1,i,r,l,n as n$2,p as p$4,o as o$2,m as m$2,q as q$2,a as a$K,k as k$5}from'./chunk-IXXQMD34.js';import {a as a$j}from'./chunk-5OV2WXAR.js';import {a as a$s}from'./chunk-TMRCPT7S.js';import {a as a$t}from'./chunk-3BMYMZQB.js';import {c as c$9,b as b$g,a as a$r}from'./chunk-CPR2CMOY.js';import {d as d$3,c as c$3,p as p$2,b as b$k,a as a$I}from'./chunk-BHM6RHTA.js';import {a as a$l,f as f$4,d as d$8,i as i$3}from'./chunk-4WVOAX2V.js';import {c as c$1,b as b$6,a as a$J}from'./chunk-LPCWROQ3.js';import {b as b$4,a as a$7}from'./chunk-P3622IM5.js';import {b as b$f,a as a$p,c as c$8}from'./chunk-GVQKAINC.js';import {b as b$8,a as a$a}from'./chunk-D5LLTUTY.js';import {c as c$5,d as d$5,e as e$5,b as b$e,g as g$4}from'./chunk-3XF7O66C.js';import {j as j$4,a as a$d,k as k$3}from'./chunk-W5VKBDSD.js';import {b as b$a,g as g$3,c as c$e,a as a$H}from'./chunk-RVAOJOXA.js';import {g as g$6,e as e$9,c as c$c,b as b$i,a as a$D}from'./chunk-JYMO7QXQ.js';import {a as a$k,e as e$a,d as d$9}from'./chunk-5ME4W4LN.js';import {a,b as b$1}from'./chunk-B6FJ6RG6.js';import {a as a$q}from'./chunk-N5HPMATQ.js';import {a as a$u}from'./chunk-BMAFHX6A.js';import {b as b$7,d as d$6,c as c$6,a as a$6,f as f$7,e as e$b}from'./chunk-KY2GOSO5.js';import {b as b$5,a as a$2,d as d$2}from'./chunk-FPDH3N3A.js';import {a as a$o}from'./chunk-FX5J6JCK.js';import {e as e$3,d as d$4}from'./chunk-SLFOUSRW.js';import {a as a$x}from'./chunk-CSZPE637.js';import {a as a$C}from'./chunk-3OGPTLI2.js';import {c as c$a,a as a$y}from'./chunk-WRZSQDZV.js';import {a as a$G,b as b$j}from'./chunk-BUYLM6QV.js';import {a as a$F}from'./chunk-NS53IPAC.js';import {f as f$5}from'./chunk-3KU3YUWD.js';import {b as b$c,a as a$m}from'./chunk-Y4Z6CEII.js';import {a as a$c}from'./chunk-Q7UGDNSM.js';import {a as a$9}from'./chunk-A5FBGRJA.js';import {a as a$w}from'./chunk-6E2Y3XGT.js';import {k as k$4,e as e$8,c as c$b,a as a$L,b as b$l}from'./chunk-2KX6KHEC.js';import {j,a as a$1,n as n$3,m as m$3,o as o$3,s as s$1,l as l$5,r as r$3,p as p$5,u as u$2,t as t$2}from'./chunk-46QH3ZVI.js';import {b as b$b,a as a$f}from'./chunk-2MTJWPQ4.js';import {a as a$h}from'./chunk-NMXGSVMD.js';import {c as c$4,g as g$1,b as b$d,a as a$i,e as e$7,l as l$3}from'./chunk-TCLKGPXF.js';import {b as b$2,d as d$1,a as a$3,e as e$4,z,y,j as j$2,k as k$2,m,n as n$1,o as o$1,l as l$1,t as t$1,p as p$3,B,r as r$2,h as h$5,s as s$2,A,C,u as u$1,f as f$6,x,w as w$1,v as v$1}from'./chunk-KFTJVVJR.js';export{s as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-KFTJVVJR.js';import {m as m$1,j as j$5,l as l$2}from'./chunk-U5ENEDJA.js';import {a as a$g}from'./chunk-GR6442P7.js';import {d as d$7,a as a$b,b as b$9}from'./chunk-C2VTO5WT.js';import {b as b$n}from'./chunk-IKUFNK46.js';import {a as a$4}from'./chunk-AFIFZTOY.js';import {k,i as i$1,e as e$2,f as f$2,h as h$2,g as g$5,c as c$d,a as a$E,l as l$4}from'./chunk-ZGHJIQXL.js';import {h,e,g,c as c$2,a as a$8,f as f$3}from'./chunk-PKKSRXUS.js';import {a as a$e}from'./chunk-TQEMLBAG.js';import {a as a$B}from'./chunk-64XWHDZ3.js';import {c as c$7}from'./chunk-25AWHAB5.js';import {a as a$A}from'./chunk-W37NOQVG.js';import {f,e as e$1,a as a$5,d as d$a,i as i$4,g as g$7}from'./chunk-FY4X2VOE.js';import {o,b as b$3,p as p$1,q as q$1,r as r$1,m as m$4,i as i$5,j as j$6,e as e$c,g as g$8,c as c$f}from'./chunk-RGNCL5OB.js';import {c as c$g}from'./chunk-2FIX2MDC.js';import {n,f as f$1,u,p,w,q,k as k$1,t,v,j as j$3,g as g$2,h as h$3,i as i$2,e as e$6,a as a$M,b as b$m,l as l$6,o as o$4}from'./chunk-VQZ5PI5J.js';import {Command,Option}from'commander';import s from'chalk';import P from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import zu from'vm';import*as M from'fs-extra';import M__default from'fs-extra';import I,{existsSync,promises,createWriteStream}from'fs';import Dn,{tmpdir,homedir}from'os';import {execa}from'execa';import St,{randomUUID,createVerify,createHash,createHmac}from'crypto';import Il from'http';import Ol from'https';function bp(){return j$6()}function jp(t,e){return t==="py"?["-3",...e]:e}function Cp(t){return typeof t=="object"&&t!==null}async function Sp(t,e,r,o=c$g()){try{let n=await execa(t,e,{cwd:r,timeout:o,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function Ep(t,e){let r=["-m","rapidkit",...t],o=bp();for(let n of o){let a=await Sp(n,jp(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return Cp(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 qi(t,e){let r=await Ep(["project","detect","--path",t,"--json"],e);return !r.ok||!r.data||r.data.schema_version!==1?{ok:false,command:r.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:r}var zi=new Set(["create"]),$n=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),xp=new Set(["pip","poetry","venv","pipx","python"]);function Yi(t){return typeof t=="string"&&xp.has(t)}function Nn(t,e){return !t||zi.has(t)?false:a$5.has(t)?true:e?.has(t)??false}function Tn(t,e=null){let r=t[0];return !r||r.startsWith("-")||zi.has(r)||r==="init"?false:Nn(r,e)?true:t.filter(n=>!n.startsWith("-")&&!$n.has(n)).length<=1?false:t.length>1}var zt=P.join(Dn.homedir(),".workspairc.json"),Rp=P.join(Dn.homedir(),".rapidkitrc.json"),Ap=P.join(Dn.homedir(),".rapidkit","config.json");function Mn(t){try{if(!I.existsSync(t))return {};let e=I.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Xi(t){if(process.platform!=="win32")try{I.chmodSync(t,384);}catch{}}function Yt(){let t=Mn(zt),e=Mn(Rp),r=Mn(Ap);return I.existsSync(zt)&&Xi(zt),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function vo(t){let r={...Yt(),...t};I.writeFileSync(zt,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Xi(zt);}function Ar(){return process.env.OPENAI_API_KEY||Yt().openaiApiKey||null}function Ln(){return Yt().aiEnabled!==false}function Fn(){return zt}function Zi(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async r=>{let o=r.key;o?o.startsWith("sk-")||(console.log(s.red(`
3
3
  \u274C Invalid API key format (should start with sk-)
4
4
  `)),process.exit(1)):o=(await b$1([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:a=>a?a.startsWith("sk-")?a.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,vo({openaiApiKey:o}),console.log(s.green(`
5
5
  \u2705 OpenAI API key saved successfully!
@@ -112,7 +112,7 @@ Workspai Private Product Manifest
112
112
  `)),console.log(s.cyan("Product:"),s.white(t.product.slug)),console.log(s.cyan("Kit:"),s.white(t.projects[0].kit)),console.log(s.cyan("Modules:"),s.white(String(t.projects[0].modules.length))),console.log(s.cyan("Module gaps:"),s.yellow(String(t.projects[0].moduleGaps.length))),console.log(s.cyan("Checksum:"),s.white(t.factory.manifestChecksum)),console.log(s.gray(`
113
113
  Wrote manifest: ${P.resolve(process.cwd(),e)}
114
114
  `));}function bc(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(r,o)=>{try{let n=o.output||yc("--output"),a=await Pc({backlogPath:r,kit:o.kit,tier:o.tier,category:o.category,limit:o.limit});a$4(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await kc(n,a,true),o.json?console.log(er(a)):od(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(er({ok:false,error:{message:a}})):console.error(s.red(`Product plan failed: ${a}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(r,o)=>{try{let n=o.output||yc("--output");vc(r);let a=await td({backlogPath:o.fromBacklog,slug:r,kit:o.kit,outputRoot:o.workspaceOutput});a$4(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=rd(n,r);await kc(i,a,o.force===true),o.json?console.log(er(a)):nd(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(er({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var Sc="rapidkit-workspace-snapshot-v1",Nr="rapidkit-workspace-snapshot-v2",sd=Sc,Ec="rapidkit-project-archive-v1",mt="workspai-archive.json",xo="rapidkit-archive.json",ad=[".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"],id=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),$r={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function rr(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function Ro(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 cd(t){try{let e=await M__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function ld(t,e){if(!t)return e;let r=t.trim().toLowerCase();return ["true","yes","1","on"].includes(r)?true:["false","no","0","off"].includes(r)?false:e}async function pd(t$1){let e=t(t$1,"policies.yml").find(r=>existsSync(r))??q(t$1,"policies.yml");if(!await M__default.pathExists(e))return {...$r};try{let r=await M__default.readFile(e,"utf-8"),o=(n,a)=>{let i=r.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return ld(i?.[1],a)};return {requireReasonForDestructiveOps:o("require_reason_for_destructive_ops",$r.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:o("require_safety_snapshot_for_destructive_ops",$r.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:o("allow_permanent_delete",$r.allowPermanentDelete)}}catch{return {...$r}}}function dd(t){return q(t,"audit","events.jsonl")}async function tt(t,e){let r={schema:"rapidkit-workspace-audit-event-v1",id:St.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},o=dd(t);return await M__default.ensureDir(P.dirname(o)),await M__default.appendFile(o,`${JSON.stringify(r)}
115
- `,"utf-8"),r}async function Ao(t,e,r){let o=await pd(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function qn(t=process.cwd()){let e=P.resolve(t),r=P.resolve(Dn.tmpdir());for(;;){if(e!==r&&k$1(e))return e;let o=P.dirname(e);if(o===e)return null;e=o;}}function Et(t){let e=t?P.resolve(t):qn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!k$1(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function xc(t$1){let e=await cd(t(t$1,"workspace.json").find(o=>existsSync(o))??q(t$1,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():P.basename(t$1)}function or(t){return q(t,"snapshots")}function Tr(t){return q(t,"archive","projects")}function tr(t){return P.join(t,"files")}function ud(t){return P.join(Dn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${St.randomBytes(4).toString("hex")}`)}function md(t,e){return P.join(or(t),`.tmp-${process.pid}-${e}-${St.randomBytes(4).toString("hex")}`)}function _o(t,e){let r=P.relative(t,e);if(!r)return true;let o=r.split(P.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>id.has(n)||a$g(n))}async function gd(t){return (await a$h(t,{descendIntoMatchedProjects:false})).map(r=>({name:P.basename(r),relativePath:P.relative(t,r)}))}async function fd(t,e){let r=[],o=new Set;for(let n of ad){let a=P.join(t,n);if(!await M__default.pathExists(a))continue;let i=w(n);if(o.has(i))continue;let c=P.join(e,i);await M__default.copy(a,c,{filter:p=>_o(t,p)}),r.push(i),o.add(i);}return r}async function Rc(t){let e=[];async function r(o){let n=[];try{n=await M__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=P.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=P.join(P.dirname(o),P.basename(w(P.basename(o))));await M__default.copy(o,n,{overwrite:false,errorOnExist:false}),await M__default.remove(o);}}async function Ac(t,e){let r=e.schema===Nr?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,r,"Workspace snapshot manifest"),await M__default.writeJson(P.join(t,"snapshot.json"),e,{spaces:2});}async function zn(t){let e=P.join(t,"snapshot.json"),r=await M__default.readJson(e);if(!r||typeof r!="object"||![Sc,Nr].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===Nr?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==Nr||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function hd(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await M__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=P.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let p=await M__default.stat(c);e+=1,r+=p.size;}catch{}}}return {files:e,bytes:r}}async function Io(t={}){let e=Et(t.workspacePath),r=t.name?t.name:`snapshot-${rr()}`,o=Ro(r),n=P.join(or(e),o),a=ud(o);if(await M__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=tr(a);try{await M__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",p=c==="full"?["."]:await fd(e,i);c==="full"&&(await M__default.copy(e,i,{filter:h=>_o(e,h)}),await Rc(i));let d={schema:sd,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await xc(e),workspacePath:e,copiedPaths:p,projects:await gd(e)};return await Ac(a,d),await M__default.ensureDir(P.dirname(n)),await M__default.move(a,n,{overwrite:false}),await tt(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:p,snapshotPath:n,projectCount:d.projects.length}}),{manifest:d,snapshotPath:n}}catch(c){throw await M__default.remove(a),await tt(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function Oo(t){let e=P.resolve(t.workspacePath),r=P.resolve(t.projectPath),o=P.relative(e,r);if(!o||o.startsWith("..")||P.isAbsolute(o)||o.split(P.sep).some(h=>h===".workspai"||h===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=P.basename(r),a=Ro(`${t.namePrefix}-${n}-${rr()}-${St.randomBytes(3).toString("hex")}`),i=P.join(or(e),a),c=md(e,a),p=P.join(tr(c),o),d=false;try{await M__default.ensureDir(P.dirname(p)),t.moveSource?(await M__default.move(r,p,{overwrite:false}),d=true):await M__default.copy(r,p,{overwrite:false,errorOnExist:true,filter:u=>_o(r,u)});let h={schema:Nr,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await xc(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await Ac(c,h),await M__default.move(c,i,{overwrite:false}),await tt(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:h,snapshotPath:i}}catch(h){if(d&&!await M__default.pathExists(r)){let u=await M__default.pathExists(p)?p:P.join(tr(i),o);await M__default.pathExists(u)&&(await M__default.ensureDir(P.dirname(r)),await M__default.move(u,r,{overwrite:false}));}throw await M__default.remove(c),await M__default.remove(i),await tt(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:h instanceof Error?h.message:String(h)}}),h}}async function _c(t){let e=Et(t.workspacePath),r=P.join(or(e),Ro(t.name));if(!await M__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await zn(r),n=tr(r),a=await hd(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function Ic(t={}){let e=Et(t.workspacePath),r=or(e);if(!await M__default.pathExists(r))return [];let o=await M__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=P.join(r,a.name);try{n.push({...await zn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var yd=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function wd(t){let e=P.dirname(t.workspacePath),r=P.basename(t.workspacePath),o=`${rr()}-${St.randomBytes(4).toString("hex")}`,n=P.join(e,`.${r}.restore-staging-${o}`),a=P.join(e,`.${r}.pre-restore-${o}`),i=P.join(e,`.${r}.restore-failed-${o}`),c=[],p=false,d=false;try{await M__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:h=>_o(t.filesRoot,h)}),await Rc(n),await M__default.rename(t.workspacePath,a),p=true,await M__default.rename(n,t.workspacePath),d=true;for(let h of yd){let u=P.join(a,h);if(!await M__default.pathExists(u))continue;let f=P.join(t.workspacePath,h);if(await M__default.pathExists(f))throw new Error(`Full restore operational path collision: ${h}`);await M__default.ensureDir(P.dirname(f)),await M__default.rename(u,f),c.push(h);}return a}catch(h){for(let u of [...c].reverse()){let f=P.join(t.workspacePath,u),v=P.join(a,u);await M__default.pathExists(f)&&(await M__default.ensureDir(P.dirname(v)),await M__default.rename(f,v));}throw d&&await M__default.pathExists(t.workspacePath)&&await M__default.rename(t.workspacePath,i),p&&await M__default.pathExists(a)&&await M__default.rename(a,t.workspacePath),await M__default.remove(i),await M__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${h instanceof Error?h.message:String(h)}`)}}async function Oc(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=P.join(tr(t.snapshotPath),r),n=P.join(e,r);await M__default.pathExists(o)&&!await M__default.pathExists(n)&&(await M__default.ensureDir(P.dirname(n)),await M__default.move(o,n,{overwrite:false})),await M__default.remove(t.snapshotPath);}async function $c(t){let e=Et(t.workspacePath),r=P.join(or(e),Ro(t.name));if(!await M__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await zn(r),n=tr(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(p=>{let d=w(p);return d.startsWith(".workspai/")?".workspai":d})));if(t.dryRun)return await tt(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await Ao(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await wd({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let p=o.recoveryScope?.relativePath;if(!p)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let d=P.join(n,p),h=P.join(e,p),u=await M__default.pathExists(h),f,v=P.join(P.dirname(h),`.${P.basename(h)}.pre-restore-${process.pid}-${St.randomBytes(4).toString("hex")}`),k=false;u&&t.safetySnapshot!==false?(f=await Oo({workspacePath:e,projectPath:h,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=f.snapshotPath):u&&(await M__default.rename(h,v),k=true);let E=P.join(P.dirname(h),`.${P.basename(h)}.restore-${process.pid}-${St.randomBytes(4).toString("hex")}`);try{await M__default.copy(d,E,{overwrite:false,errorOnExist:true}),await M__default.rename(E,h),k&&await M__default.remove(v);}catch(S){throw await M__default.remove(E),k&&await M__default.pathExists(v)&&(await M__default.remove(h),await M__default.rename(v,h)),f&&await Oc(f,e),S}}else t.safetySnapshot!==false&&(i=(await Io({workspacePath:e,name:`pre-restore-${o.name}-${rr()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let p=new Set;for(let d of o.copiedPaths){let h=w(d);p.has(h)||(await M__default.copy(P.join(n,d),P.join(e,h),{overwrite:true,errorOnExist:false}),p.add(h));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await tt(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function Nc(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function Tc(t,e){let r=Nc(e),o=P.isAbsolute(r)?P.resolve(r):P.resolve(t,r);if(o.startsWith(`${P.resolve(t)}${P.sep}`)&&await M__default.pathExists(o))return o;let a=(await a$h(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=P.relative(t,i);return P.basename(i)===r||c===r});if(a.length===0){let c=(await a$i(t)).find(p=>{let d=p.relativePath?.replace(/\\/g,"/");return p.name===r||d===r.replace(/\\/g,"/")||P.resolve(p.path)===P.resolve(r)});throw c&&!P.resolve(c.path).startsWith(`${P.resolve(t)}${P.sep}`)?new Error(`Project ${e} is a linked external project and cannot be archived or deleted by workspace lifecycle commands. Only managed projects contained by the workspace support archive/delete; manage the external source or its workspace registration explicitly.`):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 Yn(t){let{syncWorkspaceProjects:e}=await import('./workspace-5W7FYGDQ.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-JYHNEJPV.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-LQCN65P2.js');await o({workspacePath:t,mode:"managed"});}function kd(t,e){let r=St.randomBytes(4).toString("hex");return P.join(Tr(t),`${e}-${rr()}-${r}`)}async function Mc(t){let e=Wc(t),r=await M__default.readJson(e);if(!r||typeof r!="object"||r.schema!==Ec)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function Wc(t){return [mt,xo].map(e=>P.join(t,e)).find(e=>M__default.existsSync(e))??P.join(t,mt)}async function Xn(t={}){let e=Et(t.workspacePath),r=Tr(e);if(!await M__default.pathExists(r))return [];let o=await M__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=P.join(r,a.name),c=[mt,xo].map(p=>P.join(i,p)).find(p=>M__default.existsSync(p))??P.join(i,mt);try{n.push({...await Mc(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function vd(t,e){let r=Nc(e),o=P.isAbsolute(r)?P.resolve(r):P.resolve(Tr(t),r);if(o.startsWith(`${P.resolve(Tr(t))}${P.sep}`)&&(await M__default.pathExists(P.join(o,mt))||await M__default.pathExists(P.join(o,xo))))return o;let a=(await Xn({workspacePath:t})).filter(i=>P.basename(i.archivePath)===r||i.projectName===r||P.relative(Tr(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function Zn(t){let e=Et(t.workspacePath),r=await Tc(e,t.project),o=P.basename(r),n=kd(e,o),a=P.join(n,mt),i=`${n}.tmp-${process.pid}`,c=P.join(i,mt);for(let u of [mt,xo])if(await M__default.pathExists(P.join(r,u)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${u}`);if(t.dryRun)return await tt(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await Ao(e,"project.archive",{reason:t.reason,safetySnapshot:true});let p=await Oo({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),d={schema:Ec,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:p.snapshotPath};a$4(d,"contracts/project-archive.v1.json","Project archive manifest");let h=false;try{await M__default.ensureDir(P.dirname(n)),await M__default.move(r,i,{overwrite:false}),h=true,await M__default.writeJson(c,d,{spaces:2}),await M__default.rename(i,n);}catch(u){if(h&&!await M__default.pathExists(r)){let f=await M__default.pathExists(i)?i:n;await M__default.pathExists(f)&&(await M__default.remove(P.join(f,mt)),await M__default.move(f,r,{overwrite:false}));}throw await M__default.remove(i),u}return await c$4(e,[r]),await Yn(e),await tt(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath,dryRun:false}}async function Dc(t){if(!t.permanent)return Zn(t);let e=Et(t.workspacePath),r=await Tc(e,t.project),o=P.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await tt(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await Ao(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Oo({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$4(e,[r]),await Yn(e),await tt(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function Lc(t){let e=Et(t.workspacePath),r=await vd(e,t.archive),o=await Mc(r),n=t.targetName?.trim()||o.projectName,a=P.join(e,n);if(!a.startsWith(`${P.resolve(e)}${P.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await M__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await tt(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:P.join(r,mt),dryRun:true};await Ao(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await M__default.pathExists(a),c=i?await Oo({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await Io({workspacePath:e,name:`pre-restore-project-${n}-${rr()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),p=Wc(r),d=q(e,"audit","restores",`${P.basename(r)}.json`);try{await M__default.move(r,a,{overwrite:false}),await M__default.ensureDir(P.dirname(d)),await M__default.move(P.join(a,P.basename(p)),d,{overwrite:false});}catch(h){throw await M__default.pathExists(a)&&(await M__default.pathExists(d)&&await M__default.move(d,P.join(a,P.basename(p)),{overwrite:false}),await M__default.pathExists(r)||await M__default.move(a,r,{overwrite:false})),i&&await Oc(c,e),h}return await Yn(e),await tt(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:d,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:d,safetySnapshotPath:c.snapshotPath,dryRun:false}}var bd="rapidkit.infra-stack.v1",Gc=h$2.infraPlan.schemaVersion,nr=".workspai/infra/docker-compose.yml",sr=i$1.infraPlan,ts=".workspai/infra/.env.example";function jd(){let t=P.dirname(fileURLToPath(import.meta.url)),e=[P.join(t,"../../contracts/infra-stack.v1.json"),P.join(t,"../contracts/infra-stack.v1.json")];for(let r of e)if(I.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var es=null;function Tt(t){if(es)return es;let e=jd(),r=I.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==bd)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return Cd(o),(es=o),o}function Cd(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function Jc(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function ar(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Vc(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function Ed(t){let e=P.join(t,"registry.json");if(!await M__default.pathExists(e))return [];try{let o=(await M__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function xd(t){let e=P.join(t,".env.example");if(!await M__default.pathExists(e))return [];try{let r=await M__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
115
+ `,"utf-8"),r}async function Ao(t,e,r){let o=await pd(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function qn(t=process.cwd()){let e=P.resolve(t),r=P.resolve(Dn.tmpdir());for(;;){if(e!==r&&k$1(e))return e;let o=P.dirname(e);if(o===e)return null;e=o;}}function Et(t){let e=t?P.resolve(t):qn(process.cwd());if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!k$1(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function xc(t$1){let e=await cd(t(t$1,"workspace.json").find(o=>existsSync(o))??q(t$1,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():P.basename(t$1)}function or(t){return q(t,"snapshots")}function Tr(t){return q(t,"archive","projects")}function tr(t){return P.join(t,"files")}function ud(t){return P.join(Dn.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${St.randomBytes(4).toString("hex")}`)}function md(t,e){return P.join(or(t),`.tmp-${process.pid}-${e}-${St.randomBytes(4).toString("hex")}`)}function _o(t,e){let r=P.relative(t,e);if(!r)return true;let o=r.split(P.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>id.has(n)||a$g(n))}async function gd(t){return (await a$h(t,{descendIntoMatchedProjects:false})).map(r=>({name:P.basename(r),relativePath:P.relative(t,r)}))}async function fd(t,e){let r=[],o=new Set;for(let n of ad){let a=P.join(t,n);if(!await M__default.pathExists(a))continue;let i=w(n);if(o.has(i))continue;let c=P.join(e,i);await M__default.copy(a,c,{filter:p=>_o(t,p)}),r.push(i),o.add(i);}return r}async function Rc(t){let e=[];async function r(o){let n=[];try{n=await M__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=P.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=P.join(P.dirname(o),P.basename(w(P.basename(o))));await M__default.copy(o,n,{overwrite:false,errorOnExist:false}),await M__default.remove(o);}}async function Ac(t,e){let r=e.schema===Nr?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,r,"Workspace snapshot manifest"),await M__default.writeJson(P.join(t,"snapshot.json"),e,{spaces:2});}async function zn(t){let e=P.join(t,"snapshot.json"),r=await M__default.readJson(e);if(!r||typeof r!="object"||![Sc,Nr].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===Nr?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==Nr||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function hd(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await M__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=P.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let p=await M__default.stat(c);e+=1,r+=p.size;}catch{}}}return {files:e,bytes:r}}async function Io(t={}){let e=Et(t.workspacePath),r=t.name?t.name:`snapshot-${rr()}`,o=Ro(r),n=P.join(or(e),o),a=ud(o);if(await M__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=tr(a);try{await M__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",p=c==="full"?["."]:await fd(e,i);c==="full"&&(await M__default.copy(e,i,{filter:h=>_o(e,h)}),await Rc(i));let d={schema:sd,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await xc(e),workspacePath:e,copiedPaths:p,projects:await gd(e)};return await Ac(a,d),await M__default.ensureDir(P.dirname(n)),await M__default.move(a,n,{overwrite:false}),await tt(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:p,snapshotPath:n,projectCount:d.projects.length}}),{manifest:d,snapshotPath:n}}catch(c){throw await M__default.remove(a),await tt(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function Oo(t){let e=P.resolve(t.workspacePath),r=P.resolve(t.projectPath),o=P.relative(e,r);if(!o||o.startsWith("..")||P.isAbsolute(o)||o.split(P.sep).some(h=>h===".workspai"||h===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=P.basename(r),a=Ro(`${t.namePrefix}-${n}-${rr()}-${St.randomBytes(3).toString("hex")}`),i=P.join(or(e),a),c=md(e,a),p=P.join(tr(c),o),d=false;try{await M__default.ensureDir(P.dirname(p)),t.moveSource?(await M__default.move(r,p,{overwrite:false}),d=true):await M__default.copy(r,p,{overwrite:false,errorOnExist:true,filter:u=>_o(r,u)});let h={schema:Nr,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await xc(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await Ac(c,h),await M__default.move(c,i,{overwrite:false}),await tt(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:h,snapshotPath:i}}catch(h){if(d&&!await M__default.pathExists(r)){let u=await M__default.pathExists(p)?p:P.join(tr(i),o);await M__default.pathExists(u)&&(await M__default.ensureDir(P.dirname(r)),await M__default.move(u,r,{overwrite:false}));}throw await M__default.remove(c),await M__default.remove(i),await tt(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:h instanceof Error?h.message:String(h)}}),h}}async function _c(t){let e=Et(t.workspacePath),r=P.join(or(e),Ro(t.name));if(!await M__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await zn(r),n=tr(r),a=await hd(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function Ic(t={}){let e=Et(t.workspacePath),r=or(e);if(!await M__default.pathExists(r))return [];let o=await M__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=P.join(r,a.name);try{n.push({...await zn(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var yd=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function wd(t){let e=P.dirname(t.workspacePath),r=P.basename(t.workspacePath),o=`${rr()}-${St.randomBytes(4).toString("hex")}`,n=P.join(e,`.${r}.restore-staging-${o}`),a=P.join(e,`.${r}.pre-restore-${o}`),i=P.join(e,`.${r}.restore-failed-${o}`),c=[],p=false,d=false;try{await M__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:h=>_o(t.filesRoot,h)}),await Rc(n),await M__default.rename(t.workspacePath,a),p=true,await M__default.rename(n,t.workspacePath),d=true;for(let h of yd){let u=P.join(a,h);if(!await M__default.pathExists(u))continue;let f=P.join(t.workspacePath,h);if(await M__default.pathExists(f))throw new Error(`Full restore operational path collision: ${h}`);await M__default.ensureDir(P.dirname(f)),await M__default.rename(u,f),c.push(h);}return a}catch(h){for(let u of [...c].reverse()){let f=P.join(t.workspacePath,u),v=P.join(a,u);await M__default.pathExists(f)&&(await M__default.ensureDir(P.dirname(v)),await M__default.rename(f,v));}throw d&&await M__default.pathExists(t.workspacePath)&&await M__default.rename(t.workspacePath,i),p&&await M__default.pathExists(a)&&await M__default.rename(a,t.workspacePath),await M__default.remove(i),await M__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${h instanceof Error?h.message:String(h)}`)}}async function Oc(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=P.join(tr(t.snapshotPath),r),n=P.join(e,r);await M__default.pathExists(o)&&!await M__default.pathExists(n)&&(await M__default.ensureDir(P.dirname(n)),await M__default.move(o,n,{overwrite:false})),await M__default.remove(t.snapshotPath);}async function $c(t){let e=Et(t.workspacePath),r=P.join(or(e),Ro(t.name));if(!await M__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await zn(r),n=tr(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(p=>{let d=w(p);return d.startsWith(".workspai/")?".workspai":d})));if(t.dryRun)return await tt(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await Ao(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await wd({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let p=o.recoveryScope?.relativePath;if(!p)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let d=P.join(n,p),h=P.join(e,p),u=await M__default.pathExists(h),f,v=P.join(P.dirname(h),`.${P.basename(h)}.pre-restore-${process.pid}-${St.randomBytes(4).toString("hex")}`),k=false;u&&t.safetySnapshot!==false?(f=await Oo({workspacePath:e,projectPath:h,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=f.snapshotPath):u&&(await M__default.rename(h,v),k=true);let E=P.join(P.dirname(h),`.${P.basename(h)}.restore-${process.pid}-${St.randomBytes(4).toString("hex")}`);try{await M__default.copy(d,E,{overwrite:false,errorOnExist:true}),await M__default.rename(E,h),k&&await M__default.remove(v);}catch(S){throw await M__default.remove(E),k&&await M__default.pathExists(v)&&(await M__default.remove(h),await M__default.rename(v,h)),f&&await Oc(f,e),S}}else t.safetySnapshot!==false&&(i=(await Io({workspacePath:e,name:`pre-restore-${o.name}-${rr()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let p=new Set;for(let d of o.copiedPaths){let h=w(d);p.has(h)||(await M__default.copy(P.join(n,d),P.join(e,h),{overwrite:true,errorOnExist:false}),p.add(h));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await tt(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function Nc(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function Tc(t,e){let r=Nc(e),o=P.isAbsolute(r)?P.resolve(r):P.resolve(t,r);if(o.startsWith(`${P.resolve(t)}${P.sep}`)&&await M__default.pathExists(o))return o;let a=(await a$h(t,{descendIntoMatchedProjects:false})).filter(i=>{let c=P.relative(t,i);return P.basename(i)===r||c===r});if(a.length===0){let c=(await a$i(t)).find(p=>{let d=p.relativePath?.replace(/\\/g,"/");return p.name===r||d===r.replace(/\\/g,"/")||P.resolve(p.path)===P.resolve(r)});throw c&&!P.resolve(c.path).startsWith(`${P.resolve(t)}${P.sep}`)?new Error(`Project ${e} is a linked external project and cannot be archived or deleted by workspace lifecycle commands. Only managed projects contained by the workspace support archive/delete; manage the external source or its workspace registration explicitly.`):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 Yn(t){let{syncWorkspaceProjects:e}=await import('./workspace-B33BFZZ3.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-MQ3QE52V.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-ZCCHUKVI.js');await o({workspacePath:t,mode:"managed"});}function kd(t,e){let r=St.randomBytes(4).toString("hex");return P.join(Tr(t),`${e}-${rr()}-${r}`)}async function Mc(t){let e=Wc(t),r=await M__default.readJson(e);if(!r||typeof r!="object"||r.schema!==Ec)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function Wc(t){return [mt,xo].map(e=>P.join(t,e)).find(e=>M__default.existsSync(e))??P.join(t,mt)}async function Xn(t={}){let e=Et(t.workspacePath),r=Tr(e);if(!await M__default.pathExists(r))return [];let o=await M__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=P.join(r,a.name),c=[mt,xo].map(p=>P.join(i,p)).find(p=>M__default.existsSync(p))??P.join(i,mt);try{n.push({...await Mc(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function vd(t,e){let r=Nc(e),o=P.isAbsolute(r)?P.resolve(r):P.resolve(Tr(t),r);if(o.startsWith(`${P.resolve(Tr(t))}${P.sep}`)&&(await M__default.pathExists(P.join(o,mt))||await M__default.pathExists(P.join(o,xo))))return o;let a=(await Xn({workspacePath:t})).filter(i=>P.basename(i.archivePath)===r||i.projectName===r||P.relative(Tr(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function Zn(t){let e=Et(t.workspacePath),r=await Tc(e,t.project),o=P.basename(r),n=kd(e,o),a=P.join(n,mt),i=`${n}.tmp-${process.pid}`,c=P.join(i,mt);for(let u of [mt,xo])if(await M__default.pathExists(P.join(r,u)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${u}`);if(t.dryRun)return await tt(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await Ao(e,"project.archive",{reason:t.reason,safetySnapshot:true});let p=await Oo({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),d={schema:Ec,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:p.snapshotPath};a$4(d,"contracts/project-archive.v1.json","Project archive manifest");let h=false;try{await M__default.ensureDir(P.dirname(n)),await M__default.move(r,i,{overwrite:false}),h=true,await M__default.writeJson(c,d,{spaces:2}),await M__default.rename(i,n);}catch(u){if(h&&!await M__default.pathExists(r)){let f=await M__default.pathExists(i)?i:n;await M__default.pathExists(f)&&(await M__default.remove(P.join(f,mt)),await M__default.move(f,r,{overwrite:false}));}throw await M__default.remove(i),u}return await c$4(e,[r]),await Yn(e),await tt(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:p.snapshotPath,dryRun:false}}async function Dc(t){if(!t.permanent)return Zn(t);let e=Et(t.workspacePath),r=await Tc(e,t.project),o=P.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await tt(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await Ao(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Oo({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$4(e,[r]),await Yn(e),await tt(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function Lc(t){let e=Et(t.workspacePath),r=await vd(e,t.archive),o=await Mc(r),n=t.targetName?.trim()||o.projectName,a=P.join(e,n);if(!a.startsWith(`${P.resolve(e)}${P.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await M__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await tt(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:P.join(r,mt),dryRun:true};await Ao(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await M__default.pathExists(a),c=i?await Oo({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await Io({workspacePath:e,name:`pre-restore-project-${n}-${rr()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),p=Wc(r),d=q(e,"audit","restores",`${P.basename(r)}.json`);try{await M__default.move(r,a,{overwrite:false}),await M__default.ensureDir(P.dirname(d)),await M__default.move(P.join(a,P.basename(p)),d,{overwrite:false});}catch(h){throw await M__default.pathExists(a)&&(await M__default.pathExists(d)&&await M__default.move(d,P.join(a,P.basename(p)),{overwrite:false}),await M__default.pathExists(r)||await M__default.move(a,r,{overwrite:false})),i&&await Oc(c,e),h}return await Yn(e),await tt(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:d,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:d,safetySnapshotPath:c.snapshotPath,dryRun:false}}var bd="rapidkit.infra-stack.v1",Gc=h$2.infraPlan.schemaVersion,nr=".workspai/infra/docker-compose.yml",sr=i$1.infraPlan,ts=".workspai/infra/.env.example";function jd(){let t=P.dirname(fileURLToPath(import.meta.url)),e=[P.join(t,"../../contracts/infra-stack.v1.json"),P.join(t,"../contracts/infra-stack.v1.json")];for(let r of e)if(I.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var es=null;function Tt(t){if(es)return es;let e=jd(),r=I.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==bd)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return Cd(o),(es=o),o}function Cd(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function Jc(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function ar(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Vc(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function Ed(t){let e=P.join(t,"registry.json");if(!await M__default.pathExists(e))return [];try{let o=(await M__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function xd(t){let e=P.join(t,".env.example");if(!await M__default.pathExists(e))return [];try{let r=await M__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
116
116
  `)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&o.push(i[1]);}return o}catch{return []}}async function Rd(t$1){let e=t(t$1,"infra","overrides.json").find(r=>existsSync(r));if(!e)return [];try{let r=await M__default.readJson(e);return Array.isArray(r.services)?[...new Set(r.services.filter(o=>typeof o=="string"&&o.trim().length>0))]:[]}catch{return []}}async function Ad(t){let e=await d$7(t,i$1.workspaceContract);if(!e)return [];try{let r=await M__default.readJson(e),o=[];for(let n of r.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&o.push({project:a,env:i.trim().toUpperCase()});}return o}catch{return []}}function $o(t,e,r,o){t.add(r),e.push(o);}async function Kc(t){let e=P.resolve(t.workspacePath),r=t.contract||Tt(),o=new Set,n=[],a=new Set,i=new Set,c=new Set,p=await l$3(e);for(let d of p){let h=P.dirname(P.dirname(d)),u=P.basename(h);for(let f of await Ed(h)){a.add(f);for(let v of Jc(r,f))$o(o,n,v,{kind:"module",value:f,project:u});}for(let f of await xd(h)){i.add(f);for(let v of ar(r,f))$o(o,n,v,{kind:"env-var",value:f,project:u});}}for(let d of await Ad(e)){i.add(d.env);for(let h of ar(r,d.env))$o(o,n,h,{kind:"contract-env",value:d.env,project:d.project});}for(let d of await Rd(e))c.add(d),$o(o,n,d,{kind:"override",value:d});return {modules:[...a].sort(),envVars:[...i].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...o].sort()}}function _d(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let r=e.indexOf("=");if(r<=0)return null;let o=e.slice(0,r).trim();if(!/^[A-Z0-9_]+$/.test(o))return null;let n=e.slice(r+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let a=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),i=(a?a[1]:n).trim();return i?{key:o,value:i}:null}async function Id(t){if(!await M__default.pathExists(t))return {};try{let e=await M__default.readFile(t,"utf-8"),r={};for(let o of e.split(`
117
117
  `)){let n=_d(o);n&&(r[n.key]=n.value);}return r}catch{return {}}}async function Bc(t){let e={},r=await l$3(t.workspacePath);for(let o of r){let n=P.dirname(P.dirname(o)),a=await Id(P.join(n,".env.example"));for(let[i,c]of Object.entries(a))ar(t.contract,i).length>0&&(e[i]=c);}return e}function Hc(t,e){return t.filter(r=>ar(e,r).length>0).sort()}function qc(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let r=new URL(e),o=r.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(r.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(r.password||"postgres"),POSTGRES_DB:o||"postgres"}}catch{return}}function zc(t){let e=t.POSTGRES_USER||"postgres",r=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${r}`]}function Od(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
118
118
  `)?JSON.stringify(t):t}function Yc(t,e){return Object.entries(t).map(([r,o])=>`${e}${r}: ${Od(o)}`).join(`
@@ -151,8 +151,8 @@ ${r.stderr||""}`);return o?this.isMavenVersionAtLeast(o,[3,9,0])?{exitCode:0}:{e
151
151
  `,"utf-8");}function it(t,e){return P.isAbsolute(e)?e:P.join(t,e)}function uu(t,e){if(!e.trim()||P.isAbsolute(e)||/^[a-zA-Z]:[\\/]/.test(e))throw new Error(`Mirror artifact target must be a non-empty relative path: ${e}`);let r=P.resolve(t),o=P.resolve(r,e),n=P.relative(r,o);if(!n||n.startsWith("..")||P.isAbsolute(n))throw new Error(`Mirror artifact target escapes the managed artifact directory: ${e}`);return o}async function El(t,e){let r=P.relative(t,e),o=t;for(let a of r.split(P.sep).slice(0,-1)){o=P.join(o,a);let i=await promises.lstat(o).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)break;if(i.isSymbolicLink())throw new Error(`Mirror artifact target traverses a symbolic link: ${o}`);if(!i.isDirectory())throw new Error(`Mirror artifact target parent is not a directory: ${o}`)}let n=await promises.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(n?.isSymbolicLink()||n&&!n.isFile())throw new Error(`Mirror artifact target must be absent or a regular file: ${e}`)}async function mu(t,e){let r=P.resolve(t),o=P.relative(r,P.resolve(e));if(!o||o.startsWith("..")||P.isAbsolute(o))throw new Error("Managed mirror directory escapes the workspace.");let n=r;for(let a of o.split(P.sep)){n=P.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 gu(t,e){if(t.target)return t.target;if(t.source)return P.basename(t.source);if(t.url)try{let r=new URL(t.url).pathname,o=P.basename(r);if(o&&o!=="/")return o}catch{}return `${e}.artifact`}async function fu(t$1){let e=t(t$1,"trusted-sources.lock").find(o=>existsSync(o)),r=new Set(["localhost","127.0.0.1"]);if(!e)return r;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));for(let a of n)r.add(a.toLowerCase());}catch{}return r}async function hu(t,e,r){await M.ensureDir(P.dirname(e)),await new Promise((o,n)=>{let i=(t.startsWith("https://")?Ol:Il).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let p=createWriteStream(e);c.pipe(p),p.on("finish",()=>{p.close(),o();}),p.on("error",d=>{n(d);});});i.setTimeout(r,()=>{i.destroy(new Error(`Request timeout after ${r}ms`));}),i.on("error",c=>{n(c);});});}async function yu(t,e,r,o,n){let a=new URL(t),i=JSON.stringify(e),c=a.protocol==="https:"?Ol:Il;await new Promise((p,d)=>{let h=c.request({method:"POST",hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:`${a.pathname}${a.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...o?{Authorization:`Bearer ${o}`}:{},...n||{}}},u=>{if(!u.statusCode||u.statusCode<200||u.statusCode>=300){d(new Error(`HTTP ${u.statusCode||"unknown"}`)),u.resume();return}u.resume(),p();});h.setTimeout(r,()=>{h.destroy(new Error(`Request timeout after ${r}ms`));}),h.on("error",u=>{d(u);}),h.write(i),h.end();});}function xl(t){return new Promise(e=>setTimeout(e,t))}async function wu(t,e,r,o){let n=it(t,e||".workspai/reports/evidence-export-dead-letter.ndjson");return await M.ensureDir(P.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:o,payload:r})}
152
152
  `,"utf-8"),n}function ku(t,e){if(!e?.enabled)return {headers:{}};let r=process.env[e.hmacKeyEnv];if(!r)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let o=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(o,r).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":o}}}async function vu(t,e,r){let o=(r.algorithm||"sha256").toLowerCase(),n=it(t,r.publicKeyPath);if(!await M.pathExists(n))return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(o);c.update(i),c.end();let p=Buffer.from(r.signature,"base64"),d=c.verify(a,p),h=createHash("sha256").update(a).digest("hex");return {verified:d,algorithm:o,publicKeyPath:n,publicKeyFingerprint:h,signature:r.signature,message:d?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Attestation verification error: ${a.message}`}}}async function Pu(t,e,r,o){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};let a=r.signaturePath?it(t,r.signaturePath):null;if(!a||!await M.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=r.certificatePath?it(t,r.certificatePath):null;c&&i.push("--certificate",c);let p=r.bundlePath?it(t,r.bundlePath):null;p&&i.push("--bundle",p);let d=r.keyPath?it(t,r.keyPath):null;d&&i.push("--key",d),r.identity&&i.push("--certificate-identity",r.identity),r.issuer&&i.push("--certificate-oidc-issuer",r.issuer),r.rekorUrl&&i.push("--rekor-url",r.rekorUrl),o.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let h=await execa("cosign",i,{reject:false});return h.exitCode===0?{verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${h.stderr||h.stdout||"unknown error"}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}}catch(h){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${h.message}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:p,certificatePath:c,signaturePath:a}}}async function bu(t,e){let r=e.algorithm||"sha256",o=it(t,e.policyPath),n=it(t,e.signaturePath),a=it(t,e.publicKeyPath);if(!await M.pathExists(o))return {verified:false,message:`Governance policy bundle not found: ${o}`,policies:null};if(!await M.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await M.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(o,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),p=await promises.readFile(a,"utf-8"),d=createVerify(r);return d.update(i),d.end(),d.verify(p,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function ws(t$1,e){let r=[],o={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=t(t$1,"mirror-config.json").find(j=>existsSync(j))??q(t$1,"mirror-config.json"),a=q(t$1,"mirror.lock"),i=q(t$1,"mirror","artifacts"),c=q(t$1,"reports"),p=await fu(t$1);if(!await M.pathExists(n))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:r,details:o};let d={};try{d=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return r.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:r,details:o}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||d.mode==="offline-only"))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:r,details:o};await M.ensureDir(i);try{await mu(t$1,i);}catch(j){return r.push({id:"mirror.root.safety",status:"failed",message:j instanceof Error?j.message:String(j)}),{checks:r,details:o}}let u=Math.max(0,d.prefetch?.retries??2),f=Math.max(0,d.prefetch?.backoffMs??250),v=Math.max(1e3,d.prefetch?.timeoutMs??15e3),k=d.security?.requireAttestation===true,E=d.security?.requireSigstore===true,S=d.security?.requireTransparencyLog===true,N=d.security?.requireSignedGovernance===true,l=d.security?.evidenceExport,m=(process.env.RAPIDKIT_ENV||d.security?.governance?.environment||"dev").toLowerCase(),y=d.security?.governance?.policies||{};if(d.security?.governanceBundle){let j=await bu(t$1,d.security.governanceBundle);if(r.push({id:"governance.bundle.verify",status:j.verified?"passed":"failed",message:j.message}),j.verified&&j.policies)y=j.policies,o.governanceBundleVerified=true;else if(N)return {checks:r,details:o}}let w=y[m],g=S||w?.requireTransparencyLog===true,C=[],x=Array.isArray(d.artifacts)?d.artifacts:[],R=[];for(let j=0;j<x.length;j+=1){let A=x[j],O=A.id||`artifact-${j+1}`,J=A.source?it(t$1,A.source):null,F=gu(A,O),H;try{H=uu(i,F),await El(i,H);}catch(Z){r.push({id:`mirror.target.${O}`,status:"failed",message:Z instanceof Error?Z.message:String(Z)});continue}let U=false,ae=H,re=false,he=async()=>{re&&await promises.rm(ae,{force:true}).catch(()=>{});},Ve={sourceType:"path",source:J||A.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(J&&await M.pathExists(J))await M.ensureDir(P.dirname(H)),ae=`${H}.${process.pid}.${randomUUID()}.tmp`,re=true,await promises.copyFile(J,ae),o.syncedArtifacts+=1,U=true,Ve={sourceType:"path",source:J,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},r.push({id:`mirror.sync.${O}`,status:"passed",message:`Mirrored artifact ${O} from source path.`});else if(A.url){let Z="";try{Z=new URL(A.url).hostname.toLowerCase();}catch{r.push({id:`mirror.prefetch.${O}`,status:"failed",message:`Invalid URL for ${O}: ${A.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||p.has(Z))){r.push({id:`mirror.prefetch.trust.${O}`,status:"failed",message:`Untrusted mirror host for ${O}: ${Z}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await M.pathExists(H)?(U=true,Ve={sourceType:"url",source:A.url,host:Z,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},r.push({id:`mirror.prefetch.${O}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${O}.`})):r.push({id:`mirror.prefetch.${O}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${O} without an existing mirrored copy.`}),!U))continue;if(!U){await M.ensureDir(P.dirname(H)),ae=`${H}.${process.pid}.${randomUUID()}.tmp`,re=true;let Q=null,_=0;for(let V=1;V<=u+1;V+=1){_=V;try{await promises.rm(ae,{force:true}).catch(()=>{}),await hu(A.url,ae,v),o.syncedArtifacts+=1,U=true,Ve={sourceType:"url",source:A.url,host:Z,fetchedAt:new Date().toISOString(),attempts:_,trusted:true},r.push({id:`mirror.prefetch.${O}`,status:"passed",message:_>1?`Prefetched artifact ${O} from ${Z} after ${_} attempts.`:`Prefetched artifact ${O} from ${Z}.`});break}catch(K){if(Q=K,V<=u){await xl(f*V);continue}}}if(!U){await he(),r.push({id:`mirror.prefetch.${O}`,status:"failed",message:`Failed to prefetch ${O} after ${u+1} attempt(s): ${Q?.message||"unknown error"}`});continue}}if(!U){r.push({id:`mirror.prefetch.${O}`,status:"failed",message:`Failed to prefetch ${O}.`});continue}}if(!U){A.required||e.offlineMode?r.push({id:`mirror.sync.${O}`,status:"failed",message:`Mirror source missing for ${O}${J?`: ${J}`:""}`}):r.push({id:`mirror.sync.${O}`,status:"skipped",message:`Mirror source not found for optional artifact ${O}.`});continue}let Ke=await pu(ae);if(A.sha256&&A.sha256.toLowerCase()!==Ke.toLowerCase()){r.push({id:`mirror.verify.${O}`,status:"failed",message:`Checksum mismatch for ${O}.`}),await he();continue}o.verifiedArtifacts+=1,r.push({id:`mirror.verify.${O}`,status:"passed",message:`Checksum verified for ${O}.`});let ve=A.attestation?await vu(t$1,ae,A.attestation):null;if(A.attestation){if(r.push({id:`mirror.attest.${O}`,status:ve?.verified?"passed":"failed",message:ve?.message||"Attestation verification failed."}),!ve?.verified){await he();continue}}else if(k){r.push({id:`mirror.attest.${O}`,status:"failed",message:`Attestation is required but missing for ${O}.`}),await he();continue}else r.push({id:`mirror.attest.${O}`,status:"skipped",message:`No attestation provided for ${O}.`});let D=A.attestation?.sigstore,G=D?await Pu(t$1,ae,D,{requireTransparencyLog:g}):null;if(D){if(r.push({id:`mirror.sigstore.${O}`,status:G?.verified?"passed":"failed",message:G?.message||"Sigstore verification failed."}),C.push({artifactId:O,verified:!!G?.verified,tlogVerified:!!G?.tlogVerified,identity:G?.identity||null,issuer:G?.issuer||null,rekorUrl:G?.rekorUrl||null,timestamp:new Date().toISOString(),environment:m}),!G?.verified){await he();continue}}else if(E){r.push({id:`mirror.sigstore.${O}`,status:"failed",message:`Sigstore attestation is required but missing for ${O}.`}),await he();continue}else r.push({id:`mirror.sigstore.${O}`,status:"skipped",message:`No Sigstore attestation provided for ${O}.`});if(D&&G?.verified&&w){let Z=w.allowedIdentities||[];if(Z.length>0){let Q=!!G.identity&&Z.includes(G.identity);if(r.push({id:`mirror.sigstore.policy.identity.${O}`,status:Q?"passed":"failed",message:Q?`Sigstore identity policy passed for ${O} in ${m}.`:`Sigstore identity policy failed for ${O} in ${m}.`}),!Q){await he();continue}}let B=w.allowedIssuers||[];if(B.length>0){let Q=!!G.issuer&&B.includes(G.issuer);if(r.push({id:`mirror.sigstore.policy.issuer.${O}`,status:Q?"passed":"failed",message:Q?`Sigstore issuer policy passed for ${O} in ${m}.`:`Sigstore issuer policy failed for ${O} in ${m}.`}),!Q){await he();continue}}let ue=w.allowedRekorUrls||[];if(ue.length>0){let Q=!!G.rekorUrl&&ue.includes(G.rekorUrl);if(r.push({id:`mirror.sigstore.policy.rekor.${O}`,status:Q?"passed":"failed",message:Q?`Sigstore Rekor policy passed for ${O} in ${m}.`:`Sigstore Rekor policy failed for ${O} in ${m}.`}),!Q){await he();continue}}}else w&&r.push({id:`mirror.sigstore.policy.${O}`,status:"skipped",message:`Sigstore governance policy configured for ${m} but no verified Sigstore attestation for ${O}.`});re&&(await El(i,H),await promises.rename(ae,H),re=false);let oe=await promises.stat(H);R.push({id:O,path:P.relative(t$1,H),sha256:Ke,size:oe.size,provenance:Ve,attestation:{detached:{provided:!!A.attestation,verified:ve?.verified||false,algorithm:ve?.algorithm||null,publicKeyPath:ve?.publicKeyPath||null,publicKeyFingerprint:ve?.publicKeyFingerprint||null,signature:ve?.signature||null,verifiedAt:ve?.verified?new Date().toISOString():null},sigstore:{provided:!!D,verified:G?.verified||false,tlogVerified:G?.tlogVerified||false,identity:G?.identity||null,issuer:G?.issuer||null,rekorUrl:G?.rekorUrl||null,bundlePath:G?.bundlePath||null,certificatePath:G?.certificatePath||null,signaturePath:G?.signaturePath||null,verifiedAt:G?.verified?new Date().toISOString():null}}});}let b=d.retention?.keepLast;if(typeof b=="number"&&b>0){let j=new Set(R.map(O=>P.resolve(t$1,O.path))),A=(await du(i)).filter(O=>!j.has(P.resolve(O)));if(A.length>b){let O=await Promise.all(A.map(async F=>({filePath:F,stat:await promises.stat(F)})));O.sort((F,H)=>H.stat.mtimeMs-F.stat.mtimeMs);let J=O.slice(b);for(let F of J)await promises.unlink(F.filePath),o.rotatedFiles+=1;}}r.push({id:"mirror.rotate",status:"passed",message:o.rotatedFiles>0?`Mirror retention rotation removed ${o.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let T={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:d.mode||null,environment:m,artifacts:R};if(await promises.writeFile(a,`${JSON.stringify(T,null,2)}
153
153
  `,"utf-8"),o.lockWritten=true,r.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${P.relative(t$1,a)}.`}),o.transparencyEvidenceRecords=C.length,C.length>0){let j={schemaVersion:h$2.transparencyEvidence.schemaVersion,generatedAt:new Date().toISOString(),environment:m,records:C},A=new Date().toISOString().replace(/[:.]/g,"-"),O=P.join(c,`transparency-evidence-${A}.json`),J=P.join(c,"transparency-evidence.latest.json");if(b$n(`.workspai/reports/${P.basename(O)}`,j),b$n(i$1.transparencyEvidence,j),await M.ensureDir(c),await Sl(O,j),await Sl(J,j),o.transparencyEvidenceWritten=true,r.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${P.relative(t$1,J)}.`}),l?.enabled){let F=Math.max(1e3,l.timeoutMs??1e4);if(l.target==="file")if(!l.filePath)r.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let H=it(t$1,l.filePath);await M.ensureDir(P.dirname(H)),await promises.appendFile(H,`${JSON.stringify(j)}
154
- `,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=H,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${H}.`});}catch(H){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${H.message}`});}else if(l.target==="http")if(!l.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let H=Math.max(0,l.retries??0),U=Math.max(0,l.backoffMs??500),ae=ku(j,l.signing);ae.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:ae.error});try{let re=l.authTokenEnv?process.env[l.authTokenEnv]:void 0,he=false,Ve=null;for(let Ke=1;Ke<=H+1;Ke+=1)try{if(ae.error)throw new Error(ae.error);await yu(l.endpoint,j,F,re,ae.headers),o.evidenceExported=true,o.evidenceExportTarget=l.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:Ke>1?`Transparency evidence exported to HTTP endpoint ${l.endpoint} after ${Ke} attempts.`:`Transparency evidence exported to HTTP endpoint ${l.endpoint}.`}),he=true;break}catch(ve){Ve=ve,Ke<=H&&await xl(U*Ke);}if(!he)throw Ve||new Error("unknown evidence export error")}catch(re){let he=`Evidence HTTP export failed: ${re.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:he});try{let Ve=await wu(t$1,l.deadLetterPath,j,he);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${Ve}.`});}catch(Ve){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${Ve.message}`});}}}if(l.failOnError&&r.some(U=>U.status==="failed"&&(U.id==="sigstore.evidence.export.file"||U.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function en(t){let e=f$6(t.detection.runtime),r=x({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function ju(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function tn(t){if(t.existingProjectJson?.module_support===true){let e=ju(t.existingProjectJson),r=e?a$3(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}var $l=[a$M,b$m];function Cu(t,e){let r=P.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!P.isAbsolute(r)}async function rt(t){let e=await M__default.realpath(t);for(let r of $l){let o=P.join(t,r),n=await M__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await M__default.realpath(o);if(!Cu(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function Nl(t){let e=P.basename(t);return $l.includes(e)?(await M__default.lstat(t)).isSymbolicLink():false}function Tl(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Eu(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return Tl(a)||"imported-project"}function At(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function xu(t){return At(t)?"git-url":"local-folder"}async function Ru(t,e){let r=Tl(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=P.join(t,n);if(!await M__default.pathExists(a))return a;o+=1;}}function Au(t,e){let r=P.resolve(t),o=P.resolve(e),n=P.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!P.isAbsolute(n)}function _u(t,e){if(Au(t,e))throw new Error("Import source must be outside the current workspace root.")}function Iu(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function Ou(t){let e=P.basename(t);return !(await Nl(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||Iu(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function $u(t){await rt(t);for(let e of u(t,"project.json"))if(await M__default.pathExists(e))try{return await M__default.readJson(e)}catch{return null}return null}async function Nu(t){await rt(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:P.basename(t.projectPath),o=b$c({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=v(t.projectPath,"project.json"),i=v(t.projectPath,"import.json"),c=v(t.projectPath,"import-readiness.json"),p=tn({existingProjectJson:t.existingProjectJson}),d=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],h=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},u={...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:P.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:P.basename(t.projectPath),kind:t.projectKind,category:a$f(t.projectKind),project_type:a$f(t.projectKind),runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:p,modules:d,contracts:h,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},f={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:P.basename(t.projectPath)},project:{name:u.name,slug:u.slug,relative_path:n,kind:t.projectKind,category:a$f(t.projectKind),module_support:p},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$f(t.projectKind),confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:p,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},v$1=en({projectName:String(u.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:p,projectPath:t.projectPath,generatedAt:new Date(e)});return await M__default.ensureDir(P.dirname(a)),await M__default.writeJson(a,u,{spaces:2}),await M__default.writeJson(i,f,{spaces:2}),await M__default.writeJson(c,v$1,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:p}}async function Tu(t,e){let r={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,relationship:"imported",importedAt:new Date().toISOString()};await b$d(t,[r]);}async function Mu(t){await M__default.pathExists(t)&&(await rt(t),await M__default.remove(t));}async function Wu(t,e){await Mu(e),await c$4(t,[e]);}async function Ml(t){let e=P.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??xu(r),n=t.name??(o==="git-url"?Eu(r):P.basename(r)),a=await Ru(e,n),i=false;try{if(o==="local-folder"){let m=P.resolve(r),y=await M__default.stat(m).catch(()=>null);if(!y||!y.isDirectory())throw new Error("Import source is not a directory.");if(await rt(m),k$1(m))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");_u(e,m),i=true,await M__default.copy(m,a,{overwrite:false,errorOnExist:true,filter:Ou});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$e()});await rt(a);let c=await $u(a),p=m$1(a,c),d=await b$b(a,c,{runtime:p.runtime,framework:p.key}),[h,u]=await Promise.all([p$4(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):o$2(e)]),f=n$2({profile:h,runtime:p.runtime,subjectLabel:P.basename(a),mode:u}),v=m$2({profile:h,runtimes:await q$2(e,{additionalRuntimes:[p.runtime]}),mode:u}),k=f.ok?v:f;if(!k.ok&&u==="strict")throw new Error(k.message);let E=await Nu({workspacePath:e,projectPath:a,sourceType:o,detection:p,existingProjectJson:c,projectKind:d,profileCompatibility:k}),S=b$c({workspacePath:e,projectPath:a,projectName:P.basename(a)}),N={ingestionPlan:Wt({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:P.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:P.basename(a),path:a,relativePath:S.contractRelativePath,stack:p.importStack,runtime:p.runtime,framework:p.key,frameworkDisplayName:p.displayName,supportTier:p.supportTier,moduleSupport:E.moduleSupport,confidence:p.confidence,source:o,projectJsonPath:E.projectJsonPath,importJsonPath:E.importJsonPath,importReadinessPath:E.importReadinessPath,profileCompatibility:k};await Tu(e,N);let{syncWorkspaceContract:l}=await import('./workspace-contract-JYHNEJPV.js');return await l({workspacePath:e,strict:true}),await k$3({workspacePath:e,projectPath:N.path,projectName:N.name,relationship:"imported",mode:t.projectGrounding??"managed"}),N}catch(c){if(i)try{await Wu(e,a);let{syncWorkspaceContract:p}=await import('./workspace-contract-JYHNEJPV.js');await p({workspacePath:e,strict:true});}catch(p){let d=c instanceof Error?c.message:String(c),h=p instanceof Error?p.message:String(p);throw new Error(`Import failed: ${d}. Rollback also failed: ${h}`)}throw c}}function Du(t){return {schemaVersion:Zo,sourceMode:"linked",sourceCodeModified:false,projectMetadataFiles:[".workspai/project.json",".workspai/adopt.json",".workspai/adopt-readiness.json",f$1,...t==="off"?[]:[h$3,g$2,b$a,i$2]],repositoryControlFiles:[{path:".gitignore",action:"reconcile",condition:"machine-local workspace binding and project-grounding portability rules"},...t==="managed"?[{path:"AGENTS.md",action:"reconcile",condition:"managed grounding is enabled and the path is a regular file; authored deletions and symbolic links are preserved"},{path:".agents/skills/workspai-*/SKILL.md",action:"reconcile",condition:"managed provider-neutral Skill discovery is enabled; authored collisions and unsafe symbolic links are preserved"},...g$3.map(e=>({path:e,action:"reconcile",condition:"managed provider adapter is enabled; authored content, deletions, symbolic links, and unsafe parent paths are preserved"}))]:[]],workspaceOperations:["register-project","sync-contract","rebuild-model","rebuild-graph","sync-agent-grounding"]}}function Lu(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Fu(t,e){return P.resolve(t)===P.resolve(e)}async function Gu(t){await rt(t);for(let e of u(t,"project.json")){if(!await M__default.pathExists(e))continue;let r;try{r=JSON.parse((await M__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}async function Wl(t,e){let r=P.relative(t,e);if(r.startsWith("..")||P.isAbsolute(r))return true;let o=r.split(P.sep).slice(0,-1),n=t;for(let a of o){n=P.join(n,a);let i=await M__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)return false;if(i.isSymbolicLink()||!i.isDirectory())return true}return false}async function Ju(t){let e=P.join(t,".amazonq"),r=await M__default.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!r)return [e,P.join(e,"rules")];if(r.isSymbolicLink()||!r.isDirectory())return [];let o=P.join(e,"rules");return await M__default.lstat(o).catch(a=>{if(a.code==="ENOENT")return null;throw a})?[]:[o]}async function Dl(t,e){let r=[P.join(e,"AGENTS.md"),...g$3.map(n=>P.join(e,n))],o=[];for(let n of r){if(!(await M__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c}))?.isSymbolicLink())continue;let i=await a$d(e,n);i&&o.push(i);}return [v(e,"project.json"),v(e,"adopt.json"),v(e,"adopt-readiness.json"),P.join(e,f$1),P.join(e,g$2),P.join(e,h$3),P.join(e,b$a),...r,...o,P.join(e,".gitignore"),q(t,"imported-projects.json")].filter((n,a,i)=>i.indexOf(n)===a)}async function ks(t,e){let r=P.resolve(t),o=P.resolve(e);await rt(o);let n=await Dl(r,o);return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>{if(a.startsWith(`${o}${P.sep}`)&&await Wl(o,a))return {path:a,contents:null,preserve:"unsafe-parent"};let i=await M__default.lstat(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});return i?.isSymbolicLink()?{path:a,contents:null,preserve:"symbolic-link"}:{path:a,contents:i?.isFile()?await M__default.readFile(a):null}})),createdAdapterDirectories:await Ju(o)}}async function Ll(t,e,r){let o=(await Dl(e,r)).map(a=>P.resolve(a)),n=new Set([".amazonq",".amazonq/rules"].map(a=>P.resolve(r,a)));if(t.workspacePath!==P.resolve(e)||t.projectPath!==P.resolve(r)||t.files.length!==o.length||t.files.some((a,i)=>P.resolve(a.path)!==o[i])||t.createdAdapterDirectories.some(a=>!n.has(P.resolve(a)))||new Set(t.createdAdapterDirectories.map(a=>P.resolve(a))).size!==t.createdAdapterDirectories.length)throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function Vu(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,category:a$f(t.projectKind),project_type:a$f(t.projectKind),runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,framework:t.detection.key,kit:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function Ku(t,e,r){await rt(e),await Ll(r,t,e);let o=[];for(let n of r.files)try{if(n.preserve==="symbolic-link")continue;n.contents===null?await M__default.remove(n.path):(await M__default.ensureDir(P.dirname(n.path)),await M__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}for(let n of [...r.createdAdapterDirectories].reverse())try{if(await Wl(e,n))continue;await M__default.rmdir(n);}catch(a){let i=a.code;i!=="ENOENT"&&i!=="ENOTEMPTY"&&o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function vs(t){let e=P.resolve(t.workspacePath),r=P.resolve(t.source),o=await M__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await rt(r),Fu(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(k$1(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t.rollbackSnapshot??await ks(e,r);await Ll(n,e,r);let a=await Gu(r),i=j$5(a),c=m$1(r,i?null:a),p=l$2(r),d=[c.runtime,...p.filter(b=>b!==c.runtime)].filter((b,T,j)=>b!=="unknown"&&j.indexOf(b)===T);d.length===0&&d.push("unknown");let h=await b$b(r,i?{}:a,{runtime:c.runtime,framework:c.key}),u=Lu(t.name||(typeof a?.name=="string"?a.name:"")||P.basename(r))||"adopted-project",f=b$c({workspacePath:e,projectPath:r,projectName:u}),v$1=(t.now??new Date).toISOString(),k=v(r,"project.json"),E=v(r,"adopt.json"),S=v(r,"adopt-readiness.json"),N=tn({existingProjectJson:a}),[l,m]=await Promise.all([p$4(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):o$2(e)]),y=n$2({profile:l,runtime:c.runtime,subjectLabel:u,mode:m}),w=m$2({profile:l,runtimes:await q$2(e,{additionalRuntimes:d,excludeProjectPath:r}),mode:m}),g=y.ok?w:y;if(!g.ok&&m==="strict")throw new Error(g.message);let C=Vu({projectName:u,contractRelativePath:f.contractRelativePath,isExternal:f.isExternal,discoveredRelativePath:f.relativePath,detection:c,runtimeCandidates:d,existingProjectJson:a,refreshManagedDetection:i,projectKind:h,moduleSupport:N,adoptedAt:v$1}),x={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:v$1,managed_by:"workspai",mode:"linked",workspace:{name:P.basename(e),contract:i$1.workspaceContract},project:{name:u,relative_path:f.contractRelativePath,...f.isExternal?{}:{discovered_relative_path:f.relativePath},is_external:f.isExternal,kind:h,category:a$f(h),module_support:N},detection:{framework:c.key,framework_display_name:c.displayName,runtime:c.runtime,runtime_candidates:d,kind:h,category:a$f(h),confidence:c.confidence,support_tier:c.supportTier,import_stack:c.importStack,source:c.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:N,workspace_contract:"linked-project",profile_compatibility:{ok:g.ok,profile:g.profile,runtimes:g.runtimes,message:g.message,recommended_profile:g.recommendedProfile,recommended_command:g.recommendedCommand}}},R=en({projectName:u,relativePath:f.contractRelativePath,projectKind:h,source:"adopted-local",detection:c,moduleSupport:N,projectPath:r,generatedAt:new Date(v$1)});if(t.dryRun!==true)try{await rt(r),await M__default.ensureDir(P.dirname(k)),await M__default.writeJson(k,C,{spaces:2}),await M__default.writeJson(E,x,{spaces:2}),await M__default.writeJson(S,R,{spaces:2});let b={name:u,path:r,relativePath:f.contractRelativePath,relationship:"adopted",stack:c.importStack,runtime:c.runtime,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:N,confidence:c.confidence,source:"adopted-local",importedAt:v$1};await b$d(e,[b]);let{syncWorkspaceContract:T}=await import('./workspace-contract-JYHNEJPV.js');await T({workspacePath:e,strict:true}),await k$3({workspacePath:e,projectPath:r,projectName:u,relationship:"adopted",mode:t.projectGrounding??"managed",now:new Date(v$1)});}catch(b){try{await Ku(e,r,n);let{syncWorkspaceContract:T}=await import('./workspace-contract-JYHNEJPV.js');await T({workspacePath:e,strict:true});}catch(T){throw new AggregateError([b,T],`Adopt failed and rollback was incomplete: ${b instanceof Error?b.message:String(b)}`)}throw b}return {ingestionPlan:Wt({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t.projectGrounding??"managed"}),name:u,path:r,relativePath:f.relativePath,contractRelativePath:f.contractRelativePath,isExternal:f.isExternal,relationship:"adopted",stack:c.importStack,runtime:c.runtime,runtimeCandidates:d,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:N,confidence:c.confidence,projectJsonPath:k,adoptJsonPath:E,adoptReadinessPath:S,profileCompatibility:g,effects:Du(t.projectGrounding??"managed"),wroteFiles:t.dryRun!==true}}async function Uu(t){let e=await M__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=P.join(t,r),n=await M__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function Bu(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await M__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=P.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$g(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$6&&(await M__default.remove(i),e.push(P.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function Gl(t,e){if(await b$e(t,P.basename(t)),!(await g$4(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$j(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function Ps(t){let e=P.resolve(t.workspacePath);await Uu(e);let r=Wt({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!k$1(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return nn(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$5(e);try{let n=await Gl(e,t.projectGrounding??"managed");return nn(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$5(e,o).catch(()=>{}),n}}async function bs(t){if(t.dryRun){let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=P.resolve(o.outputPath),a=Fl(t,n);return nn(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?P.resolve(t.outputPath):void 0;if(e&&await M__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=P.resolve(o.outputPath);let n=Fl(t,r);if(!k$1(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await Bu(r);o.manifest?.portableContract&&await M__default.outputJson(P.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await Gl(r,t.projectGrounding??"managed");return nn(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,p,d)=>d.indexOf(c)===p),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$5(r).catch(()=>{}),await M__default.remove(r).catch(()=>{})),o}}function Fl(t,e){return Wt({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function nn(t,e){let r={schemaVersion:Xo,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$4(r,bl,"Workspace ingestion result"),r}function Jl(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function Vl(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function Kl(t){let e=t.trim(),r=e.startsWith("~/")?P.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!At(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:At(r)?r:P.resolve(r)};if(At(r))return {kind:"git-project",source:r};let n=P.resolve(r);return k$1(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var Yu=Yo,Xu=qo;function Cs(t){if(!t||typeof t!="object")return null;let e=t.code;return e==="PYTHON_NOT_FOUND"||e==="BRIDGE_VENV_BOOTSTRAP_FAILED"||e==="BRIDGE_VENV_CREATE_FAILED"||e==="BRIDGE_PIP_BOOTSTRAP_FAILED"?e:null}function Zu(t=process.argv){let e=P.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function pr(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function Qu(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Le(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function em(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Os(t){try{return em(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function Us(t,e){let r=Le(t,"--port")?.trim(),o=t[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Le(t,"--output")||".",i=P.resolve(e,a,o),c=u(i,"project.json").find(d=>I.existsSync(d))??v(i,"project.json");if(!await M__default.pathExists(c))return;let p=await M__default.readJson(c);await M__default.writeJson(c,{...p,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Bl(t){let e=Se(process.cwd()),r$1=t.trim().toLowerCase();if(!e||!r$1)return true;try{let[o,n]=await Promise.all([p$4(e),o$2(e)]),a=a$3(r$1),i=l$5(r$1),c=r$3(r$1),p=i?"node":c?.runtime??a?.runtime??"python",d=n$2({profile:o,runtime:p,subjectLabel:r$1,mode:n}),h=m$2({profile:o,runtimes:await q$2(e,{additionalRuntimes:[p]}),mode:n}),u=d.ok?h:d;if(u.ok)return true;let f=r(u);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${u.message}`)),f&&console.log(s.gray(`\u{1F4A1} ${f}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${u.message}`)),f&&console.log(s.gray(`\u{1F4A1} ${f}`));}catch{}return true}function Bs(){return j$6()}function Hl(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(P.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(P.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$5()),t.RAPIDKIT_SKIP_LOCK_SYNC||(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t.POETRY_KEYRING_ENABLED||(t.POETRY_KEYRING_ENABLED="false"),t.PYTHON_KEYRING_BACKEND||(t.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),t.POETRY_NO_INTERACTION||(t.POETRY_NO_INTERACTION="1"),t}function tm(t){return m$4(P.join(t,".venv"))}async function rm(t,e){return await je(t,["--version"],e)===0}async function Ft(t){let e=P.join(t,"go.mod");if(await M__default.pathExists(e))return "go";let r=P.join(t,"pom.xml"),o=P.join(t,"build.gradle"),n=P.join(t,"build.gradle.kts");if(await M__default.pathExists(r)||await M__default.pathExists(o)||await M__default.pathExists(n))return "java";if((await M__default.pathExists(t)?await I.promises.readdir(t,{withFileTypes:true}):[]).some(v=>v.isFile()&&v.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=P.join(t,"src");if(await M__default.pathExists(i)&&(await I.promises.readdir(i,{withFileTypes:true})).some(k=>k.isFile()&&k.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=P.join(t,"Cargo.toml");if(await M__default.pathExists(c))return "rust";let p=P.join(t,"composer.json");if(await M__default.pathExists(p))return "php";let d=P.join(t,"package.json");if(await M__default.pathExists(d))return "node";let h=P.join(t,"pyproject.toml"),u=P.join(t,"requirements.txt"),f=P.join(t,"poetry.lock");return await M__default.pathExists(h)||await M__default.pathExists(u)||await M__default.pathExists(f)?"python":null}async function om(t,e={}){let r=e.runCommand??je,o=P.join(t,".venv"),n=await M__default.pathExists(o);for(let a of e.pythonCandidates??Bs()){if(await r(a,a==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;n||await M__default.remove(o);}return 1}async function nm(t,e={}){let r=e.runCommand??je,o=P.join(t,".venv"),n=m$4(o);if(await M__default.pathExists(n)){if(await r(n,["-m","pip","--version"],t)===0)return 0;await M__default.remove(o);}let a=await om(t,e);if(a!==0)return a;n=m$4(o);let i=await r(n,["-m","pip","--version"],t);return i!==0&&await M__default.remove(o),i}async function lp(t,e={}){let r=e.runCommand??je;for(let o of e.pythonCandidates??Bs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function sm(t,e={}){let r=e.runCommand??je,o=m$4(P.join(t,".venv"));if(!await M__default.pathExists(o)){let c=await lp(t,e);if(c!==0)return c}if(!(await r("poetry",["--version"],t)===0))return 0;let a=await r("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await r("poetry",["env","use",o],t);return i!==0?i:0}async function am(t,e={}){let r=e.runCommand??je,o=m$4(P.join(t,".venv"));if(!await M__default.pathExists(o)){let i=await lp(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=P.join(t,"requirements.txt");if(await M__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=P.join(t,"pyproject.toml");return await M__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function Ss(t,e){return await sm(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 M__default.pathExists(P.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await am(t))}async function Es(t){let e=await Lt("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await rm(o,t))continue;if(await je(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function im(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Le([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Le([...e],"--java-version"),a=Le([...e],"--spring-boot-version"),i=Le([...e],"--springdoc-version"),c=Le([...e],"--group-id"),p=Le([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(p&&!/^[A-Za-z0-9_.-]+$/.test(p.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Le([...e],"--target-framework"),a=Le([...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 ql(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||Ds(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:o}=await import('./create-72ITVZXV.js');await o(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:r}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},{name:"Create it without workspace management",value:"none"}],default:1}]);if(r==="current"){let{registerWorkspaceAtPath:o}=await import('./create-72ITVZXV.js');await o(process.cwd(),{skipGit:e,yes:false,userConfig:await b()});}else r==="none"&&t.push("--no-workspace");}async function cm(t){await M__default.ensureDir(t);let e=P.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await I.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
155
- `),async()=>{await o.close().catch(()=>{}),await M__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await M__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 M__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function cn(t$1,e={}){let r=P.join(q$1(),"transactions"),o=await cm(r),n;try{await b$8(r),n=await a$a({journalDirectory:r});}catch(i){throw await o(),i}let a=new Set([P.join(q$1(),"workspaces.json"),P.join(r$1(),"workspaces.json"),a$b(t$1,g$1),b$9(t$1,g$1),a$b(t$1,a$c),b$9(t$1,a$c),...t(t$1,"imported-projects.json")]);if(e.projectPath){a.add(v(e.projectPath,"project.json")),a.add(v(e.projectPath,"context.json")),a.add(v(e.projectPath,"file-hashes.json")),a.add(v(e.projectPath,"adopt.json")),a.add(v(e.projectPath,"adopt-readiness.json")),a.add(P.join(e.projectPath,f$1)),a.add(P.join(e.projectPath,g$2)),a.add(P.join(e.projectPath,h$3)),a.add(P.join(e.projectPath,b$a)),a.add(P.join(e.projectPath,i$2));for(let i of g$3)a.add(P.join(e.projectPath,i));for(let i of await j$4({workspacePath:t$1,projectPath:e.projectPath}))a.add(i);a.add(P.join(e.projectPath,"AGENTS.md")),a.add(P.join(e.projectPath,".gitignore"));}try{let i=new Set,c=e.projectPath;for(let d of a){let u=c&&(d===P.join(c,"AGENTS.md")||g$3.some(v=>d===P.join(c,v)))?await M__default.lstat(d).catch(v=>{if(v.code==="ENOENT")return null;throw v}):null,f=d;if(u?.isSymbolicLink()&&c){let v=await a$d(c,d);if(!v)continue;f=v;}i.has(f)||(await n.captureFile(f),i.add(f));}e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let p=false;return {registerCompensation:d=>n.registerCompensation(d),commit:async()=>{p||(await n.commit(),p=true,await o());},rollback:async()=>{if(!p){p=true;try{await n.rollback();}finally{await o();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await o(),i}}async function dr(t,e){try{await t.rollback();}catch(r){throw new AggregateError([e,r],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function Ur(t,e$1,r){if(t.includes("--no-workspace")||t.includes("--dry-run"))return;if(!await M__default.pathExists(e$1)){e.warn(`Created project path was not found for workspace linking: ${e$1}`);return}let o=Se(e$1)||Se(process.cwd()),n=false,a;if(o)a=await cn(o,{projectPath:e$1});else {o=p(),a=await cn(o,{projectPath:e$1,ownedWorkspace:o});try{o=(await Hs()).workspacePath;}catch(c){await dr(a,c);}n=true;}let i="managed";try{await p$3(e$1);let c=P.relative(o,e$1);(c.startsWith("..")||P.isAbsolute(c))&&(i=(await vs({source:e$1,workspacePath:o,name:r})).relationship);let{registerProjectInWorkspaceStrict:d,registerWorkspaceStrict:h}=await import('./workspace-5W7FYGDQ.js'),{syncWorkspaceContract:u}=await import('./workspace-contract-JYHNEJPV.js');await h(o,P.basename(o)),await d(o,r,e$1),await u({workspacePath:o,strict:true});let{syncProjectIntelligenceLens:f}=await import('./project-intelligence-lens-LQCN65P2.js');await f({workspacePath:o,projectPath:e$1,projectName:r,relationship:i==="adopted"?"adopted":"managed",mode:"managed"}),await Br(o,{strict:true}),await a.commit();}catch(c){await dr(a,c);}return n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${j$3}" (${i}).`)),console.log(s.gray(` Registry: ${P.join(q$1(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${o}`))),o}async function $s(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],r=a$3(e),o=t[3];if(!r||r.owner!=="npm")return 1;if(!o)return process.stderr.write(`Usage: ${r.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
154
+ `,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=H,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${H}.`});}catch(H){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${H.message}`});}else if(l.target==="http")if(!l.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let H=Math.max(0,l.retries??0),U=Math.max(0,l.backoffMs??500),ae=ku(j,l.signing);ae.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:ae.error});try{let re=l.authTokenEnv?process.env[l.authTokenEnv]:void 0,he=false,Ve=null;for(let Ke=1;Ke<=H+1;Ke+=1)try{if(ae.error)throw new Error(ae.error);await yu(l.endpoint,j,F,re,ae.headers),o.evidenceExported=true,o.evidenceExportTarget=l.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:Ke>1?`Transparency evidence exported to HTTP endpoint ${l.endpoint} after ${Ke} attempts.`:`Transparency evidence exported to HTTP endpoint ${l.endpoint}.`}),he=true;break}catch(ve){Ve=ve,Ke<=H&&await xl(U*Ke);}if(!he)throw Ve||new Error("unknown evidence export error")}catch(re){let he=`Evidence HTTP export failed: ${re.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:he});try{let Ve=await wu(t$1,l.deadLetterPath,j,he);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${Ve}.`});}catch(Ve){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${Ve.message}`});}}}if(l.failOnError&&r.some(U=>U.status==="failed"&&(U.id==="sigstore.evidence.export.file"||U.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function en(t){let e=f$6(t.detection.runtime),r=x({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function ju(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function tn(t){if(t.existingProjectJson?.module_support===true){let e=ju(t.existingProjectJson),r=e?a$3(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}var $l=[a$M,b$m];function Cu(t,e){let r=P.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!P.isAbsolute(r)}async function rt(t){let e=await M__default.realpath(t);for(let r of $l){let o=P.join(t,r),n=await M__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await M__default.realpath(o);if(!Cu(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function Nl(t){let e=P.basename(t);return $l.includes(e)?(await M__default.lstat(t)).isSymbolicLink():false}function Tl(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Eu(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return Tl(a)||"imported-project"}function At(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function xu(t){return At(t)?"git-url":"local-folder"}async function Ru(t,e){let r=Tl(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=P.join(t,n);if(!await M__default.pathExists(a))return a;o+=1;}}function Au(t,e){let r=P.resolve(t),o=P.resolve(e),n=P.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!P.isAbsolute(n)}function _u(t,e){if(Au(t,e))throw new Error("Import source must be outside the current workspace root.")}function Iu(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function Ou(t){let e=P.basename(t);return !(await Nl(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||Iu(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function $u(t){await rt(t);for(let e of u(t,"project.json"))if(await M__default.pathExists(e))try{return await M__default.readJson(e)}catch{return null}return null}async function Nu(t){await rt(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:P.basename(t.projectPath),o=b$c({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=v(t.projectPath,"project.json"),i=v(t.projectPath,"import.json"),c=v(t.projectPath,"import-readiness.json"),p=tn({existingProjectJson:t.existingProjectJson}),d=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],h=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},u={...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:P.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:P.basename(t.projectPath),kind:t.projectKind,category:a$f(t.projectKind),project_type:a$f(t.projectKind),runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:p,modules:d,contracts:h,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},f={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:P.basename(t.projectPath)},project:{name:u.name,slug:u.slug,relative_path:n,kind:t.projectKind,category:a$f(t.projectKind),module_support:p},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$f(t.projectKind),confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:p,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},v$1=en({projectName:String(u.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:p,projectPath:t.projectPath,generatedAt:new Date(e)});return await M__default.ensureDir(P.dirname(a)),await M__default.writeJson(a,u,{spaces:2}),await M__default.writeJson(i,f,{spaces:2}),await M__default.writeJson(c,v$1,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:p}}async function Tu(t,e){let r={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,relationship:"imported",importedAt:new Date().toISOString()};await b$d(t,[r]);}async function Mu(t){await M__default.pathExists(t)&&(await rt(t),await M__default.remove(t));}async function Wu(t,e){await Mu(e),await c$4(t,[e]);}async function Ml(t){let e=P.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??xu(r),n=t.name??(o==="git-url"?Eu(r):P.basename(r)),a=await Ru(e,n),i=false;try{if(o==="local-folder"){let m=P.resolve(r),y=await M__default.stat(m).catch(()=>null);if(!y||!y.isDirectory())throw new Error("Import source is not a directory.");if(await rt(m),k$1(m))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");_u(e,m),i=true,await M__default.copy(m,a,{overwrite:false,errorOnExist:true,filter:Ou});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$e()});await rt(a);let c=await $u(a),p=m$1(a,c),d=await b$b(a,c,{runtime:p.runtime,framework:p.key}),[h,u]=await Promise.all([p$4(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):o$2(e)]),f=n$2({profile:h,runtime:p.runtime,subjectLabel:P.basename(a),mode:u}),v=m$2({profile:h,runtimes:await q$2(e,{additionalRuntimes:[p.runtime]}),mode:u}),k=f.ok?v:f;if(!k.ok&&u==="strict")throw new Error(k.message);let E=await Nu({workspacePath:e,projectPath:a,sourceType:o,detection:p,existingProjectJson:c,projectKind:d,profileCompatibility:k}),S=b$c({workspacePath:e,projectPath:a,projectName:P.basename(a)}),N={ingestionPlan:Wt({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:P.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:P.basename(a),path:a,relativePath:S.contractRelativePath,stack:p.importStack,runtime:p.runtime,framework:p.key,frameworkDisplayName:p.displayName,supportTier:p.supportTier,moduleSupport:E.moduleSupport,confidence:p.confidence,source:o,projectJsonPath:E.projectJsonPath,importJsonPath:E.importJsonPath,importReadinessPath:E.importReadinessPath,profileCompatibility:k};await Tu(e,N);let{syncWorkspaceContract:l}=await import('./workspace-contract-MQ3QE52V.js');return await l({workspacePath:e,strict:true}),await k$3({workspacePath:e,projectPath:N.path,projectName:N.name,relationship:"imported",mode:t.projectGrounding??"managed"}),N}catch(c){if(i)try{await Wu(e,a);let{syncWorkspaceContract:p}=await import('./workspace-contract-MQ3QE52V.js');await p({workspacePath:e,strict:true});}catch(p){let d=c instanceof Error?c.message:String(c),h=p instanceof Error?p.message:String(p);throw new Error(`Import failed: ${d}. Rollback also failed: ${h}`)}throw c}}function Du(t){return {schemaVersion:Zo,sourceMode:"linked",sourceCodeModified:false,projectMetadataFiles:[".workspai/project.json",".workspai/adopt.json",".workspai/adopt-readiness.json",f$1,...t==="off"?[]:[h$3,g$2,b$a,i$2]],repositoryControlFiles:[{path:".gitignore",action:"reconcile",condition:"machine-local workspace binding and project-grounding portability rules"},...t==="managed"?[{path:"AGENTS.md",action:"reconcile",condition:"managed grounding is enabled and the path is a regular file; authored deletions and symbolic links are preserved"},{path:".agents/skills/workspai-*/SKILL.md",action:"reconcile",condition:"managed provider-neutral Skill discovery is enabled; authored collisions and unsafe symbolic links are preserved"},...g$3.map(e=>({path:e,action:"reconcile",condition:"managed provider adapter is enabled; authored content, deletions, symbolic links, and unsafe parent paths are preserved"}))]:[]],workspaceOperations:["register-project","sync-contract","rebuild-model","rebuild-graph","sync-agent-grounding"]}}function Lu(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Fu(t,e){return P.resolve(t)===P.resolve(e)}async function Gu(t){await rt(t);for(let e of u(t,"project.json")){if(!await M__default.pathExists(e))continue;let r;try{r=JSON.parse((await M__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}async function Wl(t,e){let r=P.relative(t,e);if(r.startsWith("..")||P.isAbsolute(r))return true;let o=r.split(P.sep).slice(0,-1),n=t;for(let a of o){n=P.join(n,a);let i=await M__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)return false;if(i.isSymbolicLink()||!i.isDirectory())return true}return false}async function Ju(t){let e=P.join(t,".amazonq"),r=await M__default.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!r)return [e,P.join(e,"rules")];if(r.isSymbolicLink()||!r.isDirectory())return [];let o=P.join(e,"rules");return await M__default.lstat(o).catch(a=>{if(a.code==="ENOENT")return null;throw a})?[]:[o]}async function Dl(t,e){let r=[P.join(e,"AGENTS.md"),...g$3.map(n=>P.join(e,n))],o=[];for(let n of r){if(!(await M__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c}))?.isSymbolicLink())continue;let i=await a$d(e,n);i&&o.push(i);}return [v(e,"project.json"),v(e,"adopt.json"),v(e,"adopt-readiness.json"),P.join(e,f$1),P.join(e,g$2),P.join(e,h$3),P.join(e,b$a),...r,...o,P.join(e,".gitignore"),q(t,"imported-projects.json")].filter((n,a,i)=>i.indexOf(n)===a)}async function ks(t,e){let r=P.resolve(t),o=P.resolve(e);await rt(o);let n=await Dl(r,o);return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>{if(a.startsWith(`${o}${P.sep}`)&&await Wl(o,a))return {path:a,contents:null,preserve:"unsafe-parent"};let i=await M__default.lstat(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});return i?.isSymbolicLink()?{path:a,contents:null,preserve:"symbolic-link"}:{path:a,contents:i?.isFile()?await M__default.readFile(a):null}})),createdAdapterDirectories:await Ju(o)}}async function Ll(t,e,r){let o=(await Dl(e,r)).map(a=>P.resolve(a)),n=new Set([".amazonq",".amazonq/rules"].map(a=>P.resolve(r,a)));if(t.workspacePath!==P.resolve(e)||t.projectPath!==P.resolve(r)||t.files.length!==o.length||t.files.some((a,i)=>P.resolve(a.path)!==o[i])||t.createdAdapterDirectories.some(a=>!n.has(P.resolve(a)))||new Set(t.createdAdapterDirectories.map(a=>P.resolve(a))).size!==t.createdAdapterDirectories.length)throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function Vu(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,category:a$f(t.projectKind),project_type:a$f(t.projectKind),runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,framework:t.detection.key,kit:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function Ku(t,e,r){await rt(e),await Ll(r,t,e);let o=[];for(let n of r.files)try{if(n.preserve==="symbolic-link")continue;n.contents===null?await M__default.remove(n.path):(await M__default.ensureDir(P.dirname(n.path)),await M__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}for(let n of [...r.createdAdapterDirectories].reverse())try{if(await Wl(e,n))continue;await M__default.rmdir(n);}catch(a){let i=a.code;i!=="ENOENT"&&i!=="ENOTEMPTY"&&o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function vs(t){let e=P.resolve(t.workspacePath),r=P.resolve(t.source),o=await M__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await rt(r),Fu(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(k$1(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t.rollbackSnapshot??await ks(e,r);await Ll(n,e,r);let a=await Gu(r),i=j$5(a),c=m$1(r,i?null:a),p=l$2(r),d=[c.runtime,...p.filter(b=>b!==c.runtime)].filter((b,T,j)=>b!=="unknown"&&j.indexOf(b)===T);d.length===0&&d.push("unknown");let h=await b$b(r,i?{}:a,{runtime:c.runtime,framework:c.key}),u=Lu(t.name||(typeof a?.name=="string"?a.name:"")||P.basename(r))||"adopted-project",f=b$c({workspacePath:e,projectPath:r,projectName:u}),v$1=(t.now??new Date).toISOString(),k=v(r,"project.json"),E=v(r,"adopt.json"),S=v(r,"adopt-readiness.json"),N=tn({existingProjectJson:a}),[l,m]=await Promise.all([p$4(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):o$2(e)]),y=n$2({profile:l,runtime:c.runtime,subjectLabel:u,mode:m}),w=m$2({profile:l,runtimes:await q$2(e,{additionalRuntimes:d,excludeProjectPath:r}),mode:m}),g=y.ok?w:y;if(!g.ok&&m==="strict")throw new Error(g.message);let C=Vu({projectName:u,contractRelativePath:f.contractRelativePath,isExternal:f.isExternal,discoveredRelativePath:f.relativePath,detection:c,runtimeCandidates:d,existingProjectJson:a,refreshManagedDetection:i,projectKind:h,moduleSupport:N,adoptedAt:v$1}),x={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:v$1,managed_by:"workspai",mode:"linked",workspace:{name:P.basename(e),contract:i$1.workspaceContract},project:{name:u,relative_path:f.contractRelativePath,...f.isExternal?{}:{discovered_relative_path:f.relativePath},is_external:f.isExternal,kind:h,category:a$f(h),module_support:N},detection:{framework:c.key,framework_display_name:c.displayName,runtime:c.runtime,runtime_candidates:d,kind:h,category:a$f(h),confidence:c.confidence,support_tier:c.supportTier,import_stack:c.importStack,source:c.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:N,workspace_contract:"linked-project",profile_compatibility:{ok:g.ok,profile:g.profile,runtimes:g.runtimes,message:g.message,recommended_profile:g.recommendedProfile,recommended_command:g.recommendedCommand}}},R=en({projectName:u,relativePath:f.contractRelativePath,projectKind:h,source:"adopted-local",detection:c,moduleSupport:N,projectPath:r,generatedAt:new Date(v$1)});if(t.dryRun!==true)try{await rt(r),await M__default.ensureDir(P.dirname(k)),await M__default.writeJson(k,C,{spaces:2}),await M__default.writeJson(E,x,{spaces:2}),await M__default.writeJson(S,R,{spaces:2});let b={name:u,path:r,relativePath:f.contractRelativePath,relationship:"adopted",stack:c.importStack,runtime:c.runtime,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:N,confidence:c.confidence,source:"adopted-local",importedAt:v$1};await b$d(e,[b]);let{syncWorkspaceContract:T}=await import('./workspace-contract-MQ3QE52V.js');await T({workspacePath:e,strict:true}),await k$3({workspacePath:e,projectPath:r,projectName:u,relationship:"adopted",mode:t.projectGrounding??"managed",now:new Date(v$1)});}catch(b){try{await Ku(e,r,n);let{syncWorkspaceContract:T}=await import('./workspace-contract-MQ3QE52V.js');await T({workspacePath:e,strict:true});}catch(T){throw new AggregateError([b,T],`Adopt failed and rollback was incomplete: ${b instanceof Error?b.message:String(b)}`)}throw b}return {ingestionPlan:Wt({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t.projectGrounding??"managed"}),name:u,path:r,relativePath:f.relativePath,contractRelativePath:f.contractRelativePath,isExternal:f.isExternal,relationship:"adopted",stack:c.importStack,runtime:c.runtime,runtimeCandidates:d,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:N,confidence:c.confidence,projectJsonPath:k,adoptJsonPath:E,adoptReadinessPath:S,profileCompatibility:g,effects:Du(t.projectGrounding??"managed"),wroteFiles:t.dryRun!==true}}async function Uu(t){let e=await M__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=P.join(t,r),n=await M__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function Bu(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await M__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=P.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$g(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$6&&(await M__default.remove(i),e.push(P.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function Gl(t,e){if(await b$e(t,P.basename(t)),!(await g$4(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$j(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function Ps(t){let e=P.resolve(t.workspacePath);await Uu(e);let r=Wt({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!k$1(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return nn(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$5(e);try{let n=await Gl(e,t.projectGrounding??"managed");return nn(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$5(e,o).catch(()=>{}),n}}async function bs(t){if(t.dryRun){let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=P.resolve(o.outputPath),a=Fl(t,n);return nn(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?P.resolve(t.outputPath):void 0;if(e&&await M__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$2({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=P.resolve(o.outputPath);let n=Fl(t,r);if(!k$1(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await Bu(r);o.manifest?.portableContract&&await M__default.outputJson(P.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await Gl(r,t.projectGrounding??"managed");return nn(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,p,d)=>d.indexOf(c)===p),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$5(r).catch(()=>{}),await M__default.remove(r).catch(()=>{})),o}}function Fl(t,e){return Wt({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function nn(t,e){let r={schemaVersion:Xo,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$4(r,bl,"Workspace ingestion result"),r}function Jl(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function Vl(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function Kl(t){let e=t.trim(),r=e.startsWith("~/")?P.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!At(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:At(r)?r:P.resolve(r)};if(At(r))return {kind:"git-project",source:r};let n=P.resolve(r);return k$1(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var Yu=Yo,Xu=qo;function Cs(t){if(!t||typeof t!="object")return null;let e=t.code;return e==="PYTHON_NOT_FOUND"||e==="BRIDGE_VENV_BOOTSTRAP_FAILED"||e==="BRIDGE_VENV_CREATE_FAILED"||e==="BRIDGE_PIP_BOOTSTRAP_FAILED"?e:null}function Zu(t=process.argv){let e=P.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function pr(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function Qu(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Le(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function em(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Os(t){try{return em(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function Us(t,e){let r=Le(t,"--port")?.trim(),o=t[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Le(t,"--output")||".",i=P.resolve(e,a,o),c=u(i,"project.json").find(d=>I.existsSync(d))??v(i,"project.json");if(!await M__default.pathExists(c))return;let p=await M__default.readJson(c);await M__default.writeJson(c,{...p,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Bl(t){let e=Se(process.cwd()),r$1=t.trim().toLowerCase();if(!e||!r$1)return true;try{let[o,n]=await Promise.all([p$4(e),o$2(e)]),a=a$3(r$1),i=l$5(r$1),c=r$3(r$1),p=i?"node":c?.runtime??a?.runtime??"python",d=n$2({profile:o,runtime:p,subjectLabel:r$1,mode:n}),h=m$2({profile:o,runtimes:await q$2(e,{additionalRuntimes:[p]}),mode:n}),u=d.ok?h:d;if(u.ok)return true;let f=r(u);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${u.message}`)),f&&console.log(s.gray(`\u{1F4A1} ${f}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${u.message}`)),f&&console.log(s.gray(`\u{1F4A1} ${f}`));}catch{}return true}function Bs(){return j$6()}function Hl(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(P.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(P.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$5()),t.RAPIDKIT_SKIP_LOCK_SYNC||(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t.POETRY_KEYRING_ENABLED||(t.POETRY_KEYRING_ENABLED="false"),t.PYTHON_KEYRING_BACKEND||(t.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),t.POETRY_NO_INTERACTION||(t.POETRY_NO_INTERACTION="1"),t}function tm(t){return m$4(P.join(t,".venv"))}async function rm(t,e){return await je(t,["--version"],e)===0}async function Ft(t){let e=P.join(t,"go.mod");if(await M__default.pathExists(e))return "go";let r=P.join(t,"pom.xml"),o=P.join(t,"build.gradle"),n=P.join(t,"build.gradle.kts");if(await M__default.pathExists(r)||await M__default.pathExists(o)||await M__default.pathExists(n))return "java";if((await M__default.pathExists(t)?await I.promises.readdir(t,{withFileTypes:true}):[]).some(v=>v.isFile()&&v.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=P.join(t,"src");if(await M__default.pathExists(i)&&(await I.promises.readdir(i,{withFileTypes:true})).some(k=>k.isFile()&&k.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=P.join(t,"Cargo.toml");if(await M__default.pathExists(c))return "rust";let p=P.join(t,"composer.json");if(await M__default.pathExists(p))return "php";let d=P.join(t,"package.json");if(await M__default.pathExists(d))return "node";let h=P.join(t,"pyproject.toml"),u=P.join(t,"requirements.txt"),f=P.join(t,"poetry.lock");return await M__default.pathExists(h)||await M__default.pathExists(u)||await M__default.pathExists(f)?"python":null}async function om(t,e={}){let r=e.runCommand??je,o=P.join(t,".venv"),n=await M__default.pathExists(o);for(let a of e.pythonCandidates??Bs()){if(await r(a,a==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;n||await M__default.remove(o);}return 1}async function nm(t,e={}){let r=e.runCommand??je,o=P.join(t,".venv"),n=m$4(o);if(await M__default.pathExists(n)){if(await r(n,["-m","pip","--version"],t)===0)return 0;await M__default.remove(o);}let a=await om(t,e);if(a!==0)return a;n=m$4(o);let i=await r(n,["-m","pip","--version"],t);return i!==0&&await M__default.remove(o),i}async function lp(t,e={}){let r=e.runCommand??je;for(let o of e.pythonCandidates??Bs())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function sm(t,e={}){let r=e.runCommand??je,o=m$4(P.join(t,".venv"));if(!await M__default.pathExists(o)){let c=await lp(t,e);if(c!==0)return c}if(!(await r("poetry",["--version"],t)===0))return 0;let a=await r("poetry",["config","virtualenvs.in-project","true","--local"],t);if(a!==0)return a;let i=await r("poetry",["env","use",o],t);return i!==0?i:0}async function am(t,e={}){let r=e.runCommand??je,o=m$4(P.join(t,".venv"));if(!await M__default.pathExists(o)){let i=await lp(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=P.join(t,"requirements.txt");if(await M__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=P.join(t,"pyproject.toml");return await M__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function Ss(t,e){return await sm(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 M__default.pathExists(P.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await am(t))}async function Es(t){let e=await Lt("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await rm(o,t))continue;if(await je(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function im(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Le([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Le([...e],"--java-version"),a=Le([...e],"--spring-boot-version"),i=Le([...e],"--springdoc-version"),c=Le([...e],"--group-id"),p=Le([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(p&&!/^[A-Za-z0-9_.-]+$/.test(p.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Le([...e],"--target-framework"),a=Le([...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 ql(t){if(t.includes("--dry-run")||t.includes("--no-workspace")||Ds(process.cwd()))return;let e=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:o}=await import('./create-U5PQHOZ4.js');await o(process.cwd(),{skipGit:e,yes:t.includes("--yes")||t.includes("-y"),userConfig:await b()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:r}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},{name:"Create it without workspace management",value:"none"}],default:1}]);if(r==="current"){let{registerWorkspaceAtPath:o}=await import('./create-U5PQHOZ4.js');await o(process.cwd(),{skipGit:e,yes:false,userConfig:await b()});}else r==="none"&&t.push("--no-workspace");}async function cm(t){await M__default.ensureDir(t);let e=P.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await I.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
155
+ `),async()=>{await o.close().catch(()=>{}),await M__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await M__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 M__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function cn(t$1,e={}){let r=P.join(q$1(),"transactions"),o=await cm(r),n;try{await b$8(r),n=await a$a({journalDirectory:r});}catch(i){throw await o(),i}let a=new Set([P.join(q$1(),"workspaces.json"),P.join(r$1(),"workspaces.json"),a$b(t$1,g$1),b$9(t$1,g$1),a$b(t$1,a$c),b$9(t$1,a$c),...t(t$1,"imported-projects.json")]);if(e.projectPath){a.add(v(e.projectPath,"project.json")),a.add(v(e.projectPath,"context.json")),a.add(v(e.projectPath,"file-hashes.json")),a.add(v(e.projectPath,"adopt.json")),a.add(v(e.projectPath,"adopt-readiness.json")),a.add(P.join(e.projectPath,f$1)),a.add(P.join(e.projectPath,g$2)),a.add(P.join(e.projectPath,h$3)),a.add(P.join(e.projectPath,b$a)),a.add(P.join(e.projectPath,i$2));for(let i of g$3)a.add(P.join(e.projectPath,i));for(let i of await j$4({workspacePath:t$1,projectPath:e.projectPath}))a.add(i);a.add(P.join(e.projectPath,"AGENTS.md")),a.add(P.join(e.projectPath,".gitignore"));}try{let i=new Set,c=e.projectPath;for(let d of a){let u=c&&(d===P.join(c,"AGENTS.md")||g$3.some(v=>d===P.join(c,v)))?await M__default.lstat(d).catch(v=>{if(v.code==="ENOENT")return null;throw v}):null,f=d;if(u?.isSymbolicLink()&&c){let v=await a$d(c,d);if(!v)continue;f=v;}i.has(f)||(await n.captureFile(f),i.add(f));}e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let p=false;return {registerCompensation:d=>n.registerCompensation(d),commit:async()=>{p||(await n.commit(),p=true,await o());},rollback:async()=>{if(!p){p=true;try{await n.rollback();}finally{await o();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await o(),i}}async function dr(t,e){try{await t.rollback();}catch(r){throw new AggregateError([e,r],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function Ur(t,e$1,r){if(t.includes("--no-workspace")||t.includes("--dry-run"))return;if(!await M__default.pathExists(e$1)){e.warn(`Created project path was not found for workspace linking: ${e$1}`);return}let o=Se(e$1)||Se(process.cwd()),n=false,a;if(o)a=await cn(o,{projectPath:e$1});else {o=p(),a=await cn(o,{projectPath:e$1,ownedWorkspace:o});try{o=(await Hs()).workspacePath;}catch(c){await dr(a,c);}n=true;}let i="managed";try{await p$3(e$1);let c=P.relative(o,e$1);(c.startsWith("..")||P.isAbsolute(c))&&(i=(await vs({source:e$1,workspacePath:o,name:r})).relationship);let{registerProjectInWorkspaceStrict:d,registerWorkspaceStrict:h}=await import('./workspace-B33BFZZ3.js'),{syncWorkspaceContract:u}=await import('./workspace-contract-MQ3QE52V.js');await h(o,P.basename(o)),await d(o,r,e$1),await u({workspacePath:o,strict:true});let{syncProjectIntelligenceLens:f}=await import('./project-intelligence-lens-ZCCHUKVI.js');await f({workspacePath:o,projectPath:e$1,projectName:r,relationship:i==="adopted"?"adopted":"managed",mode:"managed"}),await Br(o,{strict:true}),await a.commit();}catch(c){await dr(a,c);}return n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${j$3}" (${i}).`)),console.log(s.gray(` Registry: ${P.join(q$1(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${o}`))),o}async function $s(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],r=a$3(e),o=t[3];if(!r||r.owner!=="npm")return 1;if(!o)return process.stderr.write(`Usage: ${r.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
156
156
  `),1;try{j(o);}catch(u){let f=u instanceof Error?u.message:String(u);return process.stderr.write(`${f}
157
157
  `),1}let n=im(r.id,t);if(n)return process.stderr.write(`${n}
158
158
  `),1;let a=Le(t,"--output")||process.cwd(),i=P.resolve(a,o),c=t.includes("--skip-git")||t.includes("--no-git"),p=t.includes("--skip-install"),d=t.includes("--dry-run"),h=false;try{let{default:u}=await import('fs-extra');return await u.pathExists(i)?(process.stderr.write(`\u274C Directory "${i}" already exists
@@ -173,7 +173,7 @@ Requested kit: ${n}
173
173
  Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
174
174
  Install Python 3.10+ to access all kits.
175
175
  `),1;let c=Le(t,"--output")||process.cwd(),p=P.resolve(c,a),d=false,h=t.includes("--skip-git")||t.includes("--no-git"),u=t.includes("--skip-install");try{if(await M__default.ensureDir(P.dirname(p)),await M__default.pathExists(p))return process.stderr.write(`\u274C Directory "${p}" already exists
176
- `),1;let f="pip",v=Se(process.cwd());if(v)try{let{readWorkspaceMarker:E}=await import('./workspace-marker-XGAWZZDX.js'),S=await E(v);S?.metadata?.npm?.installMethod&&(f=S.metadata.npm.installMethod,e.debug(`Detected workspace engine: ${f}`));}catch(E){e.debug("Failed to read workspace marker",E);}else e.debug("No workspace found, using default engine: pip");await M__default.ensureDir(p),d=true;let{generateDemoKit:k}=await import('./demo-kit-5UQH2OXC.js');return await k(p,{project_name:a,template:i,kit_name:n,skipGit:h,skipInstall:u,engine:f}),await Us(t,process.cwd()),await Ur(t,p,a),0}catch(f){return d&&await M__default.remove(p).catch(()=>{}),process.stderr.write(`Workspai CLI offline fallback failed: ${f?.message??f}
176
+ `),1;let f="pip",v=Se(process.cwd());if(v)try{let{readWorkspaceMarker:E}=await import('./workspace-marker-XGAWZZDX.js'),S=await E(v);S?.metadata?.npm?.installMethod&&(f=S.metadata.npm.installMethod,e.debug(`Detected workspace engine: ${f}`));}catch(E){e.debug("Failed to read workspace marker",E);}else e.debug("No workspace found, using default engine: pip");await M__default.ensureDir(p),d=true;let{generateDemoKit:k}=await import('./demo-kit-RKTHTXHJ.js');return await k(p,{project_name:a,template:i,kit_name:n,skipGit:h,skipInstall:u,engine:f}),await Us(t,process.cwd()),await Ur(t,p,a),0}catch(f){return d&&await M__default.remove(p).catch(()=>{}),process.stderr.write(`Workspai CLI offline fallback failed: ${f?.message??f}
177
177
  `),1}}function lm(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("Workspai native create is not available for this request yet.")}
178
178
  `),process.stderr.write(s.gray(`Requested: ${e}
179
179
  `)),process.stderr.write(s.gray(`Lane: ${t.lane} (${t.status})
@@ -266,16 +266,16 @@ Run:
266
266
  `),1;try{j(v);}catch(y){if(y instanceof a$1)return process.stderr.write(`${y.message}
267
267
  `),1;throw y}let k=await j$1(t,{hasYes:n$1}),E=h$1(v.trim(),{argv:t,outputParent:k});c||await M__default.ensureDir(P.dirname(E));let S=n(v.trim());if(!c&&(i(S,E,{outputParent:k})&&S&&await M__default.pathExists(S)||await M__default.pathExists(E)))return process.stderr.write(`\u274C Workspace "${v}" already exists
268
268
  `),S&&S!==E&&process.stderr.write(` Found at: ${S}
269
- `),1;let N=await b(),l=N.author||process.env.USER||"Workspai User";if(!n$1){let y=await b$1([{type:"input",name:"author",message:"Author name:",default:l}]);y.author?.trim()&&(l=y.author.trim());}let{createProject:m}=await import('./create-72ITVZXV.js');return await m(v,{skipGit:a$2,skipPythonEngine:i$1,yes:n$1,dryRun:c,userConfig:{...N,author:l},installMethod:h,profile:f,parentDirectory:P.dirname(E)}),0}catch(n){return n instanceof a$1?(process.stderr.write(`
269
+ `),1;let N=await b(),l=N.author||process.env.USER||"Workspai User";if(!n$1){let y=await b$1([{type:"input",name:"author",message:"Author name:",default:l}]);y.author?.trim()&&(l=y.author.trim());}let{createProject:m}=await import('./create-U5PQHOZ4.js');return await m(v,{skipGit:a$2,skipPythonEngine:i$1,yes:n$1,dryRun:c,userConfig:{...N,author:l},installMethod:h,profile:f,parentDirectory:P.dirname(E)}),0}catch(n){return n instanceof a$1?(process.stderr.write(`
270
270
  \u274C ${n.message}
271
271
  `),n.details&&process.stderr.write(`
272
272
  ${n.details}
273
273
  `),e.debug("Create workspace error",{code:n.code,stack:n.stack})):(process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
274
274
  `),e.debug("Unexpected create workspace error",n)),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return Xl(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitChoice:v}=await b$1([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$K()}]);if(d$1(v)||m$3(v)||s$1(v)){let S=ys(v),{projectName:N}=await b$1([{type:"input",name:"projectName",message:"Project name:",default:S,validate:w=>w.trim().length>0||"Project name is required"}]),l=t.slice(2).filter(w=>w.startsWith("-")),m=["create","project",v,N.trim(),...l];return await Bl(v)?(await ql(m),m$3(v)?await zl(m):s$1(v)?await Yl(m):await $s(m)):1}let k=ys(v),{projectName:E}=await b$1([{type:"input",name:"projectName",message:"Project name:",default:k,validate:S=>S.trim().length>0||"Project name is required"}]);t.splice(2,0,v,E.trim());}let a$1=t[2],i=a$L({kitId:a$1,framework:a$1,runtime:a$1});if(b$l(i))return lm(i),1;if(!await Bl(t[2]||""))return 1;if(await ql(t),d$1(t[2]))return await $s(t);if(m$3(t[2]))return await zl(t);if(s$1(t[2]))return await Yl(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 um(t),0;let p=[...t.filter(v=>{let k=v.split("=")[0];return !o.has(v)&&!o.has(k)})],d=Se(process.cwd()),h=t.includes("--skip-install");h&&!p.includes("--skip-essentials")&&p.push("--skip-essentials");let f=h||!!d?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$a();let v=await e$1(p,{cwd:process.cwd(),env:f});if(v===0&&d&&!t.includes("--skip-install")&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init"))),v===0){await Us(t,process.cwd());let k=t[3],E=Le(t,"--output")||process.cwd(),S=k?P.resolve(E,k):void 0,N=k&&S?await Ur(t,S,k).catch(async l=>{throw await M__default.remove(S).catch(()=>{}),l}):d;if(N)try{if(k&&S){let l=P.join(N,".python-version"),m=P.join(S,".python-version");if(I.existsSync(l)&&I.existsSync(S)){let y=I.readFileSync(l,"utf-8");I.writeFileSync(m,y.trim()+`
275
275
  `),e.debug(`Synced Python version ${y.trim()} from workspace to ${k}`);}}}catch(l){e.debug("Could not sync Python version from workspace:",l);}}return v}catch(v){let k=Cs(v);return k?await sn(t,k):(process.stderr.write(`Workspai failed to run the Python core engine: ${v?.message??v}
276
- `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$a();let n=await e$1(t,{cwd:process.cwd()});if(n===0){let a=Se(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-5W7FYGDQ.js');await i(a,true);}}return n}catch(n){let a=Cs(n);return a?await sn(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
276
+ `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$a();let n=await e$1(t,{cwd:process.cwd()});if(n===0){let a=Se(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-B33BFZZ3.js');await i(a,true);}}return n}catch(n){let a=Cs(n);return a?await sn(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
277
277
  `),1)}return await d$a(),await e$1(t,{cwd:process.cwd()})}catch(n){let a=Cs(n);return a?await sn(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
278
- `),1)}}var Zl=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],mm=[...l$4,"autopilot","pipeline","import","adopt","snapshot","live","ai","config","product","infra","shell","commands"],gm=["init"],fm=r$2,Ql=[...fm,...s$2];function hm(t){return !!t&&Xu.includes(t)}function Ts(t){let e=t[0],r=t[1];return e==="project"&&(r==="--help"||r==="-h"||r==="help")?true:Yu.some(([o,n])=>e!==o?false:r?r===n:true)}function Kr(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?Ts(t):hm(t[0])||Ts(t)}function ym(t){return !!t&&mm.includes(t)}function ep(t){return ym(t[0])||Ts(t)}function tp(t){return !!t&&us.includes(t)}async function rp(t,e){switch(t){case "bootstrap":return Nm(e);case "setup":return Tm(e);case "cache":return Wm(e);case "mirror":return Lm(e);default:{let r=t;throw new Error(`Unreachable npm-only manual command: ${String(r)}`)}}}function wm(t=process.env){let e=t.npm_config_user_agent||"",r=t.npm_execpath||"",o=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(r)||o==="exec"||o==="x"}function pp(t={}){let e=z(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 km(){return {schemaVersion:jl,cli:"workspai",version:h(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:hs,contracts:Gr(),contractCatalog:Qo()}}function dp(){let t=ul(ge),e=[...t.topLevelCommands],r=[...a$5].filter(i=>!e.includes(i)),o=["init","dev","start","build","test","lint","format","help"],n=[...Lr],a=[...Ho];return {schemaVersion:hs,scope:"global",cli:"workspai",version:h(),cwd:process.cwd(),contracts:Gr(),contractCatalog:Qo(),commands:{npmOwned:e,coreBacked:r,projectScoped:o},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...r.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...o.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function vm(t={}){let e=dp();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(ml(e.runtimeInventory.integrity));console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai command capabilities")),console.log(s.gray(`CLI: ${e.cli} v${e.version}`)),console.log(""),console.log(s.green(`npm wrapper: ${e.commands.npmOwned.join(", ")}`)),console.log(s.cyan(`Python core: ${e.commands.coreBacked.join(", ")}`)),console.log(s.yellow(`Project runtime: ${e.commands.projectScoped.join(", ")}`)),console.log(s.magenta(`Workspace intelligence: ${e.workspace.intelligenceSubcommands.join(", ")}`)),console.log(""),console.log(s.gray("Tip: run `workspai project commands --json` inside a project."));}function Ms(t){return B(t)?(pp({json:t.includes("--json")||t.includes("--ci")}),true):false}function Ws(t){let e=z(process.cwd());if(!e.projectRoot)return false;let r=A(t,process.cwd());if(!r||r.status!=="unsupported")return false;console.error(s.red(C(r,e))),process.exit(1);}function Ye(t){return I.existsSync(P.join(t,".workspai-workspace"))||I.existsSync(P.join(t,".workspai","workspace.json"))||I.existsSync(P.join(t,".rapidkit-workspace"))||I.existsSync(P.join(t,".rapidkit","workspace.json"))}function up(t){let e=t;for(;;){let r=u(e,"context.json").find(n=>I.existsSync(n));if(r)return r;let o=P.dirname(e);if(o===e)break;e=o;}return null}function Ds(t){let e=t,r=P.resolve(tmpdir());for(;;){let o=[P.join(e,".workspai-workspace"),P.join(e,".rapidkit-workspace")].find(a=>I.existsSync(a));if(o&&P.resolve(e)!==r)return o;let n=P.dirname(e);if(n===e)break;e=n;}return null}function Se(t){let e=b$5({startPath:t});return !e||P.resolve(e.workspacePath)===P.resolve(tmpdir())?null:e.workspacePath}function mp(t){try{let r=b$5({startPath:t,strict:true})?.workspacePath??null;return {workspacePath:r&&P.resolve(r)!==P.resolve(tmpdir())?r:null,error:null}}catch(e){if(e instanceof a$2&&e.code==="project.workspace.unlinked")return {workspacePath:null,error:null};if(e instanceof a$2)return {workspacePath:null,error:e};throw e}}async function Br(t,e){try{let{syncWorkspaceConsumerArtifacts:r}=await import('./workspace-onboarding-Y5RPEFUD.js');return await r(t,{silent:e?.silent})}catch(r){if(e?.strict)throw r;return e?.silent||(console.log(s.yellow(`\u26A0\uFE0F Workspace consumer sync skipped: ${r.message}`)),console.log(s.gray(" Retry: npx workspai workspace agent-sync --write --refresh-context --preset enterprise"))),null}}async function Pm(t,e=process.cwd(),r=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$3(r))return {detected:false};let n=p$1(e,r);for(let a of n){if(!await M__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 bm(t){let e=t;for(;;){let r=P.join(e,".rapidkit-workspace"),o=P.join(e,".rapidkit","workspace.json");if(!I.existsSync(r)&&I.existsSync(o))return e;let n=P.dirname(e);if(n===e)break;e=n;}return null}var gp={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function jm(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Jr(t,e){let r=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return r?r[1]==="true":gp[e]}function op(t){let e=t??"";return {mode:jm(e),dependency_sharing_mode:fp(e),rules:{enforce_workspace_marker:Jr(e,"enforce_workspace_marker"),enforce_toolchain_lock:Jr(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Jr(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Jr(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Jr(e,"require_mirror_lock_for_offline")}}}function np(t,e,r){let o=`${e}: ${r}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${o}
278
+ `),1)}}var Zl=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],mm=[...l$4,"autopilot","pipeline","import","adopt","snapshot","live","ai","config","product","infra","shell","commands"],gm=["init"],fm=r$2,Ql=[...fm,...s$2];function hm(t){return !!t&&Xu.includes(t)}function Ts(t){let e=t[0],r=t[1];return e==="project"&&(r==="--help"||r==="-h"||r==="help")?true:Yu.some(([o,n])=>e!==o?false:r?r===n:true)}function Kr(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?Ts(t):hm(t[0])||Ts(t)}function ym(t){return !!t&&mm.includes(t)}function ep(t){return ym(t[0])||Ts(t)}function tp(t){return !!t&&us.includes(t)}async function rp(t,e){switch(t){case "bootstrap":return Nm(e);case "setup":return Tm(e);case "cache":return Wm(e);case "mirror":return Lm(e);default:{let r=t;throw new Error(`Unreachable npm-only manual command: ${String(r)}`)}}}function wm(t=process.env){let e=t.npm_config_user_agent||"",r=t.npm_execpath||"",o=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(r)||o==="exec"||o==="x"}function pp(t={}){let e=z(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 km(){return {schemaVersion:jl,cli:"workspai",version:h(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:hs,contracts:Gr(),contractCatalog:Qo()}}function dp(){let t=ul(ge),e=[...t.topLevelCommands],r=[...a$5].filter(i=>!e.includes(i)),o=["init","dev","start","build","test","lint","format","help"],n=[...Lr],a=[...Ho];return {schemaVersion:hs,scope:"global",cli:"workspai",version:h(),cwd:process.cwd(),contracts:Gr(),contractCatalog:Qo(),commands:{npmOwned:e,coreBacked:r,projectScoped:o},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...r.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...o.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function vm(t={}){let e=dp();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(ml(e.runtimeInventory.integrity));console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai command capabilities")),console.log(s.gray(`CLI: ${e.cli} v${e.version}`)),console.log(""),console.log(s.green(`npm wrapper: ${e.commands.npmOwned.join(", ")}`)),console.log(s.cyan(`Python core: ${e.commands.coreBacked.join(", ")}`)),console.log(s.yellow(`Project runtime: ${e.commands.projectScoped.join(", ")}`)),console.log(s.magenta(`Workspace intelligence: ${e.workspace.intelligenceSubcommands.join(", ")}`)),console.log(""),console.log(s.gray("Tip: run `workspai project commands --json` inside a project."));}function Ms(t){return B(t)?(pp({json:t.includes("--json")||t.includes("--ci")}),true):false}function Ws(t){let e=z(process.cwd());if(!e.projectRoot)return false;let r=A(t,process.cwd());if(!r||r.status!=="unsupported")return false;console.error(s.red(C(r,e))),process.exit(1);}function Ye(t){return I.existsSync(P.join(t,".workspai-workspace"))||I.existsSync(P.join(t,".workspai","workspace.json"))||I.existsSync(P.join(t,".rapidkit-workspace"))||I.existsSync(P.join(t,".rapidkit","workspace.json"))}function up(t){let e=t;for(;;){let r=u(e,"context.json").find(n=>I.existsSync(n));if(r)return r;let o=P.dirname(e);if(o===e)break;e=o;}return null}function Ds(t){let e=t,r=P.resolve(tmpdir());for(;;){let o=[P.join(e,".workspai-workspace"),P.join(e,".rapidkit-workspace")].find(a=>I.existsSync(a));if(o&&P.resolve(e)!==r)return o;let n=P.dirname(e);if(n===e)break;e=n;}return null}function Se(t){let e=b$5({startPath:t});return !e||P.resolve(e.workspacePath)===P.resolve(tmpdir())?null:e.workspacePath}function mp(t){try{let r=b$5({startPath:t,strict:true})?.workspacePath??null;return {workspacePath:r&&P.resolve(r)!==P.resolve(tmpdir())?r:null,error:null}}catch(e){if(e instanceof a$2&&e.code==="project.workspace.unlinked")return {workspacePath:null,error:null};if(e instanceof a$2)return {workspacePath:null,error:e};throw e}}async function Br(t,e){try{let{syncWorkspaceConsumerArtifacts:r}=await import('./workspace-onboarding-ECZ2KJ2A.js');return await r(t,{silent:e?.silent})}catch(r){if(e?.strict)throw r;return e?.silent||(console.log(s.yellow(`\u26A0\uFE0F Workspace consumer sync skipped: ${r.message}`)),console.log(s.gray(" Retry: npx workspai workspace agent-sync --write --refresh-context --preset enterprise"))),null}}async function Pm(t,e=process.cwd(),r=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$3(r))return {detected:false};let n=p$1(e,r);for(let a of n){if(!await M__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 bm(t){let e=t;for(;;){let r=P.join(e,".rapidkit-workspace"),o=P.join(e,".rapidkit","workspace.json");if(!I.existsSync(r)&&I.existsSync(o))return e;let n=P.dirname(e);if(n===e)break;e=n;}return null}var gp={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function jm(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Jr(t,e){let r=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return r?r[1]==="true":gp[e]}function op(t){let e=t??"";return {mode:jm(e),dependency_sharing_mode:fp(e),rules:{enforce_workspace_marker:Jr(e,"enforce_workspace_marker"),enforce_toolchain_lock:Jr(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Jr(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Jr(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Jr(e,"require_mirror_lock_for_offline")}}}function np(t,e,r){let o=`${e}: ${r}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${o}
279
279
  rules:`):`${t.endsWith(`
280
280
  `)?t:`${t}
281
281
  `}${o}
@@ -296,10 +296,10 @@ ${o}
296
296
  `),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(R.length>0&&process.stdout.write(R),b.length>0?process.stderr.write(b):T&&process.stderr.write(`${T}
297
297
  `)),S(x??1);}),w.on("error",x=>{m||(m=true,y&&clearTimeout(y),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`Workspai could not execute ${p}: ${x.message}. Install the required runtime or tool and ensure it is available on PATH.
298
298
  `),S(1));});})}function Rm(t,e,r){if(t!=="npm")return null;let o=e[0];if(o!=="run"&&o!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=P.join(r,"package.json");if(!I.existsSync(a))return null;try{let c=JSON.parse(I.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:Am(c)}catch{return null}}function Am(t){let e=t.trim(),r=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(r)return r[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let o=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return o?o[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function ln(t,e){await M__default.outputFile(t,`${JSON.stringify(e,null,2)}
299
- `,"utf-8");}function _m(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function Im(t,e,r){let o=At(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":P.basename(e),n=_m(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=P.join(t,i);if(!await M__default.pathExists(c))return c;a+=1;}}async function Ls(t,e,r$1){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?P.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:mp(process.cwd()),i=a.workspacePath,c=false,p$1=false,d=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!Ye(n)){let f=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:f},null,2)):console.log(s.red(`\u274C ${f}`)),1}}else (!i||!Ye(i))&&(i=p(),c=true,d=true);if(!i||!Ye(i)&&!d){let f="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:f},null,2)):(console.log(s.red(`\u274C ${f}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let h="npx workspai project workspace status --json",u;try{let f=await Im(i,t,e.name);if(u=await cn(i,{ownedDestination:f,ownedWorkspace:d?i:void 0}),d){let k=await Hs({silent:e.json});i=k.workspacePath,p$1=k.created;}let v=await Ml({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});v.path!==f&&u.registerCompensation(()=>M__default.remove(v.path));try{if(r$1?.syncWorkspaceProjects)await r$1.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:k,registerWorkspaceStrict:E}=await import('./workspace-5W7FYGDQ.js');await E(i,P.basename(i)),await k(i,v.name,v.path);}await u.commit(),await Br(i,{silent:e.json});}catch(k){try{await dr(u,k);}catch(E){if(E!==k)throw E}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${k instanceof Error?k.message:String(k)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?p$1:false,projectWorkspaceCommand:h,commandsResolveWorkspaceFromProject:true,plan:v.ingestionPlan,importedProject:v},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),p$1&&console.log(s.green("\u2713 Workspace ready \xB7 1 registered project \xB7 model + graph + agent grounding sealed")),console.log(s.green(`\u2714 Imported project: ${v.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${v.path}`)),console.log(s.gray(` Stack: ${v.stack} (${v.confidence})`)),console.log(s.gray(` Source: ${e.git===true||At(t)?"git-url":"local-folder"}`)),!v.profileCompatibility.ok){let k=r(v.profileCompatibility);console.log(s.yellow(` Profile warning: ${v.profileCompatibility.message}`)),k&&console.log(s.gray(` ${k}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${h}`)),0}catch(f){if(u)try{await dr(u,f);}catch(k){k!==f&&(f=k);}let v=f instanceof Error?f.message:String(f);return e.json?console.log(JSON.stringify({error:v},null,2)):console.log(s.red(`\u274C Import failed: ${v}`)),1}}async function wp(t,e,r$1){let o,n=(y,w)=>{o=y,c$7({blockId:y,status:"running",message:w,component:"adopt"});},a=(y,w)=>{c$7({blockId:y,status:"succeeded",message:w,component:"adopt"}),o===y&&(o=void 0);},i=(y,w)=>{c$7({blockId:y,status:"skipped",message:w,component:"adopt"});},c=y=>{o&&(c$7({blockId:o,status:"failed",message:y,component:"adopt"}),o=void 0);};n("adopt.resolve","Resolving project and workspace");let p$1=P.resolve(t||process.cwd()),d=e.workspace?P.resolve(e.workspace):null,h=d?{workspacePath:d,error:null}:mp(process.cwd()),u=h.workspacePath,f=false,v=false,k=false;if(h.error)return c(h.error.message),e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:h.error.code,message:h.error.message,context:h.error.context}),null,2)):console.log(s.red(`\u274C ${h.error.message}`)),1;if(d){if(!Ye(d)){let y=`Workspace path is not a valid Workspai workspace: ${d}`;return c(y),e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C ${y}`)),1}}else (!u||!Ye(u))&&(u=p(),f=true,k=e.dryRun!==true);let E=f&&u!==null&&(e.dryRun===true||k);if(!u||!Ye(u)&&!E){let y="Not inside a Workspai workspace";return c(y),e.json?console.log(JSON.stringify({error:y},null,2)):(console.log(s.red(`\u274C ${y}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let S=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),N,l=null,m=null;try{if(e.dryRun!==true&&(N=await cn(u,{projectPath:p$1,ownedWorkspace:k?u:void 0}),k)){let b=await Hs({silent:e.json});u=b.workspacePath,v=b.created;}a("adopt.resolve","Project and workspace resolved"),n("adopt.detect","Detecting architecture and adoption effects");let y=await ks(u,p$1),w=await vs({workspacePath:u,source:p$1,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:y});a("adopt.detect","Architecture and adoption effects detected");let g="npx workspai project workspace status --json",C=e.dryRun===true?b$5({startPath:p$1}):null,x=e.dryRun!==true||C!==null&&P.resolve(C.workspacePath)===P.resolve(u)&&(!C.projectPath||P.resolve(C.projectPath)===p$1);if(e.dryRun!==true){n("adopt.link","Linking project to workspace");try{if(r$1?.registerWorkspace||r$1?.registerProjectInWorkspace||r$1?.syncWorkspaceProjects)r$1.registerWorkspace&&await r$1.registerWorkspace(u,P.basename(u)),r$1.registerProjectInWorkspace&&await r$1.registerProjectInWorkspace(u,w.name,w.path),r$1.syncWorkspaceProjects&&await r$1.syncWorkspaceProjects(u);else {let{registerProjectInWorkspaceStrict:T,registerWorkspaceStrict:j}=await import('./workspace-5W7FYGDQ.js');if(await j(u,P.basename(u)),await T(u,w.name,w.path),S)throw new Error("forced sync failure for command-level adopt rollback test")}if(a("adopt.link","Project linked to workspace"),n("adopt.publish","Sealing workspace intelligence"),l=await Br(u,{silent:e.json,strict:true}),!l?.freshnessSealed)throw new Error("Workspace consumer artifacts were generated without a freshness seal.");a("adopt.publish","Workspace intelligence freshness sealed"),n("adopt.ground","Building the project agent entry");let{buildAgentBootstrapReceipt:b}=await import('./project-agent-entry-5IUBEREI.js');if(m=await b({startPath:p$1,forAgent:"generic",validateLiveInputs:true}),m.status==="blocked")throw new Error("Adopted project did not produce a usable agent-grounding route; inspect the bootstrap checks.");await N?.commit(),a("adopt.ground","Project agent entry is ready");}catch(b){if(N)try{await dr(N,b);}catch(T){if(T!==b)throw T}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${b instanceof Error?b.message:String(b)}`)}}else i("adopt.link","Dry run: workspace link not written"),i("adopt.publish","Dry run: workspace intelligence not published"),i("adopt.ground","Dry run: project agent entry not written");if(e.json)return console.log(JSON.stringify({workspacePath:u,workspaceResolution:f?"default-auto":d?"explicit":"nearest",defaultWorkspaceCreated:f?v:false,wouldCreateDefaultWorkspace:f&&e.dryRun===true?!Ye(u):false,projectWorkspaceCommand:g,commandsResolveWorkspaceFromProject:x,dryRun:e.dryRun===true,plan:w.ingestionPlan,adoptedProject:w,consumerArtifacts:e.dryRun===true||!l?null:{freshnessSealed:l.freshnessSealed,reconciledAfterGrounding:l.reconciledAfterGrounding,warnings:l.warnings},agentBootstrap:m},null,2)),0;f&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${u}`)),v&&e.dryRun!==true&&console.log(s.green("\u2713 Workspace ready \xB7 1 registered project \xB7 model + graph + agent grounding sealed")),e.dryRun===true&&(console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.gray(" Planned effects: project metadata + workspace registration + model, graph, and agent-grounding sync.")),w.effects.repositoryControlFiles.length>0&&console.log(s.gray(` Repository controls may be reconciled: ${w.effects.repositoryControlFiles.map(b=>b.path).join(", ")}.`))),console.log(s.green(`\u2714 Adopted project: ${w.name}`)),console.log(s.gray(` Workspace: ${u}`)),console.log(s.gray(` Project: ${w.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)"));let R=w.stack==="unknown"?w.frameworkDisplayName||w.runtime:w.stack;if(console.log(s.gray(` Stack: ${R} (${w.confidence})`)),!w.profileCompatibility.ok){let b=r(w.profileCompatibility);console.log(s.yellow(` Profile warning: ${w.profileCompatibility.message}`)),b&&console.log(s.gray(` ${b}`));}return console.log(s.gray(` Report: ${w.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Consumer evidence: ${l?.freshnessSealed?"freshness sealed":"not sealed"}${l?.reconciledAfterGrounding?" after grounding reconciliation":""}.`)),console.log(s.gray(` Agent grounding: ${m?.status??"unknown"}; project environment: ${m?.readiness.projectEnvironment??"unknown"}; release: ${m?.readiness.release??"not-verified"}.`)),console.log(s.gray(` Check: ${g}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(y){if(N)try{await dr(N,y);}catch(g){g!==y&&(y=g);}let w=y instanceof Error?y.message:String(y);return c(w),e.json?console.log(JSON.stringify({error:w},null,2)):console.log(s.red(`\u274C Adopt failed: ${w}`)),1}}async function Fs(t$1){let e=new Set(["python-only","polyglot","enterprise"]),r=Om(),o="minimal",n=false;try{let p=t(t$1,"workspace.json").find(h=>I.existsSync(h))??q(t$1,"workspace.json"),d=JSON.parse(await I.promises.readFile(p,"utf-8"));o=d.profile??"minimal",n=d.bootstrap_note==="python-engine-skipped"||d.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(l(o)&&o!=="minimal")return false;if(!n&&e.has(o))return true;let p=await Gs(t$1);if(p.length===0)return false;for(let d of p){let h=j$2(d),u=h?.module_support,f=typeof h?.kit_name=="string"?h.kit_name:typeof h?.kit=="string"?h.kit:void 0,v=f?a$3(f):null;if(n||o==="minimal"){if(v?.workspacePythonEngine==="required")return true;continue}if(!(k$2(h,d)||m(h,d)||n$1(h,d))&&u!==false)return o$1(h,d)||l$1(h,d),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:p}=await import('./workspace-marker-XGAWZZDX.js'),h=(await p(t$1))?.metadata?.npm?.installMethod;(h==="poetry"||h==="venv"||h==="pipx"||h==="pip")&&(i=h);}catch{}let c=async()=>{let p=tm(t$1),d=await nm(t$1);if(d!==0)return d;let h=f$3("DEV_PATH"),f=(h?await M__default.pathExists(h):false)&&h?["-m","pip","install",h,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await je(p,f,t$1,{timeoutMs:r})};if(i==="venv"){let p=await c();if(p!==0)return p}else if(i==="poetry"){let p=P.join(t$1,"pyproject.toml"),d=false;try{d=(await I.promises.readFile(p,"utf-8")).includes("rapidkit-core");}catch{d=false;}if(d){let h=await c();if(h!==0)return h}else {let h=await je("poetry",["install","--no-root"],t$1,{timeoutMs:r});if(h!==0)return h;let u=await je("poetry",["add","rapidkit-core"],t$1,{timeoutMs:r});if(u!==0)return u}}else return 0;try{let{writeWorkspaceLauncher:p}=await import('./create-72ITVZXV.js');await p(t$1,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:p}=await import('./workspace-python-engine-state-BE4A3BL5.js');await p(t$1,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function Om(){let t=process.env.RAPIDKIT_WORKSPACE_DEPS_TIMEOUT_MS;if(t){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 12e4}async function Gs(t){let e=[],r=new Set,o=[t];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await I.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=P.join(n,i.name);if((await Promise.all([...u(c,"context.json"),...u(c,"project.json")].map(d=>M__default.pathExists(d)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function $m(t){return o$4(t)}async function Hs(t={}){let e=p(),r=P.basename(e),o=Ye(e);if(!o){let{createProject:n}=await import('./create-72ITVZXV.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:P.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b(),suppressReceipt:true});}finally{t.silent&&(console.log=i,console.warn=c,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function xs(t){let r=await Be("go",{runCommandInCwd:je,runCoreRapidkit:e$1}).initProject(t);return se(r)}function se(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Lt(t,e){let r=Be("node",{runCommandInCwd:je,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return se(n)}if(t==="dev"){let n=await r.runDev(e);return se(n)}if(t==="test"){let n=await r.runTest(e);return se(n)}if(t==="build"){let n=await r.runBuild(e);return se(n)}if(t==="lint"){let n=await r.runLint?.(e);return se(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return se(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return se(o)}async function yt(t,e){let r=Be("java",{runCommandInCwd:je,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return se(n)}if(t==="dev"){let n=await r.runDev(e);return se(n)}if(t==="test"){let n=await r.runTest(e);return se(n)}if(t==="build"){let n=await r.runBuild(e);return se(n)}if(t==="lint"){let n=await r.runLint?.(e);return se(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return se(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return se(o)}function Rs(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$7(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$b()})}async function Nm(t$1,e=Js){if(t$1.includes("--help")||t$1.includes("-h")||t$1.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(_){if(!_)return null;let V=_.trim().toLowerCase();return V==="minimal"||V==="java-only"||V==="go-only"||V==="dotnet-only"||V==="python-only"||V==="node-only"||V==="polyglot"||V==="enterprise"?V:null},i=function(_){let _e=_.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",Ie=(Ce,He)=>{let ot=_.match(new RegExp(`^\\s*${Ce}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return ot?ot[1].toLowerCase()==="true":He};return {mode:_e,dependency_sharing_mode:fp(_),rules:{enforce_workspace_marker:Ie("enforce_workspace_marker",true),enforce_toolchain_lock:Ie("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:Ie("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:Ie("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:Ie("require_mirror_lock_for_offline",true)}}};let c=["init"],p,d=false,h=false,u=false,f=false;for(let _=1;_<t$1.length;_+=1){let V=t$1[_];if(V==="--ci"){d=true;continue}if(V==="--offline"){h=true;continue}if(V==="--json"){u=true;continue}if(V==="--compliance-only"){f=true;continue}if(V==="--profile"){let K=t$1[_+1];if(!K||K.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;p=K,_+=1;continue}if(V.startsWith("--profile=")){p=V.slice(10);continue}c.push(V);}let v=a(p);if(p&&!v)return console.log(s.red(`Invalid profile: ${p}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let k=process.cwd(),E=c.slice(1).filter(_=>!_.startsWith("-"));if(E.length>0){let _=P.resolve(k,E[0]),V=j$2(_),K=I.existsSync(_)?await Ft(_):"unknown";if(!Ye(_)&&(k$2(V,_)||m(V,_)||n$1(V,_)||l$1(V,_)||o$1(V,_)||K!=="unknown"))return await e(c)}let S=P.join(k,".rapidkit-workspace"),N=P.join(k,".rapidkit","workspace.json"),l;!I.existsSync(S)&&I.existsSync(N)?l=k:(l=Se(k),l||(l=bm(k)));let m$1=[],y=null,w=null;if(l)try{let _=t(l,"workspace.json").find(_e=>I.existsSync(_e))??q(l,"workspace.json"),V=await I.promises.readFile(_,"utf-8"),K=JSON.parse(V);w=a(K.profile);}catch{w=null;}let g=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],C={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},x=v;if(!!l&&!v&&!d&&!u&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let _=w||"minimal",{chosenProfile:V}=await b$1([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${_})`,choices:g.map(K=>({name:K===_?`${C[K]} \u2190 current`:C[K],value:K})),default:g.indexOf(_)}]);x=V;}let b=x||w||"minimal";if(l&&!f)try{let V=b==="python-only"||b==="polyglot"||b==="enterprise"?"poetry":"venv",K;try{let He=(await I.promises.readFile(P.join(l,".python-version"),"utf-8")).trim();He&&(K=He);}catch{}let{syncWorkspaceFoundationFiles:_e}=await import('./create-72ITVZXV.js'),Ie=await _e(l,{workspaceName:P.basename(l),installMethod:V,pythonVersion:K,profile:b,writeMarker:true,writeGitignore:true,onlyIfMissing:true});m$1.push({id:"workspace.foundation.sync",status:Ie.length>0?"passed":"skipped",message:Ie.length>0?`Workspace foundation synchronized: ${Ie.join(", ")}`:"Workspace foundation files are already up to date."});}catch(_){m$1.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${_.message}`});}else l&&m$1.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(l&&!f&&x)try{let _=q(l,"workspace.json"),V=await I.promises.readFile(_,"utf-8"),K=JSON.parse(V);if(K.profile=x,k$5.has(x)){delete K.bootstrap_note;let Ie=K.engine&&typeof K.engine=="object"?K.engine:void 0;Ie&&delete Ie.python_core;}await M__default.ensureDir(P.dirname(_)),await I.promises.writeFile(_,JSON.stringify(K,null,2)+`
300
- `,"utf-8");let{syncWorkspaceContract:_e}=await import('./workspace-contract-JYHNEJPV.js');await _e({workspacePath:l}),m$1.push({id:"workspace.profile.sync",status:"passed",message:`Workspace profile synchronized to ${x} across canonical artifacts.`});}catch(_){m$1.push({id:"workspace.profile.sync",status:"failed",message:`Failed to synchronize workspace profile across canonical artifacts: ${_ instanceof Error?_.message:String(_)}`});}let T={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}},j=null;if(l)try{let _=t(l,"policies.yml").find(K=>I.existsSync(K));if(!_)throw new Error("policy file missing");let V=await I.promises.readFile(_,"utf-8");j=V,T=i(V);}catch{m$1.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else m$1.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(l){let _=hp(j);T.dependency_sharing_mode=_.mode,m$1.push({id:"policy.schema.dependency_sharing_mode",status:_.status,message:_.message}),m$1.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:T.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":T.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 V=I.existsSync(P.join(l,".workspai-workspace"))||I.existsSync(P.join(l,".rapidkit-workspace"));m$1.push({id:"policy.enforce_workspace_marker",status:!T.rules.enforce_workspace_marker||V?"passed":"failed",message:!T.rules.enforce_workspace_marker||V?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let K=t(l,"toolchain.lock").some(Oe=>I.existsSync(Oe));m$1.push({id:"policy.enforce_toolchain_lock",status:!T.rules.enforce_toolchain_lock||K?"passed":"failed",message:!T.rules.enforce_toolchain_lock||K?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let _e=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||t(l,"trusted-sources.lock").some(Oe=>I.existsSync(Oe));m$1.push({id:"policy.disallow_untrusted_tool_sources",status:!T.rules.disallow_untrusted_tool_sources||_e?"passed":"failed",message:!T.rules.disallow_untrusted_tool_sources||_e?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let Ie=t(l,"compatibility-matrix.json").find(Oe=>I.existsSync(Oe))??q(l,"compatibility-matrix.json"),Ce=I.existsSync(Ie),He=T.rules.enforce_compatibility_matrix;if(m$1.push({id:"policy.enforce_compatibility_matrix",status:!He||Ce?"passed":"failed",message:!He||Ce?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),Ce)try{let Oe=await I.promises.readFile(Ie,"utf-8"),ft=JSON.parse(Oe),zs=!!ft&&typeof ft=="object";m$1.push({id:"compatibility.matrix.parse",status:zs?"passed":"failed",message:zs?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{m$1.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let ot=t(l,"mirror-config.json").find(Oe=>I.existsSync(Oe))??q(l,"mirror-config.json"),ur=t(l,"mirror.lock").find(Oe=>I.existsSync(Oe))??q(l,"mirror.lock"),dn=I.existsSync(ot),un=I.existsSync(ur),qs={};if(dn)try{qs=JSON.parse(await I.promises.readFile(ot,"utf-8")),m$1.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{m$1.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(f)m$1.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let Oe=await ws(l,{ciMode:d,offlineMode:h});m$1.push(...Oe.checks.map(ft=>({id:ft.id,status:ft.status,message:ft.message}))),y=Oe.details,Oe.details.lockWritten&&(un=true);}if(h){let Oe=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||qs.enabled===true;m$1.push({id:"offline.mirror.enabled",status:Oe?"passed":"failed",message:Oe?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let ft=T.rules.require_mirror_lock_for_offline;m$1.push({id:"offline.mirror.lock",status:!ft||un?"passed":"failed",message:!ft||un?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else m$1.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Hr=m$2({profile:b,runtimes:await q$2(l),mode:T.mode});Hr.profile!=="enterprise"?m$1.push({id:Hr.checkId,status:Hr.status,message:Hr.message}):(m$1.push({id:"profile.enterprise.ci",status:d?"passed":f?"skipped":"failed",message:d?"enterprise profile running with --ci.":f?"Enterprise runtime execution skipped by --compliance-only; --ci is not required.":"enterprise profile expects --ci for deterministic non-interactive mode."}),m$1.push({id:"profile.enterprise.compatibility-matrix",status:Ce?"passed":"failed",message:Ce?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),m$1.push({id:"profile.enterprise.mirror-config",status:dn?"passed":"failed",message:dn?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}d&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),h&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let O=m$1.some(_=>_.id.startsWith("policy.schema.")&&_.status==="failed")||T.mode==="strict"&&m$1.some(_=>_.status==="failed"),F=q(l||k,"reports"),H=new Date().toISOString().replace(/[:.]/g,"-"),U=P.join(F,`bootstrap-compliance-${H}.json`),ae=P.join(F,"bootstrap-compliance.latest.json"),re={schemaVersion:h$2.bootstrapCompliance.schemaVersion,command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:l,profile:b,options:{ci:d,offline:h,strict:T.mode==="strict",complianceOnly:f},policyMode:T.mode,policyRules:T.rules,mirrorLifecycle:y,checks:m$1},he=async _=>{b$n(`.workspai/reports/${P.basename(U)}`,_),b$n(i$1.bootstrapCompliance,_),await M__default.ensureDir(F),await ln(U,_),await ln(ae,_);};if(O){let _=Rs({...re,result:"blocked",initExitCode:null},1,m$1);return await he(_),u?process.stdout.write(`${JSON.stringify(_,null,2)}
299
+ `,"utf-8");}function _m(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function Im(t,e,r){let o=At(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":P.basename(e),n=_m(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=P.join(t,i);if(!await M__default.pathExists(c))return c;a+=1;}}async function Ls(t,e,r$1){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?P.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:mp(process.cwd()),i=a.workspacePath,c=false,p$1=false,d=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!Ye(n)){let f=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:f},null,2)):console.log(s.red(`\u274C ${f}`)),1}}else (!i||!Ye(i))&&(i=p(),c=true,d=true);if(!i||!Ye(i)&&!d){let f="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:f},null,2)):(console.log(s.red(`\u274C ${f}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let h="npx workspai project workspace status --json",u;try{let f=await Im(i,t,e.name);if(u=await cn(i,{ownedDestination:f,ownedWorkspace:d?i:void 0}),d){let k=await Hs({silent:e.json});i=k.workspacePath,p$1=k.created;}let v=await Ml({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});v.path!==f&&u.registerCompensation(()=>M__default.remove(v.path));try{if(r$1?.syncWorkspaceProjects)await r$1.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:k,registerWorkspaceStrict:E}=await import('./workspace-B33BFZZ3.js');await E(i,P.basename(i)),await k(i,v.name,v.path);}await u.commit(),await Br(i,{silent:e.json});}catch(k){try{await dr(u,k);}catch(E){if(E!==k)throw E}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${k instanceof Error?k.message:String(k)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?p$1:false,projectWorkspaceCommand:h,commandsResolveWorkspaceFromProject:true,plan:v.ingestionPlan,importedProject:v},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),p$1&&console.log(s.green("\u2713 Workspace ready \xB7 1 registered project \xB7 model + graph + agent grounding sealed")),console.log(s.green(`\u2714 Imported project: ${v.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${v.path}`)),console.log(s.gray(` Stack: ${v.stack} (${v.confidence})`)),console.log(s.gray(` Source: ${e.git===true||At(t)?"git-url":"local-folder"}`)),!v.profileCompatibility.ok){let k=r(v.profileCompatibility);console.log(s.yellow(` Profile warning: ${v.profileCompatibility.message}`)),k&&console.log(s.gray(` ${k}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${h}`)),0}catch(f){if(u)try{await dr(u,f);}catch(k){k!==f&&(f=k);}let v=f instanceof Error?f.message:String(f);return e.json?console.log(JSON.stringify({error:v},null,2)):console.log(s.red(`\u274C Import failed: ${v}`)),1}}async function wp(t,e,r$1){let o,n=(y,w)=>{o=y,c$7({blockId:y,status:"running",message:w,component:"adopt"});},a=(y,w)=>{c$7({blockId:y,status:"succeeded",message:w,component:"adopt"}),o===y&&(o=void 0);},i=(y,w)=>{c$7({blockId:y,status:"skipped",message:w,component:"adopt"});},c=y=>{o&&(c$7({blockId:o,status:"failed",message:y,component:"adopt"}),o=void 0);};n("adopt.resolve","Resolving project and workspace");let p$1=P.resolve(t||process.cwd()),d=e.workspace?P.resolve(e.workspace):null,h=d?{workspacePath:d,error:null}:mp(process.cwd()),u=h.workspacePath,f=false,v=false,k=false;if(h.error)return c(h.error.message),e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:h.error.code,message:h.error.message,context:h.error.context}),null,2)):console.log(s.red(`\u274C ${h.error.message}`)),1;if(d){if(!Ye(d)){let y=`Workspace path is not a valid Workspai workspace: ${d}`;return c(y),e.json?console.log(JSON.stringify({error:y},null,2)):console.log(s.red(`\u274C ${y}`)),1}}else (!u||!Ye(u))&&(u=p(),f=true,k=e.dryRun!==true);let E=f&&u!==null&&(e.dryRun===true||k);if(!u||!Ye(u)&&!E){let y="Not inside a Workspai workspace";return c(y),e.json?console.log(JSON.stringify({error:y},null,2)):(console.log(s.red(`\u274C ${y}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let S=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),N,l=null,m=null;try{if(e.dryRun!==true&&(N=await cn(u,{projectPath:p$1,ownedWorkspace:k?u:void 0}),k)){let b=await Hs({silent:e.json});u=b.workspacePath,v=b.created;}a("adopt.resolve","Project and workspace resolved"),n("adopt.detect","Detecting architecture and adoption effects");let y=await ks(u,p$1),w=await vs({workspacePath:u,source:p$1,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:y});a("adopt.detect","Architecture and adoption effects detected");let g="npx workspai project workspace status --json",C=e.dryRun===true?b$5({startPath:p$1}):null,x=e.dryRun!==true||C!==null&&P.resolve(C.workspacePath)===P.resolve(u)&&(!C.projectPath||P.resolve(C.projectPath)===p$1);if(e.dryRun!==true){n("adopt.link","Linking project to workspace");try{if(r$1?.registerWorkspace||r$1?.registerProjectInWorkspace||r$1?.syncWorkspaceProjects)r$1.registerWorkspace&&await r$1.registerWorkspace(u,P.basename(u)),r$1.registerProjectInWorkspace&&await r$1.registerProjectInWorkspace(u,w.name,w.path),r$1.syncWorkspaceProjects&&await r$1.syncWorkspaceProjects(u);else {let{registerProjectInWorkspaceStrict:T,registerWorkspaceStrict:j}=await import('./workspace-B33BFZZ3.js');if(await j(u,P.basename(u)),await T(u,w.name,w.path),S)throw new Error("forced sync failure for command-level adopt rollback test")}if(a("adopt.link","Project linked to workspace"),n("adopt.publish","Sealing workspace intelligence"),l=await Br(u,{silent:e.json,strict:true}),!l?.freshnessSealed)throw new Error("Workspace consumer artifacts were generated without a freshness seal.");a("adopt.publish","Workspace intelligence freshness sealed"),n("adopt.ground","Building the project agent entry");let{buildAgentBootstrapReceipt:b}=await import('./project-agent-entry-MH7364BE.js');if(m=await b({startPath:p$1,forAgent:"generic",validateLiveInputs:true}),m.status==="blocked")throw new Error("Adopted project did not produce a usable agent-grounding route; inspect the bootstrap checks.");await N?.commit(),a("adopt.ground","Project agent entry is ready");}catch(b){if(N)try{await dr(N,b);}catch(T){if(T!==b)throw T}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${b instanceof Error?b.message:String(b)}`)}}else i("adopt.link","Dry run: workspace link not written"),i("adopt.publish","Dry run: workspace intelligence not published"),i("adopt.ground","Dry run: project agent entry not written");if(e.json)return console.log(JSON.stringify({workspacePath:u,workspaceResolution:f?"default-auto":d?"explicit":"nearest",defaultWorkspaceCreated:f?v:false,wouldCreateDefaultWorkspace:f&&e.dryRun===true?!Ye(u):false,projectWorkspaceCommand:g,commandsResolveWorkspaceFromProject:x,dryRun:e.dryRun===true,plan:w.ingestionPlan,adoptedProject:w,consumerArtifacts:e.dryRun===true||!l?null:{freshnessSealed:l.freshnessSealed,reconciledAfterGrounding:l.reconciledAfterGrounding,warnings:l.warnings},agentBootstrap:m},null,2)),0;f&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${u}`)),v&&e.dryRun!==true&&console.log(s.green("\u2713 Workspace ready \xB7 1 registered project \xB7 model + graph + agent grounding sealed")),e.dryRun===true&&(console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.gray(" Planned effects: project metadata + workspace registration + model, graph, and agent-grounding sync.")),w.effects.repositoryControlFiles.length>0&&console.log(s.gray(` Repository controls may be reconciled: ${w.effects.repositoryControlFiles.map(b=>b.path).join(", ")}.`))),console.log(s.green(`\u2714 Adopted project: ${w.name}`)),console.log(s.gray(` Workspace: ${u}`)),console.log(s.gray(` Project: ${w.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)"));let R=w.stack==="unknown"?w.frameworkDisplayName||w.runtime:w.stack;if(console.log(s.gray(` Stack: ${R} (${w.confidence})`)),!w.profileCompatibility.ok){let b=r(w.profileCompatibility);console.log(s.yellow(` Profile warning: ${w.profileCompatibility.message}`)),b&&console.log(s.gray(` ${b}`));}return console.log(s.gray(` Report: ${w.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Consumer evidence: ${l?.freshnessSealed?"freshness sealed":"not sealed"}${l?.reconciledAfterGrounding?" after grounding reconciliation":""}.`)),console.log(s.gray(` Agent grounding: ${m?.status??"unknown"}; project environment: ${m?.readiness.projectEnvironment??"unknown"}; release: ${m?.readiness.release??"not-verified"}.`)),console.log(s.gray(` Check: ${g}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(y){if(N)try{await dr(N,y);}catch(g){g!==y&&(y=g);}let w=y instanceof Error?y.message:String(y);return c(w),e.json?console.log(JSON.stringify({error:w},null,2)):console.log(s.red(`\u274C Adopt failed: ${w}`)),1}}async function Fs(t$1){let e=new Set(["python-only","polyglot","enterprise"]),r=Om(),o="minimal",n=false;try{let p=t(t$1,"workspace.json").find(h=>I.existsSync(h))??q(t$1,"workspace.json"),d=JSON.parse(await I.promises.readFile(p,"utf-8"));o=d.profile??"minimal",n=d.bootstrap_note==="python-engine-skipped"||d.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(l(o)&&o!=="minimal")return false;if(!n&&e.has(o))return true;let p=await Gs(t$1);if(p.length===0)return false;for(let d of p){let h=j$2(d),u=h?.module_support,f=typeof h?.kit_name=="string"?h.kit_name:typeof h?.kit=="string"?h.kit:void 0,v=f?a$3(f):null;if(n||o==="minimal"){if(v?.workspacePythonEngine==="required")return true;continue}if(!(k$2(h,d)||m(h,d)||n$1(h,d))&&u!==false)return o$1(h,d)||l$1(h,d),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:p}=await import('./workspace-marker-XGAWZZDX.js'),h=(await p(t$1))?.metadata?.npm?.installMethod;(h==="poetry"||h==="venv"||h==="pipx"||h==="pip")&&(i=h);}catch{}let c=async()=>{let p=tm(t$1),d=await nm(t$1);if(d!==0)return d;let h=f$3("DEV_PATH"),f=(h?await M__default.pathExists(h):false)&&h?["-m","pip","install",h,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await je(p,f,t$1,{timeoutMs:r})};if(i==="venv"){let p=await c();if(p!==0)return p}else if(i==="poetry"){let p=P.join(t$1,"pyproject.toml"),d=false;try{d=(await I.promises.readFile(p,"utf-8")).includes("rapidkit-core");}catch{d=false;}if(d){let h=await c();if(h!==0)return h}else {let h=await je("poetry",["install","--no-root"],t$1,{timeoutMs:r});if(h!==0)return h;let u=await je("poetry",["add","rapidkit-core"],t$1,{timeoutMs:r});if(u!==0)return u}}else return 0;try{let{writeWorkspaceLauncher:p}=await import('./create-U5PQHOZ4.js');await p(t$1,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:p}=await import('./workspace-python-engine-state-BE4A3BL5.js');await p(t$1,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function Om(){let t=process.env.RAPIDKIT_WORKSPACE_DEPS_TIMEOUT_MS;if(t){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 12e4}async function Gs(t){let e=[],r=new Set,o=[t];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await I.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=P.join(n,i.name);if((await Promise.all([...u(c,"context.json"),...u(c,"project.json")].map(d=>M__default.pathExists(d)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function $m(t){return o$4(t)}async function Hs(t={}){let e=p(),r=P.basename(e),o=Ye(e);if(!o){let{createProject:n}=await import('./create-U5PQHOZ4.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:P.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await b(),suppressReceipt:true});}finally{t.silent&&(console.log=i,console.warn=c,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function xs(t){let r=await Be("go",{runCommandInCwd:je,runCoreRapidkit:e$1}).initProject(t);return se(r)}function se(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function Lt(t,e){let r=Be("node",{runCommandInCwd:je,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return se(n)}if(t==="dev"){let n=await r.runDev(e);return se(n)}if(t==="test"){let n=await r.runTest(e);return se(n)}if(t==="build"){let n=await r.runBuild(e);return se(n)}if(t==="lint"){let n=await r.runLint?.(e);return se(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return se(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return se(o)}async function yt(t,e){let r=Be("java",{runCommandInCwd:je,runCoreRapidkit:e$1});if(t==="init"){let n=await r.initProject(e);return se(n)}if(t==="dev"){let n=await r.runDev(e);return se(n)}if(t==="test"){let n=await r.runTest(e);return se(n)}if(t==="build"){let n=await r.runBuild(e);return se(n)}if(t==="lint"){let n=await r.runLint?.(e);return se(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return se(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return se(o)}function Rs(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$7(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$b()})}async function Nm(t$1,e=Js){if(t$1.includes("--help")||t$1.includes("-h")||t$1.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(_){if(!_)return null;let V=_.trim().toLowerCase();return V==="minimal"||V==="java-only"||V==="go-only"||V==="dotnet-only"||V==="python-only"||V==="node-only"||V==="polyglot"||V==="enterprise"?V:null},i=function(_){let _e=_.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",Ie=(Ce,He)=>{let ot=_.match(new RegExp(`^\\s*${Ce}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return ot?ot[1].toLowerCase()==="true":He};return {mode:_e,dependency_sharing_mode:fp(_),rules:{enforce_workspace_marker:Ie("enforce_workspace_marker",true),enforce_toolchain_lock:Ie("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:Ie("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:Ie("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:Ie("require_mirror_lock_for_offline",true)}}};let c=["init"],p,d=false,h=false,u=false,f=false;for(let _=1;_<t$1.length;_+=1){let V=t$1[_];if(V==="--ci"){d=true;continue}if(V==="--offline"){h=true;continue}if(V==="--json"){u=true;continue}if(V==="--compliance-only"){f=true;continue}if(V==="--profile"){let K=t$1[_+1];if(!K||K.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;p=K,_+=1;continue}if(V.startsWith("--profile=")){p=V.slice(10);continue}c.push(V);}let v=a(p);if(p&&!v)return console.log(s.red(`Invalid profile: ${p}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let k=process.cwd(),E=c.slice(1).filter(_=>!_.startsWith("-"));if(E.length>0){let _=P.resolve(k,E[0]),V=j$2(_),K=I.existsSync(_)?await Ft(_):"unknown";if(!Ye(_)&&(k$2(V,_)||m(V,_)||n$1(V,_)||l$1(V,_)||o$1(V,_)||K!=="unknown"))return await e(c)}let S=P.join(k,".rapidkit-workspace"),N=P.join(k,".rapidkit","workspace.json"),l;!I.existsSync(S)&&I.existsSync(N)?l=k:(l=Se(k),l||(l=bm(k)));let m$1=[],y=null,w=null;if(l)try{let _=t(l,"workspace.json").find(_e=>I.existsSync(_e))??q(l,"workspace.json"),V=await I.promises.readFile(_,"utf-8"),K=JSON.parse(V);w=a(K.profile);}catch{w=null;}let g=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],C={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},x=v;if(!!l&&!v&&!d&&!u&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let _=w||"minimal",{chosenProfile:V}=await b$1([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${_})`,choices:g.map(K=>({name:K===_?`${C[K]} \u2190 current`:C[K],value:K})),default:g.indexOf(_)}]);x=V;}let b=x||w||"minimal";if(l&&!f)try{let V=b==="python-only"||b==="polyglot"||b==="enterprise"?"poetry":"venv",K;try{let He=(await I.promises.readFile(P.join(l,".python-version"),"utf-8")).trim();He&&(K=He);}catch{}let{syncWorkspaceFoundationFiles:_e}=await import('./create-U5PQHOZ4.js'),Ie=await _e(l,{workspaceName:P.basename(l),installMethod:V,pythonVersion:K,profile:b,writeMarker:true,writeGitignore:true,onlyIfMissing:true});m$1.push({id:"workspace.foundation.sync",status:Ie.length>0?"passed":"skipped",message:Ie.length>0?`Workspace foundation synchronized: ${Ie.join(", ")}`:"Workspace foundation files are already up to date."});}catch(_){m$1.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${_.message}`});}else l&&m$1.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(l&&!f&&x)try{let _=q(l,"workspace.json"),V=await I.promises.readFile(_,"utf-8"),K=JSON.parse(V);if(K.profile=x,k$5.has(x)){delete K.bootstrap_note;let Ie=K.engine&&typeof K.engine=="object"?K.engine:void 0;Ie&&delete Ie.python_core;}await M__default.ensureDir(P.dirname(_)),await I.promises.writeFile(_,JSON.stringify(K,null,2)+`
300
+ `,"utf-8");let{syncWorkspaceContract:_e}=await import('./workspace-contract-MQ3QE52V.js');await _e({workspacePath:l}),m$1.push({id:"workspace.profile.sync",status:"passed",message:`Workspace profile synchronized to ${x} across canonical artifacts.`});}catch(_){m$1.push({id:"workspace.profile.sync",status:"failed",message:`Failed to synchronize workspace profile across canonical artifacts: ${_ instanceof Error?_.message:String(_)}`});}let T={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}},j=null;if(l)try{let _=t(l,"policies.yml").find(K=>I.existsSync(K));if(!_)throw new Error("policy file missing");let V=await I.promises.readFile(_,"utf-8");j=V,T=i(V);}catch{m$1.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else m$1.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(l){let _=hp(j);T.dependency_sharing_mode=_.mode,m$1.push({id:"policy.schema.dependency_sharing_mode",status:_.status,message:_.message}),m$1.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:T.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":T.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 V=I.existsSync(P.join(l,".workspai-workspace"))||I.existsSync(P.join(l,".rapidkit-workspace"));m$1.push({id:"policy.enforce_workspace_marker",status:!T.rules.enforce_workspace_marker||V?"passed":"failed",message:!T.rules.enforce_workspace_marker||V?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let K=t(l,"toolchain.lock").some(Oe=>I.existsSync(Oe));m$1.push({id:"policy.enforce_toolchain_lock",status:!T.rules.enforce_toolchain_lock||K?"passed":"failed",message:!T.rules.enforce_toolchain_lock||K?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let _e=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||t(l,"trusted-sources.lock").some(Oe=>I.existsSync(Oe));m$1.push({id:"policy.disallow_untrusted_tool_sources",status:!T.rules.disallow_untrusted_tool_sources||_e?"passed":"failed",message:!T.rules.disallow_untrusted_tool_sources||_e?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let Ie=t(l,"compatibility-matrix.json").find(Oe=>I.existsSync(Oe))??q(l,"compatibility-matrix.json"),Ce=I.existsSync(Ie),He=T.rules.enforce_compatibility_matrix;if(m$1.push({id:"policy.enforce_compatibility_matrix",status:!He||Ce?"passed":"failed",message:!He||Ce?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),Ce)try{let Oe=await I.promises.readFile(Ie,"utf-8"),ft=JSON.parse(Oe),zs=!!ft&&typeof ft=="object";m$1.push({id:"compatibility.matrix.parse",status:zs?"passed":"failed",message:zs?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{m$1.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let ot=t(l,"mirror-config.json").find(Oe=>I.existsSync(Oe))??q(l,"mirror-config.json"),ur=t(l,"mirror.lock").find(Oe=>I.existsSync(Oe))??q(l,"mirror.lock"),dn=I.existsSync(ot),un=I.existsSync(ur),qs={};if(dn)try{qs=JSON.parse(await I.promises.readFile(ot,"utf-8")),m$1.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{m$1.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(f)m$1.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let Oe=await ws(l,{ciMode:d,offlineMode:h});m$1.push(...Oe.checks.map(ft=>({id:ft.id,status:ft.status,message:ft.message}))),y=Oe.details,Oe.details.lockWritten&&(un=true);}if(h){let Oe=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||qs.enabled===true;m$1.push({id:"offline.mirror.enabled",status:Oe?"passed":"failed",message:Oe?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let ft=T.rules.require_mirror_lock_for_offline;m$1.push({id:"offline.mirror.lock",status:!ft||un?"passed":"failed",message:!ft||un?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else m$1.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Hr=m$2({profile:b,runtimes:await q$2(l),mode:T.mode});Hr.profile!=="enterprise"?m$1.push({id:Hr.checkId,status:Hr.status,message:Hr.message}):(m$1.push({id:"profile.enterprise.ci",status:d?"passed":f?"skipped":"failed",message:d?"enterprise profile running with --ci.":f?"Enterprise runtime execution skipped by --compliance-only; --ci is not required.":"enterprise profile expects --ci for deterministic non-interactive mode."}),m$1.push({id:"profile.enterprise.compatibility-matrix",status:Ce?"passed":"failed",message:Ce?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),m$1.push({id:"profile.enterprise.mirror-config",status:dn?"passed":"failed",message:dn?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}d&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),h&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let O=m$1.some(_=>_.id.startsWith("policy.schema.")&&_.status==="failed")||T.mode==="strict"&&m$1.some(_=>_.status==="failed"),F=q(l||k,"reports"),H=new Date().toISOString().replace(/[:.]/g,"-"),U=P.join(F,`bootstrap-compliance-${H}.json`),ae=P.join(F,"bootstrap-compliance.latest.json"),re={schemaVersion:h$2.bootstrapCompliance.schemaVersion,command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:l,profile:b,options:{ci:d,offline:h,strict:T.mode==="strict",complianceOnly:f},policyMode:T.mode,policyRules:T.rules,mirrorLifecycle:y,checks:m$1},he=async _=>{b$n(`.workspai/reports/${P.basename(U)}`,_),b$n(i$1.bootstrapCompliance,_),await M__default.ensureDir(F),await ln(U,_),await ln(ae,_);};if(O){let _=Rs({...re,result:"blocked",initExitCode:null},1,m$1);return await he(_),u?process.stdout.write(`${JSON.stringify(_,null,2)}
301
301
  `):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${U}`))),1}if(u&&b==="enterprise"&&!d&&!f){let _=Rs({...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,m$1);return await he(_),process.stdout.write(`${JSON.stringify(_,null,2)}
302
- `),1}let Ke=async _=>{let V=process.stdout.write.bind(process.stdout),K=process.stderr.write.bind(process.stderr),_e=[],Ie=[];process.stdout.write=((Ce,He,ot)=>{let ur=typeof He=="function"?He:typeof ot=="function"?ot:void 0;return _e.push(typeof Ce=="string"?Ce:Ce instanceof Uint8Array?Buffer.from(Ce).toString("utf8"):String(Ce)),ur?.(),true}),process.stderr.write=((Ce,He,ot)=>{let ur=typeof He=="function"?He:typeof ot=="function"?ot:void 0;return Ie.push(typeof Ce=="string"?Ce:Ce instanceof Uint8Array?Buffer.from(Ce).toString("utf8"):String(Ce)),ur?.(),true});try{return {exitCode:await _(),stdout:_e.join(""),stderr:Ie.join("")}}finally{process.stdout.write=V,process.stderr.write=K;}},ve=_=>{let V=_.split(/\r?\n/).map(K=>K.trim()).filter(Boolean);return {bytes:Buffer.byteLength(_),excerpt:V.slice(0,12)}},D=0,G;if(!f)if(u){let _=await Ke(()=>e(c));D=_.exitCode,G={captured:true,stdout:ve(_.stdout),stderr:ve(_.stderr)};}else D=await e(c);let Z=m$1.filter(_=>_.status==="failed").length,B=D!==0?"failed":Z>0?"ok_with_warnings":"ok",ue=D!==0?D:Z>0?1:0,Q=Rs({...re,result:B,initExitCode:D,complianceOnly:f,...G?{initOutput:G}:{}},ue,m$1);if(await he(Q),l&&!f&&D===0)try{let{syncWorkspaceProjects:_}=await import('./workspace-5W7FYGDQ.js');await _(l,u),await Br(l,{silent:u});}catch{}if(u)process.stdout.write(`${JSON.stringify(Q,null,2)}
302
+ `),1}let Ke=async _=>{let V=process.stdout.write.bind(process.stdout),K=process.stderr.write.bind(process.stderr),_e=[],Ie=[];process.stdout.write=((Ce,He,ot)=>{let ur=typeof He=="function"?He:typeof ot=="function"?ot:void 0;return _e.push(typeof Ce=="string"?Ce:Ce instanceof Uint8Array?Buffer.from(Ce).toString("utf8"):String(Ce)),ur?.(),true}),process.stderr.write=((Ce,He,ot)=>{let ur=typeof He=="function"?He:typeof ot=="function"?ot:void 0;return Ie.push(typeof Ce=="string"?Ce:Ce instanceof Uint8Array?Buffer.from(Ce).toString("utf8"):String(Ce)),ur?.(),true});try{return {exitCode:await _(),stdout:_e.join(""),stderr:Ie.join("")}}finally{process.stdout.write=V,process.stderr.write=K;}},ve=_=>{let V=_.split(/\r?\n/).map(K=>K.trim()).filter(Boolean);return {bytes:Buffer.byteLength(_),excerpt:V.slice(0,12)}},D=0,G;if(!f)if(u){let _=await Ke(()=>e(c));D=_.exitCode,G={captured:true,stdout:ve(_.stdout),stderr:ve(_.stderr)};}else D=await e(c);let Z=m$1.filter(_=>_.status==="failed").length,B=D!==0?"failed":Z>0?"ok_with_warnings":"ok",ue=D!==0?D:Z>0?1:0,Q=Rs({...re,result:B,initExitCode:D,complianceOnly:f,...G?{initOutput:G}:{}},ue,m$1);if(await he(Q),l&&!f&&D===0)try{let{syncWorkspaceProjects:_}=await import('./workspace-B33BFZZ3.js');await _(l,u),await Br(l,{silent:u});}catch{}if(u)process.stdout.write(`${JSON.stringify(Q,null,2)}
303
303
  `);else {let _=m$1.filter(V=>V.status==="failed").length;_>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${_} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${U}`));}return ue}finally{typeof r>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=r;}}async function Tm(t$1,e=je){if(t$1.includes("--help")||t$1.includes("-h"))return console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),0;let r=(t$1[1]||"").toLowerCase(),o=t$1.includes("--json"),n=t$1.includes("--warm-deps")||t$1.includes("--warm-dependencies");if(!r||!["python","node","go","java","dotnet","rust","php"].includes(r))return o?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]"},null,2)}
304
304
  `):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),1;let a=async(v,k)=>{if(v==="node"){if(!I.existsSync(P.join(k,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let S=I.existsSync(P.join(k,"pnpm-lock.yaml")),N=I.existsSync(P.join(k,"yarn.lock"));return S?{exitCode:await e("pnpm",["install","--lockfile-only","--ignore-scripts"],k)}:N?{exitCode:await e("yarn",["install","--ignore-scripts"],k)}:{exitCode:await e("npm",["install","--package-lock-only","--ignore-scripts"],k)}}if(v==="go")return I.existsSync(P.join(k,"go.mod"))?{exitCode:await e("go",["mod","download"],k)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(v==="java"){let E=I.existsSync(P.join(k,"pom.xml")),S=I.existsSync(P.join(k,"build.gradle"))||I.existsSync(P.join(k,"build.gradle.kts")),N=P.join(k,process.platform==="win32"?"gradlew.bat":"gradlew"),l=I.existsSync(N);return !E&&!S?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:E?{exitCode:await e("mvn",["-B","-q","-DskipTests","dependency:go-offline"],k)}:{exitCode:await e(l?N:"gradle",["--no-daemon","dependencies"],k)}}return v==="dotnet"?(()=>{let S=[{dir:k,depth:0}],N=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;S.length>0;){let l=S.shift();if(!l||l.depth>3)continue;let m=[];try{m=I.readdirSync(l.dir,{withFileTypes:true});}catch{continue}for(let y of m)if(y.isFile()){let w=y.name.toLowerCase();if(w.endsWith(".sln")||w.endsWith(".csproj"))return true}else y.isDirectory()&&!N.has(y.name)&&S.push({dir:P.join(l.dir,y.name),depth:l.depth+1});}return false})()?{exitCode:await e("dotnet",["restore"],k)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:v==="rust"?I.existsSync(P.join(k,"Cargo.toml"))?{exitCode:await e("cargo",["fetch"],k)}:{exitCode:0,message:"Rust warm-up skipped: Cargo.toml not found in current directory."}:v==="php"?I.existsSync(P.join(k,"composer.json"))?{exitCode:await e("composer",["install","--no-interaction","--no-scripts"],k)}:{exitCode:0,message:"PHP warm-up skipped: composer.json not found in current directory."}:{exitCode:0,message:"Dependency warm-up is not available for this runtime."}};if(o){let v=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let E=await Be(r,{runCommandInCwd:e,runCoreRapidkit:async(y,w)=>(await g$7(y,{...w,cwd:void 0})).exitCode}).checkPrereqs(),S=Se(process.cwd()),N=S||process.cwd(),l=null;if(r==="node"&&E.exitCode===0&&(l=process.version),S&&l){let y=t(S,"toolchain.lock").find(C=>I.existsSync(C))??q(S,"toolchain.lock"),w=q(S,"toolchain.lock"),g={};try{g=JSON.parse(await I.promises.readFile(y,"utf-8"));}catch{}(!g.runtime||typeof g.runtime!="object")&&(g.runtime={}),g.runtime[r]={version:l,detectedAt:new Date().toISOString()},await M__default.ensureDir(P.dirname(w)),await I.promises.writeFile(w,JSON.stringify(g,null,2)+`
305
305
  `,"utf-8");}let m$1={requested:n,status:"not-requested",exitCode:null,targets:0,messages:[]};if(n&&E.exitCode===0){let y=[N];if(r==="java"&&S){let R=(await Gs(S)).filter(b=>{let T=j$2(b);return m(T,b)});R.length>0&&(y=R);}let w=[];for(let x of y)w.push(await a(r,x));let g=w.filter(x=>x.exitCode!==0),C=w.filter(x=>x.exitCode===0&&!/skipped/i.test(x.message||""));m$1.status=g.length>0?"failed":C.length>0?"passed":"skipped",m$1.exitCode=g[0]?.exitCode??0,m$1.targets=y.length,m$1.messages=w.map(x=>x.message).filter(x=>typeof x=="string");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:r,result:E.exitCode===0?"ok":"failed",exitCode:E.exitCode,workspacePath:S,version:l,warmDeps:n,warmDependencies:m$1},null,2)}
@@ -327,7 +327,7 @@ Hints:`));for(let v of p)console.log(s.gray(`- ${v}`));}return c.exitCode}functi
327
327
  `),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Config: ${u?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${f?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${v}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let u=await ws(o,{ciMode:true,offlineMode:e==="verify",forceRun:true}),f=u.checks.filter(E=>E.status==="failed"),v=u.checks.some(E=>E.id.startsWith("mirror.verify.")&&E.status==="failed");if(e==="verify"&&v){let E={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await h(),details:u.details,checks:u.checks};if(await d(E),r)return process.stdout.write(`${JSON.stringify(E,null,2)}
328
328
  `),1;console.log(s.red("\u274C Mirror verify failed."));for(let S of u.checks.filter(N=>N.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${S.id}: ${S.message}`));return 1}if(f.length>0){let E={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await h(),details:u.details,checks:u.checks};if(await d(E),r)return process.stdout.write(`${JSON.stringify(E,null,2)}
329
329
  `),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${f.length} issue(s).`));for(let S of f)console.log(s.gray(`- ${S.id}: ${S.message}`));return 1}let k={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:await h(),details:u.details,checks:u.checks};return await d(k),r?(process.stdout.write(`${JSON.stringify(k,null,2)}
330
- `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${u.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${u.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${u.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Js(t){let e=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await yp(r,async()=>{let n=Se(r),a=Be("python",{runCommandInCwd:je,runCoreRapidkit:e$1}),i=Be("dotnet",{runCommandInCwd:je,runCoreRapidkit:e$1}),c=Be("rust",{runCommandInCwd:je,runCoreRapidkit:e$1}),p=Be("php",{runCommandInCwd:je,runCoreRapidkit:e$1}),d=t.slice(1).filter(S=>!S.startsWith("-"));if(d.length>0){let S=P.resolve(r,d[0]),N=j$2(S),l=await Ft(S);return k$2(N,S)||l==="go"?await xs(S):m(N,S)||l==="java"?await yt("init",S):n$1(N,S)||l==="dotnet"?se(await i.initProject(S)):l$1(N,S)||l==="node"?await Es(S):o$1(N,S)||l==="python"?await Ss(S,a):l==="rust"?se(await c.initProject(S)):l==="php"?se(await p.initProject(S)):await e$1(t,{cwd:r})}let h=j$2(r),u=!!Se(r)&&r===Se(r);if(!u&&k$2(h,r))return await xs(r);let f=await Ft(r);if(!u&&(m(h,r)||f==="java"))return await yt("init",r);if(!u&&(n$1(h,r)||f==="dotnet"))return se(await i.initProject(r));if(!u&&(l$1(h,r)||f==="node"))return await Es(r);if(!u&&(o$1(h,r)||f==="python"))return await Ss(r,a);if(!u&&f==="rust")return se(await c.initProject(r));if(!u&&f==="php")return se(await p.initProject(r));let v=n||Se(r),k=up(r),E=k?P.dirname(P.dirname(k)):null;if(E&&E!==v){let S=j$2(E),N=await Ft(E);return k$2(S,E)||N==="go"?await xs(E):m(S,E)||N==="java"?await yt("init",E):n$1(S,E)||N==="dotnet"?se(await i.initProject(E)):l$1(S,E)||N==="node"?await Es(E):o$1(S,E)||N==="python"?await Ss(E,a):N==="rust"?se(await c.initProject(E)):N==="php"?se(await p.initProject(E)):await e$1(["init"],{cwd:E})}if(v&&r===v){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 S=await Fs(v);if(S!==0)return S;let{runWorkspaceStage:N}=await import('./workspace-run-GFBFGUFM.js');return (await N({workspacePath:v,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!v){let S=await b(),N=l$6(),{name:l}=$m(N);await M__default.ensureDir(N);let{createProject:m}=await import('./create-72ITVZXV.js');return await m(l,{yes:true,userConfig:S,parentDirectory:N}),0}return await e$1(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e;}}async function ap(t$1){let e=Se(t$1);if(!e)return [];let r="warn";try{let p=t(e,"policies.yml").find(u=>I.existsSync(u));if(!p)return [];let d=await I.promises.readFile(p,"utf-8");(d.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??d.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n=t(e,"toolchain.lock").find(p=>I.existsSync(p));if(!n||!I.existsSync(n))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await I.promises.readFile(n,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=j$2(t$1);k$2(c,t$1)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):l$1(c,t$1)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):m(c,t$1)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):n$1(c,t$1)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):o$1(c,t$1)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let p=t(e,"workspace.json").find(v=>I.existsSync(v));if(!p)throw new Error("workspace manifest missing");let h=JSON.parse(await I.promises.readFile(p,"utf-8")).profile??"",u=m$1(t$1,c),f=n$2({profile:h,runtime:u.runtime,subjectLabel:P.basename(t$1),mode:"strict"});f.ok||o.push(`${f.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function Fm(){let t=async m=>{if(!b$3()||!m.toLowerCase().endsWith(".cmd"))return false;try{let w=(await M__default.readFile(m,"utf8")).replace(/\r\n/g,`
330
+ `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${u.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${u.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${u.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Js(t){let e=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await yp(r,async()=>{let n=Se(r),a=Be("python",{runCommandInCwd:je,runCoreRapidkit:e$1}),i=Be("dotnet",{runCommandInCwd:je,runCoreRapidkit:e$1}),c=Be("rust",{runCommandInCwd:je,runCoreRapidkit:e$1}),p=Be("php",{runCommandInCwd:je,runCoreRapidkit:e$1}),d=t.slice(1).filter(S=>!S.startsWith("-"));if(d.length>0){let S=P.resolve(r,d[0]),N=j$2(S),l=await Ft(S);return k$2(N,S)||l==="go"?await xs(S):m(N,S)||l==="java"?await yt("init",S):n$1(N,S)||l==="dotnet"?se(await i.initProject(S)):l$1(N,S)||l==="node"?await Es(S):o$1(N,S)||l==="python"?await Ss(S,a):l==="rust"?se(await c.initProject(S)):l==="php"?se(await p.initProject(S)):await e$1(t,{cwd:r})}let h=j$2(r),u=!!Se(r)&&r===Se(r);if(!u&&k$2(h,r))return await xs(r);let f=await Ft(r);if(!u&&(m(h,r)||f==="java"))return await yt("init",r);if(!u&&(n$1(h,r)||f==="dotnet"))return se(await i.initProject(r));if(!u&&(l$1(h,r)||f==="node"))return await Es(r);if(!u&&(o$1(h,r)||f==="python"))return await Ss(r,a);if(!u&&f==="rust")return se(await c.initProject(r));if(!u&&f==="php")return se(await p.initProject(r));let v=n||Se(r),k=up(r),E=k?P.dirname(P.dirname(k)):null;if(E&&E!==v){let S=j$2(E),N=await Ft(E);return k$2(S,E)||N==="go"?await xs(E):m(S,E)||N==="java"?await yt("init",E):n$1(S,E)||N==="dotnet"?se(await i.initProject(E)):l$1(S,E)||N==="node"?await Es(E):o$1(S,E)||N==="python"?await Ss(E,a):N==="rust"?se(await c.initProject(E)):N==="php"?se(await p.initProject(E)):await e$1(["init"],{cwd:E})}if(v&&r===v){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 S=await Fs(v);if(S!==0)return S;let{runWorkspaceStage:N}=await import('./workspace-run-ZZ5WHL7W.js');return (await N({workspacePath:v,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!v){let S=await b(),N=l$6(),{name:l}=$m(N);await M__default.ensureDir(N);let{createProject:m}=await import('./create-U5PQHOZ4.js');return await m(l,{yes:true,userConfig:S,parentDirectory:N}),0}return await e$1(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e;}}async function ap(t$1){let e=Se(t$1);if(!e)return [];let r="warn";try{let p=t(e,"policies.yml").find(u=>I.existsSync(u));if(!p)return [];let d=await I.promises.readFile(p,"utf-8");(d.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??d.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n=t(e,"toolchain.lock").find(p=>I.existsSync(p));if(!n||!I.existsSync(n))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await I.promises.readFile(n,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=j$2(t$1);k$2(c,t$1)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):l$1(c,t$1)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):m(c,t$1)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):n$1(c,t$1)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):o$1(c,t$1)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let p=t(e,"workspace.json").find(v=>I.existsSync(v));if(!p)throw new Error("workspace manifest missing");let h=JSON.parse(await I.promises.readFile(p,"utf-8")).profile??"",u=m$1(t$1,c),f=n$2({profile:h,runtime:u.runtime,subjectLabel:P.basename(t$1),mode:"strict"});f.ok||o.push(`${f.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function Fm(){let t=async m=>{if(!b$3()||!m.toLowerCase().endsWith(".cmd"))return false;try{let w=(await M__default.readFile(m,"utf8")).replace(/\r\n/g,`
331
331
  `).toLowerCase(),g=w.includes("\\.rapidkit\\rapidkit"),C=w.includes("\\.rapidkit\\rapidkit.cmd")||w.includes("\\.rapidkit\\rapidkit.exe")||w.includes("\\.venv\\scripts\\rapidkit.exe");return g&&!C}catch{return false}},e$2=process.cwd(),r=process.argv.slice(2),o=r[0],n=o==="init",a=new Set(r$2),i=!o||o==="--help"||o==="-h"||o==="help",c=Ye(e$2),p=u(e$2,"project.json").some(m=>I.existsSync(m)),d=j$2(e$2),h=await Ft(e$2),u$1=k$2(d,e$2)||l$1(d,e$2)||o$1(d,e$2)||m(d,e$2)||n$1(d,e$2)||h$5(h??void 0),f=!!o&&a.has(o)&&u$1,v=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Kr(r)||r[0]==="create")return false;if(Ms(r))return true;if(r[0]==="init"&&c&&!p)return false;if(Ws(r))return true;try{let m=o==="shell"&&r[1]==="activate",y=o==="create",w=await qi(e$2,{cwd:e$2,timeoutMs:1200});if(w.ok&&w.data?.isRapidkitProject&&w.data.engine==="python"){let g=y||Kr(r);if(!i&&!m&&!g&&!n&&!f&&Tn(r)){if(o&&Ql.includes(o)){let x=await ap(e$2).catch(()=>[]);if(x.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
332
332
  `);for(let R of x)process.stderr.write(s.red(` \u2022 ${R}`)+`
333
333
  `);process.exit(1);}}let C=await e$1(process.argv.slice(2),{cwd:e$2});process.exit(C);}}}catch{}let k=up(e$2),E=b$3(),S=v?[]:p$1(e$2),N=null;for(let m of S)if(await M__default.pathExists(m)){if(await t(m)){e.warn(`Skipping legacy/broken Windows launcher candidate: ${m}. Falling back to core bridge.`);continue}N=m;break}let l=o==="create";if(o==="init"&&c&&!p)return false;if(o&&Ql.includes(o)){let m=await ap(e$2);if(m.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
@@ -362,7 +362,7 @@ Discover more:
362
362
  ${Vs} --help Product overview and first steps
363
363
  ${Vs} commands --json Complete machine-readable command inventory
364
364
  https://workspai.dev Guides, contracts, and examples
365
- `);ge.command("live [target]").description("Open a live cross-terminal execution graph for Workspai activity").option("--global","Monitor activity across all local Workspai projects and workspaces").option("--run <runId>","Show only one activity run").option("--once","Render one snapshot and exit").option("--json","Emit monitor snapshots as JSON").addOption(new Option("--projection <projection>","JSON projection: monitor or renderer-neutral board").choices(["monitor","board"]).default("monitor")).option("--refresh-ms <milliseconds>","Live refresh interval (100-5000ms)","250").option("--max-runs <count>","Maximum runs rendered in the terminal","6").option("--max-scopes <count>","Maximum local scopes discovered by --global","12").option("--classic","Use the compatibility line-oriented renderer").option("--no-color","Disable terminal colors").option("--no-motion","Disable animated flow indicators").option("--ascii","Use ASCII-only symbols and connectors").option("--accessible","Use a stable screen-reader-friendly linear view").option("--capture <file>","Write a deterministic product-ready SVG snapshot and exit").option("--capture-preset <preset>","Capture size: github, linkedin, x, square, wide","github").option("--capture-theme <theme>","Capture theme: obsidian, light, mono","obsidian").option("--no-capture-redact","Keep local workspace, project, run and argument labels in capture").option("--replay <runId>","Replay a durable activity run with pause and step controls").option("--replay-speed <multiplier>","Replay speed from 0.25 to 64","4").action(async(t,e)=>{let r=Number.parseInt(e.refreshMs??"250",10),o=Number.parseInt(e.maxRuns??"6",10),n=Number.parseInt(e.maxScopes??"12",10),a=Number.parseFloat(e.replaySpeed??"4");if(!Number.isFinite(r)||r<100||r>5e3)throw new Error("--refresh-ms must be an integer from 100 to 5000.");if(!Number.isFinite(o)||o<1||o>50)throw new Error("--max-runs must be an integer from 1 to 50.");if(!Number.isFinite(n)||n<1||n>50)throw new Error("--max-scopes must be an integer from 1 to 50.");if(!Number.isFinite(a)||a<.25||a>64)throw new Error("--replay-speed must be a number from 0.25 to 64.");if(e.projection==="board"&&e.json!==true)throw new Error("--projection board requires --json.");if(e.projection==="board"&&e.capture)throw new Error("--projection board cannot be combined with --capture; capture already uses the Activity Board internally.");if(e.global===true&&t)throw new Error("A target path cannot be combined with --global.");if(e.replay&&e.global===true)throw new Error("--replay cannot be combined with --global.");if(e.replay&&e.capture)throw new Error("--replay cannot be combined with --capture.");if(!["github","linkedin","x","square","wide"].includes(e.capturePreset??""))throw new Error("--capture-preset must be github, linkedin, x, square, or wide.");if(!["obsidian","light","mono"].includes(e.captureTheme??""))throw new Error("--capture-theme must be obsidian, light, or mono.");let{runLiveCommand:i}=await import('./live-command-5VXPR43F.js');await i({targetPath:t,runId:e.run,once:e.once===true,json:e.json===true,projection:e.projection??"monitor",refreshMs:r,maxRuns:o,classic:e.classic===true,color:e.color===false?false:void 0,motion:e.motion===false?false:void 0,ascii:e.ascii===true?true:void 0,accessible:e.accessible===true,global:e.global===true,maxScopes:n,capturePath:e.capture,capturePreset:e.capturePreset,captureTheme:e.captureTheme,captureRedact:e.captureRedact!==false,replayRunId:e.replay,replaySpeed:a});});ge.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-python-engine","Create a Python-aware workspace without installing rapidkit-core now").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, java-only, python-only, node-only, go-only, dotnet-only, polyglot, enterprise").choices(["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not link it to any workspace").hideHelp()).option("--no-update-check","Skip checking for updates").option("--trust-config","Trust and execute workspai.config.js/mjs/cjs discovered in this tree").action(async(t,e$2)=>{try{e$2.debug&&(e.setDebug(true),e.debug("Debug mode enabled"));let r=await b();e.debug("User config loaded",{...r,openaiApiKey:r.openaiApiKey?"[REDACTED]":void 0});let o=await c(process.cwd(),{trustExecutableConfig:e$2.trustConfig===true||process.env.WORKSPAI_TRUST_CONFIG==="1"});e.debug("Workspai config loaded",o);let n$1=d(r,o,{author:e$2.author,pythonVersion:void 0,skipGit:e$2.skipGit});e.debug("Merged config",n$1),e$2.updateCheck!==false&&await g(),a("workspace"),t||(vp(),process.exit(0));try{j(t);}catch(p){throw p instanceof a$1&&(e.error(`
365
+ `);ge.command("live [target]").description("Open a live cross-terminal execution graph for Workspai activity").option("--global","Monitor activity across all local Workspai projects and workspaces").option("--run <runId>","Show only one activity run").option("--once","Render one snapshot and exit").option("--json","Emit monitor snapshots as JSON").addOption(new Option("--projection <projection>","JSON projection: monitor or renderer-neutral board").choices(["monitor","board"]).default("monitor")).option("--refresh-ms <milliseconds>","Live refresh interval (100-5000ms)","250").option("--max-runs <count>","Maximum runs rendered in the terminal","6").option("--max-scopes <count>","Maximum local scopes discovered by --global","12").option("--classic","Use the compatibility line-oriented renderer").option("--no-color","Disable terminal colors").option("--no-motion","Disable animated flow indicators").option("--ascii","Use ASCII-only symbols and connectors").option("--accessible","Use a stable screen-reader-friendly linear view").option("--capture <file>","Write a deterministic product-ready SVG snapshot and exit").option("--capture-preset <preset>","Capture size: github, linkedin, x, square, wide","github").option("--capture-theme <theme>","Capture theme: obsidian, light, mono","obsidian").option("--no-capture-redact","Keep local workspace, project, run and argument labels in capture").option("--replay <runId>","Replay a durable activity run with pause and step controls").option("--replay-speed <multiplier>","Replay speed from 0.25 to 64","4").action(async(t,e)=>{let r=Number.parseInt(e.refreshMs??"250",10),o=Number.parseInt(e.maxRuns??"6",10),n=Number.parseInt(e.maxScopes??"12",10),a=Number.parseFloat(e.replaySpeed??"4");if(!Number.isFinite(r)||r<100||r>5e3)throw new Error("--refresh-ms must be an integer from 100 to 5000.");if(!Number.isFinite(o)||o<1||o>50)throw new Error("--max-runs must be an integer from 1 to 50.");if(!Number.isFinite(n)||n<1||n>50)throw new Error("--max-scopes must be an integer from 1 to 50.");if(!Number.isFinite(a)||a<.25||a>64)throw new Error("--replay-speed must be a number from 0.25 to 64.");if(e.projection==="board"&&e.json!==true)throw new Error("--projection board requires --json.");if(e.projection==="board"&&e.capture)throw new Error("--projection board cannot be combined with --capture; capture already uses the Activity Board internally.");if(e.global===true&&t)throw new Error("A target path cannot be combined with --global.");if(e.replay&&e.global===true)throw new Error("--replay cannot be combined with --global.");if(e.replay&&e.capture)throw new Error("--replay cannot be combined with --capture.");if(!["github","linkedin","x","square","wide"].includes(e.capturePreset??""))throw new Error("--capture-preset must be github, linkedin, x, square, or wide.");if(!["obsidian","light","mono"].includes(e.captureTheme??""))throw new Error("--capture-theme must be obsidian, light, or mono.");let{runLiveCommand:i}=await import('./live-command-GNAASZ7U.js');await i({targetPath:t,runId:e.run,once:e.once===true,json:e.json===true,projection:e.projection??"monitor",refreshMs:r,maxRuns:o,classic:e.classic===true,color:e.color===false?false:void 0,motion:e.motion===false?false:void 0,ascii:e.ascii===true?true:void 0,accessible:e.accessible===true,global:e.global===true,maxScopes:n,capturePath:e.capture,capturePreset:e.capturePreset,captureTheme:e.captureTheme,captureRedact:e.captureRedact!==false,replayRunId:e.replay,replaySpeed:a});});ge.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-python-engine","Create a Python-aware workspace without installing rapidkit-core now").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, java-only, python-only, node-only, go-only, dotnet-only, polyglot, enterprise").choices(["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not link it to any workspace").hideHelp()).option("--no-update-check","Skip checking for updates").option("--trust-config","Trust and execute workspai.config.js/mjs/cjs discovered in this tree").action(async(t,e$2)=>{try{e$2.debug&&(e.setDebug(true),e.debug("Debug mode enabled"));let r=await b();e.debug("User config loaded",{...r,openaiApiKey:r.openaiApiKey?"[REDACTED]":void 0});let o=await c(process.cwd(),{trustExecutableConfig:e$2.trustConfig===true||process.env.WORKSPAI_TRUST_CONFIG==="1"});e.debug("Workspai config loaded",o);let n$1=d(r,o,{author:e$2.author,pythonVersion:void 0,skipGit:e$2.skipGit});e.debug("Merged config",n$1),e$2.updateCheck!==false&&await g(),a("workspace"),t||(vp(),process.exit(0));try{j(t);}catch(p){throw p instanceof a$1&&(e.error(`
366
366
  \u274C ${p.message}`),p.details&&e.warn(`\u{1F4A1} ${p.details}
367
367
  `),process.exit(1)),p}let a$2=!!e$2.template,i$1;a$2||(e$2.here?i$1=process.cwd():e$2.output?i$1=P.resolve(e$2.output):i$1=await j$1([],{hasYes:e$2.yes}));let c$1=a$2?P.resolve(process.cwd(),t):h$1(t,{outputParent:i$1});if(_t=c$1,!e$2.dryRun){a$2||await M__default.ensureDir(P.dirname(c$1));let p=a$2?void 0:n(t);(!a$2&&i(p,c$1,{outputParent:i$1})&&p&&await M__default.pathExists(p)||await M__default.pathExists(c$1))&&(e.error(`
368
368
  \u274C Directory "${t}" already exists`),p&&p!==c$1&&console.log(s.gray(` Found at: ${p}`)),console.log(s.cyan(`
@@ -370,11 +370,11 @@ Discover more:
370
370
  `)),process.exit(1));}if(e$2.dryRun){console.log(s.cyan(`
371
371
  \u{1F50D} Dry-run mode - showing what would be created:
372
372
  `)),console.log(s.white("\u{1F4C2} Path:"),c$1),console.log(s.white("\u{1F4E6} Type:"),a$2?`Project (${e$2.template})`:"Workspace"),console.log();return}if(!e$2.yes&&!a$2?await b$1([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"Workspai User"}]):e$2.yes&&console.log(s.gray(`Using default values (--yes flag)
373
- `)),a$2){let p=String(e$2.template||"").trim(),d=b$2(p);if(d$1(d)){let l=await $s(["create","project",d,t,...e$2.skipGit?["--skip-git"]:[],...e$2.skipInstall?["--skip-install"]:[]]);l!==0&&process.exit(l);return}if(!!!Ds(process.cwd())){let{registerWorkspaceAtPath:l}=await import('./create-72ITVZXV.js');if(e$2.createWorkspace)await l(process.cwd(),{skipGit:e$2.skipGit,yes:e$2.yes,userConfig:r});else if(!e$2.noWorkspace)if(e$2.yes)await l(process.cwd(),{skipGit:e$2.skipGit,yes:true,userConfig:r});else {let{createWs:m}=await b$1([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);m&&await l(process.cwd(),{skipGit:e$2.skipGit,yes:false,userConfig:r});}}let u=["create","project",d,t,"--output",process.cwd()];e$2.yes&&u.push("--yes");let f$1=Se(process.cwd()),v=!!e$2.skipInstall,k=v||!!f$1;v&&u.push("--skip-essentials");let E=k?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,S=await f(u,{cwd:process.cwd(),env:E});S!==0&&process.exit(S),f$1&&!e$2.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init")));let N=Ds(process.cwd());if(N){let l=P.dirname(N),m=P.join(l,".python-version"),y=P.join(c$1,".python-version");try{if(await M__default.pathExists(m)){let w=I.readFileSync(m,"utf-8");I.writeFileSync(y,w.trim()+`
373
+ `)),a$2){let p=String(e$2.template||"").trim(),d=b$2(p);if(d$1(d)){let l=await $s(["create","project",d,t,...e$2.skipGit?["--skip-git"]:[],...e$2.skipInstall?["--skip-install"]:[]]);l!==0&&process.exit(l);return}if(!!!Ds(process.cwd())){let{registerWorkspaceAtPath:l}=await import('./create-U5PQHOZ4.js');if(e$2.createWorkspace)await l(process.cwd(),{skipGit:e$2.skipGit,yes:e$2.yes,userConfig:r});else if(!e$2.noWorkspace)if(e$2.yes)await l(process.cwd(),{skipGit:e$2.skipGit,yes:true,userConfig:r});else {let{createWs:m}=await b$1([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);m&&await l(process.cwd(),{skipGit:e$2.skipGit,yes:false,userConfig:r});}}let u=["create","project",d,t,"--output",process.cwd()];e$2.yes&&u.push("--yes");let f$1=Se(process.cwd()),v=!!e$2.skipInstall,k=v||!!f$1;v&&u.push("--skip-essentials");let E=k?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,S=await f(u,{cwd:process.cwd(),env:E});S!==0&&process.exit(S),f$1&&!e$2.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init")));let N=Ds(process.cwd());if(N){let l=P.dirname(N),m=P.join(l,".python-version"),y=P.join(c$1,".python-version");try{if(await M__default.pathExists(m)){let w=I.readFileSync(m,"utf-8");I.writeFileSync(y,w.trim()+`
374
374
  `),e.debug(`Synced Python version ${w.trim()} from workspace to project`);}}catch(w){e.debug("Could not sync Python version from workspace:",w);}}if(!e$2.skipInstall){let l=await e$1(["init",c$1],{cwd:process.cwd()});if(l!==0&&process.exit(l),N){let m=P.dirname(N),y=P.join(m,".python-version"),w=P.join(c$1,".python-version");try{if(await M__default.pathExists(y)){let g=I.readFileSync(y,"utf-8");I.writeFileSync(w,g.trim()+`
375
- `),e.debug(`Re-synced Python version ${g.trim()} after init`);}}catch(g){e.debug("Could not re-sync Python version after init:",g);}}}}else {let{createProject:p}=await import('./create-72ITVZXV.js');await p(t,{skipGit:e$2.skipGit,skipPythonEngine:e$2.skipPythonEngine,dryRun:e$2.dryRun,yes:e$2.yes,userConfig:n$1,installMethod:e$2.installMethod,profile:e$2.profile,parentDirectory:P.dirname(c$1)});}}catch(r){r instanceof a$1?(e.error(`
375
+ `),e.debug(`Re-synced Python version ${g.trim()} after init`);}}catch(g){e.debug("Could not re-sync Python version after init:",g);}}}}else {let{createProject:p}=await import('./create-U5PQHOZ4.js');await p(t,{skipGit:e$2.skipGit,skipPythonEngine:e$2.skipPythonEngine,dryRun:e$2.dryRun,yes:e$2.yes,userConfig:n$1,installMethod:e$2.installMethod,profile:e$2.profile,parentDirectory:P.dirname(c$1)});}}catch(r){r instanceof a$1?(e.error(`
376
376
  \u274C ${r.message}`),r.details&&e.warn(`\u{1F4A1} ${r.details}`),e.debug("Error code:",r.code)):(e.error(`
377
- \u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{_t=null;}});hc(ge);bc(ge);rl(ge);ge.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{vm({json:t.json});});ge.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:r}=await import('./analyze-IC2KRVCG.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});Zi(ge);ge.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 r(p){let d=p;for(;;){let h=u(d,"context.json").find(f=>I.existsSync(f));if(h)return h;let u$1=P.dirname(d);if(u$1===d)break;d=u$1;}return null}let o$1=r(e);function n(p){let d=p;for(;;){let h=P.join(d,".venv"),u=[P.join(d,".workspai","activate"),P.join(d,".rapidkit","activate")].find(v=>I.existsSync(v))??P.join(d,".workspai","activate");if(I.existsSync(u)||I.existsSync(h))return {venv:h,activateFile:u};let f=P.dirname(d);if(f===d)break;d=f;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow(il(e))),process.exit(1));let i;a&&I.existsSync(a.activateFile)?i=a.activateFile:a&&I.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$3();console.log(c?`call "${i}"`:`. "${i}"`);});ge.command(k.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$4({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});ge.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:r}=await import('./pipeline-SKYOXWHW.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});ge.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Os({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-RECEZAZI.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});ge.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ls(t,e);r!==0&&process.exit(r);});ge.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await wp(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});ge.command("goal [intent]").description("Compile a plain-language engineering intent into a governed, evidence-bound Goal Pack").option("--workspace <path>","Explicit canonical workspace path").option("--scope <scope>","Bound the Goal to workspace, project:<name>, or projects:<name>,<name>").addOption(new Option("--runtime <runtime>","Bind a coverage Goal to a canonical runtime in its scope").choices(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"])).addOption(new Option("--for-agent <consumer>","Portable handoff consumer").choices(["generic","claude","codex"]).default("generic")).option("--max-attempts <count>","Maximum bounded proposal attempts","5").option("--refresh","Refresh the canonical Workspace Intelligence chain before planning").option("--dry-run","Validate and preview the Goal Pack without writing artifacts").option("--status [goal-id]","Inspect the active or named Goal Pack and validate its bindings").option("--list","List registered Goal Packs in the resolved workspace").option("--activate <goal-id>","Make a registered Goal Pack the active agent objective").option("--cancel <goal-id>","Cancel a registered Goal Pack without deleting evidence").option("--prepare <goal-id>","Create and link the deterministic CLI verification contract").option("--verify <goal-id>","Run CLI-owned verification for a prepared Goal Pack").option("--no-run","Read verification evidence without executing producer commands").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let{validateGoalCommandSelection:r}=await import('./goal-command-contract-43E22XQD.js'),o=r({intent:t,...e});if(o.operation!=="plan"){let u=b$5({startPath:process.cwd(),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!u)throw new Error("No canonical Workspai workspace could be resolved.");let{buildGoalLifecycleResult:f,inspectGoalLifecycle:v,prepareGoalVerification:k,transitionGoalLifecycle:E,verifyGoalLifecycle:S}=await import('./goal-lifecycle-H55AGFCB.js'),N=e.prepare?await k({workspacePath:u.workspacePath,goalId:e.prepare}):null,l=e.verify?await S({workspacePath:u.workspacePath,goalId:e.verify,run:e.run!==false}):null,m=e.activate?await E({workspacePath:u.workspacePath,goalId:e.activate,action:"activate"}):e.cancel?await E({workspacePath:u.workspacePath,goalId:e.cancel,action:"cancel"}):null,y=await v({workspacePath:u.workspacePath,goalId:typeof e.status=="string"?e.status:m?.goal.id??N?.goal.id??l?.goal.id,validateBindings:!(e.list||e.cancel)}),w=f({operation:o.operation,activeGoalId:y.index.activeGoalId,goal:y.active,goals:y.index.goals,goalPack:y.goalPack,verifiedGoalId:l?.verifiedGoalId??N?.verifiedGoalId??null,verification:l?.verification??null});if(e.json)console.log(JSON.stringify(w,null,2));else if(e.list){console.log(s.bold(`Goals \xB7 ${y.index.goals.length}`));for(let g of y.index.goals)console.log(`${g.id===y.index.activeGoalId?s.green("\u25CF"):s.gray("\u25CB")} ${g.objective} \xB7 ${g.lifecycle} \xB7 ${g.state}`);}else y.active?(console.log(s.bold(y.active.objective)),console.log(s.gray(` Goal: ${y.active.id}`)),console.log(s.gray(` Lifecycle: ${y.active.lifecycle}`)),console.log(s.gray(` Planning state: ${y.active.state}`))):console.log(s.yellow("No active Goal Pack is registered."));return}let n=Number(e.maxAttempts??5),{planGoalPack:a}=await import('./goal-pack-6OBZOPCD.js'),c=e.json!==true&&process.stdin.isTTY===true&&process.stdout.isTTY===true?await import('./goal-interactive-selection-6YJOK4WC.js'):null,p=await a({startPath:process.cwd(),intent:o.intent,workspacePath:e.workspace,scope:e.scope,runtime:e.runtime,consumer:e.forAgent,maxAttempts:n,refresh:e.refresh===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),...c?{selectScope:c.selectGoalScopeInteractively,selectCoverageRuntime:c.selectGoalCoverageRuntimeInteractively}:{}});if(e.json){console.log(JSON.stringify(p,null,2));return}let d=p.goalPack,h=d.state==="ready-to-plan"?s.green("\u2714 Governed Goal Pack ready to plan"):d.state==="blocked"?s.red("\u25A0 Goal Pack blocked by missing bounded evidence"):d.state==="needs-evidence"?s.yellow("\u25C6 Goal Pack needs measurement evidence"):s.yellow("\u25C6 Goal Pack needs clarification");console.log(h),console.log(s.bold(` ${d.intent.statement}`)),console.log(s.gray(` Goal: ${d.id}`)),console.log(s.gray(` Scope: ${d.scope.kind} \xB7 ${d.scope.projects.length} project(s) \xB7 ${d.baseline.runtimes.length} runtime(s)`)),console.log(s.gray(` Evidence: ${d.baseline.graph.entities} entities \xB7 ${d.baseline.graph.relationships} relationships \xB7 ${d.baseline.graph.proofCoveragePercent}% relation proof coverage`)),console.log(s.gray(" Mutation: proposal only \xB7 explicit approval \xB7 CLI-owned verify/rollback")),d.decision&&console.log(s.yellow(` Decision: ${d.decision.question}`)),p.dryRun?console.log(s.cyan(" Preview only; no artifacts were written.")):(console.log(s.gray(` Goal Pack: ${d.artifacts.goalPack}`)),console.log(s.gray(` Agent handoff: ${d.artifacts.agentHandoff}`))),console.log(s.gray(` Next: ${d.commands.planVerifiedGoal??d.commands.inspectGraph}`));}catch(r){let o=r instanceof Error?r.message:String(r),n=e.verify?"verify":e.prepare?"prepare":e.activate?"activate":e.cancel?"cancel":e.list?"list":e.status!==void 0?"status":null;e.json?console.log(JSON.stringify(c$1({operation:n?`goal.${n}`:"goal.plan",code:n?`goal.${n}.failed`:"goal.plan.failed",message:o,context:{scope:e.scope??null,runtime:e.runtime??null,refresh:e.refresh===true,goalId:e.prepare??e.verify??e.activate??e.cancel??(typeof e.status=="string"?e.status:null)}}),null,2)):console.log(s.red(`\u274C Goal ${n?`${n} operation`:"planning"} failed: ${o}`)),process.exit(1);}});var pn=ge.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");pn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Io({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot create",code:"snapshot.create.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});pn.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 Ic({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){t.json&&(console.log(JSON.stringify(c$1({operation:"snapshot list",code:"snapshot.list.failed",message:e.message,context:{workspacePath:t.workspace??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});pn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await _c({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot inspect",code:"snapshot.inspect.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});pn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await $c({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot restore",code:"snapshot.restore.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});function Km(t){return (t instanceof Error?t.message:String(t)).replace(/file:\/\/\/[^\s"']+/g,"<local-path>").replace(/\\\\[^\\\s"']+[\\][^\s"']+/g,"<local-path>").replace(/[A-Za-z]:[\\/][^\s"']+/g,"<local-path>").replace(/\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\/[^\s"']+/g,"<local-path>")}async function kp(t){try{let{buildAgentBootstrapReceipt:e}=await import('./project-agent-entry-5IUBEREI.js'),r=await e({startPath:t.project,forAgent:t.forAgent,validateLiveInputs:t.liveInputs!==false});if(t.json)console.log(JSON.stringify(r,null,2));else {let o=r.status==="ready"?s.green:r.status==="degraded"?s.yellow:s.red;console.log(o(`Agent entry: ${r.status}`)),console.log(s.gray(` Project: ${r.project.name}`)),console.log(s.gray(` Workspace: ${r.workspace.name}`)),console.log(s.gray(` Consumer: ${r.resolvedHost}`)),console.log(s.gray(` Receipt: ${r.receiptId.slice(0,16)}`));for(let n of r.checks.filter(a=>a.status!=="passed"))console.log((n.status==="failed"?s.red:s.yellow)(` ${n.id}: ${n.message}`));console.log(s.gray(` Next: ${r.nextActions[0]}`));}(r.status==="blocked"||t.strict&&r.status!=="ready")&&process.exit(2);}catch(e){let r=Km(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"agent.entry.bootstrap.failed",message:r}),null,2)):console.log(s.red(`Agent entry failed: ${r}`)),process.exit(1);}}var Um=ge.command("agent").description("Bootstrap coding agents from canonical Workspai project evidence");Um.command("bootstrap").description("Issue a portable canonical-first grounding receipt for the current project").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier","generic").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless the complete entry receipt is ready").option("--json","Emit the versioned machine-readable receipt").action(async t=>kp({...t,operation:"agent bootstrap"}));var It=ge.command("project").description("Safe workspace project lifecycle operations");It.command("agent-entry [action]").description("Verify canonical-first project entry coverage for supported agent hosts").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier or all","all").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless all selected entry checks are ready").option("--json","Emit the versioned machine-readable receipt").action(async(t,e)=>{let r=t??"verify";if(r!=="verify"){let o=`Unknown project agent-entry action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project agent-entry",code:"project.agent-entry.action.invalid",message:o}),null,2)):(console.log(s.red(o)),console.log(s.gray(" workspai project agent-entry verify [--for-agent <agent|all>] [--strict] [--json]"))),process.exit(1);}await kp({...e,operation:"project agent-entry verify"});});It.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{pp({json:t.json});});It.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$5({startPath:P.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??P.join(o.projectPath,f$1),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json",pathPolicy:{classification:"machine-local",portable:false,persistence:"forbidden",disclosure:"forbidden",purpose:"runtime-workspace-resolution"}};if(Pl(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});It.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-KD4LLFGV.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let p of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${p.path}: ${p.percent===null?"unknown":`${p.percent}%`} (${p.uncovered} uncovered)`));}for(let p of o.diagnostics)console.log(s.gray(` ${p}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});It.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 Xn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});It.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Zn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});It.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Lc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});It.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Dc({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});ge.command(k.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json [mode]","Output JSON: full (default) or summary").option("--fresh","Bypass Doctor project scan cache and refresh live evidence").option("--verbose","Show every probe, lifecycle capability, and detailed project signal").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate an action or lifecycle plan without applying or executing changes").option("--apply","Apply remediation plan non-interactively").option("--runtime <runtime>","Filter Doctor capability truth by runtime family").option("--framework <framework>","Filter Doctor capability truth by framework").option("--validate","Run the versioned Doctor disease validation corpus").option("--write","Write Doctor capability/validation artifacts inside the workspace").action(async(t,e)=>{if(t&&t!=="workspace"&&t!=="project"&&t!=="capabilities"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project, capabilities")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project | npx workspai doctor capabilities")),process.exit(1)),typeof e.json=="string"&&!["full","summary"].includes(e.json)&&(console.log(s.red(`Invalid Doctor JSON mode: ${e.json}. Use full or summary.`)),process.exit(1)),t==="capabilities"){(e.fix||e.plan||e.apply||e.project)&&(console.log(s.red("Doctor capability inspection cannot be combined with repair or project-scope flags.")),process.exit(1));let{runDoctorCapabilities:i}=await import('./capabilities-command-X4WZIJNR.js'),c=await i({runtime:e.runtime,framework:e.framework,validate:e.validate===true,write:e.write===true,workspace:typeof e.workspace=="string"?e.workspace:void 0,json:!!e.json});c!==0&&process.exit(c);return}(e.runtime||e.framework||e.validate||e.write)&&(console.log(s.red('Doctor capability flags require the "doctor capabilities" scope.')),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await Pm({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-CVYUESRQ.js'),a=await n({...e,json:e.json==="summary"?"summary":!!e.json,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});ge.command(k.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
377
+ \u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{_t=null;}});hc(ge);bc(ge);rl(ge);ge.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{vm({json:t.json});});ge.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:r}=await import('./analyze-JDEWUBC6.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});Zi(ge);ge.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 r(p){let d=p;for(;;){let h=u(d,"context.json").find(f=>I.existsSync(f));if(h)return h;let u$1=P.dirname(d);if(u$1===d)break;d=u$1;}return null}let o$1=r(e);function n(p){let d=p;for(;;){let h=P.join(d,".venv"),u=[P.join(d,".workspai","activate"),P.join(d,".rapidkit","activate")].find(v=>I.existsSync(v))??P.join(d,".workspai","activate");if(I.existsSync(u)||I.existsSync(h))return {venv:h,activateFile:u};let f=P.dirname(d);if(f===d)break;d=f;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow(il(e))),process.exit(1));let i;a&&I.existsSync(a.activateFile)?i=a.activateFile:a&&I.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$3();console.log(c?`call "${i}"`:`. "${i}"`);});ge.command(k.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$4({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});ge.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:r}=await import('./pipeline-QOMXH2EK.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});ge.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Os({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-OELUFNLL.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});ge.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ls(t,e);r!==0&&process.exit(r);});ge.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await wp(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});ge.command("goal [intent]").description("Compile a plain-language engineering intent into a governed, evidence-bound Goal Pack").option("--workspace <path>","Explicit canonical workspace path").option("--scope <scope>","Bound the Goal to workspace, project:<name>, or projects:<name>,<name>").addOption(new Option("--runtime <runtime>","Bind a coverage Goal to a canonical runtime in its scope").choices(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"])).addOption(new Option("--for-agent <consumer>","Portable handoff consumer").choices(["generic","claude","codex"]).default("generic")).option("--max-attempts <count>","Maximum bounded proposal attempts","5").option("--refresh","Refresh the canonical Workspace Intelligence chain before planning").option("--dry-run","Validate and preview the Goal Pack without writing artifacts").option("--status [goal-id]","Inspect the active or named Goal Pack and validate its bindings").option("--list","List registered Goal Packs in the resolved workspace").option("--activate <goal-id>","Make a registered Goal Pack the active agent objective").option("--cancel <goal-id>","Cancel a registered Goal Pack without deleting evidence").option("--prepare <goal-id>","Create and link the deterministic CLI verification contract").option("--verify <goal-id>","Run CLI-owned verification for a prepared Goal Pack").option("--no-run","Read verification evidence without executing producer commands").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let{validateGoalCommandSelection:r}=await import('./goal-command-contract-43E22XQD.js'),o=r({intent:t,...e});if(o.operation!=="plan"){let u=b$5({startPath:process.cwd(),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!u)throw new Error("No canonical Workspai workspace could be resolved.");let{buildGoalLifecycleResult:f,inspectGoalLifecycle:v,prepareGoalVerification:k,transitionGoalLifecycle:E,verifyGoalLifecycle:S}=await import('./goal-lifecycle-BMS6GSIU.js'),N=e.prepare?await k({workspacePath:u.workspacePath,goalId:e.prepare}):null,l=e.verify?await S({workspacePath:u.workspacePath,goalId:e.verify,run:e.run!==false}):null,m=e.activate?await E({workspacePath:u.workspacePath,goalId:e.activate,action:"activate"}):e.cancel?await E({workspacePath:u.workspacePath,goalId:e.cancel,action:"cancel"}):null,y=await v({workspacePath:u.workspacePath,goalId:typeof e.status=="string"?e.status:m?.goal.id??N?.goal.id??l?.goal.id,validateBindings:!(e.list||e.cancel)}),w=f({operation:o.operation,activeGoalId:y.index.activeGoalId,goal:y.active,goals:y.index.goals,goalPack:y.goalPack,verifiedGoalId:l?.verifiedGoalId??N?.verifiedGoalId??null,verification:l?.verification??null});if(e.json)console.log(JSON.stringify(w,null,2));else if(e.list){console.log(s.bold(`Goals \xB7 ${y.index.goals.length}`));for(let g of y.index.goals)console.log(`${g.id===y.index.activeGoalId?s.green("\u25CF"):s.gray("\u25CB")} ${g.objective} \xB7 ${g.lifecycle} \xB7 ${g.state}`);}else y.active?(console.log(s.bold(y.active.objective)),console.log(s.gray(` Goal: ${y.active.id}`)),console.log(s.gray(` Lifecycle: ${y.active.lifecycle}`)),console.log(s.gray(` Planning state: ${y.active.state}`))):console.log(s.yellow("No active Goal Pack is registered."));return}let n=Number(e.maxAttempts??5),{planGoalPack:a}=await import('./goal-pack-RBSVQMMX.js'),c=e.json!==true&&process.stdin.isTTY===true&&process.stdout.isTTY===true?await import('./goal-interactive-selection-6YJOK4WC.js'):null,p=await a({startPath:process.cwd(),intent:o.intent,workspacePath:e.workspace,scope:e.scope,runtime:e.runtime,consumer:e.forAgent,maxAttempts:n,refresh:e.refresh===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),...c?{selectScope:c.selectGoalScopeInteractively,selectCoverageRuntime:c.selectGoalCoverageRuntimeInteractively}:{}});if(e.json){console.log(JSON.stringify(p,null,2));return}let d=p.goalPack,h=d.state==="ready-to-plan"?s.green("\u2714 Governed Goal Pack ready to plan"):d.state==="blocked"?s.red("\u25A0 Goal Pack blocked by missing bounded evidence"):d.state==="needs-evidence"?s.yellow("\u25C6 Goal Pack needs measurement evidence"):s.yellow("\u25C6 Goal Pack needs clarification");console.log(h),console.log(s.bold(` ${d.intent.statement}`)),console.log(s.gray(` Goal: ${d.id}`)),console.log(s.gray(` Scope: ${d.scope.kind} \xB7 ${d.scope.projects.length} project(s) \xB7 ${d.baseline.runtimes.length} runtime(s)`)),console.log(s.gray(` Evidence: ${d.baseline.graph.entities} entities \xB7 ${d.baseline.graph.relationships} relationships \xB7 ${d.baseline.graph.proofCoveragePercent}% relation proof coverage`)),console.log(s.gray(" Mutation: proposal only \xB7 explicit approval \xB7 CLI-owned verify/rollback")),d.decision&&console.log(s.yellow(` Decision: ${d.decision.question}`)),p.dryRun?console.log(s.cyan(" Preview only; no artifacts were written.")):(console.log(s.gray(` Goal Pack: ${d.artifacts.goalPack}`)),console.log(s.gray(` Agent handoff: ${d.artifacts.agentHandoff}`))),console.log(s.gray(` Next: ${d.commands.planVerifiedGoal??d.commands.inspectGraph}`));}catch(r){let o=r instanceof Error?r.message:String(r),n=e.verify?"verify":e.prepare?"prepare":e.activate?"activate":e.cancel?"cancel":e.list?"list":e.status!==void 0?"status":null;e.json?console.log(JSON.stringify(c$1({operation:n?`goal.${n}`:"goal.plan",code:n?`goal.${n}.failed`:"goal.plan.failed",message:o,context:{scope:e.scope??null,runtime:e.runtime??null,refresh:e.refresh===true,goalId:e.prepare??e.verify??e.activate??e.cancel??(typeof e.status=="string"?e.status:null)}}),null,2)):console.log(s.red(`\u274C Goal ${n?`${n} operation`:"planning"} failed: ${o}`)),process.exit(1);}});var pn=ge.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");pn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Io({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot create",code:"snapshot.create.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});pn.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 Ic({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){t.json&&(console.log(JSON.stringify(c$1({operation:"snapshot list",code:"snapshot.list.failed",message:e.message,context:{workspacePath:t.workspace??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});pn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await _c({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot inspect",code:"snapshot.inspect.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});pn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await $c({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot restore",code:"snapshot.restore.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});function Km(t){return (t instanceof Error?t.message:String(t)).replace(/file:\/\/\/[^\s"']+/g,"<local-path>").replace(/\\\\[^\\\s"']+[\\][^\s"']+/g,"<local-path>").replace(/[A-Za-z]:[\\/][^\s"']+/g,"<local-path>").replace(/\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\/[^\s"']+/g,"<local-path>")}async function kp(t){try{let{buildAgentBootstrapReceipt:e}=await import('./project-agent-entry-MH7364BE.js'),r=await e({startPath:t.project,forAgent:t.forAgent,validateLiveInputs:t.liveInputs!==false});if(t.json)console.log(JSON.stringify(r,null,2));else {let o=r.status==="ready"?s.green:r.status==="degraded"?s.yellow:s.red;console.log(o(`Agent entry: ${r.status}`)),console.log(s.gray(` Project: ${r.project.name}`)),console.log(s.gray(` Workspace: ${r.workspace.name}`)),console.log(s.gray(` Consumer: ${r.resolvedHost}`)),console.log(s.gray(` Receipt: ${r.receiptId.slice(0,16)}`));for(let n of r.checks.filter(a=>a.status!=="passed"))console.log((n.status==="failed"?s.red:s.yellow)(` ${n.id}: ${n.message}`));console.log(s.gray(` Next: ${r.nextActions[0]}`));}(r.status==="blocked"||t.strict&&r.status!=="ready")&&process.exit(2);}catch(e){let r=Km(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"agent.entry.bootstrap.failed",message:r}),null,2)):console.log(s.red(`Agent entry failed: ${r}`)),process.exit(1);}}var Um=ge.command("agent").description("Bootstrap coding agents from canonical Workspai project evidence");Um.command("bootstrap").description("Issue a portable canonical-first grounding receipt for the current project").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier","generic").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless the complete entry receipt is ready").option("--json","Emit the versioned machine-readable receipt").action(async t=>kp({...t,operation:"agent bootstrap"}));var It=ge.command("project").description("Safe workspace project lifecycle operations");It.command("agent-entry [action]").description("Verify canonical-first project entry coverage for supported agent hosts").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier or all","all").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless all selected entry checks are ready").option("--json","Emit the versioned machine-readable receipt").action(async(t,e)=>{let r=t??"verify";if(r!=="verify"){let o=`Unknown project agent-entry action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project agent-entry",code:"project.agent-entry.action.invalid",message:o}),null,2)):(console.log(s.red(o)),console.log(s.gray(" workspai project agent-entry verify [--for-agent <agent|all>] [--strict] [--json]"))),process.exit(1);}await kp({...e,operation:"project agent-entry verify"});});It.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{pp({json:t.json});});It.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$5({startPath:P.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??P.join(o.projectPath,f$1),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json",pathPolicy:{classification:"machine-local",portable:false,persistence:"forbidden",disclosure:"forbidden",purpose:"runtime-workspace-resolution"}};if(Pl(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});It.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-JPWTBSSJ.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let p of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${p.path}: ${p.percent===null?"unknown":`${p.percent}%`} (${p.uncovered} uncovered)`));}for(let p of o.diagnostics)console.log(s.gray(` ${p}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});It.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 Xn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});It.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Zn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});It.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Lc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});It.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Dc({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});ge.command(k.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json [mode]","Output JSON: full (default) or summary").option("--fresh","Bypass Doctor project scan cache and refresh live evidence").option("--verbose","Show every probe, lifecycle capability, and detailed project signal").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate an action or lifecycle plan without applying or executing changes").option("--apply","Apply remediation plan non-interactively").option("--runtime <runtime>","Filter Doctor capability truth by runtime family").option("--framework <framework>","Filter Doctor capability truth by framework").option("--validate","Run the versioned Doctor disease validation corpus").option("--write","Write Doctor capability/validation artifacts inside the workspace").action(async(t,e)=>{if(t&&t!=="workspace"&&t!=="project"&&t!=="capabilities"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project, capabilities")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project | npx workspai doctor capabilities")),process.exit(1)),typeof e.json=="string"&&!["full","summary"].includes(e.json)&&(console.log(s.red(`Invalid Doctor JSON mode: ${e.json}. Use full or summary.`)),process.exit(1)),t==="capabilities"){(e.fix||e.plan||e.apply||e.project)&&(console.log(s.red("Doctor capability inspection cannot be combined with repair or project-scope flags.")),process.exit(1));let{runDoctorCapabilities:i}=await import('./capabilities-command-RAAYENQ6.js'),c=await i({runtime:e.runtime,framework:e.framework,validate:e.validate===true,write:e.write===true,workspace:typeof e.workspace=="string"?e.workspace:void 0,json:!!e.json});c!==0&&process.exit(c);return}(e.runtime||e.framework||e.validate||e.write)&&(console.log(s.red('Doctor capability flags require the "doctor capabilities" scope.')),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await Pm({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-D7YI7LSA.js'),a=await n({...e,json:e.json==="summary"?"summary":!!e.json,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});ge.command(k.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
378
378
  workspace run <stage> \u2014 fleet stage execution across discovered projects
379
379
  stages: init | test | build | start | <custom-from-context>
380
380
  workspace explain|why \u2014 blocker/project narrative (--write for artifact)
@@ -390,18 +390,18 @@ Workspace Actions:
390
390
  Fleet lifecycle run | init
391
391
 
392
392
  Use "workspai commands --json" for the contract-backed runtime inventory.
393
- See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=l=>{let m=n.workspace?P.resolve(n.workspace):null,y=null,w=null;try{y=b$5({startPath:process.cwd(),explicitWorkspacePath:m,strict:true})?.workspacePath??null;}catch(x){if(x instanceof a$2)w=x;else throw x}if(!y||!Ye(y)){let x=w?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${l}`,code:w?.code??"workspace.root.required",message:x,context:{cwd:P.resolve(process.cwd()),...m?{requestedWorkspace:m}:{},...w?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${x}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let g=P.resolve(process.cwd()),C=P.resolve(y);return g!==C&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${y} for "${l}" (current directory: ${g}).`)),y},i=l=>process.argv.includes(l),c=l=>Le(process.argv,l),p=()=>n.output||c("--output"),d=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0},h=(l,m,y)=>{if(l===void 0)return;let w=Number.parseInt(l,10);if(!Number.isFinite(w)||w<1||w>y)throw new Error(`${m} must be an integer between 1 and ${y}.`);return w},u=()=>({...n.graphInventoryLimit!==void 0?{inventoryFileLimitPerProject:h(n.graphInventoryLimit,"--graph-inventory-limit",2e6)}:{},...n.graphSemanticBudget!==void 0?{semanticFilesPerProject:h(n.graphSemanticBudget,"--graph-semantic-budget",25e4)}:{},...n.graphDeepBudget!==void 0?{maxFilesPerProject:h(n.graphDeepBudget,"--graph-deep-budget",1e5)}:{},...n.graphSourceBudget!==void 0?{sourceFilesPerProject:h(n.graphSourceBudget,"--graph-source-budget",5e4)}:{}}),f=(l,m)=>{if(!l)return;let y=l.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!y)throw new Error(`${m} must be a byte size such as 500gb or 2tb.`);let w={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},g=Number(y[1])*w[y[2]||"b"];if(!Number.isSafeInteger(Math.floor(g))||g<=0)throw new Error(`${m} is outside the supported numeric range.`);return Math.floor(g)},v=()=>{let l=n.downloadTimeoutMs,m=l===void 0?void 0:Number.parseInt(l,10);if(m!==void 0&&(!Number.isFinite(m)||m<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:f(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:f(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:m,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},k=new Set(Object.values(Fr).flatMap(l=>[...l.flags])),E=new Set(process.argv.slice(2).filter(l=>l.startsWith("--")).map(l=>l.split("=",1)[0]).filter(l=>k.has(l))),S=Fr[t]?.flags,N=S?[...E].filter(l=>!S.includes(l)):[];if(N.length>0){let l=`${N.join(", ")} ${N.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||E.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:l,exitCode:2,context:{action:t,unsupportedFlags:N,allowedFlags:S}}),null,2)):(console.log(s.red(`\u274C ${l}`)),console.log(s.gray(` Allowed flags: ${S.join(", ")||"none"}`))),process.exit(2);}if((ll(t)||t==="trace"||t==="feedback"||t==="mcp")&&c$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:l}=await import('./workspace-5W7FYGDQ.js');await l({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let l=a("intelligence"),{runWorkspaceIntelligenceChain:m}=await import('./workspace-intelligence-runner-OWN5ZI6W.js'),y=await m({workspacePath:l,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(y,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${y.status}`));for(let w of y.stages)console.log(s.gray(` ${w.id}: ${w.status} \u2014 ${w.message}`));console.log(s.gray(` Evidence: ${y.artifactPath}`));}y.exitCode!==0&&process.exit(y.exitCode);}else if(t==="model"){let l=a("model"),{buildWorkspaceModelCached:m,buildWorkspaceModelIncremental:y,createWorkspaceModelBuildProvenance:w,writeWorkspaceModel:g}=await import('./workspace-model-R4ISKDB2.js'),C=n.incremental===true||i("--incremental"),x=n.cache===true||i("--cache")||C,R={workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:n.strict===true||i("--strict")},b,T;if(C){let O=await y(R);b=O.model,T=O.mode;}else {let O=await m({...R,cache:x});b=O.model,T=O.cache;}b={...b,build:w({mode:C?"incremental":x?"cache":"full",engineStatus:T})};let j;(n.write===true||i("--write"))&&(j=await g(b,l));let A=(n.strict===true||i("--strict"))&&b.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...b,...j?{outputPath:j}:{}},null,2)),A&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${b.workspace.name}`)),C?console.log(s.gray(` Build: ${T} (incremental)`)):x&&console.log(s.gray(` Cache: ${T}`)),console.log(s.gray(` Projects: ${b.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${b.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${b.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${b.identity.workspaceType}`)),console.log(s.gray(` Validation: ${b.validation?.status??"unknown"} (${b.validation?.errors??0} error, ${b.validation?.warnings??0} warning)`)),console.log(j?s.gray(` Written: ${j}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),A&&process.exit(1);}else if(t==="agent-sync"){let l=a("agent-sync"),{syncWorkspaceAgentGrounding:m,parseAgentGroundingTargets:y}=await import('./workspace-agent-sync-OZCDQORK.js'),w=n.strict===true||i("--strict"),g=n.write===true||i("--write"),C=i("--dry-run"),x=await m({workspacePath:l,scope:n.scope,agent:n.forAgent,write:g&&!C,dryRun:C,strict:w,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:y(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(x,null,2));else {console.log(s.green(`\u2714 Agent grounding ${g&&!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=g&&!C?x.writtenFiles:x.skippedFiles;if(R.length>0&&console.log(s.gray(` Files: ${R.join(", ")}`)),x.strictViolations.length>0)for(let b of x.strictViolations)console.log(s.red(`\u274C ${b}`));}w&&x.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let l=e??"status",{approveWorkspaceRepair:m,cancelWorkspaceRepair:y,decideWorkspaceRepair:w,executeWorkspaceRepair:g,inspectWorkspaceRepairCapabilities:C,listWorkspaceRepairTransactions:x,planWorkspaceRepair:R,planWorkspaceRepairProposal:b,readWorkspaceRepairTransaction:T,rollbackWorkspaceRepair:j}=await import('./workspace-repair-engine-FNLL5ZDK.js');if(l==="capabilities"){let U;if(n.workspace)U=a("repair capabilities");else try{let re=b$5({startPath:process.cwd(),strict:false})?.workspacePath;re&&Ye(re)&&(U=re);}catch{}let ae=await C(U?{workspacePath:U,project:n.project}:n.project?{project:n.project}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(ae,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${ae.adapters.length}`));for(let re of ae.adapters)console.log(s.gray(` ${re.id.padEnd(14)} ${re.support.padEnd(11)} ${re.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let A=a("repair"),O=n.transaction??(["plan","propose","capabilities"].includes(l)?void 0:r),J=()=>{if(!O?.trim())throw new Error(`workspace repair ${l} requires --transaction <id> (or the id as the next positional argument).`);return O.trim()},F;if(l==="plan"){let U=n.card??r;if(!U?.trim())throw new Error("workspace repair plan requires --card <id>.");F=await R({workspacePath:A,cardId:U.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="propose"){let U=n.proposal??r;if(!U?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let ae=P.resolve(A,U.trim()),re=P.relative(A,ae);if(re.startsWith("..")||P.isAbsolute(re))throw new Error("The repair proposal file must be inside the canonical workspace.");let he=await M__default.lstat(ae).catch(()=>{});if(!he?.isFile()||he.isSymbolicLink()||he.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");F=await b({workspacePath:A,proposal:await M__default.readJson(ae),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="approve")F=await m({workspacePath:A,transactionId:J(),approvedBy:n.approvedBy});else if(l==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");F=await w({workspacePath:A,transactionId:J(),decision:n.decision});}else if(l==="execute"||l==="resume")F=await g({workspacePath:A,transactionId:J()});else if(l==="status")F=await T({workspacePath:A,transactionId:J()});else if(l==="list")F=await x(A);else if(l==="rollback")F=await j({workspacePath:A,transactionId:J()});else if(l==="cancel")F=await y({workspacePath:A,transactionId:J()});else throw new Error(`Unknown workspace repair action: ${l}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let H=P.join(A,e$2.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$6(`workspace repair ${l}`,F,H),null,2));else if(Array.isArray(F)){console.log(s.green(`\u2714 Workspace repair transactions: ${F.length}`));for(let U of F.slice(0,20))console.log(s.gray(` ${U.transactionId} \xB7 ${U.target.cardId} \xB7 ${U.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${F.state}`)),console.log(s.gray(` Transaction: ${F.transactionId}`)),console.log(s.gray(` Target: ${F.target.cardId}`));for(let U of F.stages)console.log(s.gray(` ${U.status.padEnd(8)} ${U.kind}: ${U.summary}`));F.decision&&console.log(s.yellow(` Decision: ${F.decision.reason}`)),console.log(s.gray(` Evidence: ${e$2.repairTransaction}`));}Array.isArray(F)||(F.state==="decision-required"&&process.exit(2),(F.state==="rolled-back"||F.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let l=a("remediation-plan"),{buildArtifactRemediationPlan:m,writeArtifactRemediationPlan:y}=await import('./artifact-remediation-plan-GFFHC2ZU.js'),w=await m({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),g;if((n.write===true||i("--write"))&&(g=await y(w,l)),n.json===true||i("--json")){console.log(JSON.stringify(b$6("workspace remediation-plan",w,g),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${w.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${w.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${w.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${w.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${w.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${w.summary.risk.safe}, guarded=${w.summary.risk.guarded}, invasive=${w.summary.risk.invasive}`));for(let C of w.actions.slice(0,8))console.log(s.gray(` \u2022 ${C.cardId}: ${C.title} (${C.mode}, ${C.risk})`));w.actions.length>8&&console.log(s.gray(` \u2026 ${w.actions.length-8} more action(s)`)),console.log(g?s.gray(` Written: ${g}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let l=a("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:m,writeWorkspaceAgentContext:y}=await import('./workspace-context-L65BR5L6.js'),w=n.strict===true||i("--strict"),g=await m({workspacePath:l,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:false}),C,x;if((n.write===true||i("--write"))&&(C=await y(g,l),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:T,parseAgentGroundingTargets:j}=await import('./workspace-agent-sync-OZCDQORK.js');if(x=await T({workspacePath:l,scope:n.scope,agent:g.agent,write:true,refreshContext:false,strict:w,preset:n.preset==="minimal"?"minimal":"enterprise",targets:j(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${x.writtenFiles.length} file(s) updated`)),w&&x.strictViolations.length>0){for(let A of x.strictViolations)console.log(s.red(`\u274C ${A}`));process.exit(1);}}let R=w&&g.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...g,...C?{outputPath:C}:{},...x?{agentGroundingSync:x}:{}},null,2)),R&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${g.workspace.name}`)),console.log(s.gray(` Agent: ${g.agent}`)),console.log(s.gray(` Scope: ${g.scope.activeProject??g.scope.requested}`)),console.log(s.gray(` Projects included: ${g.projects.length}`)),console.log(s.gray(` Safe commands: ${g.safeCommands.length}`)),console.log(s.gray(` Validation: ${g.validation.status} (${g.validation.errors} error, ${g.validation.warnings} warning)`)),console.log(C?s.gray(` Written: ${C}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),R){for(let b of g.validation.issues)console.log(s.red(`\u274C ${b.severity}:${b.code}:${b.target}`));process.exit(1);}}else if(t==="snapshot"){let l=a("snapshot"),{buildWorkspaceModelSnapshot:m,writeWorkspaceModelSnapshot:y}=await import('./workspace-intelligence-3C47PK4L.js'),w=await m({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),g=await y(w,l);if(n.json){console.log(JSON.stringify(b$6("workspace snapshot",w,g),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${w.model.workspace.name}`)),console.log(s.gray(` Hash: ${w.modelHash}`)),console.log(s.gray(` Projects: ${w.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${w.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${g}`));}else if(t==="diff"){let l=a("diff"),m=n.from||e;m||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:y,writeWorkspaceModelDiff:w}=await import('./workspace-intelligence-3C47PK4L.js'),g;try{g=await y({workspacePath:l,fromPath:m,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:m},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 w(g,l);if(n.json){console.log(JSON.stringify(b$6("workspace diff",g,C),null,2));return}let x=g.summary.changed?s.yellow:s.green;console.log(x(`\u2714 Workspace model diff: ${g.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Added projects: ${g.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${g.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${g.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${g.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${g.summary.validationChanges}`)),g.git?.available&&console.log(s.gray(` Git: ${g.git.dirty?"dirty":"clean"} (${g.summary.gitChangedFiles} mapped change(s))`));for(let R of g.changes.slice(0,12))console.log(s.gray(` \u2022 ${R.type} ${R.target}: ${R.message}`));g.changes.length>12&&console.log(s.gray(` \u2026 ${g.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${C}`));}else if(t==="impact"){let l=a("impact"),m=n.from||e;m||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:y,writeWorkspaceImpact:w}=await import('./workspace-intelligence-3C47PK4L.js'),g;try{g=await y({workspacePath:l,fromPath:m,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:m},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 w(g,l);if(n.json){console.log(JSON.stringify(b$6("workspace impact",g,C),null,2));return}let x=g.summary.risk==="critical"||g.summary.risk==="high"?s.red:g.summary.risk==="medium"?s.yellow:s.green;console.log(x(`\u2714 Workspace impact: ${g.summary.risk}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Affected projects: ${g.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${g.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${g.summary.recommendedCommands}`));for(let R of g.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${R.title}: ${R.summary}`));g.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${g.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${C}`));}else if(t==="verify"){let l=a("verify"),{buildWorkspaceVerify:m,writeWorkspaceVerify:y,evaluateWorkspaceVerifyGate:w}=await import('./workspace-verify-AXVX3PF3.js'),g=await m({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),C=await y(g,l),x=w(g,{strict:n.strict===true||i("--strict")}),R=x.exitCode,{recordWorkspaceHistory:b,historyEntryFromVerify:T}=await import('./workspace-history-JKW3VJO3.js');if(await b(l,T(g,x.passed)),n.json){console.log(JSON.stringify(b$6("workspace verify",{...g,gate:x},C,R),null,2)),R!==0&&process.exit(R);return}let j=g.summary.verdict==="ready"?s.green:g.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(j(`\u2714 Workspace verify: ${g.summary.verdict}`)),console.log(s.gray(` Freshness: ${g.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${g.impact.risk}`)),console.log(s.gray(` Steps: ${g.steps.length}`)),console.log(s.gray(` Passed ${g.summary.stepsPassed}, warn ${g.summary.stepsWarn}, failed ${g.summary.stepsFailed}, missing ${g.summary.stepsMissing}`));for(let A of g.steps.slice(0,10))console.log(s.gray(` \u2022 ${A.id}: ${A.status} \u2014 ${A.message}`));if(g.steps.length>10&&console.log(s.gray(` \u2026 ${g.steps.length-10} more step(s)`)),g.policyViolations.length>0){console.log(s.gray(` Policy (${g.policyMode}): ${g.policyViolations.length} violation(s)`));for(let A of g.policyViolations.slice(0,5)){let O=A.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${O} [${A.source}] ${A.code}: ${A.message}`);}}console.log(s.gray(` Gate (${x.mode}): ${x.passed?"passed":"blocked"}`));for(let A of x.reasons.slice(0,5))console.log(s.red(` \u2717 ${A}`));console.log(s.gray(` Written: ${C}`)),R!==0&&process.exit(R);}else if(t==="graph"){let l=a("graph"),{buildWorkspaceModel:m,workspaceModelProjectTopology:y}=await import('./workspace-model-R4ISKDB2.js'),{buildGraphEmit:w,renderGraphDot:g,renderGraphMermaid:C,explainGraphNode:x}=await import('./workspace-graph-2A5THUCI.js'),R=(e||"emit").toLowerCase(),b=["emit","dot","mermaid","jsonld","graphml","gexf","explain","entities","search","benchmark","benchmark-suite","evidence","path","overlay"];if(!b.includes(R)){let D=`Unknown workspace graph mode '${R}'.`;n.json?console.log(JSON.stringify(c$1({operation:`workspace graph ${R}`,code:"workspace.graph.mode.unsupported",message:D,exitCode:2,context:{mode:R,supportedModes:b},examples:["workspai workspace graph emit --json"]}),null,2)):(console.log(s.red(`\u274C ${D}`)),console.log(s.gray(` Supported: ${b.join(", ")}`))),process.exit(2);}let T=new Set(["benchmark","benchmark-suite","entities","evidence","path","search"]),j=n.refreshGraph===true||i("--refresh-graph"),A=T.has(R)&&!j?await(await import('./workspace-knowledge-graph-snapshot-SNI5K2RL.js')).readWorkspaceKnowledgeGraphSnapshot(l):null,O=A?.status==="hit"?A.graph:null,J=A?.status==="hit"?A.model:await m({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),F=y(J);F||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:R,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let H=async()=>{if(O)return O;let{buildWorkspaceKnowledgeGraph:D}=await import('./workspace-knowledge-graph-AKG5NUU6.js'),{hashWorkspaceModel:G}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:oe}=await import('./workspace-contract-JYHNEJPV.js'),Z=null;try{Z=(await oe({workspacePath:l})).contract;}catch{}return D({...u(),workspacePath:l,workspace:{name:J.workspace.name,...J.workspace.profile?{profile:J.workspace.profile}:{}},projects:J.projects.map(B=>({id:B.name,path:B.path,...B.absolutePath?{absolutePath:B.absolutePath}:{},runtime:B.runtime,runtimeCandidates:B.runtimeCandidates,framework:B.framework,kind:B.kind,category:B.category,...B.governance?{governance:B.governance}:{},...B.kit?{kit:B.kit}:{}})),projectTopology:F,contract:Z,now:new Date(J.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:G(J)}})};if(R==="dot"||R==="mermaid"){let D=R==="dot"?g(F):C(F),G=p();if(G){let oe=P.resolve(l,G);await M__default.outputFile(oe,`${D}
393
+ See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=l=>{let m=n.workspace?P.resolve(n.workspace):null,y=null,w=null;try{y=b$5({startPath:process.cwd(),explicitWorkspacePath:m,strict:true})?.workspacePath??null;}catch(x){if(x instanceof a$2)w=x;else throw x}if(!y||!Ye(y)){let x=w?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${l}`,code:w?.code??"workspace.root.required",message:x,context:{cwd:P.resolve(process.cwd()),...m?{requestedWorkspace:m}:{},...w?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${x}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let g=P.resolve(process.cwd()),C=P.resolve(y);return g!==C&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${y} for "${l}" (current directory: ${g}).`)),y},i=l=>process.argv.includes(l),c=l=>Le(process.argv,l),p=()=>n.output||c("--output"),d=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0},h=(l,m,y)=>{if(l===void 0)return;let w=Number.parseInt(l,10);if(!Number.isFinite(w)||w<1||w>y)throw new Error(`${m} must be an integer between 1 and ${y}.`);return w},u=()=>({...n.graphInventoryLimit!==void 0?{inventoryFileLimitPerProject:h(n.graphInventoryLimit,"--graph-inventory-limit",2e6)}:{},...n.graphSemanticBudget!==void 0?{semanticFilesPerProject:h(n.graphSemanticBudget,"--graph-semantic-budget",25e4)}:{},...n.graphDeepBudget!==void 0?{maxFilesPerProject:h(n.graphDeepBudget,"--graph-deep-budget",1e5)}:{},...n.graphSourceBudget!==void 0?{sourceFilesPerProject:h(n.graphSourceBudget,"--graph-source-budget",5e4)}:{}}),f=(l,m)=>{if(!l)return;let y=l.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!y)throw new Error(`${m} must be a byte size such as 500gb or 2tb.`);let w={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},g=Number(y[1])*w[y[2]||"b"];if(!Number.isSafeInteger(Math.floor(g))||g<=0)throw new Error(`${m} is outside the supported numeric range.`);return Math.floor(g)},v=()=>{let l=n.downloadTimeoutMs,m=l===void 0?void 0:Number.parseInt(l,10);if(m!==void 0&&(!Number.isFinite(m)||m<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:f(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:f(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:m,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},k=new Set(Object.values(Fr).flatMap(l=>[...l.flags])),E=new Set(process.argv.slice(2).filter(l=>l.startsWith("--")).map(l=>l.split("=",1)[0]).filter(l=>k.has(l))),S=Fr[t]?.flags,N=S?[...E].filter(l=>!S.includes(l)):[];if(N.length>0){let l=`${N.join(", ")} ${N.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||E.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:l,exitCode:2,context:{action:t,unsupportedFlags:N,allowedFlags:S}}),null,2)):(console.log(s.red(`\u274C ${l}`)),console.log(s.gray(` Allowed flags: ${S.join(", ")||"none"}`))),process.exit(2);}if((ll(t)||t==="trace"||t==="feedback"||t==="mcp")&&c$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:l}=await import('./workspace-B33BFZZ3.js');await l({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let l=a("intelligence"),{runWorkspaceIntelligenceChain:m}=await import('./workspace-intelligence-runner-6ZAV6RO4.js'),y=await m({workspacePath:l,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(y,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${y.status}`));for(let w of y.stages)console.log(s.gray(` ${w.id}: ${w.status} \u2014 ${w.message}`));console.log(s.gray(` Evidence: ${y.artifactPath}`));}y.exitCode!==0&&process.exit(y.exitCode);}else if(t==="model"){let l=a("model"),{buildWorkspaceModelCached:m,buildWorkspaceModelIncremental:y,createWorkspaceModelBuildProvenance:w,writeWorkspaceModel:g}=await import('./workspace-model-GVXNLSQM.js'),C=n.incremental===true||i("--incremental"),x=n.cache===true||i("--cache")||C,R={workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:n.strict===true||i("--strict")},b,T;if(C){let O=await y(R);b=O.model,T=O.mode;}else {let O=await m({...R,cache:x});b=O.model,T=O.cache;}b={...b,build:w({mode:C?"incremental":x?"cache":"full",engineStatus:T})};let j;(n.write===true||i("--write"))&&(j=await g(b,l));let A=(n.strict===true||i("--strict"))&&b.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...b,...j?{outputPath:j}:{}},null,2)),A&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${b.workspace.name}`)),C?console.log(s.gray(` Build: ${T} (incremental)`)):x&&console.log(s.gray(` Cache: ${T}`)),console.log(s.gray(` Projects: ${b.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${b.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${b.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${b.identity.workspaceType}`)),console.log(s.gray(` Validation: ${b.validation?.status??"unknown"} (${b.validation?.errors??0} error, ${b.validation?.warnings??0} warning)`)),console.log(j?s.gray(` Written: ${j}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),A&&process.exit(1);}else if(t==="agent-sync"){let l=a("agent-sync"),{syncWorkspaceAgentGrounding:m,parseAgentGroundingTargets:y}=await import('./workspace-agent-sync-T3MJO2MX.js'),w=n.strict===true||i("--strict"),g=n.write===true||i("--write"),C=i("--dry-run"),x=await m({workspacePath:l,scope:n.scope,agent:n.forAgent,write:g&&!C,dryRun:C,strict:w,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:y(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(x,null,2));else {console.log(s.green(`\u2714 Agent grounding ${g&&!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=g&&!C?x.writtenFiles:x.skippedFiles;if(R.length>0&&console.log(s.gray(` Files: ${R.join(", ")}`)),x.strictViolations.length>0)for(let b of x.strictViolations)console.log(s.red(`\u274C ${b}`));}w&&x.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let l=e??"status",{approveWorkspaceRepair:m,cancelWorkspaceRepair:y,decideWorkspaceRepair:w,executeWorkspaceRepair:g,inspectWorkspaceRepairCapabilities:C,listWorkspaceRepairTransactions:x,planWorkspaceRepair:R,planWorkspaceRepairProposal:b,readWorkspaceRepairTransaction:T,rollbackWorkspaceRepair:j}=await import('./workspace-repair-engine-CKJCTWKX.js');if(l==="capabilities"){let U;if(n.workspace)U=a("repair capabilities");else try{let re=b$5({startPath:process.cwd(),strict:false})?.workspacePath;re&&Ye(re)&&(U=re);}catch{}let ae=await C(U?{workspacePath:U,project:n.project}:n.project?{project:n.project}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(ae,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${ae.adapters.length}`));for(let re of ae.adapters)console.log(s.gray(` ${re.id.padEnd(14)} ${re.support.padEnd(11)} ${re.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let A=a("repair"),O=n.transaction??(["plan","propose","capabilities"].includes(l)?void 0:r),J=()=>{if(!O?.trim())throw new Error(`workspace repair ${l} requires --transaction <id> (or the id as the next positional argument).`);return O.trim()},F;if(l==="plan"){let U=n.card??r;if(!U?.trim())throw new Error("workspace repair plan requires --card <id>.");F=await R({workspacePath:A,cardId:U.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="propose"){let U=n.proposal??r;if(!U?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let ae=P.resolve(A,U.trim()),re=P.relative(A,ae);if(re.startsWith("..")||P.isAbsolute(re))throw new Error("The repair proposal file must be inside the canonical workspace.");let he=await M__default.lstat(ae).catch(()=>{});if(!he?.isFile()||he.isSymbolicLink()||he.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");F=await b({workspacePath:A,proposal:await M__default.readJson(ae),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="approve")F=await m({workspacePath:A,transactionId:J(),approvedBy:n.approvedBy});else if(l==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");F=await w({workspacePath:A,transactionId:J(),decision:n.decision});}else if(l==="execute"||l==="resume")F=await g({workspacePath:A,transactionId:J()});else if(l==="status")F=await T({workspacePath:A,transactionId:J()});else if(l==="list")F=await x(A);else if(l==="rollback")F=await j({workspacePath:A,transactionId:J()});else if(l==="cancel")F=await y({workspacePath:A,transactionId:J()});else throw new Error(`Unknown workspace repair action: ${l}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let H=P.join(A,e$2.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$6(`workspace repair ${l}`,F,H),null,2));else if(Array.isArray(F)){console.log(s.green(`\u2714 Workspace repair transactions: ${F.length}`));for(let U of F.slice(0,20))console.log(s.gray(` ${U.transactionId} \xB7 ${U.target.cardId} \xB7 ${U.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${F.state}`)),console.log(s.gray(` Transaction: ${F.transactionId}`)),console.log(s.gray(` Target: ${F.target.cardId}`));for(let U of F.stages)console.log(s.gray(` ${U.status.padEnd(8)} ${U.kind}: ${U.summary}`));F.decision&&console.log(s.yellow(` Decision: ${F.decision.reason}`)),console.log(s.gray(` Evidence: ${e$2.repairTransaction}`));}Array.isArray(F)||(F.state==="decision-required"&&process.exit(2),(F.state==="rolled-back"||F.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let l=a("remediation-plan"),{buildArtifactRemediationPlan:m,writeArtifactRemediationPlan:y}=await import('./artifact-remediation-plan-I7IKC5MR.js'),w=await m({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),g;if((n.write===true||i("--write"))&&(g=await y(w,l)),n.json===true||i("--json")){console.log(JSON.stringify(b$6("workspace remediation-plan",w,g),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${w.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${w.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${w.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${w.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${w.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${w.summary.risk.safe}, guarded=${w.summary.risk.guarded}, invasive=${w.summary.risk.invasive}`));for(let C of w.actions.slice(0,8))console.log(s.gray(` \u2022 ${C.cardId}: ${C.title} (${C.mode}, ${C.risk})`));w.actions.length>8&&console.log(s.gray(` \u2026 ${w.actions.length-8} more action(s)`)),console.log(g?s.gray(` Written: ${g}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let l=a("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:m,writeWorkspaceAgentContext:y}=await import('./workspace-context-KOCEP4MJ.js'),w=n.strict===true||i("--strict"),g=await m({workspacePath:l,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:false}),C,x;if((n.write===true||i("--write"))&&(C=await y(g,l),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:T,parseAgentGroundingTargets:j}=await import('./workspace-agent-sync-T3MJO2MX.js');if(x=await T({workspacePath:l,scope:n.scope,agent:g.agent,write:true,refreshContext:false,strict:w,preset:n.preset==="minimal"?"minimal":"enterprise",targets:j(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${x.writtenFiles.length} file(s) updated`)),w&&x.strictViolations.length>0){for(let A of x.strictViolations)console.log(s.red(`\u274C ${A}`));process.exit(1);}}let R=w&&g.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...g,...C?{outputPath:C}:{},...x?{agentGroundingSync:x}:{}},null,2)),R&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${g.workspace.name}`)),console.log(s.gray(` Agent: ${g.agent}`)),console.log(s.gray(` Scope: ${g.scope.activeProject??g.scope.requested}`)),console.log(s.gray(` Projects included: ${g.projects.length}`)),console.log(s.gray(` Safe commands: ${g.safeCommands.length}`)),console.log(s.gray(` Validation: ${g.validation.status} (${g.validation.errors} error, ${g.validation.warnings} warning)`)),console.log(C?s.gray(` Written: ${C}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),R){for(let b of g.validation.issues)console.log(s.red(`\u274C ${b.severity}:${b.code}:${b.target}`));process.exit(1);}}else if(t==="snapshot"){let l=a("snapshot"),{buildWorkspaceModelSnapshot:m,writeWorkspaceModelSnapshot:y}=await import('./workspace-intelligence-TFEQBPUP.js'),w=await m({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),g=await y(w,l);if(n.json){console.log(JSON.stringify(b$6("workspace snapshot",w,g),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${w.model.workspace.name}`)),console.log(s.gray(` Hash: ${w.modelHash}`)),console.log(s.gray(` Projects: ${w.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${w.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${g}`));}else if(t==="diff"){let l=a("diff"),m=n.from||e;m||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:y,writeWorkspaceModelDiff:w}=await import('./workspace-intelligence-TFEQBPUP.js'),g;try{g=await y({workspacePath:l,fromPath:m,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:m},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 w(g,l);if(n.json){console.log(JSON.stringify(b$6("workspace diff",g,C),null,2));return}let x=g.summary.changed?s.yellow:s.green;console.log(x(`\u2714 Workspace model diff: ${g.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Added projects: ${g.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${g.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${g.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${g.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${g.summary.validationChanges}`)),g.git?.available&&console.log(s.gray(` Git: ${g.git.dirty?"dirty":"clean"} (${g.summary.gitChangedFiles} mapped change(s))`));for(let R of g.changes.slice(0,12))console.log(s.gray(` \u2022 ${R.type} ${R.target}: ${R.message}`));g.changes.length>12&&console.log(s.gray(` \u2026 ${g.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${C}`));}else if(t==="impact"){let l=a("impact"),m=n.from||e;m||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:y,writeWorkspaceImpact:w}=await import('./workspace-intelligence-TFEQBPUP.js'),g;try{g=await y({workspacePath:l,fromPath:m,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:m},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 w(g,l);if(n.json){console.log(JSON.stringify(b$6("workspace impact",g,C),null,2));return}let x=g.summary.risk==="critical"||g.summary.risk==="high"?s.red:g.summary.risk==="medium"?s.yellow:s.green;console.log(x(`\u2714 Workspace impact: ${g.summary.risk}`)),console.log(s.gray(` From: ${g.fromRef}`)),console.log(s.gray(` Affected projects: ${g.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${g.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${g.summary.recommendedCommands}`));for(let R of g.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${R.title}: ${R.summary}`));g.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${g.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${C}`));}else if(t==="verify"){let l=a("verify"),{buildWorkspaceVerify:m,writeWorkspaceVerify:y,evaluateWorkspaceVerifyGate:w}=await import('./workspace-verify-D3QTMAUI.js'),g=await m({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),C=await y(g,l),x=w(g,{strict:n.strict===true||i("--strict")}),R=x.exitCode,{recordWorkspaceHistory:b,historyEntryFromVerify:T}=await import('./workspace-history-7HDZZ4G5.js');if(await b(l,T(g,x.passed)),n.json){console.log(JSON.stringify(b$6("workspace verify",{...g,gate:x},C,R),null,2)),R!==0&&process.exit(R);return}let j=g.summary.verdict==="ready"?s.green:g.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(j(`\u2714 Workspace verify: ${g.summary.verdict}`)),console.log(s.gray(` Freshness: ${g.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${g.impact.risk}`)),console.log(s.gray(` Steps: ${g.steps.length}`)),console.log(s.gray(` Passed ${g.summary.stepsPassed}, warn ${g.summary.stepsWarn}, failed ${g.summary.stepsFailed}, missing ${g.summary.stepsMissing}`));for(let A of g.steps.slice(0,10))console.log(s.gray(` \u2022 ${A.id}: ${A.status} \u2014 ${A.message}`));if(g.steps.length>10&&console.log(s.gray(` \u2026 ${g.steps.length-10} more step(s)`)),g.policyViolations.length>0){console.log(s.gray(` Policy (${g.policyMode}): ${g.policyViolations.length} violation(s)`));for(let A of g.policyViolations.slice(0,5)){let O=A.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${O} [${A.source}] ${A.code}: ${A.message}`);}}console.log(s.gray(` Gate (${x.mode}): ${x.passed?"passed":"blocked"}`));for(let A of x.reasons.slice(0,5))console.log(s.red(` \u2717 ${A}`));console.log(s.gray(` Written: ${C}`)),R!==0&&process.exit(R);}else if(t==="graph"){let l=a("graph"),{buildWorkspaceModel:m,workspaceModelProjectTopology:y}=await import('./workspace-model-GVXNLSQM.js'),{buildGraphEmit:w,renderGraphDot:g,renderGraphMermaid:C,explainGraphNode:x}=await import('./workspace-graph-2A5THUCI.js'),R=(e||"emit").toLowerCase(),b=["emit","dot","mermaid","jsonld","graphml","gexf","explain","entities","search","benchmark","benchmark-suite","evidence","path","overlay"];if(!b.includes(R)){let D=`Unknown workspace graph mode '${R}'.`;n.json?console.log(JSON.stringify(c$1({operation:`workspace graph ${R}`,code:"workspace.graph.mode.unsupported",message:D,exitCode:2,context:{mode:R,supportedModes:b},examples:["workspai workspace graph emit --json"]}),null,2)):(console.log(s.red(`\u274C ${D}`)),console.log(s.gray(` Supported: ${b.join(", ")}`))),process.exit(2);}let T=new Set(["benchmark","benchmark-suite","entities","evidence","path","search"]),j=n.refreshGraph===true||i("--refresh-graph"),A=T.has(R)&&!j?await(await import('./workspace-knowledge-graph-snapshot-GPBDAKAU.js')).readWorkspaceKnowledgeGraphSnapshot(l):null,O=A?.status==="hit"?A.graph:null,J=A?.status==="hit"?A.model:await m({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),F=y(J);F||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:R,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let H=async()=>{if(O)return O;let{buildWorkspaceKnowledgeGraph:D}=await import('./workspace-knowledge-graph-AUXYL3L6.js'),{hashWorkspaceModel:G}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:oe}=await import('./workspace-contract-MQ3QE52V.js'),Z=null;try{Z=(await oe({workspacePath:l})).contract;}catch{}return D({...u(),workspacePath:l,workspace:{name:J.workspace.name,...J.workspace.profile?{profile:J.workspace.profile}:{}},projects:J.projects.map(B=>({id:B.name,path:B.path,...B.absolutePath?{absolutePath:B.absolutePath}:{},runtime:B.runtime,runtimeCandidates:B.runtimeCandidates,framework:B.framework,kind:B.kind,category:B.category,...B.governance?{governance:B.governance}:{},...B.kit?{kit:B.kit}:{}})),projectTopology:F,contract:Z,now:new Date(J.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:G(J)}})};if(R==="dot"||R==="mermaid"){let D=R==="dot"?g(F):C(F),G=p();if(G){let oe=P.resolve(l,G);await M__default.outputFile(oe,`${D}
394
394
  `,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${R}`,{format:R,nodeCount:F.stats.nodeCount,edgeCount:F.stats.edgeCount},oe),null,2)):(console.log(s.green(`\u2714 Workspace dependency graph exported as ${R}`)),console.log(s.gray(` Written: ${oe}`)));return}console.log(D);return}if(R==="jsonld"||R==="graphml"||R==="gexf"){let D=await H(),{renderWorkspaceKnowledgeGraphGexf:G,renderWorkspaceKnowledgeGraphGraphMl:oe,renderWorkspaceKnowledgeGraphJsonLd:Z}=await import('./workspace-knowledge-graph-export-UYAYFTWX.js'),B=R==="jsonld"?Z(D):R==="graphml"?oe(D):G(D),ue=p();if(ue){let Q=P.resolve(l,ue);await M__default.outputFile(Q,`${B}
395
- `,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${R}`,{format:R,entityCount:D.entities.length,relationCount:D.relations.length,proofCount:D.proofs.length},Q),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${R}`)),console.log(s.gray(` Written: ${Q}`)));return}console.log(B);return}if(R==="explain"){let D=(n.scope?.replace(/^project:/,"")||r||"").trim();D||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let G=x(F,D);if(n.json){console.log(JSON.stringify(G,null,2)),G.found||process.exit(1);return}G.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${D}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${G.project}`)),G.centrality&&console.log(s.gray(` Centrality: fanIn ${G.centrality.fanIn}, fanOut ${G.centrality.fanOut}, reach ${G.centrality.reach}, betweenness ${G.centrality.betweenness}${G.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${G.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${G.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${G.transitiveDependents.length}`));for(let oe of G.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${oe.id} (d${oe.distance}, via ${oe.via??"\u2014"})`));return}if(R==="entities"){let D=await H(),{queryKnowledgeEntities:G}=await import('./workspace-knowledge-graph-query-DXA4CROE.js'),oe=(r||n.kind||"").trim()||void 0;if(oe){let{WORKSPACE_KNOWLEDGE_ENTITY_KINDS:V}=await import('./workspace-knowledge-graph-contract-X52KXBXJ.js');V.includes(oe)||(console.log(s.red(`\u274C Unknown graph entity kind: ${oe}`)),console.log(s.gray(` Supported: ${V.join(", ")}`)),process.exit(1));}let Z=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,B=G(D,oe,Z),ue=n.limit??c("--limit"),Q=ue===void 0?void 0:Number.parseInt(ue,10);Q!==void 0&&(!Number.isFinite(Q)||Q<1||Q>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let _=Q===void 0?B:B.slice(0,Q);if(n.json){console.log(JSON.stringify({schemaVersion:D.schemaVersion,generatedAt:D.generatedAt,kind:oe??null,...Z?{projectId:Z}:{},count:_.length,totalMatches:B.length,truncated:_.length<B.length,entities:_},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${oe?`: ${oe}`:""}`)),console.log(s.gray(` Count: ${_.length}/${B.length}${_.length<B.length?" (bounded)":""}`));for(let V of _)console.log(s.gray(` \u2022 ${V.kind}: ${V.label} [${V.id}]`));return}if(R==="benchmark-suite"){let D=(r||"agent-core.v1").trim(),{WORKSPACE_INTELLIGENCE_BENCHMARK_REPORT_PATH:G,WORKSPACE_INTELLIGENCE_BENCHMARK_SUITES:oe,buildWorkspaceIntelligenceBenchmark:Z,writeWorkspaceIntelligenceBenchmark:B}=await import('./workspace-intelligence-benchmark-SRDIHX3X.js');D in oe||(console.log(s.red(`\u274C Unknown benchmark suite: ${D}`)),console.log(s.gray(` Supported: ${Object.keys(oe).join(", ")}`)),process.exit(2));let ue=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(ue)||ue<1||ue>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let Q=await H(),_=await Z({workspacePath:l,graph:Q,suite:D,limit:ue,...n.from?{baselineEvaluationPath:n.from}:{}}),K=n.write===true||i("--write")||!!p()?await B(l,_,p()??G):void 0;if(n.json){console.log(JSON.stringify(b$6("workspace graph benchmark-suite",_,K),null,2));return}console.log(s.green(`\u2714 Workspace Intelligence benchmark: ${_.suite.title}`)),console.log(s.gray(` Scenarios: ${_.retrievalSummary.matchedScenarioCount}/${_.retrievalSummary.scenarioCount} matched \xB7 ${_.retrievalSummary.status}`)),console.log(s.gray(` Median estimated retrieval: ${_.retrievalSummary.medianRetrievalEstimatedTokens} tokens \xB7 p95 ${_.retrievalSummary.p95RetrievalEstimatedTokens}`)),console.log(s.gray(` Median estimated payload reduction: ${_.retrievalSummary.medianEstimatedReductionPercent}%`)),console.log(s.gray(` Model evaluation: ${_.evaluation.availability} (${_.evaluation.provenance})`)),console.log(s.yellow(` ${_.methodology.claimBoundary}`)),K&&console.log(s.gray(` Written: ${K}`));return}if(R==="search"||R==="benchmark"){let D=(r||"").trim();D||(console.log(s.red(`\u274C workspace graph ${R} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${R} "authentication endpoint" --json`)),process.exit(1));let G=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(G)||G<1||G>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let oe=await H();if(R==="benchmark"){let _=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,{buildWorkspaceGraphTokenEfficiencyReport:V}=await import('./workspace-graph-token-efficiency-NPECU6Y5.js'),K=await V({workspacePath:l,graph:oe,query:D,limit:G,..._?{projectId:_}:{}});n.json?console.log(JSON.stringify(K,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${D}`)),console.log(s.gray(` Estimated tokens: ${K.corpus.estimatedTokens} corpus \u2192 ${K.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${K.savings.reductionRatio}\xD7 (${K.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${K.retrieval.matchCount}`)),console.log(s.yellow(` ${K.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:Z}=await import('./workspace-knowledge-graph-query-DXA4CROE.js'),B=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,ue=n.kind?String(n.kind).trim():void 0;if(ue){let{WORKSPACE_KNOWLEDGE_ENTITY_KINDS:_}=await import('./workspace-knowledge-graph-contract-X52KXBXJ.js');_.includes(ue)||(console.log(s.red(`\u274C Unknown graph entity kind: ${ue}`)),console.log(s.gray(` Supported: ${_.join(", ")}`)),process.exit(1));}let Q=Z(oe,{query:D,limit:G,...ue?{kind:ue}:{},...B?{projectId:B}:{},projection:"agent"});if(n.json)console.log(JSON.stringify(Q,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${D}`)),console.log(s.gray(` ${Q.entities.length}/${Q.totalMatches} match(es)${Q.truncated?" (bounded)":""}`));for(let _ of Q.entities)console.log(s.gray(` \u2022 ${_.kind}: ${_.label} [${_.id}]`));}return}if(R==="evidence"){let D=(r||"").trim();D||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let G=await H(),{queryKnowledgeEvidence:oe}=await import('./workspace-knowledge-graph-query-DXA4CROE.js'),Z=oe(G,D);if(n.json)console.log(JSON.stringify(Z,null,2));else if(Z.found){console.log(s.green(`\u2714 Graph evidence: ${D}`));for(let B of Z.proofs)console.log(s.gray(` \u2022 ${B.artifact}${B.pointer?`#${B.pointer}`:""} [${B.provider}/${B.trust}/${B.confidence}]`));}else {console.log(s.red(Z.candidates.length>0?`\u274C Graph query is ambiguous: ${D}`:`\u274C Graph entity or relation not found: ${D}`));for(let B of Z.candidates.slice(0,10))console.log(s.gray(` \u2022 ${B}`));}Z.found||process.exit(1);return}if(R==="path"){let D=(r||"").trim(),G=(o||"").trim();(!D||!G)&&(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 oe=await H(),{queryKnowledgePath:Z}=await import('./workspace-knowledge-graph-query-DXA4CROE.js'),B=Z(oe,D,G);if(n.json)console.log(JSON.stringify(B,null,2));else if(B.found){console.log(s.green(`\u2714 Graph proof path: ${D} \u2192 ${G}`));for(let ue of B.hops)console.log(s.gray(` \u2022 ${ue.from} ${ue.direction==="forward"?"\u2192":"\u2190"} ${ue.to} [${ue.kind}]`));console.log(s.gray(` Proofs: ${B.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${D} and ${G}.`));B.found||process.exit(1);return}if(R==="overlay"){let D=(n.from||r||"").trim();D||(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 G=P.resolve(l,D),oe;try{oe=JSON.parse(await M__default.readFile(G,"utf8"));}catch(_e){console.log(s.red(`\u274C Could not read the base knowledge graph: ${_e instanceof Error?_e.message:String(_e)}`)),process.exit(1);}let Z=oe&&typeof oe=="object"?oe:{},B=Z.graph,ue=B&&typeof B=="object"?B:{},Q=Z.schemaVersion===f$2.knowledgeGraph?Z:Z.knowledgeGraph??ue.knowledgeGraph;(!Q||typeof Q!="object"||Q.schemaVersion!==f$2.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${f$2.knowledgeGraph} document.`)),process.exit(1));let _=await H(),{buildWorkspaceKnowledgeGraphChangeOverlay:V}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),K=V(Q,_);if(n.json){console.log(JSON.stringify(K,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${D}`)),console.log(s.gray(` Risk: ${K.summary.risk}`)),console.log(s.gray(` Entities: +${K.summary.entityAdds} -${K.summary.entityRemovals} ~${K.summary.entityChanges}`)),console.log(s.gray(` Relations: +${K.summary.relationAdds} -${K.summary.relationRemovals} ~${K.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${K.summary.proofAdds} -${K.summary.proofRemovals} ~${K.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${K.summary.impactedEntities} entities \xB7 ${K.summary.changedArtifacts} proof artifacts`));return}let U=w(F),{writeWorkspaceModel:ae}=await import('./workspace-model-R4ISKDB2.js');await ae(J,l,{refreshKnowledgeGraph:j});let re=await M__default.readJson(P.join(l,e$2.knowledgeGraph)),he={...U,knowledgeGraph:re},Ve=p();if(Ve){let D=P.resolve(l,Ve);await M__default.outputFile(D,`${JSON.stringify(he,null,2)}
396
- `,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace graph emit",{format:"json",nodeCount:F.stats.nodeCount,edgeCount:F.stats.edgeCount,entityCount:re.entities.length,relationCount:re.relations.length,proofCount:re.proofs.length},D),null,2)):(console.log(s.green("\u2714 Workspace graph artifact exported as JSON")),console.log(s.gray(` Written: ${D}`)));return}if(n.json){console.log(JSON.stringify(he,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${U.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${U.graph.stats.edgeCount} (inferred ${U.graph.stats.inferredEdges}, contract ${U.graph.stats.contractEdges}, manual ${U.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${U.integrity.ok?"ok":"issues"} (cycles ${U.integrity.stats.cycleCount}, dangling ${U.integrity.stats.danglingCount}, orphans ${U.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${U.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${re.quality.entityCount} entities \xB7 ${re.quality.relationCount} relations \xB7 ${re.quality.proofCount} proofs \xB7 ${re.providers.length} providers`));let Ke=(re.source.inputs?.scopes??[]).filter(D=>D.truncated),ve=re.quality.completeness;if(Ke.length>0?console.log(s.yellow(` Inventory: emergency-bounded \u2014 ${Ke.map(D=>`${D.kind}:${D.id} indexed ${D.fileCount}/${D.eligibleFileCountExact===false?"at-least-":""}${D.eligibleFileCount??D.fileCount} eligible files`).join(", ")}`)):console.log(s.gray(` Inventory: complete \u2014 ${ve?.inventory.indexedFiles??(re.source.inputs?.scopes??[]).reduce((D,G)=>D+G.fileCount,0)} eligible files indexed across ${ve?.inventory.scopeCount??(re.source.inputs?.scopes??[]).length} scope(s)`)),ve){let D=`${ve.providers.complete} complete \xB7 ${ve.providers.bounded} adaptive-bounded \xB7 ${ve.providers.notApplicable} not-applicable \xB7 ${ve.providers.failed} failed`;console.log(ve.status==="complete"?s.gray(` Provider coverage: ${D}`):s.yellow(` Provider coverage: ${D}`));}console.log(s.gray(" Query: workspace graph search <query> | entities [kind] | path <from> <to> | evidence <entity-or-relation> | overlay --from <graph.json>")),console.log(s.gray(" Render: workspace graph dot | mermaid | jsonld | graphml | gexf [--output <file>]"));}else if(t==="watch"){let l=a("watch"),{runWorkspaceWatch:m}=await import('./workspace-watch-RLBEJKXE.js'),y=n.once===true||i("--once"),w=n.graphStream===true||i("--graph-stream"),g=n.json===true||w,C=w?new(await import('./workspace-graph-stream-45JHE4MG.js')).WorkspaceGraphStreamPublisher({workspacePath:l}):null,x=new AbortController,R=()=>x.abort();process.once("SIGINT",R),process.once("SIGTERM",R),g||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await m({workspacePath:l,once:y,signal:x.signal,buildOptions:{workspacePath:l,observableScanDepth:d()},onProgress:b=>{g||console.error(s.gray(` ${b}`));},onModel:C?async b=>{let T=(await import('./workspace-model-R4ISKDB2.js')).workspaceModelProjectTopology(b);if(!T)return;let{buildWorkspaceKnowledgeGraph:j}=await import('./workspace-knowledge-graph-AKG5NUU6.js'),{readWorkspaceContract:A}=await import('./workspace-contract-JYHNEJPV.js'),O=null;try{O=(await A({workspacePath:l})).contract;}catch{}let J=await j({...u(),workspacePath:l,workspace:{name:b.workspace.name,...b.workspace.profile?{profile:b.workspace.profile}:{}},projects:b.projects.map(F=>({id:F.name,path:F.path,...F.absolutePath?{absolutePath:F.absolutePath}:{},runtime:F.runtime,runtimeCandidates:F.runtimeCandidates,framework:F.framework,...F.kit?{kit:F.kit}:{}})),projectTopology:T,contract:O,now:new Date(b.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(b)}});console.log(JSON.stringify(C.publish(b,J)));}:void 0,emit:b=>{if(w)return;if(g){console.log(JSON.stringify(b));return}if(b.kind==="ready"){console.log(s.gray(` Ready: ${b.graph.nodeCount} nodes, ${b.graph.edgeCount} edges (hash ${b.modelHash.slice(0,12)})`));return}if(b.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${b.error??"unknown error"}`));return}if(b.kind==="unchanged"){console.log(s.gray(` No structural change (${b.mode}, ${b.durationMs}ms)`));return}let T=[];b.changedProjects.length>0&&T.push(`changed: ${b.changedProjects.join(", ")}`),b.addedProjects.length>0&&T.push(`added: ${b.addedProjects.join(", ")}`),b.removedProjects.length>0&&T.push(`removed: ${b.removedProjects.join(", ")}`),b.graph.edgesAdded.length>0&&T.push(`+${b.graph.edgesAdded.length} edges`),b.graph.edgesRemoved.length>0&&T.push(`-${b.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${b.mode}, ${b.durationMs}ms): ${T.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R),!g&&!y&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=a("sync"),{syncWorkspaceProjects:m}=await import('./workspace-5W7FYGDQ.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${P.basename(l)}`));let y=await m(l,n.json===true);await Br(l,{silent:n.json===true});let{syncWorkspaceProjectLenses:w}=await import('./project-intelligence-lens-LQCN65P2.js'),g=await w({workspacePath:l,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:C}=await import('./workspace-registry-summary-STGUGROG.js'),x=await C(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:y,contractSynced:true,projectLenses:{synced:g.projects.length,skipped:g.skipped},registrySummary:x},null,2));}else if(t==="registry"){let l=a("registry"),m=e||"status";m!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${m}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:y,resolveWorkspaceRegisteredProjects:w}=await import('./workspace-registry-summary-STGUGROG.js'),g=await y(l);if(n.json){console.log(JSON.stringify(g,null,2));return}let C=await w(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${g.authority}`)),console.log(s.gray(` Projects: ${g.projectCount}`)),console.log(s.gray(` Summary: ${g.registrySummaryPath}`)),C.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=a("foundation"),m=e||"ensure";m!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${m}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:y}=await import('./workspace-foundation-VIB3PXNH.js'),w=await y(l,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(w,null,2));return}w.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${w.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=a("policy"),m=await Dm(l,e,r,o,n.json===true||i("--json"));m!==0&&process.exit(m);}else if(t==="contract"){let l=a("contract"),{buildWorkspaceContractGraph:m,readWorkspaceContract:y,syncWorkspaceContract:w,verifyWorkspaceContract:g,writeWorkspaceContract:C,WORKSPACE_CONTRACT_PATH:x}=await import('./workspace-contract-JYHNEJPV.js'),R=e||"inspect",b=p(),T=R==="graph"||R==="sync"?void 0:b;try{if(R==="init"){let j=await C({workspacePath:l,outputPath:T,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${j.contractPath}`)),console.log(s.gray(` Projects: ${j.contract.projects.length}`));return}if(R==="inspect"){let j=await y({workspacePath:l,contractPath:T});if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${j.contractPath}`)),console.log(s.gray(` Workspace: ${j.contract.workspace.name}`)),console.log(s.gray(` Projects: ${j.contract.projects.length}`)),console.log(s.gray(` Schema: v${j.contract.schemaVersion}`));return}if(R==="sync"){let j=await w({workspacePath:l,strict:n.strict===true||i("--strict")});if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Workspace contract synchronized: ${j.contractPath}`)),console.log(s.gray(` Projects: ${j.contract.projects.length}`)),console.log(s.gray(` Added: ${j.addedProjects.join(", ")||"none"}`)),console.log(s.gray(` Updated: ${j.updatedProjects.join(", ")||"none"}`));return}if(R==="verify"){let j=await g({workspacePath:l,contractPath:T,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:A}=await import('./workspace-contract-JYHNEJPV.js'),O=await A({workspacePath:l,result:j});if(n.json)console.log(JSON.stringify({...j,evidencePath:O},null,2));else {let J=j.status==="passed"?s.green:s.red;console.log(J(`\u2714 Workspace contract verification ${j.status}: ${j.contractPath}`)),console.log(s.gray(` Projects: ${j.projectCount}`));for(let F of j.checks){let H=F.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${H} ${F.id}: ${F.message}`));}for(let F of j.violations)console.log(s.gray(` Violation: ${F}`));}(j.status==="failed"||j.status!=="passed"&&n.strict)&&process.exit(1);return}if(R==="graph"){let j=await m({workspacePath:l,contractPath:T});if(b){let A=P.resolve(l,b);await M__default.outputFile(A,`${JSON.stringify(j,null,2)}
397
- `,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace contract graph",{projectCount:j.graph.summary.projectCount,relationshipEdges:j.graph.summary.relationshipEdges,entityCount:j.graph.summary.entityCount,knowledgeRelations:j.graph.summary.knowledgeRelations,proofCount:j.graph.summary.proofCount},A),null,2)):(console.log(s.green("\u2714 Workspace contract graph exported as JSON")),console.log(s.gray(` Written: ${A}`)));return}if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${j.contractPath}`)),console.log(s.gray(` Workspace: ${j.graph.workspace.name}`)),console.log(s.gray(` Projects: ${j.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${j.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${j.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${j.graph.summary.relationshipEdges} (${j.graph.summary.inferredEdges} inferred, ${j.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${j.graph.summary.connectedProjects}/${j.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(j.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(j.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${j.graph.summary.orphanProjects} \xB7 Hotspots: ${j.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${j.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${j.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${j.graph.summary.entityCount} entities \xB7 ${j.graph.summary.knowledgeRelations} relations \xB7 ${j.graph.summary.proofCount} proofs \xB7 ${j.graph.summary.providerCount} providers \xB7 ${j.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${j.graph.summary.portCount}`));for(let A of j.graph.nodes){let O=A.ports.map(F=>`${F.name}:${F.port}`).join(", ")||"none",J=A.operationalProfile?` risk=${A.operationalProfile.weight}/${A.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${A.id} (${A.runtime||"unknown"}${A.framework?`/${A.framework}`:""}) ports=${O} manifests=${A.files.manifests.length}${J}`));}for(let A of j.graph.edges){let O=A.type==="event"?`event:${A.label}`:A.label;console.log(s.gray(` ${A.from} -> ${A.to} [${O}]`));}if(j.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let A of j.graph.dependencyGraph.edges)console.log(s.gray(` ${A.from} -> ${A.to} [${A.kind}/${A.source}/${A.confidence}] evidence=${A.evidence.length}`));}for(let A of j.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${A.severity}: ${A.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${R}`)),console.log(s.white(` npx workspai workspace contract init|inspect|sync|verify|graph [--output ${x}]`)),process.exit(1);}catch(j){n.json&&(console.log(JSON.stringify({command:`workspace contract ${R}`,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${R}.failed`,message:j.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${R} failed: ${j.message}`)),process.exit(1);}}else if(t==="share"){let l=a("share"),m=p()||e,{createWorkspaceShareBundle:y}=await import('./workspace-5W7FYGDQ.js'),w=await y(l,{outputPath:m,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:l,bundlePath:w,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: ${w}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=a("export");try{let{exportWorkspaceArchive:m}=await import('./workspace-archive-NOSGRKRZ.js'),y=n.archiveCompression?.trim().toLowerCase()??"store";if(y!=="store"&&y!=="deflate")throw new Error("--archive-compression must be store or deflate.");let w=await m({workspacePath:l,outputPath:p()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:y});if(n.json){console.log(JSON.stringify(w,null,2));return}let g=(w.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${w.archivePath}`)),console.log(s.gray(` Files: ${w.manifest.files.length}`)),console.log(s.gray(` Size: ${g} MB`)),w.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(m){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:m.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${m.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let l=r;l||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:m,inspectWorkspaceArchive:y,verifyWorkspaceArchive:w}=await import('./workspace-archive-NOSGRKRZ.js');try{if(e==="inspect"){let C=await y({archivePathOrUrl:l,safety:v()});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 m({archivePathOrUrl:l,strict:n.strict===true||i("--strict"),safety:v()});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 b=R.status==="passed"?"\u2714":R.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${b} ${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 g=await w({archivePathOrUrl:l,requireChecksums:n.strict===true||i("--strict"),safety:v()});if(n.json)console.log(JSON.stringify(g,null,2));else if(g.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${g.archivePath}`)),console.log(s.gray(` Files: ${g.verifiedFiles}/${g.fileCount}`));else {let C=g.status==="failed"?s.red:s.yellow;console.log(C(`\u274C Workspace archive verification ${g.status}: ${g.archivePath}`)),g.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${g.missingArchiveEntries.join(", ")}`)),g.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${g.extraArchiveEntries.join(", ")}`)),g.mismatches.length&&console.log(s.gray(` Mismatches: ${g.mismatches.map(x=>x.path).join(", ")}`)),g.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${g.missingChecksumFiles.join(", ")}`));}(g.status==="failed"||g.status==="warning"&&n.strict)&&process.exit(1);}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,error:{code:`workspace.archive.${e}.failed`,message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${g.message}`)),process.exit(1);}}else if(t==="connect"){let l=P.resolve(e||process.cwd());try{let m=await Ps({workspacePath:l,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.status==="preview"?`\u2714 Workspace connection preview: ${l}`:`\u2714 Workspace connected: ${l}`));for(let y of m.warnings)console.log(s.yellow(` \u26A0 ${y}`));}catch(m){let y=m instanceof Error?m.message:String(m);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:y}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${y}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let m=await bs({archivePathOrUrl:l,outputPath:p(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:v()});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.status==="preview"?`\u2714 Workspace import preview: ${m.workspacePath}`:`\u2714 Workspace imported and registered: ${m.workspacePath}`));for(let y of m.warnings)console.log(s.yellow(` \u26A0 ${y}`));}else {let{hydrateWorkspaceArchive:m}=await import('./workspace-archive-NOSGRKRZ.js'),y=await m({archivePathOrUrl:l,outputPath:p(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:v()});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(y.dryRun?`\u2714 Workspace archive hydrate preview: ${y.outputPath}`:`\u2714 Workspace archive hydrated: ${y.outputPath}`)),console.log(s.gray(` Files: ${y.files.length}`)),y.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${y.manifest.workspaceName}`));}}catch(m){let y=m instanceof Error?m.message:String(m);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:y,context:{archivePathOrUrl:l,...p()?{outputPath:p()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,...p()?{outputPath:p()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:y}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${y}`)),process.exit(1);}}else if(t==="run"){let l=a(`run ${e||""}`.trim()),m=new Set(["init","test","build","start"]),y=e?.trim()??"";y||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .workspai/context.json commands")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2)),m.has(y)||(!/^[a-z][a-z0-9_-]*$/i.test(y)||y==="dev"||y==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${y}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),y==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let w=Os({raw:n.maxWorkers,operation:`workspace run ${y}`,json:n.json===true||i("--json")});if(y==="init"&&n.json!==true){let x=await Fs(l);x!==0&&process.exit(x);}let{runWorkspaceStage:g}=await import('./workspace-run-GFBFGUFM.js'),C=await g({workspacePath:l,stage:y,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:w,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true,planOnly:n.plan===true,runtime:n.runtime});n.json&&console.log(JSON.stringify(C,null,2)),C.summary.exitCode!==0&&process.exit(C.summary.exitCode);}else if(t==="explain"||t==="why"){let l=a(t),{parseWorkspaceExplainTarget:m}=await import('./workspace-explain-contract-WMREJWHF.js'),{buildWorkspaceExplain:y,writeWorkspaceExplainReport:w}=await import('./workspace-explain-SUBK6FLO.js'),g=(e??r??"").trim();!g&&n.scope&&(g=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),g||(g="release-blocked");let C=m(g);C||(console.log(s.red(`\u274C Invalid explain target: ${g}`)),process.exit(1));let x=await y({workspacePath:l,target:C}),R=n.write===true||i("--write"),b;if(R&&(b=await w(x,l,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$6(`workspace ${t}`,x,b),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${x.summary}`));for(let T of x.sections)console.log(s.bold(`
395
+ `,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${R}`,{format:R,entityCount:D.entities.length,relationCount:D.relations.length,proofCount:D.proofs.length},Q),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${R}`)),console.log(s.gray(` Written: ${Q}`)));return}console.log(B);return}if(R==="explain"){let D=(n.scope?.replace(/^project:/,"")||r||"").trim();D||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let G=x(F,D);if(n.json){console.log(JSON.stringify(G,null,2)),G.found||process.exit(1);return}G.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${D}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${G.project}`)),G.centrality&&console.log(s.gray(` Centrality: fanIn ${G.centrality.fanIn}, fanOut ${G.centrality.fanOut}, reach ${G.centrality.reach}, betweenness ${G.centrality.betweenness}${G.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${G.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${G.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${G.transitiveDependents.length}`));for(let oe of G.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${oe.id} (d${oe.distance}, via ${oe.via??"\u2014"})`));return}if(R==="entities"){let D=await H(),{queryKnowledgeEntities:G}=await import('./workspace-knowledge-graph-query-A7TKONWY.js'),oe=(r||n.kind||"").trim()||void 0;if(oe){let{WORKSPACE_KNOWLEDGE_ENTITY_KINDS:V}=await import('./workspace-knowledge-graph-contract-X52KXBXJ.js');V.includes(oe)||(console.log(s.red(`\u274C Unknown graph entity kind: ${oe}`)),console.log(s.gray(` Supported: ${V.join(", ")}`)),process.exit(1));}let Z=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,B=G(D,oe,Z),ue=n.limit??c("--limit"),Q=ue===void 0?void 0:Number.parseInt(ue,10);Q!==void 0&&(!Number.isFinite(Q)||Q<1||Q>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let _=Q===void 0?B:B.slice(0,Q);if(n.json){console.log(JSON.stringify({schemaVersion:D.schemaVersion,generatedAt:D.generatedAt,kind:oe??null,...Z?{projectId:Z}:{},count:_.length,totalMatches:B.length,truncated:_.length<B.length,entities:_},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${oe?`: ${oe}`:""}`)),console.log(s.gray(` Count: ${_.length}/${B.length}${_.length<B.length?" (bounded)":""}`));for(let V of _)console.log(s.gray(` \u2022 ${V.kind}: ${V.label} [${V.id}]`));return}if(R==="benchmark-suite"){let D=(r||"agent-core.v1").trim(),{WORKSPACE_INTELLIGENCE_BENCHMARK_REPORT_PATH:G,WORKSPACE_INTELLIGENCE_BENCHMARK_SUITES:oe,buildWorkspaceIntelligenceBenchmark:Z,writeWorkspaceIntelligenceBenchmark:B}=await import('./workspace-intelligence-benchmark-PLVUBGWO.js');D in oe||(console.log(s.red(`\u274C Unknown benchmark suite: ${D}`)),console.log(s.gray(` Supported: ${Object.keys(oe).join(", ")}`)),process.exit(2));let ue=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(ue)||ue<1||ue>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let Q=await H(),_=await Z({workspacePath:l,graph:Q,suite:D,limit:ue,...n.from?{baselineEvaluationPath:n.from}:{}}),K=n.write===true||i("--write")||!!p()?await B(l,_,p()??G):void 0;if(n.json){console.log(JSON.stringify(b$6("workspace graph benchmark-suite",_,K),null,2));return}console.log(s.green(`\u2714 Workspace Intelligence benchmark: ${_.suite.title}`)),console.log(s.gray(` Scenarios: ${_.retrievalSummary.matchedScenarioCount}/${_.retrievalSummary.scenarioCount} matched \xB7 ${_.retrievalSummary.status}`)),console.log(s.gray(` Median estimated retrieval: ${_.retrievalSummary.medianRetrievalEstimatedTokens} tokens \xB7 p95 ${_.retrievalSummary.p95RetrievalEstimatedTokens}`)),console.log(s.gray(` Median estimated payload reduction: ${_.retrievalSummary.medianEstimatedReductionPercent}%`)),console.log(s.gray(` Model evaluation: ${_.evaluation.availability} (${_.evaluation.provenance})`)),console.log(s.yellow(` ${_.methodology.claimBoundary}`)),K&&console.log(s.gray(` Written: ${K}`));return}if(R==="search"||R==="benchmark"){let D=(r||"").trim();D||(console.log(s.red(`\u274C workspace graph ${R} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${R} "authentication endpoint" --json`)),process.exit(1));let G=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(G)||G<1||G>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let oe=await H();if(R==="benchmark"){let _=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,{buildWorkspaceGraphTokenEfficiencyReport:V}=await import('./workspace-graph-token-efficiency-5LJKQU2J.js'),K=await V({workspacePath:l,graph:oe,query:D,limit:G,..._?{projectId:_}:{}});n.json?console.log(JSON.stringify(K,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${D}`)),console.log(s.gray(` Estimated tokens: ${K.corpus.estimatedTokens} corpus \u2192 ${K.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${K.savings.reductionRatio}\xD7 (${K.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${K.retrieval.matchCount}`)),console.log(s.yellow(` ${K.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:Z}=await import('./workspace-knowledge-graph-query-A7TKONWY.js'),B=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,ue=n.kind?String(n.kind).trim():void 0;if(ue){let{WORKSPACE_KNOWLEDGE_ENTITY_KINDS:_}=await import('./workspace-knowledge-graph-contract-X52KXBXJ.js');_.includes(ue)||(console.log(s.red(`\u274C Unknown graph entity kind: ${ue}`)),console.log(s.gray(` Supported: ${_.join(", ")}`)),process.exit(1));}let Q=Z(oe,{query:D,limit:G,...ue?{kind:ue}:{},...B?{projectId:B}:{},projection:"agent"});if(n.json)console.log(JSON.stringify(Q,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${D}`)),console.log(s.gray(` ${Q.entities.length}/${Q.totalMatches} match(es)${Q.truncated?" (bounded)":""}`));for(let _ of Q.entities)console.log(s.gray(` \u2022 ${_.kind}: ${_.label} [${_.id}]`));}return}if(R==="evidence"){let D=(r||"").trim();D||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let G=await H(),{queryKnowledgeEvidence:oe}=await import('./workspace-knowledge-graph-query-A7TKONWY.js'),Z=oe(G,D);if(n.json)console.log(JSON.stringify(Z,null,2));else if(Z.found){console.log(s.green(`\u2714 Graph evidence: ${D}`));for(let B of Z.proofs)console.log(s.gray(` \u2022 ${B.artifact}${B.pointer?`#${B.pointer}`:""} [${B.provider}/${B.trust}/${B.confidence}]`));}else {console.log(s.red(Z.candidates.length>0?`\u274C Graph query is ambiguous: ${D}`:`\u274C Graph entity or relation not found: ${D}`));for(let B of Z.candidates.slice(0,10))console.log(s.gray(` \u2022 ${B}`));}Z.found||process.exit(1);return}if(R==="path"){let D=(r||"").trim(),G=(o||"").trim();(!D||!G)&&(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 oe=await H(),{queryKnowledgePath:Z}=await import('./workspace-knowledge-graph-query-A7TKONWY.js'),B=Z(oe,D,G);if(n.json)console.log(JSON.stringify(B,null,2));else if(B.found){console.log(s.green(`\u2714 Graph proof path: ${D} \u2192 ${G}`));for(let ue of B.hops)console.log(s.gray(` \u2022 ${ue.from} ${ue.direction==="forward"?"\u2192":"\u2190"} ${ue.to} [${ue.kind}]`));console.log(s.gray(` Proofs: ${B.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${D} and ${G}.`));B.found||process.exit(1);return}if(R==="overlay"){let D=(n.from||r||"").trim();D||(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 G=P.resolve(l,D),oe;try{oe=JSON.parse(await M__default.readFile(G,"utf8"));}catch(_e){console.log(s.red(`\u274C Could not read the base knowledge graph: ${_e instanceof Error?_e.message:String(_e)}`)),process.exit(1);}let Z=oe&&typeof oe=="object"?oe:{},B=Z.graph,ue=B&&typeof B=="object"?B:{},Q=Z.schemaVersion===f$2.knowledgeGraph?Z:Z.knowledgeGraph??ue.knowledgeGraph;(!Q||typeof Q!="object"||Q.schemaVersion!==f$2.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${f$2.knowledgeGraph} document.`)),process.exit(1));let _=await H(),{buildWorkspaceKnowledgeGraphChangeOverlay:V}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),K=V(Q,_);if(n.json){console.log(JSON.stringify(K,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${D}`)),console.log(s.gray(` Risk: ${K.summary.risk}`)),console.log(s.gray(` Entities: +${K.summary.entityAdds} -${K.summary.entityRemovals} ~${K.summary.entityChanges}`)),console.log(s.gray(` Relations: +${K.summary.relationAdds} -${K.summary.relationRemovals} ~${K.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${K.summary.proofAdds} -${K.summary.proofRemovals} ~${K.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${K.summary.impactedEntities} entities \xB7 ${K.summary.changedArtifacts} proof artifacts`));return}let U=w(F),{writeWorkspaceModel:ae}=await import('./workspace-model-GVXNLSQM.js');await ae(J,l,{refreshKnowledgeGraph:j});let re=await M__default.readJson(P.join(l,e$2.knowledgeGraph)),he={...U,knowledgeGraph:re},Ve=p();if(Ve){let D=P.resolve(l,Ve);await M__default.outputFile(D,`${JSON.stringify(he,null,2)}
396
+ `,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace graph emit",{format:"json",nodeCount:F.stats.nodeCount,edgeCount:F.stats.edgeCount,entityCount:re.entities.length,relationCount:re.relations.length,proofCount:re.proofs.length},D),null,2)):(console.log(s.green("\u2714 Workspace graph artifact exported as JSON")),console.log(s.gray(` Written: ${D}`)));return}if(n.json){console.log(JSON.stringify(he,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${U.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${U.graph.stats.edgeCount} (inferred ${U.graph.stats.inferredEdges}, contract ${U.graph.stats.contractEdges}, manual ${U.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${U.integrity.ok?"ok":"issues"} (cycles ${U.integrity.stats.cycleCount}, dangling ${U.integrity.stats.danglingCount}, orphans ${U.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${U.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${re.quality.entityCount} entities \xB7 ${re.quality.relationCount} relations \xB7 ${re.quality.proofCount} proofs \xB7 ${re.providers.length} providers`));let Ke=(re.source.inputs?.scopes??[]).filter(D=>D.truncated),ve=re.quality.completeness;if(Ke.length>0?console.log(s.yellow(` Inventory: emergency-bounded \u2014 ${Ke.map(D=>`${D.kind}:${D.id} indexed ${D.fileCount}/${D.eligibleFileCountExact===false?"at-least-":""}${D.eligibleFileCount??D.fileCount} eligible files`).join(", ")}`)):console.log(s.gray(` Inventory: complete \u2014 ${ve?.inventory.indexedFiles??(re.source.inputs?.scopes??[]).reduce((D,G)=>D+G.fileCount,0)} eligible files indexed across ${ve?.inventory.scopeCount??(re.source.inputs?.scopes??[]).length} scope(s)`)),ve){let D=`${ve.providers.complete} complete \xB7 ${ve.providers.bounded} adaptive-bounded \xB7 ${ve.providers.notApplicable} not-applicable \xB7 ${ve.providers.failed} failed`;console.log(ve.status==="complete"?s.gray(` Provider coverage: ${D}`):s.yellow(` Provider coverage: ${D}`));}console.log(s.gray(" Query: workspace graph search <query> | entities [kind] | path <from> <to> | evidence <entity-or-relation> | overlay --from <graph.json>")),console.log(s.gray(" Render: workspace graph dot | mermaid | jsonld | graphml | gexf [--output <file>]"));}else if(t==="watch"){let l=a("watch"),{runWorkspaceWatch:m}=await import('./workspace-watch-XYJEW2Z2.js'),y=n.once===true||i("--once"),w=n.graphStream===true||i("--graph-stream"),g=n.json===true||w,C=w?new(await import('./workspace-graph-stream-XTGGBD7D.js')).WorkspaceGraphStreamPublisher({workspacePath:l}):null,x=new AbortController,R=()=>x.abort();process.once("SIGINT",R),process.once("SIGTERM",R),g||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await m({workspacePath:l,once:y,signal:x.signal,buildOptions:{workspacePath:l,observableScanDepth:d()},onProgress:b=>{g||console.error(s.gray(` ${b}`));},onModel:C?async b=>{let T=(await import('./workspace-model-GVXNLSQM.js')).workspaceModelProjectTopology(b);if(!T)return;let{buildWorkspaceKnowledgeGraph:j}=await import('./workspace-knowledge-graph-AUXYL3L6.js'),{readWorkspaceContract:A}=await import('./workspace-contract-MQ3QE52V.js'),O=null;try{O=(await A({workspacePath:l})).contract;}catch{}let J=await j({...u(),workspacePath:l,workspace:{name:b.workspace.name,...b.workspace.profile?{profile:b.workspace.profile}:{}},projects:b.projects.map(F=>({id:F.name,path:F.path,...F.absolutePath?{absolutePath:F.absolutePath}:{},runtime:F.runtime,runtimeCandidates:F.runtimeCandidates,framework:F.framework,...F.kit?{kit:F.kit}:{}})),projectTopology:T,contract:O,now:new Date(b.generatedAt),source:{kind:"workspace-model",artifact:e$2.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(b)}});console.log(JSON.stringify(C.publish(b,J)));}:void 0,emit:b=>{if(w)return;if(g){console.log(JSON.stringify(b));return}if(b.kind==="ready"){console.log(s.gray(` Ready: ${b.graph.nodeCount} nodes, ${b.graph.edgeCount} edges (hash ${b.modelHash.slice(0,12)})`));return}if(b.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${b.error??"unknown error"}`));return}if(b.kind==="unchanged"){console.log(s.gray(` No structural change (${b.mode}, ${b.durationMs}ms)`));return}let T=[];b.changedProjects.length>0&&T.push(`changed: ${b.changedProjects.join(", ")}`),b.addedProjects.length>0&&T.push(`added: ${b.addedProjects.join(", ")}`),b.removedProjects.length>0&&T.push(`removed: ${b.removedProjects.join(", ")}`),b.graph.edgesAdded.length>0&&T.push(`+${b.graph.edgesAdded.length} edges`),b.graph.edgesRemoved.length>0&&T.push(`-${b.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${b.mode}, ${b.durationMs}ms): ${T.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R),!g&&!y&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=a("sync"),{syncWorkspaceProjects:m}=await import('./workspace-B33BFZZ3.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${P.basename(l)}`));let y=await m(l,n.json===true);await Br(l,{silent:n.json===true});let{syncWorkspaceProjectLenses:w}=await import('./project-intelligence-lens-ZCCHUKVI.js'),g=await w({workspacePath:l,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:C}=await import('./workspace-registry-summary-5SFBTRGQ.js'),x=await C(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:y,contractSynced:true,projectLenses:{synced:g.projects.length,skipped:g.skipped},registrySummary:x},null,2));}else if(t==="registry"){let l=a("registry"),m=e||"status";m!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${m}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:y,resolveWorkspaceRegisteredProjects:w}=await import('./workspace-registry-summary-5SFBTRGQ.js'),g=await y(l);if(n.json){console.log(JSON.stringify(g,null,2));return}let C=await w(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${g.authority}`)),console.log(s.gray(` Projects: ${g.projectCount}`)),console.log(s.gray(` Summary: ${g.registrySummaryPath}`)),C.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=a("foundation"),m=e||"ensure";m!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${m}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:y}=await import('./workspace-foundation-O7O3QIS4.js'),w=await y(l,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(w,null,2));return}w.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${w.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=a("policy"),m=await Dm(l,e,r,o,n.json===true||i("--json"));m!==0&&process.exit(m);}else if(t==="contract"){let l=a("contract"),{buildWorkspaceContractGraph:m,readWorkspaceContract:y,syncWorkspaceContract:w,verifyWorkspaceContract:g,writeWorkspaceContract:C,WORKSPACE_CONTRACT_PATH:x}=await import('./workspace-contract-MQ3QE52V.js'),R=e||"inspect",b=p(),T=R==="graph"||R==="sync"?void 0:b;try{if(R==="init"){let j=await C({workspacePath:l,outputPath:T,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${j.contractPath}`)),console.log(s.gray(` Projects: ${j.contract.projects.length}`));return}if(R==="inspect"){let j=await y({workspacePath:l,contractPath:T});if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${j.contractPath}`)),console.log(s.gray(` Workspace: ${j.contract.workspace.name}`)),console.log(s.gray(` Projects: ${j.contract.projects.length}`)),console.log(s.gray(` Schema: v${j.contract.schemaVersion}`));return}if(R==="sync"){let j=await w({workspacePath:l,strict:n.strict===true||i("--strict")});if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Workspace contract synchronized: ${j.contractPath}`)),console.log(s.gray(` Projects: ${j.contract.projects.length}`)),console.log(s.gray(` Added: ${j.addedProjects.join(", ")||"none"}`)),console.log(s.gray(` Updated: ${j.updatedProjects.join(", ")||"none"}`));return}if(R==="verify"){let j=await g({workspacePath:l,contractPath:T,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:A}=await import('./workspace-contract-MQ3QE52V.js'),O=await A({workspacePath:l,result:j});if(n.json)console.log(JSON.stringify({...j,evidencePath:O},null,2));else {let J=j.status==="passed"?s.green:s.red;console.log(J(`\u2714 Workspace contract verification ${j.status}: ${j.contractPath}`)),console.log(s.gray(` Projects: ${j.projectCount}`));for(let F of j.checks){let H=F.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${H} ${F.id}: ${F.message}`));}for(let F of j.violations)console.log(s.gray(` Violation: ${F}`));}(j.status==="failed"||j.status!=="passed"&&n.strict)&&process.exit(1);return}if(R==="graph"){let j=await m({workspacePath:l,contractPath:T});if(b){let A=P.resolve(l,b);await M__default.outputFile(A,`${JSON.stringify(j,null,2)}
397
+ `,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace contract graph",{projectCount:j.graph.summary.projectCount,relationshipEdges:j.graph.summary.relationshipEdges,entityCount:j.graph.summary.entityCount,knowledgeRelations:j.graph.summary.knowledgeRelations,proofCount:j.graph.summary.proofCount},A),null,2)):(console.log(s.green("\u2714 Workspace contract graph exported as JSON")),console.log(s.gray(` Written: ${A}`)));return}if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${j.contractPath}`)),console.log(s.gray(` Workspace: ${j.graph.workspace.name}`)),console.log(s.gray(` Projects: ${j.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${j.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${j.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${j.graph.summary.relationshipEdges} (${j.graph.summary.inferredEdges} inferred, ${j.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${j.graph.summary.connectedProjects}/${j.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(j.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(j.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${j.graph.summary.orphanProjects} \xB7 Hotspots: ${j.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${j.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${j.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${j.graph.summary.entityCount} entities \xB7 ${j.graph.summary.knowledgeRelations} relations \xB7 ${j.graph.summary.proofCount} proofs \xB7 ${j.graph.summary.providerCount} providers \xB7 ${j.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${j.graph.summary.portCount}`));for(let A of j.graph.nodes){let O=A.ports.map(F=>`${F.name}:${F.port}`).join(", ")||"none",J=A.operationalProfile?` risk=${A.operationalProfile.weight}/${A.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${A.id} (${A.runtime||"unknown"}${A.framework?`/${A.framework}`:""}) ports=${O} manifests=${A.files.manifests.length}${J}`));}for(let A of j.graph.edges){let O=A.type==="event"?`event:${A.label}`:A.label;console.log(s.gray(` ${A.from} -> ${A.to} [${O}]`));}if(j.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let A of j.graph.dependencyGraph.edges)console.log(s.gray(` ${A.from} -> ${A.to} [${A.kind}/${A.source}/${A.confidence}] evidence=${A.evidence.length}`));}for(let A of j.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${A.severity}: ${A.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${R}`)),console.log(s.white(` npx workspai workspace contract init|inspect|sync|verify|graph [--output ${x}]`)),process.exit(1);}catch(j){n.json&&(console.log(JSON.stringify({command:`workspace contract ${R}`,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${R}.failed`,message:j.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${R} failed: ${j.message}`)),process.exit(1);}}else if(t==="share"){let l=a("share"),m=p()||e,{createWorkspaceShareBundle:y}=await import('./workspace-B33BFZZ3.js'),w=await y(l,{outputPath:m,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:l,bundlePath:w,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: ${w}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=a("export");try{let{exportWorkspaceArchive:m}=await import('./workspace-archive-NOSGRKRZ.js'),y=n.archiveCompression?.trim().toLowerCase()??"store";if(y!=="store"&&y!=="deflate")throw new Error("--archive-compression must be store or deflate.");let w=await m({workspacePath:l,outputPath:p()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:y});if(n.json){console.log(JSON.stringify(w,null,2));return}let g=(w.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${w.archivePath}`)),console.log(s.gray(` Files: ${w.manifest.files.length}`)),console.log(s.gray(` Size: ${g} MB`)),w.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(m){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:m.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${m.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let l=r;l||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:m,inspectWorkspaceArchive:y,verifyWorkspaceArchive:w}=await import('./workspace-archive-NOSGRKRZ.js');try{if(e==="inspect"){let C=await y({archivePathOrUrl:l,safety:v()});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 m({archivePathOrUrl:l,strict:n.strict===true||i("--strict"),safety:v()});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 b=R.status==="passed"?"\u2714":R.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${b} ${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 g=await w({archivePathOrUrl:l,requireChecksums:n.strict===true||i("--strict"),safety:v()});if(n.json)console.log(JSON.stringify(g,null,2));else if(g.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${g.archivePath}`)),console.log(s.gray(` Files: ${g.verifiedFiles}/${g.fileCount}`));else {let C=g.status==="failed"?s.red:s.yellow;console.log(C(`\u274C Workspace archive verification ${g.status}: ${g.archivePath}`)),g.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${g.missingArchiveEntries.join(", ")}`)),g.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${g.extraArchiveEntries.join(", ")}`)),g.mismatches.length&&console.log(s.gray(` Mismatches: ${g.mismatches.map(x=>x.path).join(", ")}`)),g.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${g.missingChecksumFiles.join(", ")}`));}(g.status==="failed"||g.status==="warning"&&n.strict)&&process.exit(1);}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,error:{code:`workspace.archive.${e}.failed`,message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${g.message}`)),process.exit(1);}}else if(t==="connect"){let l=P.resolve(e||process.cwd());try{let m=await Ps({workspacePath:l,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.status==="preview"?`\u2714 Workspace connection preview: ${l}`:`\u2714 Workspace connected: ${l}`));for(let y of m.warnings)console.log(s.yellow(` \u26A0 ${y}`));}catch(m){let y=m instanceof Error?m.message:String(m);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:y}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${y}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let m=await bs({archivePathOrUrl:l,outputPath:p(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:v()});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.status==="preview"?`\u2714 Workspace import preview: ${m.workspacePath}`:`\u2714 Workspace imported and registered: ${m.workspacePath}`));for(let y of m.warnings)console.log(s.yellow(` \u26A0 ${y}`));}else {let{hydrateWorkspaceArchive:m}=await import('./workspace-archive-NOSGRKRZ.js'),y=await m({archivePathOrUrl:l,outputPath:p(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:v()});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(y.dryRun?`\u2714 Workspace archive hydrate preview: ${y.outputPath}`:`\u2714 Workspace archive hydrated: ${y.outputPath}`)),console.log(s.gray(` Files: ${y.files.length}`)),y.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${y.manifest.workspaceName}`));}}catch(m){let y=m instanceof Error?m.message:String(m);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:y,context:{archivePathOrUrl:l,...p()?{outputPath:p()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,...p()?{outputPath:p()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:y}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${y}`)),process.exit(1);}}else if(t==="run"){let l=a(`run ${e||""}`.trim()),m=new Set(["init","test","build","start"]),y=e?.trim()??"";y||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .workspai/context.json commands")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2)),m.has(y)||(!/^[a-z][a-z0-9_-]*$/i.test(y)||y==="dev"||y==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${y}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),y==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let w=Os({raw:n.maxWorkers,operation:`workspace run ${y}`,json:n.json===true||i("--json")});if(y==="init"&&n.json!==true){let x=await Fs(l);x!==0&&process.exit(x);}let{runWorkspaceStage:g}=await import('./workspace-run-ZZ5WHL7W.js'),C=await g({workspacePath:l,stage:y,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:w,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true,planOnly:n.plan===true,runtime:n.runtime});n.json&&console.log(JSON.stringify(C,null,2)),C.summary.exitCode!==0&&process.exit(C.summary.exitCode);}else if(t==="explain"||t==="why"){let l=a(t),{parseWorkspaceExplainTarget:m}=await import('./workspace-explain-contract-WMREJWHF.js'),{buildWorkspaceExplain:y,writeWorkspaceExplainReport:w}=await import('./workspace-explain-DTFCKYXK.js'),g=(e??r??"").trim();!g&&n.scope&&(g=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),g||(g="release-blocked");let C=m(g);C||(console.log(s.red(`\u274C Invalid explain target: ${g}`)),process.exit(1));let x=await y({workspacePath:l,target:C}),R=n.write===true||i("--write"),b;if(R&&(b=await w(x,l,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$6(`workspace ${t}`,x,b),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${x.summary}`));for(let T of x.sections)console.log(s.bold(`
398
398
  ${T.title}`)),console.log(T.body);b&&console.log(s.gray(`
399
- Written: ${b}`));}else if(t==="trace"){let l=a("trace"),m=n.from||e;m||(console.log(s.red("\u274C workspace trace requires --from <diff-ref>")),console.log(s.gray(" npx workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{resolveWorkspaceTraceTarget:y}=await import('./workspace-explain-contract-WMREJWHF.js'),{buildWorkspaceExplain:w,writeWorkspaceExplainReport:g}=await import('./workspace-explain-SUBK6FLO.js'),C=y(m);(!C||C.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${m}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.workspai/reports/workspace-model-diff-last-run.json")),process.exit(1));let x=await w({workspacePath:l,target:C}),R=n.write===true||i("--write"),b;if(R&&(b=await g(x,l,"trace")),n.json){console.log(JSON.stringify(b$6("workspace trace",x,b),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${x.summary}`));for(let T of x.sections)console.log(s.bold(`
399
+ Written: ${b}`));}else if(t==="trace"){let l=a("trace"),m=n.from||e;m||(console.log(s.red("\u274C workspace trace requires --from <diff-ref>")),console.log(s.gray(" npx workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{resolveWorkspaceTraceTarget:y}=await import('./workspace-explain-contract-WMREJWHF.js'),{buildWorkspaceExplain:w,writeWorkspaceExplainReport:g}=await import('./workspace-explain-DTFCKYXK.js'),C=y(m);(!C||C.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${m}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.workspai/reports/workspace-model-diff-last-run.json")),process.exit(1));let x=await w({workspacePath:l,target:C}),R=n.write===true||i("--write"),b;if(R&&(b=await g(x,l,"trace")),n.json){console.log(JSON.stringify(b$6("workspace trace",x,b),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${x.summary}`));for(let T of x.sections)console.log(s.bold(`
400
400
  ${T.title}`)),console.log(T.body);b&&console.log(s.gray(`
401
401
  Written: ${b}`));}else if(t==="eval"){let l=a("eval"),m=(e||"status").toLowerCase(),{WORKSPACE_EVALUATION_LAST_RUN_PATH:y,WORKSPACE_EVALUATION_LIVE_PATH:w,appendWorkspaceEvaluationEvent:g,compareWorkspaceEvaluations:C,createWorkspaceEvaluation:x,finalizeWorkspaceEvaluation:R,readWorkspaceEvaluation:b,writeWorkspaceEvaluation:T}=await import('./workspace-intelligence-evaluation-OJIQS5SN.js');if(m==="init"){let j=(r||"").trim(),A=(o||"workspace-intelligence").trim(),O=["full-corpus","grep","vector","graph","workspace-intelligence","custom"];(!j||!O.includes(A))&&(console.log(s.red("\u274C workspace eval init requires <task> and an optional valid strategy.")),console.log(s.gray(` Strategies: ${O.join(" | ")}
402
- npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:J}=await import('./workspace-marker-XGAWZZDX.js'),F=await J(l),H=x({workspacePath:l,workspaceName:F?.name,taskId:j,strategy:A}),U=await T(l,H);if(n.json){console.log(JSON.stringify(b$6("workspace eval init",H,U),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${j}`)),console.log(s.gray(` Run: ${H.runId}`)),console.log(s.gray(` Strategy: ${H.configuration.strategy}`)),console.log(s.gray(` Live: ${U}`));return}if(m==="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:j,readStdinAll:A}=await import('./workspace-feedback-MWGCT5R2.js'),O=j(await A());O||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let J=await g({workspacePath:l,payload:O});console.log(JSON.stringify(J,null,2));}catch(J){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:J instanceof Error?J.message:String(J),context:{workspacePath:l}}),null,2)),process.exit(1);}return}if(m==="report"){let j=await R({workspacePath:l}),A=p(),O=j.outputPath;if(A){let J=P.resolve(l,A);P.resolve(j.outputPath)!==J&&await M__default.copy(j.outputPath,J,{overwrite:true}),O=J;}if(n.json){console.log(JSON.stringify(b$6("workspace eval report",j.report,O),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${j.report.runId}`)),console.log(s.gray(` Tokens: ${j.report.summary.tokens.observedTotal} \xB7 model calls ${j.report.summary.modelCalls} \xB7 tool calls ${j.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${j.report.summary.outcome.status}${j.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${O}`));return}if(m==="compare"){let j=(n.from||r||"").trim();j||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let A=await b(l,y),O=await b(l,j),J=C(A,O);if(n.json){console.log(JSON.stringify(J,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${J.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${J.delta.tokens}`)),console.log(s.gray(` Reduction: ${J.delta.reductionPercent===null?"unavailable":`${J.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${J.comparableOutcome?"yes":"no"}`));return}if(m==="status"){let j;try{j=await b(l,w);}catch{j=await b(l,y);}if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Evaluation ${j.status}: ${j.configuration.taskId}`)),console.log(s.gray(` Run: ${j.runId}`)),console.log(s.gray(` Events: ${j.events.length}`)),console.log(s.gray(` Tokens: ${j.summary.tokens.observedTotal} (${j.summary.tokenSources.providerReported} provider-reported calls, ${j.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${m}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let l=a("feedback"),m=(e||"record").toLowerCase();m!=="record"&&(console.log(s.red(`Unknown feedback action: ${m}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace feedback record requires --json (stdin payload)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace feedback record requires piped JSON on stdin (not a TTY)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:y,parseFeedbackStdinPayload:w,readStdinAll:g}=await import('./workspace-feedback-MWGCT5R2.js'),C=await g(),x=w(C);x||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let R=await y({workspacePath:l,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==="goal"){let l=a("goal"),m=(e||"status").toLowerCase(),y=r?.trim(),{planVerifiedGoal:w,readVerifiedGoal:g,verifyVerifiedGoal:C,VERIFIED_GOAL_SCHEMA_VERSION:x}=await import('./verified-goal-HN7G532B.js'),R=b=>{if(n.json){console.log(JSON.stringify(b,null,2));return}let T=b.goal;console.log(b.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(b.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),T&&console.log(s.bold(` ${T.summary}`)),console.log(s.gray(` Goal: ${b.status.goalId}`)),console.log(s.gray(` Progress: ${b.status.progress.message}`)),console.log(s.gray(` State: ${b.status.state}`)),b.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${b.status.blockingReasons[0]}`)),b.status.nextActions.length>0&&console.log(s.gray(` Next: ${b.status.nextActions[0]}`)),console.log(s.gray(` Status: ${b.status.artifactPath}`));};if(m==="plan"){if(!y||!["release-readiness","dependency-security","test-coverage"].includes(y)){let J="Goal kind must be release-readiness, dependency-security, or test-coverage.";n.json?console.log(JSON.stringify(c$1({operation:"workspace goal plan",code:"workspace.goal.kind.invalid",message:J}),null,2)):console.log(s.red(`\u274C ${J}`)),process.exit(1);}let T=Number(n.target??80);if(!Number.isFinite(T)||T<0||T>100)throw new Error("--target must be a number from 0 to 100.");let j=["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"],A=n.runtime;if(y==="test-coverage"&&A!==void 0&&!j.includes(A))throw new Error(`--runtime must be one of: ${j.join(", ")}.`);let O=await w({workspacePath:l,kind:y,scope:n.scope,target:T,runtime:y==="test-coverage"?A:void 0,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});R(O);}else if(m==="status"){if(!y)throw new Error("workspace goal status requires a goal id.");let b=await g(l,y);R({...b,resumed:b.status.state!=="verified"});}else if(m==="verify"){if(!y)throw new Error("workspace goal verify requires a goal id.");let b=await g(l,y),T=await C({workspacePath:l,goalId:y,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});R({goal:b.goal,status:T}),T.state!=="verified"&&process.exit(2);}else {let b=`Unknown workspace goal action: ${m}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:b,context:{schemaVersion:x,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${b}`)),process.exit(1);}}else if(t==="mcp"){let l=a("mcp"),m=(e||"serve").toLowerCase();m!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:m,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${m}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${m}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:y}=await import('./workspace-mcp-serve-PK226GMV.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await y({workspacePath:l});}else if(t==="init"){n.json||(console.log(s.yellow("\u2139 workspace init is an alias of: npx workspai workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
402
+ npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:J}=await import('./workspace-marker-XGAWZZDX.js'),F=await J(l),H=x({workspacePath:l,workspaceName:F?.name,taskId:j,strategy:A}),U=await T(l,H);if(n.json){console.log(JSON.stringify(b$6("workspace eval init",H,U),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${j}`)),console.log(s.gray(` Run: ${H.runId}`)),console.log(s.gray(` Strategy: ${H.configuration.strategy}`)),console.log(s.gray(` Live: ${U}`));return}if(m==="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:j,readStdinAll:A}=await import('./workspace-feedback-3YLIUFQ7.js'),O=j(await A());O||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let J=await g({workspacePath:l,payload:O});console.log(JSON.stringify(J,null,2));}catch(J){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:J instanceof Error?J.message:String(J),context:{workspacePath:l}}),null,2)),process.exit(1);}return}if(m==="report"){let j=await R({workspacePath:l}),A=p(),O=j.outputPath;if(A){let J=P.resolve(l,A);P.resolve(j.outputPath)!==J&&await M__default.copy(j.outputPath,J,{overwrite:true}),O=J;}if(n.json){console.log(JSON.stringify(b$6("workspace eval report",j.report,O),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${j.report.runId}`)),console.log(s.gray(` Tokens: ${j.report.summary.tokens.observedTotal} \xB7 model calls ${j.report.summary.modelCalls} \xB7 tool calls ${j.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${j.report.summary.outcome.status}${j.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${O}`));return}if(m==="compare"){let j=(n.from||r||"").trim();j||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let A=await b(l,y),O=await b(l,j),J=C(A,O);if(n.json){console.log(JSON.stringify(J,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${J.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${J.delta.tokens}`)),console.log(s.gray(` Reduction: ${J.delta.reductionPercent===null?"unavailable":`${J.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${J.comparableOutcome?"yes":"no"}`));return}if(m==="status"){let j;try{j=await b(l,w);}catch{j=await b(l,y);}if(n.json){console.log(JSON.stringify(j,null,2));return}console.log(s.green(`\u2714 Evaluation ${j.status}: ${j.configuration.taskId}`)),console.log(s.gray(` Run: ${j.runId}`)),console.log(s.gray(` Events: ${j.events.length}`)),console.log(s.gray(` Tokens: ${j.summary.tokens.observedTotal} (${j.summary.tokenSources.providerReported} provider-reported calls, ${j.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${m}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let l=a("feedback"),m=(e||"record").toLowerCase();m!=="record"&&(console.log(s.red(`Unknown feedback action: ${m}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace feedback record requires --json (stdin payload)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace feedback record requires piped JSON on stdin (not a TTY)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:y,parseFeedbackStdinPayload:w,readStdinAll:g}=await import('./workspace-feedback-3YLIUFQ7.js'),C=await g(),x=w(C);x||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let R=await y({workspacePath:l,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==="goal"){let l=a("goal"),m=(e||"status").toLowerCase(),y=r?.trim(),{planVerifiedGoal:w,readVerifiedGoal:g,verifyVerifiedGoal:C,VERIFIED_GOAL_SCHEMA_VERSION:x}=await import('./verified-goal-XUXU2X5H.js'),R=b=>{if(n.json){console.log(JSON.stringify(b,null,2));return}let T=b.goal;console.log(b.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(b.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),T&&console.log(s.bold(` ${T.summary}`)),console.log(s.gray(` Goal: ${b.status.goalId}`)),console.log(s.gray(` Progress: ${b.status.progress.message}`)),console.log(s.gray(` State: ${b.status.state}`)),b.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${b.status.blockingReasons[0]}`)),b.status.nextActions.length>0&&console.log(s.gray(` Next: ${b.status.nextActions[0]}`)),console.log(s.gray(` Status: ${b.status.artifactPath}`));};if(m==="plan"){if(!y||!["release-readiness","dependency-security","test-coverage"].includes(y)){let J="Goal kind must be release-readiness, dependency-security, or test-coverage.";n.json?console.log(JSON.stringify(c$1({operation:"workspace goal plan",code:"workspace.goal.kind.invalid",message:J}),null,2)):console.log(s.red(`\u274C ${J}`)),process.exit(1);}let T=Number(n.target??80);if(!Number.isFinite(T)||T<0||T>100)throw new Error("--target must be a number from 0 to 100.");let j=["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"],A=n.runtime;if(y==="test-coverage"&&A!==void 0&&!j.includes(A))throw new Error(`--runtime must be one of: ${j.join(", ")}.`);let O=await w({workspacePath:l,kind:y,scope:n.scope,target:T,runtime:y==="test-coverage"?A:void 0,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});R(O);}else if(m==="status"){if(!y)throw new Error("workspace goal status requires a goal id.");let b=await g(l,y);R({...b,resumed:b.status.state!=="verified"});}else if(m==="verify"){if(!y)throw new Error("workspace goal verify requires a goal id.");let b=await g(l,y),T=await C({workspacePath:l,goalId:y,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});R({goal:b.goal,status:T}),T.state!=="verified"&&process.exit(2);}else {let b=`Unknown workspace goal action: ${m}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:b,context:{schemaVersion:x,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${b}`)),process.exit(1);}}else if(t==="mcp"){let l=a("mcp"),m=(e||"serve").toLowerCase();m!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:m,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${m}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${m}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:y}=await import('./workspace-mcp-serve-TDUXJUAA.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await y({workspacePath:l});}else if(t==="init"){n.json||(console.log(s.yellow("\u2139 workspace init is an alias of: npx workspai workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
403
403
  npx workspai init | npx workspai workspace init | npx workspai workspace run init
404
- `)));let l=a("init"),m=Os({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let g=await Fs(l);g!==0&&process.exit(g);}let{runWorkspaceStage:y}=await import('./workspace-run-GFBFGUFM.js'),w=await y({workspacePath:l,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:m,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(w,null,2)),w.summary.exitCode!==0&&process.exit(w.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:Lr}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${Lr.join(", ")}`)),process.exit(1);});function Vr(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function vp(){let t=n=>n.replace(/\bnpx (?:rapidkit|workspai)\b/g,As),e=(n,a)=>{let i=t(n);if(i.length>65){console.log(s.cyan(` ${i}`)),console.log(s.gray(` ${a}`));return}console.log(s.cyan(` ${i.padEnd(67)} `)+s.gray(a));},r=(n,a)=>{console.log(s.white(` ${n}`));for(let i=0;i<a.length;i+=8)console.log(s.gray(` ${a.slice(i,i+8).join(" \xB7 ")}`));};console.log(s.white(`Usage:
404
+ `)));let l=a("init"),m=Os({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let g=await Fs(l);g!==0&&process.exit(g);}let{runWorkspaceStage:y}=await import('./workspace-run-ZZ5WHL7W.js'),w=await y({workspacePath:l,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:m,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(w,null,2)),w.summary.exitCode!==0&&process.exit(w.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:Lr}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${Lr.join(", ")}`)),process.exit(1);});function Vr(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function vp(){let t=n=>n.replace(/\bnpx (?:rapidkit|workspai)\b/g,As),e=(n,a)=>{let i=t(n);if(i.length>65){console.log(s.cyan(` ${i}`)),console.log(s.gray(` ${a}`));return}console.log(s.cyan(` ${i.padEnd(67)} `)+s.gray(a));},r=(n,a)=>{console.log(s.white(` ${n}`));for(let i=0;i<a.length;i+=8)console.log(s.gray(` ${a.slice(i,i+8).join(" \xB7 ")}`));};console.log(s.white(`Usage:
405
405
  `)),console.log(s.cyan(` ${As} <command> [options]
406
406
  `)),Gm==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${As}.
407
407
  `)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems