rapidkit 0.42.0 → 0.42.2

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 (52) hide show
  1. package/README.md +53 -9
  2. package/contracts/agent-customization-pack.v1.json +29 -29
  3. package/contracts/create-planner-capabilities.v1.json +2 -2
  4. package/contracts/extension-cli-compatibility.v1.json +2 -2
  5. package/contracts/runtime-command-surface.v1.json +2 -2
  6. package/contracts/workspace-registry.v1.json +1 -1
  7. package/contracts/workspace-run-last.v1.json +1 -1
  8. package/dist/autopilot-release-5J55NPXF.js +1 -0
  9. package/dist/{chunk-YWUWRSNO.js → chunk-4EIQRQSA.js} +1 -1
  10. package/dist/{chunk-QOH5TIRZ.js → chunk-6WDDATKQ.js} +1 -1
  11. package/dist/{chunk-2ZLIVGO7.js → chunk-7M2VBCAX.js} +1 -1
  12. package/dist/{chunk-FEA53XL6.js → chunk-7V7C6GXV.js} +1 -1
  13. package/dist/{chunk-DZU4KPPW.js → chunk-CXWWNQDF.js} +1 -1
  14. package/dist/{chunk-5QAVZET2.js → chunk-DMITBXR2.js} +1 -1
  15. package/dist/{chunk-4ZSDU5OO.js → chunk-FLFZC7ZV.js} +1 -1
  16. package/dist/{chunk-QKVEWX4L.js → chunk-JN6R5UP4.js} +2 -2
  17. package/dist/chunk-KEMWZUGO.js +5 -0
  18. package/dist/{chunk-IS2XUPMP.js → chunk-KQRXY2GJ.js} +1 -1
  19. package/dist/{chunk-FSIZLBTL.js → chunk-KUOCSDIY.js} +1 -1
  20. package/dist/{chunk-FB35IONI.js → chunk-MOAQ3WU6.js} +1 -1
  21. package/dist/{chunk-F7GYXSBT.js → chunk-NN3IV4U6.js} +1 -1
  22. package/dist/chunk-QKVDG6FD.js +32 -0
  23. package/dist/{chunk-LANBSCGS.js → chunk-RQIHAPF3.js} +1 -1
  24. package/dist/{chunk-M44C2P3R.js → chunk-S4U2FRJV.js} +1 -1
  25. package/dist/{chunk-YM5Q3PV6.js → chunk-TQULVWUA.js} +1 -1
  26. package/dist/{chunk-5PFGOXBQ.js → chunk-WKCBS5DC.js} +1 -1
  27. package/dist/{create-EAE2AJJL.js → create-TPFUONHK.js} +1 -1
  28. package/dist/{demo-kit-N5U3NGAE.js → demo-kit-4NCHGEA6.js} +1 -1
  29. package/dist/{doctor-E6JE4Q3B.js → doctor-O2B3XNAB.js} +1 -1
  30. package/dist/{dotnet-webapi-clean-K33C77EI.js → dotnet-webapi-clean-LV3MADHG.js} +1 -1
  31. package/dist/{gofiber-standard-BQ4HCXL2.js → gofiber-standard-25DZS5UY.js} +1 -1
  32. package/dist/{gogin-standard-PUBCYW3A.js → gogin-standard-FMVHPLO5.js} +1 -1
  33. package/dist/index.js +21 -20
  34. package/dist/{pipeline-TRA4MMZC.js → pipeline-PX6ZUINW.js} +1 -1
  35. package/dist/{springboot-standard-XFVQI37R.js → springboot-standard-LMZF7OJS.js} +1 -1
  36. package/dist/{workspace-IBTKZX7T.js → workspace-MPKEUHFP.js} +1 -1
  37. package/dist/{workspace-agent-sync-LEYLJ42D.js → workspace-agent-sync-XD32GG5V.js} +1 -1
  38. package/dist/{workspace-context-NTG3D4DI.js → workspace-context-QFES7YBC.js} +1 -1
  39. package/dist/workspace-explain-Q7TJCHD5.js +1 -0
  40. package/dist/{workspace-foundation-6AUEEJQQ.js → workspace-foundation-2OVUZXPT.js} +1 -1
  41. package/dist/{workspace-intelligence-C6NT557E.js → workspace-intelligence-FJP5ONDB.js} +1 -1
  42. package/dist/{workspace-mcp-serve-GM7A3IVM.js → workspace-mcp-serve-DFJIUTL5.js} +1 -1
  43. package/dist/{workspace-model-AOTSEAVW.js → workspace-model-IDRCH3VI.js} +1 -1
  44. package/dist/workspace-run-NULA72JV.js +1 -0
  45. package/dist/{workspace-verify-7R3XBNKE.js → workspace-verify-K4RSQIXT.js} +1 -1
  46. package/dist/{workspace-watch-SGY2DEZ5.js → workspace-watch-PFJDHPXI.js} +1 -1
  47. package/package.json +1 -1
  48. package/dist/autopilot-release-MVFRZMHD.js +0 -1
  49. package/dist/chunk-3HBNF2A3.js +0 -32
  50. package/dist/chunk-Q2KZIBV4.js +0 -5
  51. package/dist/workspace-explain-P2EBRNP6.js +0 -1
  52. package/dist/workspace-run-ATFFJCMK.js +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$d}from'./chunk-ICGWHIMK.js';import {b as b$5,a as a$4}from'./chunk-FEA53XL6.js';import {a as a$b}from'./chunk-ULIVVMT6.js';import {b as b$6,d as d$3,a as a$3,c as c$1,f as f$4,e as e$4}from'./chunk-PCXSTKZ5.js';import {a as a$6}from'./chunk-KMUWWZRT.js';import {a as a$c}from'./chunk-2E6WGUN6.js';import {b as b$a,a as a$f,l as l$3}from'./chunk-3HBNF2A3.js';import {a as a$h}from'./chunk-YM5Q3PV6.js';import {c as c$5,a as a$i}from'./chunk-QOH5TIRZ.js';import {e as e$3}from'./chunk-FB35IONI.js';import {a as a$g}from'./chunk-COBMOVUK.js';import {g,b as b$2,c,d,n,l,h as h$1,m,k,a as a$7,j as j$2,f as f$5,i as i$6}from'./chunk-YWUWRSNO.js';import {a as a$1,b as b$3}from'./chunk-CDCYRBAY.js';import {a as a$9}from'./chunk-A5FBGRJA.js';import {a as a$e}from'./chunk-AQ4XZZC6.js';import {f as f$3,g as g$2,h as h$3,i as i$3,j as j$3,c as c$6,a as a$j}from'./chunk-FSIZLBTL.js';import {m as m$1,d as d$4,e as e$1,f as f$2,g as g$1,h as h$2,i,q,j as j$1,s as s$1,k as k$1,c as c$3,l as l$1,r,t,n as n$3,p,a as a$l,o as o$2}from'./chunk-2ZLIVGO7.js';export{l as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-2ZLIVGO7.js';import {i as i$1}from'./chunk-4KUIFXHM.js';import {f as f$6}from'./chunk-3PTJID76.js';import {h,a as a$2,m as m$2,l as l$2,n as n$2,k as k$2,o as o$1,i as i$5}from'./chunk-LANBSCGS.js';import {b as b$4,d as d$1,a as a$5,e as e$2}from'./chunk-5QAVZET2.js';import {b as b$8,d as d$6}from'./chunk-2LBPX5K3.js';import {a as a$a}from'./chunk-TDSIF42O.js';import {b,a}from'./chunk-Q2KZIBV4.js';import {f,d as d$2,b as b$7}from'./chunk-OLDPVVSV.js';import {c as c$7}from'./chunk-MIWDCR6I.js';import {f as f$1,e,d as d$5,i as i$2,a as a$8,g as g$3}from'./chunk-FMBSON6H.js';import {b as b$1,n as n$1,o,c as c$4,i as i$4,h as h$4,p as p$1,l as l$4,e as e$5,g as g$4}from'./chunk-WRMCPKGA.js';import {c as c$8}from'./chunk-2FIX2MDC.js';import {c as c$2,b as b$9,a as a$k}from'./chunk-HHJAANUC.js';import {Command,Option}from'commander';import s from'chalk';import v from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Dl from'vm';import*as E from'fs-extra';import E__default from'fs-extra';import j,{promises,createWriteStream}from'fs';import js,{tmpdir}from'os';import {execa}from'execa';import jr,{createVerify,createHash,createHmac}from'crypto';import Ni from'http';import Di from'https';function Ea(){return i$4()}function _a(t,e){return t==="py"?["-3",...e]:e}function Aa(t){return typeof t=="object"&&t!==null}async function Ia(t,e,o,r=c$8()){try{let n=await execa(t,e,{cwd:o,timeout:r,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function $a(t,e){let o=["-m","rapidkit",...t],r=Ea();for(let n of r){let i=await Ia(n,_a(n,o),e?.cwd,e?.timeoutMs);if(!i.ok)continue;let a=(i.stdout??"").trim();try{let l=JSON.parse(a);return Aa(l)?{ok:true,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,data:l}:{ok:false,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}catch{return {ok:false,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}}return {ok:false}}async function ws(t,e){let o=await $a(["project","detect","--path",t,"--json"],e);return !o.ok||!o.data||o.data.schema_version!==1?{ok:false,command:o.command,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr}:o}var ks=new Set(["create"]),pr=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),Oa=new Set(["pip","poetry","venv","pipx","python"]);function vs(t){return typeof t=="string"&&Oa.has(t)}function ur(t,e){return !t||ks.has(t)?false:a$8.has(t)?true:e?.has(t)??false}function mr(t,e=null){let o=t[0];return !o||o.startsWith("-")||ks.has(o)||o==="init"?false:ur(o,e)?true:t.filter(n=>!n.startsWith("-")&&!pr.has(n)).length<=1?false:t.length>1}var vt=v.join(js.homedir(),".rapidkitrc.json"),Ma=v.join(js.homedir(),".rapidkit","config.json");function Ps(t){try{if(!j.existsSync(t))return {};let e=j.readFileSync(t,"utf-8"),o=JSON.parse(e);return !o||typeof o!="object"||Array.isArray(o)?{}:o}catch{return {}}}function Ss(t){if(process.platform!=="win32")try{j.chmodSync(t,384);}catch{}}function Pt(){let t=Ps(vt),e=Ps(Ma);return j.existsSync(vt)&&Ss(vt),{...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled,telemetry:t.telemetry??e.telemetry}}function Po(t){let o={...Pt(),...t};j.writeFileSync(vt,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),Ss(vt);}function Ut(){return process.env.OPENAI_API_KEY||Pt().openaiApiKey||null}function fr(){return Pt().aiEnabled!==false}function gr(){return vt}function xs(t){let e=t.command("config").description("Configure RapidKit settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async o=>{let r=o.key;r?r.startsWith("sk-")||(console.log(s.red(`
2
+ import {a as a$d}from'./chunk-ICGWHIMK.js';import {b as b$5,a as a$4}from'./chunk-7V7C6GXV.js';import {a as a$b}from'./chunk-ULIVVMT6.js';import {b as b$6,d as d$3,a as a$3,c as c$1,f as f$4,e as e$4}from'./chunk-PCXSTKZ5.js';import {a as a$6}from'./chunk-KMUWWZRT.js';import {a as a$c}from'./chunk-2E6WGUN6.js';import {b as b$a,a as a$f,l as l$3}from'./chunk-QKVDG6FD.js';import {a as a$h}from'./chunk-TQULVWUA.js';import {c as c$5,a as a$i}from'./chunk-6WDDATKQ.js';import {e as e$3}from'./chunk-MOAQ3WU6.js';import {a as a$g}from'./chunk-COBMOVUK.js';import {g,b as b$2,c,d,n,l,h as h$1,m,k,a as a$7,j as j$2,f as f$5,i as i$6}from'./chunk-4EIQRQSA.js';import {a as a$1,b as b$3}from'./chunk-CDCYRBAY.js';import {a as a$9}from'./chunk-A5FBGRJA.js';import {a as a$e}from'./chunk-AQ4XZZC6.js';import {f as f$3,g as g$2,h as h$3,i as i$3,j as j$3,c as c$6,a as a$j}from'./chunk-KUOCSDIY.js';import {m as m$1,d as d$4,e as e$1,f as f$2,g as g$1,h as h$2,i,q,j as j$1,s as s$1,k as k$1,c as c$3,l as l$1,r,t,n as n$3,p,a as a$l,o as o$2}from'./chunk-7M2VBCAX.js';export{l as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-7M2VBCAX.js';import {i as i$1}from'./chunk-4KUIFXHM.js';import {f as f$6}from'./chunk-3PTJID76.js';import {h,a as a$2,m as m$2,l as l$2,n as n$2,k as k$2,o as o$1,i as i$5}from'./chunk-RQIHAPF3.js';import {b as b$4,d as d$1,a as a$5,e as e$2}from'./chunk-DMITBXR2.js';import {b as b$8,d as d$6}from'./chunk-2LBPX5K3.js';import {a as a$a}from'./chunk-TDSIF42O.js';import {b,a}from'./chunk-KEMWZUGO.js';import {f,d as d$2,b as b$7}from'./chunk-OLDPVVSV.js';import {c as c$7}from'./chunk-MIWDCR6I.js';import {f as f$1,e,d as d$5,i as i$2,a as a$8,g as g$3}from'./chunk-FMBSON6H.js';import {b as b$1,n as n$1,o,c as c$4,i as i$4,h as h$4,p as p$1,l as l$4,e as e$5,g as g$4}from'./chunk-WRMCPKGA.js';import {c as c$8}from'./chunk-2FIX2MDC.js';import {c as c$2,b as b$9,a as a$k}from'./chunk-HHJAANUC.js';import {Command,Option}from'commander';import s from'chalk';import v from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Dl from'vm';import*as E from'fs-extra';import E__default from'fs-extra';import j,{promises,createWriteStream}from'fs';import js,{tmpdir}from'os';import {execa}from'execa';import jr,{createVerify,createHash,createHmac}from'crypto';import Ni from'http';import Di from'https';function Ea(){return i$4()}function _a(t,e){return t==="py"?["-3",...e]:e}function Aa(t){return typeof t=="object"&&t!==null}async function Ia(t,e,o,r=c$8()){try{let n=await execa(t,e,{cwd:o,timeout:r,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function $a(t,e){let o=["-m","rapidkit",...t],r=Ea();for(let n of r){let i=await Ia(n,_a(n,o),e?.cwd,e?.timeoutMs);if(!i.ok)continue;let a=(i.stdout??"").trim();try{let l=JSON.parse(a);return Aa(l)?{ok:true,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,data:l}:{ok:false,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}catch{return {ok:false,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}}return {ok:false}}async function ws(t,e){let o=await $a(["project","detect","--path",t,"--json"],e);return !o.ok||!o.data||o.data.schema_version!==1?{ok:false,command:o.command,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr}:o}var ks=new Set(["create"]),pr=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),Oa=new Set(["pip","poetry","venv","pipx","python"]);function vs(t){return typeof t=="string"&&Oa.has(t)}function ur(t,e){return !t||ks.has(t)?false:a$8.has(t)?true:e?.has(t)??false}function mr(t,e=null){let o=t[0];return !o||o.startsWith("-")||ks.has(o)||o==="init"?false:ur(o,e)?true:t.filter(n=>!n.startsWith("-")&&!pr.has(n)).length<=1?false:t.length>1}var vt=v.join(js.homedir(),".rapidkitrc.json"),Ma=v.join(js.homedir(),".rapidkit","config.json");function Ps(t){try{if(!j.existsSync(t))return {};let e=j.readFileSync(t,"utf-8"),o=JSON.parse(e);return !o||typeof o!="object"||Array.isArray(o)?{}:o}catch{return {}}}function Ss(t){if(process.platform!=="win32")try{j.chmodSync(t,384);}catch{}}function Pt(){let t=Ps(vt),e=Ps(Ma);return j.existsSync(vt)&&Ss(vt),{...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled,telemetry:t.telemetry??e.telemetry}}function Po(t){let o={...Pt(),...t};j.writeFileSync(vt,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),Ss(vt);}function Ut(){return process.env.OPENAI_API_KEY||Pt().openaiApiKey||null}function fr(){return Pt().aiEnabled!==false}function gr(){return vt}function xs(t){let e=t.command("config").description("Configure RapidKit settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async o=>{let r=o.key;r?r.startsWith("sk-")||(console.log(s.red(`
3
3
  \u274C Invalid API key format (should start with sk-)
4
4
  `)),process.exit(1)):r=(await b$3([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:i=>i?i.startsWith("sk-")?i.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,Po({openaiApiKey:r}),console.log(s.green(`
5
5
  \u2705 OpenAI API key saved successfully!
@@ -112,7 +112,7 @@ RapidKit 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: ${v.resolve(process.cwd(),e)}
114
114
  `));}function qs(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(o,r)=>{try{let n=await Hs({backlogPath:o,kit:r.kit,tier:r.tier,category:r.category,limit:r.limit});r.output&&await Vs(r.output,n,true),r.json?console.log(xt(n)):ac(n,r.output);}catch(n){let i=n instanceof Error?n.message:String(n);r.json?console.log(xt({ok:false,error:{message:i}})):console.error(s.red(`Product plan failed: ${i}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(o,r)=>{try{Bs(o);let n=await sc({backlogPath:r.fromBacklog,slug:o,kit:r.kit,outputRoot:r.workspaceOutput}),i=ic(r.output,o);await Vs(i,n,r.force===true),r.json?console.log(xt(n)):cc(n,i);}catch(n){let i=n instanceof Error?n.message:String(n);r.json?console.log(xt({ok:false,error:{message:i}})):console.error(s.red(`Product manifest create failed: ${i}`)),process.exit(1);}});}var Ys="rapidkit-workspace-snapshot-v1",Qs="rapidkit-project-archive-v1",lc=[".rapidkit/workspace.json",".rapidkit-workspace","rapidkit.config.json","rapidkit.config.js","rapidkit.config.cjs","rapidkit.config.mjs","package.json"],dc=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),Ht={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function Ct(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function Sr(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 pc(t){try{let e=await E__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function uc(t,e){if(!t)return e;let o=t.trim().toLowerCase();return ["true","yes","1","on"].includes(o)?true:["false","no","0","off"].includes(o)?false:e}async function mc(t){let e=v.join(t,".rapidkit","policies.yml");if(!await E__default.pathExists(e))return {...Ht};try{let o=await E__default.readFile(e,"utf-8"),r=(n,i)=>{let a=o.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return uc(a?.[1],i)};return {requireReasonForDestructiveOps:r("require_reason_for_destructive_ops",Ht.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:r("require_safety_snapshot_for_destructive_ops",Ht.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:r("allow_permanent_delete",Ht.allowPermanentDelete)}}catch{return {...Ht}}}function fc(t){return v.join(t,".rapidkit","audit","events.jsonl")}async function Ke(t,e){let o={schema:"rapidkit-workspace-audit-event-v1",id:jr.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},r=fc(t);return await E__default.ensureDir(v.dirname(r)),await E__default.appendFile(r,`${JSON.stringify(o)}
115
- `,"utf-8"),o}async function _o(t,e,o){let r=await mc(t);if(r.requireReasonForDestructiveOps&&!o.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(r.requireSafetySnapshotForDestructiveOps&&o.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(o.permanent&&!r.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return r}function xr(t=process.cwd()){let e=v.resolve(t),o=v.resolve(js.tmpdir());for(;;){if(e!==o&&(E__default.existsSync(v.join(e,".rapidkit-workspace"))||E__default.existsSync(v.join(e,".rapidkit","workspace.json"))))return e;let r=v.dirname(e);if(r===e)return null;e=r;}}function Ze(t){let e=t?v.resolve(t):xr(process.cwd());if(!e)throw new Error("Not inside a RapidKit workspace. Run from workspace root or pass --workspace.");if(!E__default.existsSync(v.join(e,".rapidkit-workspace"))&&!E__default.existsSync(v.join(e,".rapidkit","workspace.json")))throw new Error(`Workspace path is not a RapidKit workspace: ${e}`);return e}async function gc(t){let e=await pc(v.join(t,".rapidkit","workspace.json")),o=e?.workspace_name??e?.name;return typeof o=="string"&&o.trim()?o.trim():v.basename(t)}function Ao(t){return v.join(t,".rapidkit","snapshots")}function qt(t){return v.join(t,".rapidkit","archive","projects")}function Cr(t){return v.join(t,"files")}function yc(t){return v.join(js.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${jr.randomBytes(4).toString("hex")}`)}function Rr(t,e){let o=v.relative(t,e);if(!o)return true;let r=o.split(v.sep);return r[0]===".rapidkit"&&["snapshots","archive","audit"].includes(r[1]||"")?false:!r.some(n=>dc.has(n))}async function hc(t){return (await a$a(t,{descendIntoMatchedProjects:false})).map(o=>({name:v.basename(o),relativePath:v.relative(t,o)}))}async function wc(t,e){let o=[];for(let r of lc){let n=v.join(t,r);if(!await E__default.pathExists(n))continue;let i=v.join(e,r);await E__default.copy(n,i,{filter:a=>Rr(t,a)}),o.push(r);}return o}async function kc(t,e){await E__default.writeJson(v.join(t,"snapshot.json"),e,{spaces:2});}async function Er(t){let e=v.join(t,"snapshot.json"),o=await E__default.readJson(e);if(!o||typeof o!="object"||o.schema!==Ys)throw new Error(`Invalid RapidKit workspace snapshot manifest: ${e}`);return o}async function vc(t){let e=0,o=0,r=[t];for(;r.length>0;){let n=r.shift();if(!n)continue;let i=[];try{i=await E__default.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){let l=v.join(n,a.name);if(a.isDirectory()){r.push(l);continue}if(a.isFile())try{let c=await E__default.stat(l);e+=1,o+=c.size;}catch{}}}return {files:e,bytes:o}}async function Rt(t={}){let e=Ze(t.workspacePath),o=t.name?t.name:`snapshot-${Ct()}`,r=Sr(o),n=v.join(Ao(e),r),i=yc(r);if(await E__default.pathExists(n))throw new Error(`Snapshot already exists: ${r}`);let a=Cr(i);try{await E__default.ensureDir(a);let l=t.includeProjects?"full":"metadata",c=l==="full"?["."]:await wc(e,a);l==="full"&&await E__default.copy(e,a,{filter:m=>Rr(e,m)});let u={schema:Ys,name:r,mode:l,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await gc(e),workspacePath:e,copiedPaths:c,projects:await hc(e)};return await kc(i,u),await E__default.ensureDir(v.dirname(n)),await E__default.move(i,n,{overwrite:false}),await Ke(e,{action:"snapshot.create",target:r,status:"succeeded",reason:t.reason,details:{mode:l,copiedPaths:c,snapshotPath:n,projectCount:u.projects.length}}),{manifest:u,snapshotPath:n}}catch(l){throw await E__default.remove(i),await Ke(e,{action:"snapshot.create",target:r,status:"failed",reason:t.reason,details:{error:l instanceof Error?l.message:String(l)}}),l}}async function Xs(t){let e=Ze(t.workspacePath),o=v.join(Ao(e),Sr(t.name));if(!await E__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await Er(o),n=Cr(o),i=await vc(n);return {manifest:r,snapshotPath:o,filesRoot:n,estimatedFileCount:i.files,estimatedBytes:i.bytes}}async function Zs(t={}){let e=Ze(t.workspacePath),o=Ao(e);if(!await E__default.pathExists(o))return [];let r=await E__default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=v.join(o,i.name);try{n.push({...await Er(a),snapshotPath:a});}catch{}}return n.sort((i,a)=>a.createdAt.localeCompare(i.createdAt))}async function ei(t){let e=Ze(t.workspacePath),o=v.join(Ao(e),Sr(t.name));if(!await E__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await Er(o),n=Cr(o),i=r.mode==="full"?["."]:Array.from(new Set(r.copiedPaths.map(c=>c.startsWith(".rapidkit/")?".rapidkit":c)));if(t.dryRun)return await Ke(e,{action:"snapshot.restore",target:r.name,status:"planned",reason:t.reason,details:{restoredPaths:i}}),{workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await _o(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let a;if(t.safetySnapshot!==false&&(a=(await Rt({workspacePath:e,name:`pre-restore-${r.name}-${Ct()}`,reason:`Automatic safety snapshot before restoring ${r.name}`,includeProjects:false})).snapshotPath),r.mode==="full")await E__default.copy(n,e,{overwrite:true,errorOnExist:false,filter:c=>Rr(n,c)});else for(let c of r.copiedPaths)await E__default.copy(v.join(n,c),v.join(e,c),{overwrite:true,errorOnExist:false});let l={workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:false,safetySnapshotPath:a};return await Ke(e,{action:"snapshot.restore",target:r.name,status:"succeeded",reason:t.reason,details:{restoredPaths:i,safetySnapshotPath:a}}),l}function ti(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function oi(t,e){let o=ti(e),r=v.isAbsolute(o)?v.resolve(o):v.resolve(t,o);if(r.startsWith(`${v.resolve(t)}${v.sep}`)&&await E__default.pathExists(r))return r;let i=(await a$a(t,{descendIntoMatchedProjects:false})).filter(a=>{let l=v.relative(t,a);return v.basename(a)===o||l===o});if(i.length===0)throw new Error(`Project not found in workspace: ${e}`);if(i.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return i[0]}async function _r(t){try{let{syncWorkspaceProjects:e}=await import('./workspace-IBTKZX7T.js');await e(t,true);}catch{}}function Pc(t,e){let o=jr.randomBytes(4).toString("hex");return v.join(qt(t),`${e}-${Ct()}-${o}`)}async function ri(t){let e=v.join(t,"rapidkit-archive.json"),o=await E__default.readJson(e);if(!o||typeof o!="object"||o.schema!==Qs)throw new Error(`Invalid RapidKit archive manifest: ${e}`);return o}async function Ar(t={}){let e=Ze(t.workspacePath),o=qt(e);if(!await E__default.pathExists(o))return [];let r=await E__default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=v.join(o,i.name),l=v.join(a,"rapidkit-archive.json");try{n.push({...await ri(a),archivePath:a,manifestPath:l});}catch{}}return n.sort((i,a)=>a.archivedAt.localeCompare(i.archivedAt))}async function bc(t,e){let o=ti(e),r=v.isAbsolute(o)?v.resolve(o):v.resolve(qt(t),o);if(r.startsWith(`${v.resolve(qt(t))}${v.sep}`)&&await E__default.pathExists(v.join(r,"rapidkit-archive.json")))return r;let i=(await Ar({workspacePath:t})).filter(a=>v.basename(a.archivePath)===o||a.projectName===o||v.relative(qt(t),a.archivePath)===o);if(i.length===0)throw new Error(`Archived project not found: ${e}`);if(i.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return i[0].archivePath}async function Ir(t){let e=Ze(t.workspacePath),o=await oi(e,t.project),r=v.basename(o),n=Pc(e,r),i=v.join(n,"rapidkit-archive.json");if(t.dryRun)return await Ke(e,{action:"project.archive",target:r,status:"planned",reason:t.reason,details:{projectPath:o,archivePath:n}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,dryRun:true};await _o(e,"project.archive",{reason:t.reason,safetySnapshot:true});let a=await Rt({workspacePath:e,name:`pre-archive-${r}-${Ct()}`,reason:t.reason||`Automatic safety snapshot before archiving ${r}`,includeProjects:false});await E__default.ensureDir(v.dirname(n)),await E__default.move(o,n,{overwrite:false});let l={schema:Qs,projectName:r,originalPath:o,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:a.snapshotPath};return await E__default.writeJson(i,l,{spaces:2}),await c$2(e,[o]),await _r(e),await Ke(e,{action:"project.archive",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath,dryRun:false}}async function ni(t){if(!t.permanent)return Ir(t);let e=Ze(t.workspacePath),o=await oi(e,t.project),r=v.basename(o);if(t.confirm!==r)throw new Error(`Permanent delete requires --confirm ${r}`);if(t.dryRun)return await Ke(e,{action:"project.delete",target:r,status:"planned",reason:t.reason,details:{projectPath:o,permanent:true}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",dryRun:true};await _o(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Rt({workspacePath:e,name:`pre-delete-${r}-${Ct()}`,reason:t.reason||`Automatic safety snapshot before deleting ${r}`,includeProjects:false});return await E__default.remove(o),await c$2(e,[o]),await _r(e),await Ke(e,{action:"project.delete",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function si(t){let e=Ze(t.workspacePath),o=await bc(e,t.archive),r=await ri(o),n=t.targetName?.trim()||r.projectName,i=v.join(e,n);if(!i.startsWith(`${v.resolve(e)}${v.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await E__default.pathExists(i)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${i}`);if(t.dryRun)return await Ke(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:o,projectPath:i}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:v.join(o,"rapidkit-archive.json"),dryRun:true};await _o(e,"project.restore",{reason:t.reason,safetySnapshot:true});let a=await Rt({workspacePath:e,name:`pre-restore-project-${n}-${Ct()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false});return await E__default.move(o,i,{overwrite:t.force===true}),await _r(e),await Ke(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:o,projectPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:v.join(i,"rapidkit-archive.json"),safetySnapshotPath:a.snapshotPath,dryRun:false}}var Sc="rapidkit.infra-stack.v1",ai="rapidkit.infra-plan.v1",Et=".rapidkit/infra/docker-compose.yml",_t=".rapidkit/reports/infra-plan.json",Mr=".rapidkit/infra/.env.example";function xc(){let t=v.dirname(fileURLToPath(import.meta.url)),e=[v.join(t,"../../contracts/infra-stack.v1.json"),v.join(t,"../contracts/infra-stack.v1.json")];for(let o of e)if(j.existsSync(o))return o;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var Or=null;function pt(t){if(Or)return Or;let e=xc(),o=j.readFileSync(e,"utf-8"),r=JSON.parse(o);if(r.schemaVersion!==Sc)throw new Error(`Unsupported infra stack schema: ${r.schemaVersion}`);return Cc(r),(Or=r),r}function Cc(t){let e=new Set(Object.keys(t.services));for(let[o,r]of Object.entries(t.moduleMappings)){if(!Array.isArray(r))throw new Error(`Invalid moduleMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`moduleMappings/${o} references unknown service '${n}'`)}for(let[o,r]of Object.entries(t.envVarMappings)){if(!Array.isArray(r))throw new Error(`Invalid envVarMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`envVarMappings/${o} references unknown service '${n}'`)}}function ci(t,e){let o=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[o]||[]}function At(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function li(t,e){let o={};for(let r of e){let n=t.services[r];n&&Object.assign(o,n.connectionEnv);}return o}async function Rc(t){let e=v.join(t,"registry.json");if(!await E__default.pathExists(e))return [];try{let r=(await E__default.readJson(e)).installed_modules||[];return [...new Set(r.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function Ec(t){let e=v.join(t,".env.example");if(!await E__default.pathExists(e))return [];try{let o=await E__default.readFile(e,"utf-8"),r=[];for(let n of o.split(`
115
+ `,"utf-8"),o}async function _o(t,e,o){let r=await mc(t);if(r.requireReasonForDestructiveOps&&!o.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(r.requireSafetySnapshotForDestructiveOps&&o.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(o.permanent&&!r.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return r}function xr(t=process.cwd()){let e=v.resolve(t),o=v.resolve(js.tmpdir());for(;;){if(e!==o&&(E__default.existsSync(v.join(e,".rapidkit-workspace"))||E__default.existsSync(v.join(e,".rapidkit","workspace.json"))))return e;let r=v.dirname(e);if(r===e)return null;e=r;}}function Ze(t){let e=t?v.resolve(t):xr(process.cwd());if(!e)throw new Error("Not inside a RapidKit workspace. Run from workspace root or pass --workspace.");if(!E__default.existsSync(v.join(e,".rapidkit-workspace"))&&!E__default.existsSync(v.join(e,".rapidkit","workspace.json")))throw new Error(`Workspace path is not a RapidKit workspace: ${e}`);return e}async function gc(t){let e=await pc(v.join(t,".rapidkit","workspace.json")),o=e?.workspace_name??e?.name;return typeof o=="string"&&o.trim()?o.trim():v.basename(t)}function Ao(t){return v.join(t,".rapidkit","snapshots")}function qt(t){return v.join(t,".rapidkit","archive","projects")}function Cr(t){return v.join(t,"files")}function yc(t){return v.join(js.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${jr.randomBytes(4).toString("hex")}`)}function Rr(t,e){let o=v.relative(t,e);if(!o)return true;let r=o.split(v.sep);return r[0]===".rapidkit"&&["snapshots","archive","audit"].includes(r[1]||"")?false:!r.some(n=>dc.has(n))}async function hc(t){return (await a$a(t,{descendIntoMatchedProjects:false})).map(o=>({name:v.basename(o),relativePath:v.relative(t,o)}))}async function wc(t,e){let o=[];for(let r of lc){let n=v.join(t,r);if(!await E__default.pathExists(n))continue;let i=v.join(e,r);await E__default.copy(n,i,{filter:a=>Rr(t,a)}),o.push(r);}return o}async function kc(t,e){await E__default.writeJson(v.join(t,"snapshot.json"),e,{spaces:2});}async function Er(t){let e=v.join(t,"snapshot.json"),o=await E__default.readJson(e);if(!o||typeof o!="object"||o.schema!==Ys)throw new Error(`Invalid RapidKit workspace snapshot manifest: ${e}`);return o}async function vc(t){let e=0,o=0,r=[t];for(;r.length>0;){let n=r.shift();if(!n)continue;let i=[];try{i=await E__default.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){let l=v.join(n,a.name);if(a.isDirectory()){r.push(l);continue}if(a.isFile())try{let c=await E__default.stat(l);e+=1,o+=c.size;}catch{}}}return {files:e,bytes:o}}async function Rt(t={}){let e=Ze(t.workspacePath),o=t.name?t.name:`snapshot-${Ct()}`,r=Sr(o),n=v.join(Ao(e),r),i=yc(r);if(await E__default.pathExists(n))throw new Error(`Snapshot already exists: ${r}`);let a=Cr(i);try{await E__default.ensureDir(a);let l=t.includeProjects?"full":"metadata",c=l==="full"?["."]:await wc(e,a);l==="full"&&await E__default.copy(e,a,{filter:m=>Rr(e,m)});let u={schema:Ys,name:r,mode:l,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await gc(e),workspacePath:e,copiedPaths:c,projects:await hc(e)};return await kc(i,u),await E__default.ensureDir(v.dirname(n)),await E__default.move(i,n,{overwrite:false}),await Ke(e,{action:"snapshot.create",target:r,status:"succeeded",reason:t.reason,details:{mode:l,copiedPaths:c,snapshotPath:n,projectCount:u.projects.length}}),{manifest:u,snapshotPath:n}}catch(l){throw await E__default.remove(i),await Ke(e,{action:"snapshot.create",target:r,status:"failed",reason:t.reason,details:{error:l instanceof Error?l.message:String(l)}}),l}}async function Xs(t){let e=Ze(t.workspacePath),o=v.join(Ao(e),Sr(t.name));if(!await E__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await Er(o),n=Cr(o),i=await vc(n);return {manifest:r,snapshotPath:o,filesRoot:n,estimatedFileCount:i.files,estimatedBytes:i.bytes}}async function Zs(t={}){let e=Ze(t.workspacePath),o=Ao(e);if(!await E__default.pathExists(o))return [];let r=await E__default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=v.join(o,i.name);try{n.push({...await Er(a),snapshotPath:a});}catch{}}return n.sort((i,a)=>a.createdAt.localeCompare(i.createdAt))}async function ei(t){let e=Ze(t.workspacePath),o=v.join(Ao(e),Sr(t.name));if(!await E__default.pathExists(o))throw new Error(`Snapshot not found: ${t.name}`);let r=await Er(o),n=Cr(o),i=r.mode==="full"?["."]:Array.from(new Set(r.copiedPaths.map(c=>c.startsWith(".rapidkit/")?".rapidkit":c)));if(t.dryRun)return await Ke(e,{action:"snapshot.restore",target:r.name,status:"planned",reason:t.reason,details:{restoredPaths:i}}),{workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await _o(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let a;if(t.safetySnapshot!==false&&(a=(await Rt({workspacePath:e,name:`pre-restore-${r.name}-${Ct()}`,reason:`Automatic safety snapshot before restoring ${r.name}`,includeProjects:false})).snapshotPath),r.mode==="full")await E__default.copy(n,e,{overwrite:true,errorOnExist:false,filter:c=>Rr(n,c)});else for(let c of r.copiedPaths)await E__default.copy(v.join(n,c),v.join(e,c),{overwrite:true,errorOnExist:false});let l={workspacePath:e,snapshotPath:o,restoredPaths:i,dryRun:false,safetySnapshotPath:a};return await Ke(e,{action:"snapshot.restore",target:r.name,status:"succeeded",reason:t.reason,details:{restoredPaths:i,safetySnapshotPath:a}}),l}function ti(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function oi(t,e){let o=ti(e),r=v.isAbsolute(o)?v.resolve(o):v.resolve(t,o);if(r.startsWith(`${v.resolve(t)}${v.sep}`)&&await E__default.pathExists(r))return r;let i=(await a$a(t,{descendIntoMatchedProjects:false})).filter(a=>{let l=v.relative(t,a);return v.basename(a)===o||l===o});if(i.length===0)throw new Error(`Project not found in workspace: ${e}`);if(i.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return i[0]}async function _r(t){try{let{syncWorkspaceProjects:e}=await import('./workspace-MPKEUHFP.js');await e(t,true);}catch{}}function Pc(t,e){let o=jr.randomBytes(4).toString("hex");return v.join(qt(t),`${e}-${Ct()}-${o}`)}async function ri(t){let e=v.join(t,"rapidkit-archive.json"),o=await E__default.readJson(e);if(!o||typeof o!="object"||o.schema!==Qs)throw new Error(`Invalid RapidKit archive manifest: ${e}`);return o}async function Ar(t={}){let e=Ze(t.workspacePath),o=qt(e);if(!await E__default.pathExists(o))return [];let r=await E__default.readdir(o,{withFileTypes:true}),n=[];for(let i of r){if(!i.isDirectory())continue;let a=v.join(o,i.name),l=v.join(a,"rapidkit-archive.json");try{n.push({...await ri(a),archivePath:a,manifestPath:l});}catch{}}return n.sort((i,a)=>a.archivedAt.localeCompare(i.archivedAt))}async function bc(t,e){let o=ti(e),r=v.isAbsolute(o)?v.resolve(o):v.resolve(qt(t),o);if(r.startsWith(`${v.resolve(qt(t))}${v.sep}`)&&await E__default.pathExists(v.join(r,"rapidkit-archive.json")))return r;let i=(await Ar({workspacePath:t})).filter(a=>v.basename(a.archivePath)===o||a.projectName===o||v.relative(qt(t),a.archivePath)===o);if(i.length===0)throw new Error(`Archived project not found: ${e}`);if(i.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return i[0].archivePath}async function Ir(t){let e=Ze(t.workspacePath),o=await oi(e,t.project),r=v.basename(o),n=Pc(e,r),i=v.join(n,"rapidkit-archive.json");if(t.dryRun)return await Ke(e,{action:"project.archive",target:r,status:"planned",reason:t.reason,details:{projectPath:o,archivePath:n}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,dryRun:true};await _o(e,"project.archive",{reason:t.reason,safetySnapshot:true});let a=await Rt({workspacePath:e,name:`pre-archive-${r}-${Ct()}`,reason:t.reason||`Automatic safety snapshot before archiving ${r}`,includeProjects:false});await E__default.ensureDir(v.dirname(n)),await E__default.move(o,n,{overwrite:false});let l={schema:Qs,projectName:r,originalPath:o,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:a.snapshotPath};return await E__default.writeJson(i,l,{spaces:2}),await c$2(e,[o]),await _r(e),await Ke(e,{action:"project.archive",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"archive",archivePath:n,manifestPath:i,safetySnapshotPath:a.snapshotPath,dryRun:false}}async function ni(t){if(!t.permanent)return Ir(t);let e=Ze(t.workspacePath),o=await oi(e,t.project),r=v.basename(o);if(t.confirm!==r)throw new Error(`Permanent delete requires --confirm ${r}`);if(t.dryRun)return await Ke(e,{action:"project.delete",target:r,status:"planned",reason:t.reason,details:{projectPath:o,permanent:true}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",dryRun:true};await _o(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await Rt({workspacePath:e,name:`pre-delete-${r}-${Ct()}`,reason:t.reason||`Automatic safety snapshot before deleting ${r}`,includeProjects:false});return await E__default.remove(o),await c$2(e,[o]),await _r(e),await Ke(e,{action:"project.delete",target:r,status:"succeeded",reason:t.reason,details:{projectPath:o,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:r,projectPath:o,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function si(t){let e=Ze(t.workspacePath),o=await bc(e,t.archive),r=await ri(o),n=t.targetName?.trim()||r.projectName,i=v.join(e,n);if(!i.startsWith(`${v.resolve(e)}${v.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await E__default.pathExists(i)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${i}`);if(t.dryRun)return await Ke(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:o,projectPath:i}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:v.join(o,"rapidkit-archive.json"),dryRun:true};await _o(e,"project.restore",{reason:t.reason,safetySnapshot:true});let a=await Rt({workspacePath:e,name:`pre-restore-project-${n}-${Ct()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false});return await E__default.move(o,i,{overwrite:t.force===true}),await _r(e),await Ke(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:o,projectPath:i,safetySnapshotPath:a.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:i,action:"restore",archivePath:o,manifestPath:v.join(i,"rapidkit-archive.json"),safetySnapshotPath:a.snapshotPath,dryRun:false}}var Sc="rapidkit.infra-stack.v1",ai="rapidkit.infra-plan.v1",Et=".rapidkit/infra/docker-compose.yml",_t=".rapidkit/reports/infra-plan.json",Mr=".rapidkit/infra/.env.example";function xc(){let t=v.dirname(fileURLToPath(import.meta.url)),e=[v.join(t,"../../contracts/infra-stack.v1.json"),v.join(t,"../contracts/infra-stack.v1.json")];for(let o of e)if(j.existsSync(o))return o;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var Or=null;function pt(t){if(Or)return Or;let e=xc(),o=j.readFileSync(e,"utf-8"),r=JSON.parse(o);if(r.schemaVersion!==Sc)throw new Error(`Unsupported infra stack schema: ${r.schemaVersion}`);return Cc(r),(Or=r),r}function Cc(t){let e=new Set(Object.keys(t.services));for(let[o,r]of Object.entries(t.moduleMappings)){if(!Array.isArray(r))throw new Error(`Invalid moduleMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`moduleMappings/${o} references unknown service '${n}'`)}for(let[o,r]of Object.entries(t.envVarMappings)){if(!Array.isArray(r))throw new Error(`Invalid envVarMappings entry for ${o}`);for(let n of r)if(!e.has(n))throw new Error(`envVarMappings/${o} references unknown service '${n}'`)}}function ci(t,e){let o=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[o]||[]}function At(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function li(t,e){let o={};for(let r of e){let n=t.services[r];n&&Object.assign(o,n.connectionEnv);}return o}async function Rc(t){let e=v.join(t,"registry.json");if(!await E__default.pathExists(e))return [];try{let r=(await E__default.readJson(e)).installed_modules||[];return [...new Set(r.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function Ec(t){let e=v.join(t,".env.example");if(!await E__default.pathExists(e))return [];try{let o=await E__default.readFile(e,"utf-8"),r=[];for(let n of o.split(`
116
116
  `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let a=i.match(/^([A-Z0-9_]+)=/);a?.[1]&&r.push(a[1]);}return r}catch{return []}}async function _c(t){let e=v.join(t,".rapidkit","infra","overrides.json");if(!await E__default.pathExists(e))return [];try{let o=await E__default.readJson(e);return Array.isArray(o.services)?[...new Set(o.services.filter(r=>typeof r=="string"&&r.trim().length>0))]:[]}catch{return []}}async function Ac(t){let e=v.join(t,".rapidkit","workspace.contract.json");if(!await E__default.pathExists(e))return [];try{let o=await E__default.readJson(e),r=[];for(let n of o.projects||[]){let i=typeof n.slug=="string"?n.slug:"unknown";for(let a of n.contracts?.env||[])typeof a=="string"&&a.trim()&&r.push({project:i,env:a.trim().toUpperCase()});}return r}catch{return []}}function Io(t,e,o,r){t.add(o),e.push(r);}async function di(t){let e=v.resolve(t.workspacePath),o=t.contract||pt(),r=new Set,n=[],i=new Set,a=new Set,l=new Set,c=await f$6(e);for(let u of c){let m=v.dirname(v.dirname(u)),d=v.basename(m);for(let p of await Rc(m)){i.add(p);for(let f of ci(o,p))Io(r,n,f,{kind:"module",value:p,project:d});}for(let p of await Ec(m)){a.add(p);for(let f of At(o,p))Io(r,n,f,{kind:"env-var",value:p,project:d});}}for(let u of await Ac(e)){a.add(u.env);for(let m of At(o,u.env))Io(r,n,m,{kind:"contract-env",value:u.env,project:u.project});}for(let u of await _c(e))l.add(u),Io(r,n,u,{kind:"override",value:u});return {modules:[...i].sort(),envVars:[...a].sort(),overrides:[...l].sort(),sources:n,serviceIds:[...r].sort()}}function Ic(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let o=e.indexOf("=");if(o<=0)return null;let r=e.slice(0,o).trim();if(!/^[A-Z0-9_]+$/.test(r))return null;let n=e.slice(o+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let i=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),a=(i?i[1]:n).trim();return a?{key:r,value:a}:null}async function $c(t){if(!await E__default.pathExists(t))return {};try{let e=await E__default.readFile(t,"utf-8"),o={};for(let r of e.split(`
117
117
  `)){let n=Ic(r);n&&(o[n.key]=n.value);}return o}catch{return {}}}async function ui(t){let e={},o=await f$6(t.workspacePath);for(let r of o){let n=v.dirname(v.dirname(r)),i=await $c(v.join(n,".env.example"));for(let[a,l]of Object.entries(i))At(t.contract,a).length>0&&(e[a]=l);}return e}function mi(t,e){return t.filter(o=>At(e,o).length>0).sort()}function fi(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let o=new URL(e),r=o.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(o.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(o.password||"postgres"),POSTGRES_DB:r||"postgres"}}catch{return}}function gi(t){let e=t.POSTGRES_USER||"postgres",o=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${o}`]}function Oc(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
118
118
  `)?JSON.stringify(t):t}function yi(t,e){return Object.entries(t).map(([o,r])=>`${e}${o}: ${Oc(r)}`).join(`
@@ -154,8 +154,8 @@ ${o.stderr||""}`);return r?this.isMavenVersionAtLeast(r,[3,9,0])?{exitCode:0}:{e
154
154
  `),1;try{h(r);}catch(u){let m=u instanceof Error?u.message:String(u);return process.stderr.write(`${m}
155
155
  `),1}let n=Kl(o.id,t);if(n)return process.stderr.write(`${n}
156
156
  `),1;let i=Ee(t,"--output")||process.cwd(),a=v.resolve(i,r),l=t.includes("--skip-git")||t.includes("--no-git"),c=t.includes("--skip-install");try{let{default:u}=await import('fs-extra');if(await u.ensureDir(v.dirname(a)),await u.pathExists(a))return process.stderr.write(`\u274C Directory "${a}" already exists
157
- `),1;await u.ensureDir(a),await e$2(o,{projectName:r,projectPath:a,args:t,skipGit:l,skipInstall:c});let m=Z(process.cwd());if(m){let{syncWorkspaceProjects:d}=await import('./workspace-IBTKZX7T.js');await d(m,true);}return 0}catch(u){return process.stderr.write(`RapidKit ${o.id} generator failed: ${u?.message??u}
158
- `),1}}async function Yi(t){let e=k$2(t[2]);if(!e)return 1;try{let o=await o$1({args:t});if(!o.dryRun){let r=Z(process.cwd()),n=false;r||(r=(await pn()).workspacePath,n=true);let{registerProjectInWorkspace:i,registerWorkspace:a,syncWorkspaceProjects:l}=await import('./workspace-IBTKZX7T.js'),c=i$5({workspacePath:r,result:o});await a(r,v.basename(r)),await b$9(r,[c]),await i(r,o.projectName,o.projectPath),await l(r,true),await qe(r,{silent:true}),n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a RapidKit workspace \u2014 linked to managed workspace "${f$5}" (${c.relationship}).`)),console.log(s.gray(` Registry: ${v.join(p$1(),"workspaces.json")}`)),console.log(s.gray(" Tip: run from inside a workspace next time, or create one with `rapidkit create workspace`.")));}return 0}catch(o){return process.stderr.write(`RapidKit ${e.kitId} generator failed: ${o?.message??o}
157
+ `),1;await u.ensureDir(a),await e$2(o,{projectName:r,projectPath:a,args:t,skipGit:l,skipInstall:c});let m=Z(process.cwd());if(m){let{syncWorkspaceProjects:d}=await import('./workspace-MPKEUHFP.js');await d(m,true);}return 0}catch(u){return process.stderr.write(`RapidKit ${o.id} generator failed: ${u?.message??u}
158
+ `),1}}async function Yi(t){let e=k$2(t[2]);if(!e)return 1;try{let o=await o$1({args:t});if(!o.dryRun){let r=Z(process.cwd()),n=false;r||(r=(await pn()).workspacePath,n=true);let{registerProjectInWorkspace:i,registerWorkspace:a,syncWorkspaceProjects:l}=await import('./workspace-MPKEUHFP.js'),c=i$5({workspacePath:r,result:o});await a(r,v.basename(r)),await b$9(r,[c]),await i(r,o.projectName,o.projectPath),await l(r,true),await qe(r,{silent:true}),n&&(console.log(s.gray(`\u2139\uFE0F Project created outside a RapidKit workspace \u2014 linked to managed workspace "${f$5}" (${c.relationship}).`)),console.log(s.gray(` Registry: ${v.join(p$1(),"workspaces.json")}`)),console.log(s.gray(" Tip: run from inside a workspace next time, or create one with `rapidkit create workspace`.")));}return 0}catch(o){return process.stderr.write(`RapidKit ${e.kitId} generator failed: ${o?.message??o}
159
159
  `),t[3]||process.stderr.write(`Usage: ${n$2(e.id)}
160
160
  `),1}}async function zo(t,e){if(t.includes("--json"))return process.stderr.write("RapidKit (npm) offline fallback does not support --json for `create` commands.\nInstall Python 3.10+ and retry the same command.\n"),1;if(t[0]!=="create")return 1;if(t[1]!=="project")return process.stderr.write(`RapidKit (npm) could not run the Python core engine for \`create\`.
161
161
  Reason: ${e}.
@@ -168,7 +168,7 @@ Requested kit: ${n}
168
168
  Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
169
169
  Install Python 3.10+ to access all kits.
170
170
  `),1;let l=Ee(t,"--output")||process.cwd(),c=v.resolve(l,i),u=t.includes("--skip-git")||t.includes("--no-git"),m=t.includes("--skip-install");try{if(await E__default.ensureDir(v.dirname(c)),await E__default.pathExists(c))return process.stderr.write(`\u274C Directory "${c}" already exists
171
- `),1;let d="pip",p=Z(process.cwd());if(p)try{let{readWorkspaceMarker:g}=await import('./workspace-marker-5GAJSOFP.js'),y=await g(p);y?.metadata?.npm?.installMethod&&(d=y.metadata.npm.installMethod,f.debug(`Detected workspace engine: ${d}`));}catch(g){f.debug("Failed to read workspace marker",g);}else f.debug("No workspace found, using default engine: pip");await E__default.ensureDir(c);let{generateDemoKit:f$1}=await import('./demo-kit-N5U3NGAE.js');if(await f$1(c,{project_name:i,template:a,kit_name:n,skipGit:u,skipInstall:m,engine:d}),p){let{syncWorkspaceProjects:g}=await import('./workspace-IBTKZX7T.js');await g(p,true),await qe(p,{silent:true});}return 0}catch(d){return process.stderr.write(`RapidKit (npm) offline fallback failed: ${d?.message??d}
171
+ `),1;let d="pip",p=Z(process.cwd());if(p)try{let{readWorkspaceMarker:g}=await import('./workspace-marker-5GAJSOFP.js'),y=await g(p);y?.metadata?.npm?.installMethod&&(d=y.metadata.npm.installMethod,f.debug(`Detected workspace engine: ${d}`));}catch(g){f.debug("Failed to read workspace marker",g);}else f.debug("No workspace found, using default engine: pip");await E__default.ensureDir(c);let{generateDemoKit:f$1}=await import('./demo-kit-4NCHGEA6.js');if(await f$1(c,{project_name:i,template:a,kit_name:n,skipGit:u,skipInstall:m,engine:d}),p){let{syncWorkspaceProjects:g}=await import('./workspace-MPKEUHFP.js');await g(p,true),await qe(p,{silent:true});}return 0}catch(d){return process.stderr.write(`RapidKit (npm) offline fallback failed: ${d?.message??d}
172
172
  `),1}}function Gl(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("RapidKit native create is not available for this request yet.")}
173
173
  `),process.stderr.write(s.gray(`Requested: ${e}
174
174
  `)),process.stderr.write(s.gray(`Lane: ${t.lane} (${t.status})
@@ -181,11 +181,11 @@ Install Python 3.10+ to access all kits.
181
181
  `),1;try{h(f);}catch(S){if(S instanceof a$2)return process.stderr.write(`${S.message}
182
182
  `),1;throw S}let g=await n(t,{hasYes:n$1}),y=l(f.trim(),{argv:t,outputParent:g});l$1||await E__default.ensureDir(v.dirname(y));let w=h$1(f.trim());if(!l$1&&(m(w,y,{outputParent:g})&&w&&await E__default.pathExists(w)||await E__default.pathExists(y)))return process.stderr.write(`\u274C Workspace "${f}" already exists
183
183
  `),w&&w!==y&&process.stderr.write(` Found at: ${w}
184
- `),1;let P=await b$2(),k$1=P.author||process.env.USER||"RapidKit User";if(!n$1){let S=await b$3([{type:"input",name:"author",message:"Author name:",default:k$1}]);S.author?.trim()&&(k$1=S.author.trim());}let{createProject:h$2}=await import('./create-EAE2AJJL.js');return await h$2(f,{skipGit:i,skipPythonEngine:a,yes:n$1,dryRun:l$1,userConfig:{...P,author:k$1},installMethod:m$1,profile:p,parentDirectory:v.dirname(y)}),l$1||(console.log(s.gray(`\u2139\uFE0F Workspace root: ${y}`)),console.log(s.gray(` Next: ${k(y)} && npx rapidkit create project`))),0}catch(n){return process.stderr.write(`RapidKit (npm) failed to create workspace: ${n?.message??n}
184
+ `),1;let P=await b$2(),k$1=P.author||process.env.USER||"RapidKit User";if(!n$1){let S=await b$3([{type:"input",name:"author",message:"Author name:",default:k$1}]);S.author?.trim()&&(k$1=S.author.trim());}let{createProject:h$2}=await import('./create-TPFUONHK.js');return await h$2(f,{skipGit:i,skipPythonEngine:a,yes:n$1,dryRun:l$1,userConfig:{...P,author:k$1},installMethod:m$1,profile:p,parentDirectory:v.dirname(y)}),l$1||(console.log(s.gray(`\u2139\uFE0F Workspace root: ${y}`)),console.log(s.gray(` Next: ${k(y)} && npx rapidkit create project`))),0}catch(n){return process.stderr.write(`RapidKit (npm) failed to create workspace: ${n?.message??n}
185
185
  `),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))try{return await d$5(),await e(["create","project","--help"],{cwd:process.cwd()})}catch(k){return process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${k?.message??k}
186
- `),1}if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a$1("create project");let{kitChoice:k}=await b$3([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$7()}]);if(d$1(k)||l$2(k)){let b=Vr(k),{projectName:A}=await b$3([{type:"input",name:"projectName",message:"Project name:",default:b,validate:J=>J.trim().length>0||"Project name is required"}]),N=t.slice(2).filter(J=>J.startsWith("-")),H=["create","project",k,A.trim(),...N];if(!await qi(k))return 1;let Y=l$2(k)?await Yi(H):await rn(H),U=Z(process.cwd());return Y===0&&U&&await qe(U),Y}let h=Vr(k),{projectName:S}=await b$3([{type:"input",name:"projectName",message:"Project name:",default:h,validate:b=>b.trim().length>0||"Project name is required"}]);t.splice(2,0,k,S.trim());}let i=t[2],a=f$3({kitId:i,framework:i,runtime:i});if(g$2(a))return Gl(a),1;if(!await qi(t[2]||""))return 1;if(d$1(t[2])){let k=await rn(t),h=Z(process.cwd());return k===0&&h&&await qe(h),k}if(l$2(t[2]))return await Yi(t);let l=t.includes("--create-workspace"),c=t.includes("--no-workspace"),u=t.includes("--yes")||t.includes("-y"),m=t.includes("--skip-git")||t.includes("--no-git");if(!!!an(process.cwd())){let{registerWorkspaceAtPath:k}=await import('./create-EAE2AJJL.js');if(l)await k(process.cwd(),{skipGit:m,yes:u,userConfig:await b$2()});else if(!c)if(u)await k(process.cwd(),{skipGit:m,yes:true,userConfig:await b$2()});else {let{createWs:h}=await b$3([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);h&&await k(process.cwd(),{skipGit:m,yes:false,userConfig:await b$2()});}}let f$1=[...t.filter(k=>{let h=k.split("=")[0];return !r.has(k)&&!r.has(h)})],g=Z(process.cwd()),P=t.includes("--skip-install")||!!g?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$5();let k=await e(f$1,{cwd:process.cwd(),env:P});if(k===0&&g&&!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 rapidkit init"))),k===0){let h=g||Z(process.cwd());if(h){try{let b=t[3];if(b){let A=t.indexOf("--output"),N=A>=0?t[A+1]:".",H=v.resolve(process.cwd(),N,b),Y=v.join(h,".python-version"),U=v.join(H,".python-version");if(j.existsSync(Y)&&j.existsSync(H)){let J=j.readFileSync(Y,"utf-8");j.writeFileSync(U,J.trim()+`
187
- `),f.debug(`Synced Python version ${J.trim()} from workspace to ${b}`);}}}catch(b){f.debug("Could not sync Python version from workspace:",b);}let{syncWorkspaceProjects:S}=await import('./workspace-IBTKZX7T.js');await S(h,true),await qe(h);}}return k}catch(k){let h=Qr(k);return h?await zo(f$1,h):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${k?.message??k}
188
- `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$5();let n=await e(t,{cwd:process.cwd()});if(n===0){let i=Z(process.cwd());if(i){let{syncWorkspaceProjects:a}=await import('./workspace-IBTKZX7T.js');await a(i,true);}}return n}catch(n){let i=Qr(n);return i?await zo(t,i):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${n?.message??n}
186
+ `),1}if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a$1("create project");let{kitChoice:k}=await b$3([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$7()}]);if(d$1(k)||l$2(k)){let b=Vr(k),{projectName:A}=await b$3([{type:"input",name:"projectName",message:"Project name:",default:b,validate:J=>J.trim().length>0||"Project name is required"}]),N=t.slice(2).filter(J=>J.startsWith("-")),H=["create","project",k,A.trim(),...N];if(!await qi(k))return 1;let Y=l$2(k)?await Yi(H):await rn(H),U=Z(process.cwd());return Y===0&&U&&await qe(U),Y}let h=Vr(k),{projectName:S}=await b$3([{type:"input",name:"projectName",message:"Project name:",default:h,validate:b=>b.trim().length>0||"Project name is required"}]);t.splice(2,0,k,S.trim());}let i=t[2],a=f$3({kitId:i,framework:i,runtime:i});if(g$2(a))return Gl(a),1;if(!await qi(t[2]||""))return 1;if(d$1(t[2])){let k=await rn(t),h=Z(process.cwd());return k===0&&h&&await qe(h),k}if(l$2(t[2]))return await Yi(t);let l=t.includes("--create-workspace"),c=t.includes("--no-workspace"),u=t.includes("--yes")||t.includes("-y"),m=t.includes("--skip-git")||t.includes("--no-git");if(!!!an(process.cwd())){let{registerWorkspaceAtPath:k}=await import('./create-TPFUONHK.js');if(l)await k(process.cwd(),{skipGit:m,yes:u,userConfig:await b$2()});else if(!c)if(u)await k(process.cwd(),{skipGit:m,yes:true,userConfig:await b$2()});else {let{createWs:h}=await b$3([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);h&&await k(process.cwd(),{skipGit:m,yes:false,userConfig:await b$2()});}}let f$1=[...t.filter(k=>{let h=k.split("=")[0];return !r.has(k)&&!r.has(h)})],g=Z(process.cwd()),P=t.includes("--skip-install")||!!g?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$5();let k=await e(f$1,{cwd:process.cwd(),env:P});if(k===0&&g&&!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 rapidkit init"))),k===0){let h=g||Z(process.cwd());if(h){try{let b=t[3];if(b){let A=t.indexOf("--output"),N=A>=0?t[A+1]:".",H=v.resolve(process.cwd(),N,b),Y=v.join(h,".python-version"),U=v.join(H,".python-version");if(j.existsSync(Y)&&j.existsSync(H)){let J=j.readFileSync(Y,"utf-8");j.writeFileSync(U,J.trim()+`
187
+ `),f.debug(`Synced Python version ${J.trim()} from workspace to ${b}`);}}}catch(b){f.debug("Could not sync Python version from workspace:",b);}let{syncWorkspaceProjects:S}=await import('./workspace-MPKEUHFP.js');await S(h,true),await qe(h);}}return k}catch(k){let h=Qr(k);return h?await zo(f$1,h):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${k?.message??k}
188
+ `),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$5();let n=await e(t,{cwd:process.cwd()});if(n===0){let i=Z(process.cwd());if(i){let{syncWorkspaceProjects:a}=await import('./workspace-MPKEUHFP.js');await a(i,true);}}return n}catch(n){let i=Qr(n);return i?await zo(t,i):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${n?.message??n}
189
189
  `),1)}return await d$5(),await e(t,{cwd:process.cwd()})}catch(n){let i=Qr(n);return i?await zo(t,i):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${n?.message??n}
190
190
  `),1)}}var Qi=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],ya=["analyze","readiness","doctor","autopilot","pipeline","import","adopt","snapshot","workspace","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands"],Ul=["analyze","readiness","doctor","autopilot","pipeline","import","adopt","snapshot","workspace","ai","config","product","infra","shell","commands"],Vl=["bootstrap","setup","cache","mirror"],Bl=[["project","commands"],["project","archives"],["project","archive"],["project","restore"],["project","delete"]],Hl=["init"],ql=k$1,Xi=[...ql,...l$1];function zl(t){return !!t&&ya.includes(t)}function ha(t){let e=t[0],o=t[1];return Bl.some(([r,n])=>e!==r?false:o?o===n:true)}function eo(t){return zl(t[0])||ha(t)}function Yl(t){return !!t&&Ul.includes(t)}function Zi(t){return Yl(t[0])||ha(t)}function ea(t){return !!t&&Vl.includes(t)}function Ql(t=process.env){let e=t.npm_config_user_agent||"",o=t.npm_execpath||"",r=t.npm_command||"";return e.startsWith("npm/")||e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(o)||/(?:^|[/\\])npm(?:\.cmd)?$/i.test(o)||r==="exec"||r==="x"||r==="run-script"}function wa(t={}){let e=q(process.cwd());if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("RapidKit 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"}`));}var ka="rapidkit-command-capabilities-v1",Xl="rapidkit-version-v1";function Zl(){return {schemaVersion:Xl,cli:"rapidkit-npm",version:b(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:ka,contracts:Uo()}}function ed(){let t=[...ya,"project"],e=["version","create","add","list","info","upgrade","diff","merge","optimize","license","checkpoint","reconcile","rollback","uninstall","frameworks","modules"],o=["init","dev","start","build","test","lint","format","help"],r=[...Ko],n=[...Go];return {schemaVersion:ka,scope:"global",cli:"rapidkit-npm",version:b(),cwd:process.cwd(),contracts:Uo(),commands:{npmOwned:t,coreBacked:e,projectScoped:o},workspace:{command:"workspace",subcommands:r,intelligenceSubcommands:n},commandMap:Object.fromEntries([...t.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...e.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"}])])}}function td(t={}){let e=ed();if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("RapidKit 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 `rapidkit project commands --json` inside a project."));}function nn(t){return s$1(t)?(wa({json:t.includes("--json")||t.includes("--ci")}),true):false}function sn(t$1){let e=q(process.cwd());if(!e.projectRoot)return false;let o=r(t$1,process.cwd());if(!o||o.status!=="unsupported")return false;console.error(s.red(t(o,e))),process.exit(1);}function We(t){return j.existsSync(v.join(t,".rapidkit-workspace"))||j.existsSync(v.join(t,".rapidkit","workspace.json"))}function va(t){let e=t;for(;;){let o=v.join(e,".rapidkit","context.json");if(j.existsSync(o))return o;let r=v.dirname(e);if(r===e)break;e=r;}return null}function an(t){let e=t,o=v.resolve(tmpdir());for(;;){let r=v.join(e,".rapidkit-workspace");if(j.existsSync(r)&&v.resolve(e)!==o)return r;let n=v.dirname(e);if(n===e)break;e=n;}return null}function Z(t){let e=t,o=v.resolve(tmpdir());for(;;){let r=v.join(e,".rapidkit-workspace");if(j.existsSync(r)&&v.resolve(e)!==o)return e;let n=v.dirname(e);if(n===e)break;e=n;}return null}async function qe(t,e){try{let{syncWorkspaceContract:o}=await import('./workspace-contract-OO4GMENV.js'),r=await o({workspacePath:t});if(!e?.silent&&(r.addedProjects.length>0||r.updatedProjects.length>0)&&console.log(s.gray(`\u2139\uFE0F Workspace contract synced (${r.contract.projects.length} project(s)).`)),!e?.silent&&r.verification.status!=="passed"){console.log(s.yellow("\u26A0\uFE0F Workspace contract verification failed after project sync."));for(let n of r.verification.violations)console.log(s.gray(` Violation: ${n}`));console.log(s.white(" Next: npx rapidkit workspace contract inspect"));}}catch(o){e?.silent||console.log(s.yellow(`\u26A0\uFE0F Workspace contract sync skipped: ${o.message}`));}}async function od(t,e=process.cwd(),o$1=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$1(o$1))return {detected:false};let n=o(e,o$1);for(let i of n){if(!await E__default.pathExists(i))continue;let a=i.toLowerCase();if(a.endsWith("rapidkit.cmd")||a.endsWith("rapidkit.exe"))return {detected:true,candidatePath:i,reason:"Found workspace-local rapidkit launcher on Windows."}}return {detected:false}}function rd(t){let e=t;for(;;){let o=v.join(e,".rapidkit-workspace"),r=v.join(e,".rapidkit","workspace.json");if(!j.existsSync(o)&&j.existsSync(r))return e;let n=v.dirname(e);if(n===e)break;e=n;}return null}var Pa={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function nd(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function Zt(t,e){let o=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return o?o[1]==="true":Pa[e]}function ta(t){let e=t??"";return {mode:nd(e),dependency_sharing_mode:ba(e),rules:{enforce_workspace_marker:Zt(e,"enforce_workspace_marker"),enforce_toolchain_lock:Zt(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:Zt(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:Zt(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:Zt(e,"require_mirror_lock_for_offline")}}}function oa(t,e,o){let r=`${e}: ${o}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(i.test(t))return t.replace(i,r);let a=/^[\t ]*rules:\s*(?:#.*)?$/m;return a.test(t)?t.replace(a,`${r}
191
191
  rules:`):`${t.endsWith(`
@@ -207,10 +207,10 @@ ${r}
207
207
  `),w(124);}},y)),p||(b.stdout?.on("data",N=>{P.push(N);}),b.stderr?.on("data",N=>{k.push(N);})),b.on("close",N=>{if(h)return;h=true,S&&clearTimeout(S);let H=Buffer.concat(P),Y=Buffer.concat(k),U=N&&N!==0&&H.length===0&&Y.length===0&&t==="npm"?f():"";process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] runCommandInCwd.close=${JSON.stringify({code:N,stdoutBytes:H.length,stderrBytes:Y.length,npmFailureExcerptBytes:U.length})}
208
208
  `),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(H.length>0&&process.stdout.write(H),Y.length>0?process.stderr.write(Y):U&&process.stderr.write(`${U}
209
209
  `)),w(N??1);}),b.on("error",()=>{h||(h=true,S&&clearTimeout(S),w(1));});})}function ld(t,e,o){if(t!=="npm")return null;let r=e[0];if(r!=="run"&&r!=="run-script")return null;let n=e.find((a,l)=>l>0&&!a.startsWith("-"));if(!n)return null;let i=v.join(o,"package.json");if(!j.existsSync(i))return null;try{let l=JSON.parse(j.readFileSync(i,"utf8")).scripts?.[n];return typeof l!="string"?null:dd(l)}catch{return null}}function dd(t){let e=t.trim(),o=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(o)return o[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let r=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return r?r[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function Be(t,e){await E__default.outputFile(t,`${JSON.stringify(e,null,2)}
210
- `,"utf-8");}async function pd(t,e,o){let r=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?v.resolve(e.workspace):null,i=n??Z(process.cwd()),a=false,l=false;if(n){if(!We(n)){let d=`Workspace path is not a valid RapidKit workspace: ${n}`;return e.json?console.log(JSON.stringify({error:d},null,2)):console.log(s.red(`\u274C ${d}`)),1}}else if(!i||!We(i)){let d=await pn();i=d.workspacePath,a=true,l=d.created;}if(!i||!We(i)){let d="Not inside a RapidKit workspace";return e.json?console.log(JSON.stringify({error:d},null,2)):(console.log(s.red(`\u274C ${d}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let c=`cd ${i}`,u=o?.syncWorkspaceProjects??(async d=>{if(r)throw new Error("forced sync failure for command-level import rollback test");let{syncWorkspaceProjects:p}=await import('./workspace-IBTKZX7T.js');await p(d,true),await qe(d,{silent:true});}),m=o?.rollbackImportedProjectImport??Gi;try{let d=await Ui({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0});try{await u(i);}catch(p){await m(i,d.path);try{await u(i);}catch{}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${p instanceof Error?p.message:String(p)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?l:false,suggestedCdCommand:c,importedProject:d},null,2)),0;if(a&&console.log(s.yellow(`\u2139 Imported outside a workspace, so RapidKit used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${d.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${d.path}`)),console.log(s.gray(` Stack: ${d.stack} (${d.confidence})`)),console.log(s.gray(` Source: ${e.git===true||Yr(t)?"git-url":"local-folder"}`)),!d.profileCompatibility.ok){let p=qo(d.profileCompatibility);console.log(s.yellow(` Profile warning: ${d.profileCompatibility.message}`)),p&&console.log(s.gray(` ${p}`));}return console.log(s.gray(` Next shell step: ${c}`)),0}catch(d){let p=d instanceof Error?d.message:String(d);return e.json?console.log(JSON.stringify({error:p},null,2)):console.log(s.red(`\u274C Import failed: ${p}`)),1}}async function ud(t,e,o){let r=v.resolve(t||process.cwd()),n=e.workspace?v.resolve(e.workspace):null,i=n??Z(process.cwd()),a=false,l=false;if(n){if(!We(n)){let f=`Workspace path is not a valid RapidKit workspace: ${n}`;return e.json?console.log(JSON.stringify({error:f},null,2)):console.log(s.red(`\u274C ${f}`)),1}}else if(!i||!We(i)){let f=await pn();i=f.workspacePath,a=true,l=f.created;}if(!i||!We(i)){let f="Not inside a RapidKit 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 c=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),u=o?.syncWorkspaceProjects??(async f=>{if(c)throw new Error("forced sync failure for command-level adopt rollback test");let{syncWorkspaceProjects:g}=await import('./workspace-IBTKZX7T.js');await g(f,true),await qe(f,{silent:true});}),m=o?.registerProjectInWorkspace??(async(f,g,y)=>{let{registerProjectInWorkspace:w}=await import('./workspace-IBTKZX7T.js');await w(f,g,y);}),d=o?.registerWorkspace??(async(f,g)=>{let{registerWorkspace:y}=await import('./workspace-IBTKZX7T.js');await y(f,g);}),p=o?.rollbackAdoptedProjectImport??Vi;try{let f=v.join(r,".rapidkit","project.json"),g=await E__default.pathExists(f)?await E__default.readJson(f):null,y=await Bi({workspacePath:i,source:r,name:e.name,dryRun:e.dryRun===true});if(e.dryRun!==true)try{await d(i,v.basename(i)),await m(i,y.name,y.path),await u(i);}catch(w){throw await p(i,y.path,g),new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${w instanceof Error?w.message:String(w)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?l:false,dryRun:e.dryRun===true,adoptedProject:y},null,2)),0;if(a&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so RapidKit used the default workspace: ${i}`)),e.dryRun===true&&console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.green(`\u2714 Adopted project: ${y.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${y.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${y.stack} (${y.confidence})`)),!y.profileCompatibility.ok){let w=qo(y.profileCompatibility);console.log(s.yellow(` Profile warning: ${y.profileCompatibility.message}`)),w&&console.log(s.gray(` ${w}`));}return console.log(s.gray(` Report: ${y.adoptReadinessPath}`)),console.log(s.gray(" Next: npx rapidkit workspace model --json")),0}catch(f){let g=f instanceof Error?f.message:String(f);return e.json?console.log(JSON.stringify({error:g},null,2)):console.log(s.red(`\u274C Adopt failed: ${g}`)),1}}async function cn(t){let e=new Set(["python-only","polyglot","enterprise"]),o=md(),r="minimal",n=false;try{let c=v.join(t,".rapidkit","workspace.json"),u=JSON.parse(await j.promises.readFile(c,"utf-8"));r=u.profile??"minimal",n=u.bootstrap_note==="python-engine-skipped"||u.engine?.python_core?.status==="skipped";}catch{r="minimal";}if(!await(async()=>{if(!n&&e.has(r))return true;let c=await xa(t);if(c.length===0)return false;for(let u of c){let m=d$4(u),d=m?.module_support,p=j$1(u);if(n){if(p?.moduleSupport===true)return true;continue}if(!(e$1(m,u)||g$1(m,u)||h$2(m,u))&&d!==false)return i(m,u)||f$2(m,u),true}return false})())return 0;let a="poetry";try{let{readWorkspaceMarker:c}=await import('./workspace-marker-5GAJSOFP.js'),m=(await c(t))?.metadata?.npm?.installMethod;(m==="poetry"||m==="venv"||m==="pipx"||m==="pip")&&(a=m);}catch{}let l=async()=>{let c=Wl(t);if(!await E__default.pathExists(c)){let p=await Fl(t);if(p!==0)return p}let u=process.env.RAPIDKIT_DEV_PATH,d=(u?await E__default.pathExists(u):false)&&u?["-m","pip","install",u,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await B(c,d,t,{timeoutMs:o})};if(a==="venv"){let c=await l();if(c!==0)return c}else if(a==="poetry"){let c=v.join(t,"pyproject.toml"),u=false;try{u=(await j.promises.readFile(c,"utf-8")).includes("rapidkit-core");}catch{u=false;}if(u){let m=await l();if(m!==0)return m}else {let m=await B("poetry",["install","--no-root"],t,{timeoutMs:o});if(m!==0)return m;let d=await B("poetry",["add","rapidkit-core"],t,{timeoutMs:o});if(d!==0)return d}}else return 0;try{let{writeWorkspaceLauncher:c}=await import('./create-EAE2AJJL.js');await c(t,a==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:c}=await import('./workspace-python-engine-state-AEEZ7QYB.js');await c(t,{installMethod:a==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function md(){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 xa(t){let e=[],o=new Set,r=[t];for(;r.length>0;){let n=r.pop();if(!n||o.has(n))continue;o.add(n);let i=[];try{i=await j.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){if(!a.isDirectory()||a.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(a.name))continue;let l=v.join(n,a.name),c=v.join(l,".rapidkit","context.json"),u=v.join(l,".rapidkit","project.json");if(await E__default.pathExists(c)||await E__default.pathExists(u)){e.push(l);continue}r.push(l);}}return e}function fd(t){return i$6(t)}async function pn(){let t=j$2(),e=v.basename(t),o=We(t);await E__default.ensureDir(v.join(t,".rapidkit")),await b$8(t,d$6(e,b()));let r=v.join(t,".rapidkit","workspace.json");return await E__default.pathExists(r)||await Be(r,{name:e,workspace_name:e,profile:"minimal",createdAt:new Date().toISOString(),createdBy:"rapidkit-npm-import-fallback"}),{workspacePath:t,created:!o}}async function en(t){let o=await Ne("go",{runCommandInCwd:B,runCoreRapidkit:e}).initProject(t);return X(o)}function X(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function gt(t,e$1){let o=Ne("node",{runCommandInCwd:B,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return X(n)}if(t==="dev"){let n=await o.runDev(e$1);return X(n)}if(t==="test"){let n=await o.runTest(e$1);return X(n)}if(t==="build"){let n=await o.runBuild(e$1);return X(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return X(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return X(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return X(r)}async function He(t,e$1){let o=Ne("java",{runCommandInCwd:B,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return X(n)}if(t==="dev"){let n=await o.runDev(e$1);return X(n)}if(t==="test"){let n=await o.runTest(e$1);return X(n)}if(t==="build"){let n=await o.runBuild(e$1);return X(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return X(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return X(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return X(r)}function tn(t,e,o){let r=o.filter(n=>n.status==="failed").map(n=>{let i=n.id||"check";return n.message?`${i}: ${n.message}`:i}).slice(0,12);return f$4(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:r,runId:e$4()})}async function na(t,e=ln){let o=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let i$1=function(x){if(!x)return null;let $=x.trim().toLowerCase();return $==="minimal"||$==="java-only"||$==="go-only"||$==="dotnet-only"||$==="python-only"||$==="node-only"||$==="polyglot"||$==="enterprise"?$:null},a=function(x){let Fe=x.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",ye=(se,be)=>{let Ae=x.match(new RegExp(`^\\s*${se}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return Ae?Ae[1].toLowerCase()==="true":be};return {mode:Fe,dependency_sharing_mode:ba(x),rules:{enforce_workspace_marker:ye("enforce_workspace_marker",true),enforce_toolchain_lock:ye("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:ye("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:ye("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:ye("require_mirror_lock_for_offline",true)}}};let l=["init"],c,u=false,m=false,d=false,p=false;for(let x=1;x<t.length;x+=1){let $=t[x];if($==="--ci"){u=true;continue}if($==="--offline"){m=true;continue}if($==="--json"){d=true;continue}if($==="--compliance-only"){p=true;continue}if($==="--profile"){let Q=t[x+1];if(!Q||Q.startsWith("-"))return console.log(s.yellow("Usage: rapidkit bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;c=Q,x+=1;continue}if($.startsWith("--profile=")){c=$.slice(10);continue}l.push($);}let f=i$1(c);if(c&&!f)return console.log(s.red(`Invalid profile: ${c}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let g=process.cwd(),y=l.slice(1).filter(x=>!x.startsWith("-"));if(y.length>0){let x=v.resolve(g,y[0]),$=d$4(x),Q=j.existsSync(x)?await yt(x):"unknown";if(!We(x)&&(e$1($,x)||g$1($,x)||h$2($,x)||f$2($,x)||i($,x)||Q!=="unknown"))return await e(l)}let w=v.join(g,".rapidkit-workspace"),P=v.join(g,".rapidkit","workspace.json"),k;!j.existsSync(w)&&j.existsSync(P)?k=g:(k=Z(g),k||(k=rd(g)));let h=[],S=null,b=null;if(k)try{let x=v.join(k,".rapidkit","workspace.json"),$=await j.promises.readFile(x,"utf-8"),Q=JSON.parse($);b=i$1(Q.profile);}catch{b=null;}let A=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],N={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"},H=f;if(!!k&&!f&&!u&&!d&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let x=b||"minimal",{chosenProfile:$}=await b$3([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${x})`,choices:A.map(Q=>({name:Q===x?`${N[Q]} \u2190 current`:N[Q],value:Q})),default:A.indexOf(x)}]);H=$;}let U=H||b||"minimal";if(k)try{let $=U==="python-only"||U==="polyglot"||U==="enterprise"?"poetry":"venv",Q;try{let be=(await j.promises.readFile(v.join(k,".python-version"),"utf-8")).trim();be&&(Q=be);}catch{}let{syncWorkspaceFoundationFiles:Fe}=await import('./create-EAE2AJJL.js'),ye=await Fe(k,{workspaceName:v.basename(k),installMethod:$,pythonVersion:Q,profile:U,writeMarker:true,writeGitignore:true,onlyIfMissing:true});h.push({id:"workspace.legacy.sync",status:ye.length>0?"passed":"skipped",message:ye.length>0?`Legacy workspace foundation synchronized: ${ye.join(", ")}`:"Workspace foundation files are already up to date."});}catch(x){h.push({id:"workspace.legacy.sync",status:"failed",message:`Failed to synchronize legacy workspace foundation files: ${x.message}`});}if(k&&H&&H!==b)try{let x=v.join(k,".rapidkit","workspace.json"),$=await j.promises.readFile(x,"utf-8"),Q=JSON.parse($);Q.profile=H,await j.promises.writeFile(x,JSON.stringify(Q,null,2)+`
210
+ `,"utf-8");}async function pd(t,e,o){let r=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?v.resolve(e.workspace):null,i=n??Z(process.cwd()),a=false,l=false;if(n){if(!We(n)){let d=`Workspace path is not a valid RapidKit workspace: ${n}`;return e.json?console.log(JSON.stringify({error:d},null,2)):console.log(s.red(`\u274C ${d}`)),1}}else if(!i||!We(i)){let d=await pn();i=d.workspacePath,a=true,l=d.created;}if(!i||!We(i)){let d="Not inside a RapidKit workspace";return e.json?console.log(JSON.stringify({error:d},null,2)):(console.log(s.red(`\u274C ${d}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let c=`cd ${i}`,u=o?.syncWorkspaceProjects??(async d=>{if(r)throw new Error("forced sync failure for command-level import rollback test");let{syncWorkspaceProjects:p}=await import('./workspace-MPKEUHFP.js');await p(d,true),await qe(d,{silent:true});}),m=o?.rollbackImportedProjectImport??Gi;try{let d=await Ui({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0});try{await u(i);}catch(p){await m(i,d.path);try{await u(i);}catch{}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${p instanceof Error?p.message:String(p)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?l:false,suggestedCdCommand:c,importedProject:d},null,2)),0;if(a&&console.log(s.yellow(`\u2139 Imported outside a workspace, so RapidKit used the default workspace: ${i}`)),console.log(s.green(`\u2714 Imported project: ${d.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${d.path}`)),console.log(s.gray(` Stack: ${d.stack} (${d.confidence})`)),console.log(s.gray(` Source: ${e.git===true||Yr(t)?"git-url":"local-folder"}`)),!d.profileCompatibility.ok){let p=qo(d.profileCompatibility);console.log(s.yellow(` Profile warning: ${d.profileCompatibility.message}`)),p&&console.log(s.gray(` ${p}`));}return console.log(s.gray(` Next shell step: ${c}`)),0}catch(d){let p=d instanceof Error?d.message:String(d);return e.json?console.log(JSON.stringify({error:p},null,2)):console.log(s.red(`\u274C Import failed: ${p}`)),1}}async function ud(t,e,o){let r=v.resolve(t||process.cwd()),n=e.workspace?v.resolve(e.workspace):null,i=n??Z(process.cwd()),a=false,l=false;if(n){if(!We(n)){let f=`Workspace path is not a valid RapidKit workspace: ${n}`;return e.json?console.log(JSON.stringify({error:f},null,2)):console.log(s.red(`\u274C ${f}`)),1}}else if(!i||!We(i)){let f=await pn();i=f.workspacePath,a=true,l=f.created;}if(!i||!We(i)){let f="Not inside a RapidKit 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 c=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),u=o?.syncWorkspaceProjects??(async f=>{if(c)throw new Error("forced sync failure for command-level adopt rollback test");let{syncWorkspaceProjects:g}=await import('./workspace-MPKEUHFP.js');await g(f,true),await qe(f,{silent:true});}),m=o?.registerProjectInWorkspace??(async(f,g,y)=>{let{registerProjectInWorkspace:w}=await import('./workspace-MPKEUHFP.js');await w(f,g,y);}),d=o?.registerWorkspace??(async(f,g)=>{let{registerWorkspace:y}=await import('./workspace-MPKEUHFP.js');await y(f,g);}),p=o?.rollbackAdoptedProjectImport??Vi;try{let f=v.join(r,".rapidkit","project.json"),g=await E__default.pathExists(f)?await E__default.readJson(f):null,y=await Bi({workspacePath:i,source:r,name:e.name,dryRun:e.dryRun===true});if(e.dryRun!==true)try{await d(i,v.basename(i)),await m(i,y.name,y.path),await u(i);}catch(w){throw await p(i,y.path,g),new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${w instanceof Error?w.message:String(w)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:a?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:a?l:false,dryRun:e.dryRun===true,adoptedProject:y},null,2)),0;if(a&&console.log(s.yellow(`\u2139 Adopted outside a workspace, so RapidKit used the default workspace: ${i}`)),e.dryRun===true&&console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.green(`\u2714 Adopted project: ${y.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Project: ${y.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)")),console.log(s.gray(` Stack: ${y.stack} (${y.confidence})`)),!y.profileCompatibility.ok){let w=qo(y.profileCompatibility);console.log(s.yellow(` Profile warning: ${y.profileCompatibility.message}`)),w&&console.log(s.gray(` ${w}`));}return console.log(s.gray(` Report: ${y.adoptReadinessPath}`)),console.log(s.gray(" Next: npx rapidkit workspace model --json")),0}catch(f){let g=f instanceof Error?f.message:String(f);return e.json?console.log(JSON.stringify({error:g},null,2)):console.log(s.red(`\u274C Adopt failed: ${g}`)),1}}async function cn(t){let e=new Set(["python-only","polyglot","enterprise"]),o=md(),r="minimal",n=false;try{let c=v.join(t,".rapidkit","workspace.json"),u=JSON.parse(await j.promises.readFile(c,"utf-8"));r=u.profile??"minimal",n=u.bootstrap_note==="python-engine-skipped"||u.engine?.python_core?.status==="skipped";}catch{r="minimal";}if(!await(async()=>{if(!n&&e.has(r))return true;let c=await xa(t);if(c.length===0)return false;for(let u of c){let m=d$4(u),d=m?.module_support,p=j$1(u);if(n){if(p?.moduleSupport===true)return true;continue}if(!(e$1(m,u)||g$1(m,u)||h$2(m,u))&&d!==false)return i(m,u)||f$2(m,u),true}return false})())return 0;let a="poetry";try{let{readWorkspaceMarker:c}=await import('./workspace-marker-5GAJSOFP.js'),m=(await c(t))?.metadata?.npm?.installMethod;(m==="poetry"||m==="venv"||m==="pipx"||m==="pip")&&(a=m);}catch{}let l=async()=>{let c=Wl(t);if(!await E__default.pathExists(c)){let p=await Fl(t);if(p!==0)return p}let u=process.env.RAPIDKIT_DEV_PATH,d=(u?await E__default.pathExists(u):false)&&u?["-m","pip","install",u,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await B(c,d,t,{timeoutMs:o})};if(a==="venv"){let c=await l();if(c!==0)return c}else if(a==="poetry"){let c=v.join(t,"pyproject.toml"),u=false;try{u=(await j.promises.readFile(c,"utf-8")).includes("rapidkit-core");}catch{u=false;}if(u){let m=await l();if(m!==0)return m}else {let m=await B("poetry",["install","--no-root"],t,{timeoutMs:o});if(m!==0)return m;let d=await B("poetry",["add","rapidkit-core"],t,{timeoutMs:o});if(d!==0)return d}}else return 0;try{let{writeWorkspaceLauncher:c}=await import('./create-TPFUONHK.js');await c(t,a==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:c}=await import('./workspace-python-engine-state-AEEZ7QYB.js');await c(t,{installMethod:a==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function md(){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 xa(t){let e=[],o=new Set,r=[t];for(;r.length>0;){let n=r.pop();if(!n||o.has(n))continue;o.add(n);let i=[];try{i=await j.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let a of i){if(!a.isDirectory()||a.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(a.name))continue;let l=v.join(n,a.name),c=v.join(l,".rapidkit","context.json"),u=v.join(l,".rapidkit","project.json");if(await E__default.pathExists(c)||await E__default.pathExists(u)){e.push(l);continue}r.push(l);}}return e}function fd(t){return i$6(t)}async function pn(){let t=j$2(),e=v.basename(t),o=We(t);await E__default.ensureDir(v.join(t,".rapidkit")),await b$8(t,d$6(e,b()));let r=v.join(t,".rapidkit","workspace.json");return await E__default.pathExists(r)||await Be(r,{name:e,workspace_name:e,profile:"minimal",createdAt:new Date().toISOString(),createdBy:"rapidkit-npm-import-fallback"}),{workspacePath:t,created:!o}}async function en(t){let o=await Ne("go",{runCommandInCwd:B,runCoreRapidkit:e}).initProject(t);return X(o)}function X(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function gt(t,e$1){let o=Ne("node",{runCommandInCwd:B,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return X(n)}if(t==="dev"){let n=await o.runDev(e$1);return X(n)}if(t==="test"){let n=await o.runTest(e$1);return X(n)}if(t==="build"){let n=await o.runBuild(e$1);return X(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return X(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return X(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return X(r)}async function He(t,e$1){let o=Ne("java",{runCommandInCwd:B,runCoreRapidkit:e});if(t==="init"){let n=await o.initProject(e$1);return X(n)}if(t==="dev"){let n=await o.runDev(e$1);return X(n)}if(t==="test"){let n=await o.runTest(e$1);return X(n)}if(t==="build"){let n=await o.runBuild(e$1);return X(n)}if(t==="lint"){let n=await o.runLint?.(e$1);return X(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await o.runFormat?.(e$1);return X(n??{exitCode:1,message:"Format is not supported."})}let r=await o.runStart(e$1);return X(r)}function tn(t,e,o){let r=o.filter(n=>n.status==="failed").map(n=>{let i=n.id||"check";return n.message?`${i}: ${n.message}`:i}).slice(0,12);return f$4(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:r,runId:e$4()})}async function na(t,e=ln){let o=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let i$1=function(x){if(!x)return null;let $=x.trim().toLowerCase();return $==="minimal"||$==="java-only"||$==="go-only"||$==="dotnet-only"||$==="python-only"||$==="node-only"||$==="polyglot"||$==="enterprise"?$:null},a=function(x){let Fe=x.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",ye=(se,be)=>{let Ae=x.match(new RegExp(`^\\s*${se}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return Ae?Ae[1].toLowerCase()==="true":be};return {mode:Fe,dependency_sharing_mode:ba(x),rules:{enforce_workspace_marker:ye("enforce_workspace_marker",true),enforce_toolchain_lock:ye("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:ye("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:ye("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:ye("require_mirror_lock_for_offline",true)}}};let l=["init"],c,u=false,m=false,d=false,p=false;for(let x=1;x<t.length;x+=1){let $=t[x];if($==="--ci"){u=true;continue}if($==="--offline"){m=true;continue}if($==="--json"){d=true;continue}if($==="--compliance-only"){p=true;continue}if($==="--profile"){let Q=t[x+1];if(!Q||Q.startsWith("-"))return console.log(s.yellow("Usage: rapidkit bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;c=Q,x+=1;continue}if($.startsWith("--profile=")){c=$.slice(10);continue}l.push($);}let f=i$1(c);if(c&&!f)return console.log(s.red(`Invalid profile: ${c}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let g=process.cwd(),y=l.slice(1).filter(x=>!x.startsWith("-"));if(y.length>0){let x=v.resolve(g,y[0]),$=d$4(x),Q=j.existsSync(x)?await yt(x):"unknown";if(!We(x)&&(e$1($,x)||g$1($,x)||h$2($,x)||f$2($,x)||i($,x)||Q!=="unknown"))return await e(l)}let w=v.join(g,".rapidkit-workspace"),P=v.join(g,".rapidkit","workspace.json"),k;!j.existsSync(w)&&j.existsSync(P)?k=g:(k=Z(g),k||(k=rd(g)));let h=[],S=null,b=null;if(k)try{let x=v.join(k,".rapidkit","workspace.json"),$=await j.promises.readFile(x,"utf-8"),Q=JSON.parse($);b=i$1(Q.profile);}catch{b=null;}let A=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],N={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"},H=f;if(!!k&&!f&&!u&&!d&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let x=b||"minimal",{chosenProfile:$}=await b$3([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${x})`,choices:A.map(Q=>({name:Q===x?`${N[Q]} \u2190 current`:N[Q],value:Q})),default:A.indexOf(x)}]);H=$;}let U=H||b||"minimal";if(k)try{let $=U==="python-only"||U==="polyglot"||U==="enterprise"?"poetry":"venv",Q;try{let be=(await j.promises.readFile(v.join(k,".python-version"),"utf-8")).trim();be&&(Q=be);}catch{}let{syncWorkspaceFoundationFiles:Fe}=await import('./create-TPFUONHK.js'),ye=await Fe(k,{workspaceName:v.basename(k),installMethod:$,pythonVersion:Q,profile:U,writeMarker:true,writeGitignore:true,onlyIfMissing:true});h.push({id:"workspace.legacy.sync",status:ye.length>0?"passed":"skipped",message:ye.length>0?`Legacy workspace foundation synchronized: ${ye.join(", ")}`:"Workspace foundation files are already up to date."});}catch(x){h.push({id:"workspace.legacy.sync",status:"failed",message:`Failed to synchronize legacy workspace foundation files: ${x.message}`});}if(k&&H&&H!==b)try{let x=v.join(k,".rapidkit","workspace.json"),$=await j.promises.readFile(x,"utf-8"),Q=JSON.parse($);Q.profile=H,await j.promises.writeFile(x,JSON.stringify(Q,null,2)+`
211
211
  `,"utf-8");}catch{}let J={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}},Se=null;if(k)try{let x=await j.promises.readFile(v.join(k,".rapidkit","policies.yml"),"utf-8");Se=x,J=a(x);}catch{h.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else h.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(k){let x=ja(Se);J.dependency_sharing_mode=x.mode,h.push({id:"policy.schema.dependency_sharing_mode",status:x.status,message:x.message}),h.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:J.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":J.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 $=j.existsSync(v.join(k,".rapidkit-workspace"));h.push({id:"policy.enforce_workspace_marker",status:!J.rules.enforce_workspace_marker||$?"passed":"failed",message:!J.rules.enforce_workspace_marker||$?"Workspace marker policy satisfied.":"Workspace marker policy failed: .rapidkit-workspace is missing."});let Q=j.existsSync(v.join(k,".rapidkit","toolchain.lock"));h.push({id:"policy.enforce_toolchain_lock",status:!J.rules.enforce_toolchain_lock||Q?"passed":"failed",message:!J.rules.enforce_toolchain_lock||Q?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .rapidkit/toolchain.lock is missing."});let Fe=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||j.existsSync(v.join(k,".rapidkit","trusted-sources.lock"));h.push({id:"policy.disallow_untrusted_tool_sources",status:!J.rules.disallow_untrusted_tool_sources||Fe?"passed":"failed",message:!J.rules.disallow_untrusted_tool_sources||Fe?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .rapidkit/trusted-sources.lock."});let ye=v.join(k,".rapidkit","compatibility-matrix.json"),se=j.existsSync(ye),be=J.rules.enforce_compatibility_matrix;if(h.push({id:"policy.enforce_compatibility_matrix",status:!be||se?"passed":"failed",message:!be||se?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .rapidkit/compatibility-matrix.json is missing."}),se)try{let Ye=await j.promises.readFile(ye,"utf-8"),Tt=JSON.parse(Ye),mn=!!Tt&&typeof Tt=="object";h.push({id:"compatibility.matrix.parse",status:mn?"passed":"failed",message:mn?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{h.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let Ae=v.join(k,".rapidkit","mirror-config.json"),Dt=v.join(k,".rapidkit","mirror.lock"),Xo=j.existsSync(Ae),Zo=j.existsSync(Dt),un={};if(Xo)try{un=JSON.parse(await j.promises.readFile(Ae,"utf-8")),h.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{h.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .rapidkit/mirror-config.json."});}let er=await Br(k,{ciMode:u,offlineMode:m});if(h.push(...er.checks.map(Ye=>({id:Ye.id,status:Ye.status,message:Ye.message}))),S=er.details,er.details.lockWritten&&(Zo=true),m){let Ye=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||un.enabled===true;h.push({id:"offline.mirror.enabled",status:Ye?"passed":"failed",message:Ye?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .rapidkit/mirror-config.json {"enabled": true}).'});let Tt=J.rules.require_mirror_lock_for_offline;h.push({id:"offline.mirror.lock",status:!Tt||Zo?"passed":"failed",message:!Tt||Zo?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .rapidkit/mirror.lock is missing."});}else h.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let oo=mt({profile:U,runtimes:await ft(k),mode:J.mode});oo.profile!=="enterprise"?h.push({id:oo.checkId,status:oo.status,message:oo.message}):(h.push({id:"profile.enterprise.ci",status:u?"passed":"failed",message:u?"enterprise profile running with --ci.":"enterprise profile expects --ci for deterministic non-interactive mode."}),h.push({id:"profile.enterprise.compatibility-matrix",status:se?"passed":"failed",message:se?"enterprise profile has compatibility matrix.":"enterprise profile requires .rapidkit/compatibility-matrix.json."}),h.push({id:"profile.enterprise.mirror-config",status:Xo?"passed":"failed",message:Xo?"enterprise profile has mirror configuration.":"enterprise profile requires .rapidkit/mirror-config.json."}));}u&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),m&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let V=h.some(x=>x.id.startsWith("policy.schema.")&&x.status==="failed")||J.mode==="strict"&&h.some(x=>x.status==="failed"),R=k||g,ee=v.join(R,".rapidkit","reports"),de=new Date().toISOString().replace(/[:.]/g,"-"),q=v.join(ee,`bootstrap-compliance-${de}.json`),pe=v.join(ee,"bootstrap-compliance.latest.json"),ve={command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:k,profile:U,options:{ci:u,offline:m,strict:J.mode==="strict"},policyMode:J.mode,policyRules:J.rules,mirrorLifecycle:S,checks:h};if(V){let x=tn({...ve,result:"blocked",initExitCode:null},1,h);return await E__default.ensureDir(ee),await Be(q,x),await Be(pe,x),d?process.stdout.write(`${JSON.stringify(x,null,2)}
212
212
  `):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${q}`))),1}if(d&&U==="enterprise"&&!u){let x=tn({...ve,result:"blocked",initExitCode:null,complianceOnly:false,bootstrapRuntimeSkipped:{reason:"enterprise JSON bootstrap requires --ci for deterministic non-interactive execution.",nextAction:"npx rapidkit bootstrap --profile enterprise --ci --json"}},1,h);return await E__default.ensureDir(ee),await Be(q,x),await Be(pe,x),process.stdout.write(`${JSON.stringify(x,null,2)}
213
- `),1}let ue=async x=>{let $=process.stdout.write.bind(process.stdout),Q=process.stderr.write.bind(process.stderr),Fe=[],ye=[];process.stdout.write=((se,be,Ae)=>{let Dt=typeof be=="function"?be:typeof Ae=="function"?Ae:void 0;return Fe.push(typeof se=="string"?se:se instanceof Uint8Array?Buffer.from(se).toString("utf8"):String(se)),Dt?.(),true}),process.stderr.write=((se,be,Ae)=>{let Dt=typeof be=="function"?be:typeof Ae=="function"?Ae:void 0;return ye.push(typeof se=="string"?se:se instanceof Uint8Array?Buffer.from(se).toString("utf8"):String(se)),Dt?.(),true});try{return {exitCode:await x(),stdout:Fe.join(""),stderr:ye.join("")}}finally{process.stdout.write=$,process.stderr.write=Q;}},ge=x=>{let $=x.split(/\r?\n/).map(Q=>Q.trim()).filter(Boolean);return {bytes:Buffer.byteLength(x),excerpt:$.slice(0,12)}},M=0,at;if(!(d&&p))if(d){let x=await ue(()=>e(l));M=x.exitCode,at={captured:true,stdout:ge(x.stdout),stderr:ge(x.stderr)};}else M=await e(l);let ht=h.filter(x=>x.status==="failed").length,Nt=M!==0?"failed":ht>0?"ok_with_warnings":"ok",me=M!==0?M:ht>0?1:0,ze=tn({...ve,result:Nt,initExitCode:M,complianceOnly:d&&p,...at?{initOutput:at}:{}},me,h);if(await E__default.ensureDir(ee),await Be(q,ze),await Be(pe,ze),k&&M===0)try{let{syncWorkspaceProjects:x}=await import('./workspace-IBTKZX7T.js');await x(k,d),await qe(k,{silent:d});}catch{}if(d)process.stdout.write(`${JSON.stringify(ze,null,2)}
213
+ `),1}let ue=async x=>{let $=process.stdout.write.bind(process.stdout),Q=process.stderr.write.bind(process.stderr),Fe=[],ye=[];process.stdout.write=((se,be,Ae)=>{let Dt=typeof be=="function"?be:typeof Ae=="function"?Ae:void 0;return Fe.push(typeof se=="string"?se:se instanceof Uint8Array?Buffer.from(se).toString("utf8"):String(se)),Dt?.(),true}),process.stderr.write=((se,be,Ae)=>{let Dt=typeof be=="function"?be:typeof Ae=="function"?Ae:void 0;return ye.push(typeof se=="string"?se:se instanceof Uint8Array?Buffer.from(se).toString("utf8"):String(se)),Dt?.(),true});try{return {exitCode:await x(),stdout:Fe.join(""),stderr:ye.join("")}}finally{process.stdout.write=$,process.stderr.write=Q;}},ge=x=>{let $=x.split(/\r?\n/).map(Q=>Q.trim()).filter(Boolean);return {bytes:Buffer.byteLength(x),excerpt:$.slice(0,12)}},M=0,at;if(!(d&&p))if(d){let x=await ue(()=>e(l));M=x.exitCode,at={captured:true,stdout:ge(x.stdout),stderr:ge(x.stderr)};}else M=await e(l);let ht=h.filter(x=>x.status==="failed").length,Nt=M!==0?"failed":ht>0?"ok_with_warnings":"ok",me=M!==0?M:ht>0?1:0,ze=tn({...ve,result:Nt,initExitCode:M,complianceOnly:d&&p,...at?{initOutput:at}:{}},me,h);if(await E__default.ensureDir(ee),await Be(q,ze),await Be(pe,ze),k&&M===0)try{let{syncWorkspaceProjects:x}=await import('./workspace-MPKEUHFP.js');await x(k,d),await qe(k,{silent:d});}catch{}if(d)process.stdout.write(`${JSON.stringify(ze,null,2)}
214
214
  `);else {let x=h.filter($=>$.status==="failed").length;x>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${x} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${q}`));}return M}finally{typeof o>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=o;}}async function sa(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: rapidkit setup <python|node|go|java|dotnet> [--warm-deps]")),0;let e$1=(t[1]||"").toLowerCase(),o=t.includes("--json"),r=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!e$1||!["python","node","go","java","dotnet"].includes(e$1))return o?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: rapidkit setup <python|node|go|java|dotnet> [--warm-deps]"},null,2)}
215
215
  `):console.log(s.yellow("Usage: rapidkit setup <python|node|go|java|dotnet> [--warm-deps]")),1;let n=async(p,f)=>{if(p==="node"){if(!j.existsSync(v.join(f,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let y=j.existsSync(v.join(f,"pnpm-lock.yaml")),w=j.existsSync(v.join(f,"yarn.lock"));return y?{exitCode:await B("pnpm",["install","--lockfile-only","--ignore-scripts"],f)}:w?{exitCode:await B("yarn",["install","--ignore-scripts"],f)}:{exitCode:await B("npm",["install","--package-lock-only","--ignore-scripts"],f)}}if(p==="go")return j.existsSync(v.join(f,"go.mod"))?{exitCode:await B("go",["mod","download"],f)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(p==="java"){let g=j.existsSync(v.join(f,"pom.xml")),y=j.existsSync(v.join(f,"build.gradle"))||j.existsSync(v.join(f,"build.gradle.kts")),w=v.join(f,process.platform==="win32"?"gradlew.bat":"gradlew"),P=j.existsSync(w);return !g&&!y?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:g?{exitCode:await B("mvn",["-B","-q","-DskipTests","dependency:go-offline"],f)}:{exitCode:await B(P?w:"gradle",["--no-daemon","dependencies"],f)}}return p==="dotnet"?(()=>{let y=[{dir:f,depth:0}],w=new Set(["bin","obj",".git","node_modules",".rapidkit"]);for(;y.length>0;){let P=y.shift();if(!P||P.depth>3)continue;let k=[];try{k=j.readdirSync(P.dir,{withFileTypes:true});}catch{continue}for(let h of k)if(h.isFile()){let S=h.name.toLowerCase();if(S.endsWith(".sln")||S.endsWith(".csproj"))return true}else h.isDirectory()&&!w.has(h.name)&&y.push({dir:v.join(P.dir,h.name),depth:P.depth+1});}return false})()?{exitCode:await B("dotnet",["restore"],f)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:{exitCode:0,message:"Dependency warm-up currently applies to node/go/java/dotnet runtimes."}};if(o){let p=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let g=await Ne(e$1,{runCommandInCwd:B,runCoreRapidkit:async(P,k)=>(await g$3(P,{...k,cwd:void 0})).exitCode}).checkPrereqs(),y=Z(process.cwd()),w=null;if(e$1==="node"&&g.exitCode===0&&(w=process.version),y&&w){let P=v.join(y,".rapidkit","toolchain.lock"),k={};try{k=JSON.parse(await j.promises.readFile(P,"utf-8"));}catch{}(!k.runtime||typeof k.runtime!="object")&&(k.runtime={}),k.runtime[e$1]={version:w,detectedAt:new Date().toISOString()},await E__default.ensureDir(v.dirname(P)),await j.promises.writeFile(P,JSON.stringify(k,null,2)+`
216
216
  `,"utf-8");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:e$1,result:g.exitCode===0?"ok":"failed",exitCode:g.exitCode,workspacePath:y,version:w,warmDeps:r},null,2)}
@@ -239,7 +239,7 @@ Hints:`));for(let p of l)console.log(s.gray(`- ${p}`));}return a.exitCode}functi
239
239
  `),0):(console.log(s.cyan("RapidKit mirror status")),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Config: ${p?"present":"missing"} (${i})`)),console.log(s.gray(`Lock: ${g?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${y}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let d=await Br(r,{ciMode:true,offlineMode:e==="verify",forceRun:true}),p=d.checks.filter(y=>y.status==="failed"),f=d.checks.some(y=>y.id.startsWith("mirror.verify.")&&y.status==="failed");if(e==="verify"&&f){let y={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:d.details,checks:d.checks};if(await u(y),o)return process.stdout.write(`${JSON.stringify(y,null,2)}
240
240
  `),1;console.log(s.red("\u274C Mirror verify failed."));for(let w of d.checks.filter(P=>P.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${w.id}: ${w.message}`));return 1}if(p.length>0){let y={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:d.details,checks:d.checks};if(await u(y),o)return process.stdout.write(`${JSON.stringify(y,null,2)}
241
241
  `),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${p.length} issue(s).`));for(let w of p)console.log(s.gray(`- ${w.id}: ${w.message}`));return 1}let g={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:d.details,checks:d.checks};return await u(g),o?(process.stdout.write(`${JSON.stringify(g,null,2)}
242
- `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${d.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${d.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${d.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),1}async function ln(t){let e$2=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$2>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let o=process.cwd(),r=await Sa(o,async()=>{let n=Z(o),i$1=Ne("python",{runCommandInCwd:B,runCoreRapidkit:e}),a=Ne("dotnet",{runCommandInCwd:B,runCoreRapidkit:e}),l=t.slice(1).filter(g=>!g.startsWith("-"));if(l.length>0){let g=v.resolve(o,l[0]),y=d$4(g),w=await yt(g);return e$1(y,g)||w==="go"?await en(g):g$1(y,g)||w==="java"?await He("init",g):h$2(y,g)||w==="dotnet"?X(await a.initProject(g)):f$2(y,g)||w==="node"?await Zr(g):i(y,g)||w==="python"?await Xr(g,i$1):await e(t,{cwd:o})}let c=d$4(o),u=!!Z(o)&&o===Z(o);if(!u&&e$1(c,o))return await en(o);let m=await yt(o);if(!u&&(g$1(c,o)||m==="java"))return await He("init",o);if(!u&&(h$2(c,o)||m==="dotnet"))return X(await a.initProject(o));if(!u&&(f$2(c,o)||m==="node"))return await Zr(o);if(!u&&(i(c,o)||m==="python"))return await Xr(o,i$1);let d=n||Z(o),p=va(o),f=p?v.dirname(v.dirname(p)):null;if(f&&f!==d){let g=d$4(f),y=await yt(f);return e$1(g,f)||y==="go"?await en(f):g$1(g,f)||y==="java"?await He("init",f):h$2(g,f)||y==="dotnet"?X(await a.initProject(f)):f$2(g,f)||y==="node"?await Zr(f):i(g,f)||y==="python"?await Xr(f,i$1):await e(["init"],{cwd:f})}if(d&&o===d){console.log(s.yellow("\u26A0\uFE0F Running `npx rapidkit 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 g=await cn(d);if(g!==0)return g;let{runWorkspaceStage:y}=await import('./workspace-run-ATFFJCMK.js');return (await y({workspacePath:d,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!d){let g$1=await b$2(),y=g(),{name:w}=fd(y);await E__default.ensureDir(y);let{createProject:P}=await import('./create-EAE2AJJL.js');return await P(w,{yes:true,userConfig:g$1,parentDirectory:y}),0}return await e(t,{cwd:o})});return r.ok?r.value:r.code}finally{typeof e$2>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$2;}}async function ca(t){let e=Z(t);if(!e)return [];let o="warn";try{let c=await j.promises.readFile(v.join(e,".rapidkit","policies.yml"),"utf-8");(c.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??c.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(o="strict");}catch{return []}if(o!=="strict")return [];let r=[],n=v.join(e,".rapidkit","toolchain.lock");if(!j.existsSync(n))return r.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain)."),r;let i$2={};try{i$2=JSON.parse(await j.promises.readFile(n,"utf-8"));}catch{return r.push("toolchain.lock is invalid JSON \u2014 regenerate it with `rapidkit bootstrap` before running commands in strict mode."),r}let a=i$2.runtime??{},l=d$4(t);e$1(l,t)&&!a.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."):f$2(l,t)&&!a.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."):g$1(l,t)&&!a.java?.version?r.push("java.version is not pinned in toolchain.lock \u2014 run `rapidkit setup java` first."):h$2(l,t)&&!a.dotnet?.version?r.push("dotnet.version is not pinned in toolchain.lock \u2014 run `rapidkit setup dotnet` first."):i(l,t)&&!a.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");try{let u=JSON.parse(await j.promises.readFile(v.join(e,".rapidkit","workspace.json"),"utf-8")).profile??"",m=i$1(t,l),d=nt({profile:u,runtime:m.runtime,subjectLabel:v.basename(t),mode:"strict"});d.ok||r.push(`${d.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return r}async function hd(){let t=async h=>{if(!b$1()||!h.toLowerCase().endsWith(".cmd"))return false;try{let b=(await E__default.readFile(h,"utf8")).replace(/\r\n/g,`
242
+ `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${d.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${d.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${d.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),1}async function ln(t){let e$2=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$2>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let o=process.cwd(),r=await Sa(o,async()=>{let n=Z(o),i$1=Ne("python",{runCommandInCwd:B,runCoreRapidkit:e}),a=Ne("dotnet",{runCommandInCwd:B,runCoreRapidkit:e}),l=t.slice(1).filter(g=>!g.startsWith("-"));if(l.length>0){let g=v.resolve(o,l[0]),y=d$4(g),w=await yt(g);return e$1(y,g)||w==="go"?await en(g):g$1(y,g)||w==="java"?await He("init",g):h$2(y,g)||w==="dotnet"?X(await a.initProject(g)):f$2(y,g)||w==="node"?await Zr(g):i(y,g)||w==="python"?await Xr(g,i$1):await e(t,{cwd:o})}let c=d$4(o),u=!!Z(o)&&o===Z(o);if(!u&&e$1(c,o))return await en(o);let m=await yt(o);if(!u&&(g$1(c,o)||m==="java"))return await He("init",o);if(!u&&(h$2(c,o)||m==="dotnet"))return X(await a.initProject(o));if(!u&&(f$2(c,o)||m==="node"))return await Zr(o);if(!u&&(i(c,o)||m==="python"))return await Xr(o,i$1);let d=n||Z(o),p=va(o),f=p?v.dirname(v.dirname(p)):null;if(f&&f!==d){let g=d$4(f),y=await yt(f);return e$1(g,f)||y==="go"?await en(f):g$1(g,f)||y==="java"?await He("init",f):h$2(g,f)||y==="dotnet"?X(await a.initProject(f)):f$2(g,f)||y==="node"?await Zr(f):i(g,f)||y==="python"?await Xr(f,i$1):await e(["init"],{cwd:f})}if(d&&o===d){console.log(s.yellow("\u26A0\uFE0F Running `npx rapidkit 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 g=await cn(d);if(g!==0)return g;let{runWorkspaceStage:y}=await import('./workspace-run-NULA72JV.js');return (await y({workspacePath:d,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!d){let g$1=await b$2(),y=g(),{name:w}=fd(y);await E__default.ensureDir(y);let{createProject:P}=await import('./create-TPFUONHK.js');return await P(w,{yes:true,userConfig:g$1,parentDirectory:y}),0}return await e(t,{cwd:o})});return r.ok?r.value:r.code}finally{typeof e$2>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$2;}}async function ca(t){let e=Z(t);if(!e)return [];let o="warn";try{let c=await j.promises.readFile(v.join(e,".rapidkit","policies.yml"),"utf-8");(c.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??c.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(o="strict");}catch{return []}if(o!=="strict")return [];let r=[],n=v.join(e,".rapidkit","toolchain.lock");if(!j.existsSync(n))return r.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain)."),r;let i$2={};try{i$2=JSON.parse(await j.promises.readFile(n,"utf-8"));}catch{return r.push("toolchain.lock is invalid JSON \u2014 regenerate it with `rapidkit bootstrap` before running commands in strict mode."),r}let a=i$2.runtime??{},l=d$4(t);e$1(l,t)&&!a.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."):f$2(l,t)&&!a.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."):g$1(l,t)&&!a.java?.version?r.push("java.version is not pinned in toolchain.lock \u2014 run `rapidkit setup java` first."):h$2(l,t)&&!a.dotnet?.version?r.push("dotnet.version is not pinned in toolchain.lock \u2014 run `rapidkit setup dotnet` first."):i(l,t)&&!a.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");try{let u=JSON.parse(await j.promises.readFile(v.join(e,".rapidkit","workspace.json"),"utf-8")).profile??"",m=i$1(t,l),d=nt({profile:u,runtime:m.runtime,subjectLabel:v.basename(t),mode:"strict"});d.ok||r.push(`${d.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return r}async function hd(){let t=async h=>{if(!b$1()||!h.toLowerCase().endsWith(".cmd"))return false;try{let b=(await E__default.readFile(h,"utf8")).replace(/\r\n/g,`
243
243
  `).toLowerCase(),A=b.includes("\\.rapidkit\\rapidkit"),N=b.includes("\\.rapidkit\\rapidkit.cmd")||b.includes("\\.rapidkit\\rapidkit.exe")||b.includes("\\.venv\\scripts\\rapidkit.exe");return A&&!N}catch{return false}},e$2=process.cwd(),o$1=process.argv.slice(2),r=o$1[0],n=r==="init",i$1=new Set(k$1),a=!r||r==="--help"||r==="-h"||r==="help",l=We(e$2),c=j.existsSync(v.join(e$2,".rapidkit","project.json")),u=d$4(e$2),m=await yt(e$2),d=e$1(u,e$2)||f$2(u,e$2)||i(u,e$2)||g$1(u,e$2)||h$2(u,e$2)||c$3(m??void 0),p=!!r&&i$1.has(r)&&d,f$1=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(eo(o$1)||o$1[0]==="create")return false;if(nn(o$1))return true;if(o$1[0]==="init"&&l&&!c)return false;if(sn(o$1))return true;try{let h=r==="shell"&&o$1[1]==="activate",S=r==="create",b=await ws(e$2,{cwd:e$2,timeoutMs:1200});if(b.ok&&b.data?.isRapidkitProject&&b.data.engine==="python"){let A=S||eo(o$1);if(!a&&!h&&!A&&!n&&!p&&mr(o$1)){if(r&&Xi.includes(r)){let H=await ca(e$2).catch(()=>[]);if(H.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
244
244
  `);for(let Y of H)process.stderr.write(s.red(` \u2022 ${Y}`)+`
245
245
  `);process.exit(1);}}let N=await e(process.argv.slice(2),{cwd:e$2});process.exit(N);}}}catch{}let g=va(e$2),y=b$1(),w=f$1?[]:o(e$2),P=null;for(let h of w)if(await E__default.pathExists(h)){if(await t(h)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${h}. Falling back to core bridge.`);continue}P=h;break}let k=r==="create";if(r==="init"&&l&&!c)return false;if(r&&Xi.includes(r)){let h=await ca(e$2);if(h.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
@@ -318,22 +318,23 @@ Use "rapidkit help <command>" for more information.
318
318
  `)),process.exit(1));}if(e$1.dryRun){console.log(s.cyan(`
319
319
  \u{1F50D} Dry-run mode - showing what would be created:
320
320
  `)),console.log(s.white("\u{1F4C2} Path:"),l$1),console.log(s.white("\u{1F4E6} Type:"),i?`Project (${e$1.template})`:"Workspace"),console.log();return}if(!e$1.yes&&!i?await b$3([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"RapidKit User"}]):e$1.yes&&console.log(s.gray(`Using default values (--yes flag)
321
- `)),i){let c=String(e$1.template||"").trim(),u=b$4(c);if(d$1(u)){let k=await rn(["create","project",u,t,...e$1.skipGit?["--skip-git"]:[]]);k!==0&&process.exit(k);return}if(!!!an(process.cwd())){let{registerWorkspaceAtPath:k}=await import('./create-EAE2AJJL.js');if(e$1.createWorkspace)await k(process.cwd(),{skipGit:e$1.skipGit,yes:e$1.yes,userConfig:o});else if(!e$1.noWorkspace)if(e$1.yes)await k(process.cwd(),{skipGit:e$1.skipGit,yes:true,userConfig:o});else {let{createWs:h}=await b$3([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);h&&await k(process.cwd(),{skipGit:e$1.skipGit,yes:false,userConfig:o});}}let d=["create","project",u,t,"--output",process.cwd()];e$1.yes&&d.push("--yes");let p=Z(process.cwd()),f$2=!!e$1.skipInstall,g=f$2||!!p;f$2&&d.push("--skip-essentials");let y=g?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,w=await f$1(d,{cwd:process.cwd(),env:y});w!==0&&process.exit(w),p&&!e$1.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx rapidkit init")));let P=an(process.cwd());if(P){let k=v.dirname(P),h=v.join(k,".python-version"),S=v.join(l$1,".python-version");try{if(await E__default.pathExists(h)){let b=j.readFileSync(h,"utf-8");j.writeFileSync(S,b.trim()+`
321
+ `)),i){let c=String(e$1.template||"").trim(),u=b$4(c);if(d$1(u)){let k=await rn(["create","project",u,t,...e$1.skipGit?["--skip-git"]:[]]);k!==0&&process.exit(k);return}if(!!!an(process.cwd())){let{registerWorkspaceAtPath:k}=await import('./create-TPFUONHK.js');if(e$1.createWorkspace)await k(process.cwd(),{skipGit:e$1.skipGit,yes:e$1.yes,userConfig:o});else if(!e$1.noWorkspace)if(e$1.yes)await k(process.cwd(),{skipGit:e$1.skipGit,yes:true,userConfig:o});else {let{createWs:h}=await b$3([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);h&&await k(process.cwd(),{skipGit:e$1.skipGit,yes:false,userConfig:o});}}let d=["create","project",u,t,"--output",process.cwd()];e$1.yes&&d.push("--yes");let p=Z(process.cwd()),f$2=!!e$1.skipInstall,g=f$2||!!p;f$2&&d.push("--skip-essentials");let y=g?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,w=await f$1(d,{cwd:process.cwd(),env:y});w!==0&&process.exit(w),p&&!e$1.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx rapidkit init")));let P=an(process.cwd());if(P){let k=v.dirname(P),h=v.join(k,".python-version"),S=v.join(l$1,".python-version");try{if(await E__default.pathExists(h)){let b=j.readFileSync(h,"utf-8");j.writeFileSync(S,b.trim()+`
322
322
  `),f.debug(`Synced Python version ${b.trim()} from workspace to project`);}}catch(b){f.debug("Could not sync Python version from workspace:",b);}}if(!e$1.skipInstall){let k=await e(["init",l$1],{cwd:process.cwd()});if(k!==0&&process.exit(k),P){let h=v.dirname(P),S=v.join(h,".python-version"),b=v.join(l$1,".python-version");try{if(await E__default.pathExists(S)){let A=j.readFileSync(S,"utf-8");j.writeFileSync(b,A.trim()+`
323
- `),f.debug(`Re-synced Python version ${A.trim()} after init`);}}catch(A){f.debug("Could not re-sync Python version after init:",A);}}}}else {let{createProject:c}=await import('./create-EAE2AJJL.js');await c(t,{skipGit:e$1.skipGit,skipPythonEngine:e$1.skipPythonEngine,dryRun:e$1.dryRun,yes:e$1.yes,userConfig:n$1,installMethod:e$1.installMethod,profile:e$1.profile,parentDirectory:v.dirname(l$1)}),console.log(s.gray(`\u2139\uFE0F Workspace root: ${l$1}`)),console.log(s.gray(` Next: ${k(l$1)} && npx rapidkit create project`));}}catch(o){o instanceof a$2?(f.error(`
323
+ `),f.debug(`Re-synced Python version ${A.trim()} after init`);}}catch(A){f.debug("Could not re-sync Python version after init:",A);}}}}else {let{createProject:c}=await import('./create-TPFUONHK.js');await c(t,{skipGit:e$1.skipGit,skipPythonEngine:e$1.skipPythonEngine,dryRun:e$1.dryRun,yes:e$1.yes,userConfig:n$1,installMethod:e$1.installMethod,profile:e$1.profile,parentDirectory:v.dirname(l$1)}),console.log(s.gray(`\u2139\uFE0F Workspace root: ${l$1}`)),console.log(s.gray(` Next: ${k(l$1)} && npx rapidkit create project`));}}catch(o){o instanceof a$2?(f.error(`
324
324
  \u274C ${o.message}`),o.details&&f.warn(`\u{1F4A1} ${o.details}`),f.debug("Error code:",o.code)):(f.error(`
325
- \u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{st=null;}});Gs(oe);qs(oe);bi(oe);oe.command("commands").description("Show effective RapidKit command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{td({json:t.json});});oe.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:o}=await import('./analyze-XSPWKPA4.js'),r=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(r,null,2)):o(r),r.summary.verdict==="blocked"&&process.exit(2);}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify({schemaVersion:"rapidkit-analyze-error-v1",ok:false,error:{message:o}},null,2)):console.error(s.red(`Analyze failed: ${o}`)),process.exit(1);}});xs(oe);oe.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(c){let u=c;for(;;){let m=v.join(u,".rapidkit","context.json");if(j.existsSync(m))return m;let d=v.dirname(u);if(d===u)break;u=d;}return null}let r=o(e);function n(c){let u=c;for(;;){let m=v.join(u,".venv"),d=v.join(u,".rapidkit","activate");if(j.existsSync(d)||j.existsSync(m))return {venv:m,activateFile:d};let p=v.dirname(u);if(p===u)break;u=p;}return null}let i=n(e);!r&&!i&&(console.log(s.yellow("No RapidKit project found in this directory")),process.exit(1));let a;i&&j.existsSync(i.activateFile)?a=i.activateFile:i&&j.existsSync(i.venv)?a=n$1(i.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let l=b$1();console.log(l?`call "${a}"`:`. "${a}"`);});oe.command("readiness").description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$5({json:t.json,strict:t.strict,skipVerify:t.skipVerify});});oe.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:o}=await import('./pipeline-TRA4MMZC.js');await o({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.noAgentSync===true,agentSync:t.agentSync===true?true:t.noAgentSync?false:void 0});});oe.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let o=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(o)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let r=Number(e.maxWorkers??""),n=Number.isFinite(r)?Math.max(1,Math.trunc(r)):void 0,{runAutopilotRelease:i}=await import('./autopilot-release-MVFRZMHD.js'),a;try{a=await i({workspacePath:process.cwd(),mode:o,since:e.since,parallel:e.parallel===true,maxWorkers:n,json:e.json===true,output:e.output});}catch(l){let c=l instanceof Error?l.message:String(l);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);});oe.command("import <source>").description("Import a local backend project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await pd(t,e);o!==0&&process.exit(o);});oe.command("adopt [source]").description("Adopt an existing local project into a RapidKit workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await ud(t,e);o!==0&&process.exit(o);});var Qo=oe.command("snapshot").description("Create, list, and restore RapidKit workspace snapshots");Qo.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Rt({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot create failed: ${o.message}`)),process.exit(1);}});Qo.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Zs({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let o of e)console.log(s.cyan(o.name)),console.log(s.gray(` ${o.createdAt} | ${o.mode} | ${o.projects.length} project(s)`)),console.log(s.gray(` ${o.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});Qo.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Xs({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.cyan(`Snapshot: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Created: ${o.manifest.createdAt}`)),console.log(s.gray(` Projects: ${o.manifest.projects.length}`)),console.log(s.gray(` Files: ${o.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${o.estimatedBytes}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot inspect failed: ${o.message}`)),process.exit(1);}});Qo.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await ei({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(o,null,2));return}o.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${o.snapshotPath}`)),console.log(s.gray(` Restored paths: ${o.restoredPaths.join(", ")}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot restore failed: ${o.message}`)),process.exit(1);}});var to=oe.command("project").description("Safe workspace project lifecycle operations");to.command("commands").description("Show effective commands supported by the current RapidKit project").option("--json","Emit machine-readable JSON output").action(async t=>{wa({json:t.json});});to.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Ar({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let o of e)console.log(s.cyan(o.projectName)),console.log(s.gray(` Archived: ${o.archivedAt}`)),console.log(s.gray(` Path: ${o.archivePath}`)),o.reason&&console.log(s.gray(` Reason: ${o.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});to.command("archive <project>").description("Move a project into .rapidkit/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Ir({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project archive dry-run: ${o.projectName}`):s.green(`\u2714 Project archived: ${o.projectName}`)),console.log(s.gray(` From: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` To: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project archive failed: ${o.message}`)),process.exit(1);}});to.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await si({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project restore dry-run: ${o.projectName}`):s.green(`\u2714 Project restored: ${o.projectName}`)),console.log(s.gray(` From: ${o.archivePath}`)),console.log(s.gray(` To: ${o.projectPath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project restore failed: ${o.message}`)),process.exit(1);}});to.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await ni({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}let r=o.action==="archive"?"archived":"deleted";console.log(o.dryRun?s.cyan(`Project ${r} dry-run: ${o.projectName}`):s.green(`\u2714 Project ${r}: ${o.projectName}`)),console.log(s.gray(` Path: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` Archive: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project delete failed: ${o.message}`)),process.exit(1);}});oe.command("doctor [scope]").description("\u{1FA7A} Check RapidKit system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx rapidkit doctor | npx rapidkit doctor workspace | npx rapidkit doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let o=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!o.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let r=await od({scope:t,workspaceFlag:e.workspace});r.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),r.candidatePath&&console.log(s.gray(` Candidate: ${r.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package rapidkit rapidkit doctor workspace")));let{runDoctor:n}=await import('./doctor-E6JE4Q3B.js'),i=await n({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});i!==0&&process.exit(i);});oe.command("workspace <action> [subaction] [key] [value]").description(`Manage RapidKit workspaces (list, sync, policy, share, export, run, intelligence)
325
+ \u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{st=null;}});Gs(oe);qs(oe);bi(oe);oe.command("commands").description("Show effective RapidKit command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{td({json:t.json});});oe.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:o}=await import('./analyze-XSPWKPA4.js'),r=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(r,null,2)):o(r),r.summary.verdict==="blocked"&&process.exit(2);}catch(e){let o=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify({schemaVersion:"rapidkit-analyze-error-v1",ok:false,error:{message:o}},null,2)):console.error(s.red(`Analyze failed: ${o}`)),process.exit(1);}});xs(oe);oe.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(c){let u=c;for(;;){let m=v.join(u,".rapidkit","context.json");if(j.existsSync(m))return m;let d=v.dirname(u);if(d===u)break;u=d;}return null}let r=o(e);function n(c){let u=c;for(;;){let m=v.join(u,".venv"),d=v.join(u,".rapidkit","activate");if(j.existsSync(d)||j.existsSync(m))return {venv:m,activateFile:d};let p=v.dirname(u);if(p===u)break;u=p;}return null}let i=n(e);!r&&!i&&(console.log(s.yellow("No RapidKit project found in this directory")),process.exit(1));let a;i&&j.existsSync(i.activateFile)?a=i.activateFile:i&&j.existsSync(i.venv)?a=n$1(i.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let l=b$1();console.log(l?`call "${a}"`:`. "${a}"`);});oe.command("readiness").description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$5({json:t.json,strict:t.strict,skipVerify:t.skipVerify});});oe.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:o}=await import('./pipeline-PX6ZUINW.js');await o({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.noAgentSync===true,agentSync:t.agentSync===true?true:t.noAgentSync?false:void 0});});oe.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let o=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(o)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let r=Number(e.maxWorkers??""),n=Number.isFinite(r)?Math.max(1,Math.trunc(r)):void 0,{runAutopilotRelease:i}=await import('./autopilot-release-5J55NPXF.js'),a;try{a=await i({workspacePath:process.cwd(),mode:o,since:e.since,parallel:e.parallel===true,maxWorkers:n,json:e.json===true,output:e.output});}catch(l){let c=l instanceof Error?l.message:String(l);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);});oe.command("import <source>").description("Import a local backend project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await pd(t,e);o!==0&&process.exit(o);});oe.command("adopt [source]").description("Adopt an existing local project into a RapidKit workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let o=await ud(t,e);o!==0&&process.exit(o);});var Qo=oe.command("snapshot").description("Create, list, and restore RapidKit workspace snapshots");Qo.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Rt({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot create failed: ${o.message}`)),process.exit(1);}});Qo.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Zs({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let o of e)console.log(s.cyan(o.name)),console.log(s.gray(` ${o.createdAt} | ${o.mode} | ${o.projects.length} project(s)`)),console.log(s.gray(` ${o.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});Qo.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Xs({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(s.cyan(`Snapshot: ${o.manifest.name}`)),console.log(s.gray(` Mode: ${o.manifest.mode}`)),console.log(s.gray(` Created: ${o.manifest.createdAt}`)),console.log(s.gray(` Projects: ${o.manifest.projects.length}`)),console.log(s.gray(` Files: ${o.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${o.estimatedBytes}`)),console.log(s.gray(` Path: ${o.snapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot inspect failed: ${o.message}`)),process.exit(1);}});Qo.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await ei({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(o,null,2));return}o.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${o.snapshotPath}`)),console.log(s.gray(` Restored paths: ${o.restoredPaths.join(", ")}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Snapshot restore failed: ${o.message}`)),process.exit(1);}});var to=oe.command("project").description("Safe workspace project lifecycle operations");to.command("commands").description("Show effective commands supported by the current RapidKit project").option("--json","Emit machine-readable JSON output").action(async t=>{wa({json:t.json});});to.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Ar({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let o of e)console.log(s.cyan(o.projectName)),console.log(s.gray(` Archived: ${o.archivedAt}`)),console.log(s.gray(` Path: ${o.archivePath}`)),o.reason&&console.log(s.gray(` Reason: ${o.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});to.command("archive <project>").description("Move a project into .rapidkit/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await Ir({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project archive dry-run: ${o.projectName}`):s.green(`\u2714 Project archived: ${o.projectName}`)),console.log(s.gray(` From: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` To: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project archive failed: ${o.message}`)),process.exit(1);}});to.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await si({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.dryRun?s.cyan(`Project restore dry-run: ${o.projectName}`):s.green(`\u2714 Project restored: ${o.projectName}`)),console.log(s.gray(` From: ${o.archivePath}`)),console.log(s.gray(` To: ${o.projectPath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project restore failed: ${o.message}`)),process.exit(1);}});to.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let o=await ni({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(o,null,2));return}let r=o.action==="archive"?"archived":"deleted";console.log(o.dryRun?s.cyan(`Project ${r} dry-run: ${o.projectName}`):s.green(`\u2714 Project ${r}: ${o.projectName}`)),console.log(s.gray(` Path: ${o.projectPath}`)),o.archivePath&&console.log(s.gray(` Archive: ${o.archivePath}`)),o.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${o.safetySnapshotPath}`));}catch(o){console.log(s.red(`\u274C Project delete failed: ${o.message}`)),process.exit(1);}});oe.command("doctor [scope]").description("\u{1FA7A} Check RapidKit system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx rapidkit doctor | npx rapidkit doctor workspace | npx rapidkit doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let o=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!o.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let r=await od({scope:t,workspaceFlag:e.workspace});r.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),r.candidatePath&&console.log(s.gray(` Candidate: ${r.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package rapidkit rapidkit doctor workspace")));let{runDoctor:n}=await import('./doctor-O2B3XNAB.js'),i=await n({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});i!==0&&process.exit(i);});oe.command("workspace <action> [subaction] [key] [value]").description(`Manage RapidKit workspaces (list, sync, policy, share, export, run, intelligence)
326
326
  workspace run <stage> \u2014 fleet stage execution across discovered projects
327
327
  stages: init | test | build | start | <custom-from-context>
328
328
  workspace explain|why \u2014 blocker/project narrative (--write for artifact)
329
329
  workspace trace \u2014 diff \u2192 blast radius \u2192 gates narrative (--from <diff>)
330
- workspace mcp serve \u2014 read-mostly stdio MCP bridge over workspace evidence`).option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--output <file>","Output file path for workspace share bundle").option("--from <file>","Input workspace model snapshot/report for workspace diff").option("--from-impact <file>","Input workspace impact report for workspace verify (defaults to last-run impact)").option("--include-paths","Include absolute paths in workspace share bundle").option("--write","Write workspace intelligence artifact to .rapidkit/reports").option("--include-evidence","Read status metadata from referenced evidence reports").option("--scan-depth <count>","Observable project discovery depth for large monorepos").option("--cache","Reuse cached workspace model when inputs are unchanged (keyed by inputsHash)").option("--incremental","Rebuild only changed projects and re-infer only their incident graph edges (graph-aware)").option("--once","For workspace watch: do the initial in-memory build and exit (no watcher)").option("--for-agent [agent]","Build an agent-ready workspace context pack").option("--agent-sync","After --write on context, sync cross-tool agent grounding files (AGENTS.md, Copilot, Cursor, Claude)").option("--no-agent-sync","Skip automatic agent grounding sync after context --write").option("--target <targets>","Agent customization targets for agent-sync (all|vscode|agents,copilot,cursor,claude,codex,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").option("--refresh-context","Rebuild workspace-context-agent.json during agent-sync").option("--experimental-hooks","Generate advisory VS Code agent hook design files during enterprise agent-sync").option("--hydrate-prompts","Hydrate matching Copilot prompt files with workspace-specific verification steps during agent-sync").option("--scope <scope>","Scope workspace intelligence output, e.g. project:<name>").option("--no-doctor","Exclude doctor evidence in workspace share bundle").option("--no-blueprint","Exclude reproducibility blueprint from workspace share bundle").option("--include-env","Include .env/private key files in workspace export archive").option("--force","Overwrite an existing hydrate output directory").option("--refresh","Publish workspace registry summary before reading status").option("--dry-run","Preview hydrate without writing files").option("--affected","Run only affected projects (requires git diff context)").option("--blast-radius","Include downstream dependents from workspace dependency graph").option("--since <ref>","Git ref for affected calculation (default: HEAD~1)").option("--parallel","Run project stages in parallel").option("--max-workers <count>","Maximum parallel workers (default: min(4, selected))").option("--continue-on-error","Continue running remaining projects after a failure").option("--reuse-passed","Skip projects that already passed this stage in workspace-run-last.json").option("--json","Emit machine-readable JSON output").option("--ci","Build CI-oriented command plans where supported").option("--strict","Return non-zero exit on warn/fail gate outcomes").option("--no-gates","Skip doctor/readiness pre-run gates").action(async function(t,e,o,r){let n=this.opts(),i=c=>{let m=(n.workspace?v.resolve(n.workspace):null)??a$6(process.cwd())??Z(process.cwd());(!m||!We(m))&&(console.log(s.red("\u274C Not inside a RapidKit workspace")),console.log(s.gray("\u{1F4A1} Run from a workspace directory or pass --workspace <path>.")),process.exit(1));let d=v.resolve(process.cwd()),p=v.resolve(m);return d!==p&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${m} for "${c}" (current directory: ${d}).`)),m},a=c=>process.argv.includes(c),l=()=>{if(!n.scanDepth)return;let c=Number.parseInt(n.scanDepth,10);return Number.isFinite(c)?c:void 0};if((Ei(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||a("--json"),strict:n.strict===true||a("--strict")}}),t==="list"){let{listWorkspaces:c}=await import('./workspace-IBTKZX7T.js');await c({json:n.json===true||a("--json")});}else if(t==="model"){let c=i("model"),{buildWorkspaceModelCached:u,buildWorkspaceModelIncremental:m,writeWorkspaceModel:d}=await import('./workspace-model-AOTSEAVW.js'),p=n.incremental===true||a("--incremental"),f=n.cache===true||a("--cache")||p,g={workspacePath:c,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l(),strict:n.strict===true||a("--strict")},y,w;if(p){let h=await m(g);y=h.model,w=h.mode;}else {let h=await u({...g,cache:f});y=h.model,w=h.cache;}let P;(n.write===true||a("--write"))&&(P=await d(y,c));let k=(n.strict===true||a("--strict"))&&y.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...y,...P?{outputPath:P}:{}},null,2)),k&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${y.workspace.name}`)),p?console.log(s.gray(` Build: ${w} (incremental)`)):f&&console.log(s.gray(` Cache: ${w}`)),console.log(s.gray(` Projects: ${y.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${y.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${y.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${y.identity.workspaceType}`)),console.log(s.gray(` Validation: ${y.validation?.status??"unknown"} (${y.validation?.errors??0} error, ${y.validation?.warnings??0} warning)`)),console.log(P?s.gray(` Written: ${P}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-model.json")),k&&process.exit(1);}else if(t==="agent-sync"){let c=i("agent-sync"),{syncWorkspaceAgentGrounding:u,parseAgentGroundingTargets:m}=await import('./workspace-agent-sync-LEYLJ42D.js'),d=n.strict===true||a("--strict"),p=n.write===true||a("--write"),f=a("--dry-run"),g=await u({workspacePath:c,scope:n.scope,agent:n.forAgent,write:p&&!f,dryRun:f,strict:d,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||a("--refresh-context")||a("--refresh"),targets:m(n.target),experimentalHooks:n.experimentalHooks===true||a("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||a("--hydrate-prompts"),staleAfterHours:24});if(n.json)console.log(JSON.stringify(g,null,2));else {console.log(s.green(`\u2714 Agent grounding ${p&&!f?"synced":"planned"}`)),console.log(s.gray(` Index: ${g.indexPath}`)),g.contextPath&&console.log(s.gray(` Context: ${g.contextPath}`)),g.blockers.length>0&&console.log(s.yellow(` Blockers: ${g.blockers.slice(0,3).join(" \xB7 ")}`));let y=p&&!f?g.writtenFiles:g.skippedFiles;if(y.length>0&&console.log(s.gray(` Files: ${y.join(", ")}`)),g.strictViolations.length>0)for(let w of g.strictViolations)console.log(s.red(`\u274C ${w}`));}d&&g.strictViolations.length>0&&process.exit(1);}else if(t==="remediation-plan"){let c=i("remediation-plan"),{buildArtifactRemediationPlan:u,writeArtifactRemediationPlan:m}=await import('./artifact-remediation-plan-HRR3WH7T.js'),d=await u({workspacePath:c,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),ciMode:n.ci===true||a("--ci")}),p;if((n.write===true||a("--write"))&&(p=await m(d,c)),n.json===true||a("--json")){console.log(JSON.stringify({...d,...p?{outputPath:p}:{}},null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${d.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${d.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${d.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${d.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${d.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${d.summary.risk.safe}, guarded=${d.summary.risk.guarded}, invasive=${d.summary.risk.invasive}`));for(let f of d.actions.slice(0,8))console.log(s.gray(` \u2022 ${f.cardId}: ${f.title} (${f.mode}, ${f.risk})`));d.actions.length>8&&console.log(s.gray(` \u2026 ${d.actions.length-8} more action(s)`)),console.log(p?s.gray(` Written: ${p}`):s.gray(" Add --write to persist .rapidkit/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let c=i("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx rapidkit workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:u,writeWorkspaceAgentContext:m}=await import('./workspace-context-NTG3D4DI.js'),d=n.strict===true||a("--strict"),p=await u({workspacePath:c,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l(),strict:false}),f,g;if((n.write===true||a("--write"))&&(f=await m(p,c),(n.agentSync===true||a("--agent-sync")||n.noAgentSync!==true)&&!a("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:k}=await import('./workspace-agent-sync-LEYLJ42D.js');if(g=await P({workspacePath:c,scope:n.scope,agent:p.agent,write:true,refreshContext:false,strict:d,preset:n.preset==="minimal"?"minimal":"enterprise",targets:k(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${g.writtenFiles.length} file(s) updated`)),d&&g.strictViolations.length>0){for(let h of g.strictViolations)console.log(s.red(`\u274C ${h}`));process.exit(1);}}let y=d&&p.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...p,...f?{outputPath:f}:{},...g?{agentGroundingSync:g}:{}},null,2)),y&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${p.workspace.name}`)),console.log(s.gray(` Agent: ${p.agent}`)),console.log(s.gray(` Scope: ${p.scope.activeProject??p.scope.requested}`)),console.log(s.gray(` Projects included: ${p.projects.length}`)),console.log(s.gray(` Safe commands: ${p.safeCommands.length}`)),console.log(s.gray(` Validation: ${p.validation.status} (${p.validation.errors} error, ${p.validation.warnings} warning)`)),console.log(f?s.gray(` Written: ${f}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-context-agent.json")),y){for(let w of p.validation.issues)console.log(s.red(`\u274C ${w.severity}:${w.code}:${w.target}`));process.exit(1);}}else if(t==="snapshot"){let c=i("snapshot"),{buildWorkspaceModelSnapshot:u,writeWorkspaceModelSnapshot:m}=await import('./workspace-intelligence-C6NT557E.js'),d=await u({workspacePath:c,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()}),p=await m(d,c);if(n.json){console.log(JSON.stringify({...d,outputPath:p},null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${d.model.workspace.name}`)),console.log(s.gray(` Hash: ${d.modelHash}`)),console.log(s.gray(` Projects: ${d.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${d.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${p}`));}else if(t==="diff"){let c=i("diff"),u=n.from||e;u||((n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-diff-error-v1",command:"workspace diff",status:"error",workspacePath:c,error:{code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>."},examples:["npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json","npx rapidkit workspace diff --from .rapidkit/reports/workspace-model.json --json","npx rapidkit 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 rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx rapidkit workspace diff --from .rapidkit/reports/workspace-model.json --json")),console.log(s.gray(" npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx rapidkit workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:m,writeWorkspaceModelDiff:d}=await import('./workspace-intelligence-C6NT557E.js'),p;try{p=await m({workspacePath:c,fromPath:u,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()});}catch(y){throw (n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-diff-error-v1",command:"workspace diff",status:"error",workspacePath:c,fromPath:u,error:{code:"workspace.diff.input_unreadable",message:y.message},nextActions:["npx rapidkit workspace snapshot create --json","npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json"]},null,2)),process.exit(1)),y}let f=await d(p,c);if(n.json){console.log(JSON.stringify({...p,outputPath:f},null,2));return}let g=p.summary.changed?s.yellow:s.green;console.log(g(`\u2714 Workspace model diff: ${p.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${p.fromRef}`)),console.log(s.gray(` Added projects: ${p.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${p.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${p.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${p.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${p.summary.validationChanges}`)),p.git?.available&&console.log(s.gray(` Git: ${p.git.dirty?"dirty":"clean"} (${p.summary.gitChangedFiles} mapped change(s))`));for(let y of p.changes.slice(0,12))console.log(s.gray(` \u2022 ${y.type} ${y.target}: ${y.message}`));p.changes.length>12&&console.log(s.gray(` \u2026 ${p.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="impact"){let c=i("impact"),u=n.from||e;u||((n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-impact-error-v1",command:"workspace impact",status:"error",workspacePath:c,error:{code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>."},examples:["npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json","npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <snapshot-model-or-diff-report>")),console.log(s.gray(" npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:m,writeWorkspaceImpact:d}=await import('./workspace-intelligence-C6NT557E.js'),p;try{p=await m({workspacePath:c,fromPath:u,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()});}catch(y){throw (n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-impact-error-v1",command:"workspace impact",status:"error",workspacePath:c,fromPath:u,error:{code:"workspace.impact.input_unreadable",message:y.message},nextActions:["npx rapidkit workspace snapshot create --json","npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json","npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json"]},null,2)),process.exit(1)),y}let f=await d(p,c);if(n.json){console.log(JSON.stringify({...p,outputPath:f},null,2));return}let g=p.summary.risk==="critical"||p.summary.risk==="high"?s.red:p.summary.risk==="medium"?s.yellow:s.green;console.log(g(`\u2714 Workspace impact: ${p.summary.risk}`)),console.log(s.gray(` From: ${p.fromRef}`)),console.log(s.gray(` Affected projects: ${p.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${p.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${p.summary.recommendedCommands}`));for(let y of p.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${y.title}: ${y.summary}`));p.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${p.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="verify"){let c=i("verify"),{buildWorkspaceVerify:u,writeWorkspaceVerify:m,evaluateWorkspaceVerifyGate:d}=await import('./workspace-verify-7R3XBNKE.js'),p=await u({workspacePath:c,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()}),f=await m(p,c),g=d(p,{strict:n.strict===true||a("--strict")}),y=g.exitCode,{recordWorkspaceHistory:w,historyEntryFromVerify:P}=await import('./workspace-history-DSCH7PQZ.js');if(await w(c,P(p,g.passed)),n.json){console.log(JSON.stringify({...p,gate:g,outputPath:f},null,2)),y!==0&&process.exit(y);return}let k=p.summary.verdict==="ready"?s.green:p.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(k(`\u2714 Workspace verify: ${p.summary.verdict}`)),console.log(s.gray(` Freshness: ${p.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${p.impact.risk}`)),console.log(s.gray(` Steps: ${p.steps.length}`)),console.log(s.gray(` Passed ${p.summary.stepsPassed}, warn ${p.summary.stepsWarn}, failed ${p.summary.stepsFailed}, missing ${p.summary.stepsMissing}`));for(let h of p.steps.slice(0,10))console.log(s.gray(` \u2022 ${h.id}: ${h.status} \u2014 ${h.message}`));if(p.steps.length>10&&console.log(s.gray(` \u2026 ${p.steps.length-10} more step(s)`)),p.policyViolations.length>0){console.log(s.gray(` Policy (${p.policyMode}): ${p.policyViolations.length} violation(s)`));for(let h of p.policyViolations.slice(0,5)){let S=h.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${S} [${h.source}] ${h.code}: ${h.message}`);}}console.log(s.gray(` Gate (${g.mode}): ${g.passed?"passed":"blocked"}`));for(let h of g.reasons.slice(0,5))console.log(s.red(` \u2717 ${h}`));console.log(s.gray(` Written: ${f}`)),y!==0&&process.exit(y);}else if(t==="graph"){let c=i("graph"),{buildWorkspaceModel:u}=await import('./workspace-model-AOTSEAVW.js'),{buildGraphEmit:m,renderGraphDot:d,renderGraphMermaid:p,explainGraphNode:f}=await import('./workspace-graph-2A5THUCI.js'),y=(await u({workspacePath:c,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()})).graph,w=(e||"emit").toLowerCase();if(y||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:w,result:"error",workspacePath:c,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)),w==="dot"){console.log(d(y));return}if(w==="mermaid"){console.log(p(y));return}if(w==="explain"){let k=(n.scope?.replace(/^project:/,"")||o||"").trim();k||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:c,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx rapidkit workspace graph explain <project> --json","npx rapidkit 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 rapidkit workspace graph explain <project> --json")),console.log(s.gray(" npx rapidkit workspace graph explain --scope project:<name>")),process.exit(1));let h=f(y,k);if(n.json){console.log(JSON.stringify(h,null,2)),h.found||process.exit(1);return}h.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${k}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${h.project}`)),h.centrality&&console.log(s.gray(` Centrality: fanIn ${h.centrality.fanIn}, fanOut ${h.centrality.fanOut}, reach ${h.centrality.reach}, betweenness ${h.centrality.betweenness}${h.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${h.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${h.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${h.transitiveDependents.length}`));for(let S of h.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${S.id} (d${S.distance}, via ${S.via??"\u2014"})`));return}let P=m(y);if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${P.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${P.graph.stats.edgeCount} (inferred ${P.graph.stats.inferredEdges}, contract ${P.graph.stats.contractEdges}, manual ${P.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${P.integrity.ok?"ok":"issues"} (cycles ${P.integrity.stats.cycleCount}, dangling ${P.integrity.stats.danglingCount}, orphans ${P.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${P.hotspots.join(", ")||"none"}`)),console.log(s.gray(" Render: workspace graph dot | workspace graph mermaid"));}else if(t==="watch"){let c=i("watch"),{runWorkspaceWatch:u}=await import('./workspace-watch-SGY2DEZ5.js'),m=n.once===true||a("--once"),d=n.json===true,p=new AbortController,f=()=>p.abort();process.once("SIGINT",f),process.once("SIGTERM",f),d||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await u({workspacePath:c,once:m,signal:p.signal,buildOptions:{workspacePath:c,observableScanDepth:l()},onProgress:g=>{d||console.error(s.gray(` ${g}`));},emit:g=>{if(d){console.log(JSON.stringify(g));return}if(g.kind==="ready"){console.log(s.gray(` Ready: ${g.graph.nodeCount} nodes, ${g.graph.edgeCount} edges (hash ${g.modelHash.slice(0,12)})`));return}if(g.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${g.error??"unknown error"}`));return}if(g.kind==="unchanged"){console.log(s.gray(` No structural change (${g.mode}, ${g.durationMs}ms)`));return}let y=[];g.changedProjects.length>0&&y.push(`changed: ${g.changedProjects.join(", ")}`),g.addedProjects.length>0&&y.push(`added: ${g.addedProjects.join(", ")}`),g.removedProjects.length>0&&y.push(`removed: ${g.removedProjects.join(", ")}`),g.graph.edgesAdded.length>0&&y.push(`+${g.graph.edgesAdded.length} edges`),g.graph.edgesRemoved.length>0&&y.push(`-${g.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${g.mode}, ${g.durationMs}ms): ${y.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",f),process.removeListener("SIGTERM",f),!d&&!m&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let c=i("sync"),{syncWorkspaceProjects:u}=await import('./workspace-IBTKZX7T.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${v.basename(c)}`));let m=await u(c,n.json===true);await qe(c,{silent:n.json===true});let{readWorkspaceRegistrySummary:d}=await import('./workspace-registry-summary-X5WRUU3T.js'),p=await d(c);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:c,registry:m,contractSynced:true,registrySummary:p},null,2));}else if(t==="registry"){let c=i("registry"),u=e||"status";u!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${u}`)),console.log(s.gray(" npx rapidkit workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:m,readWorkspaceRegistrySummary:d,resolveWorkspaceRegisteredProjects:p}=await import('./workspace-registry-summary-X5WRUU3T.js'),g=n.refresh===true||a("--refresh")||n.force===true||a("--force")?await m(c):await d(c)||await m(c);if(n.json){console.log(JSON.stringify(g,null,2));return}let y=await p(c);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}`)),y.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let c=i("foundation"),u=e||"ensure";u!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${u}`)),console.log(s.gray(" npx rapidkit workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:m}=await import('./workspace-foundation-6AUEEJQQ.js'),d=await m(c,{force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(d,null,2));return}d.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${d.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let c=i("policy"),u=await yd(c,e,o,r,n.json===true||a("--json"));u!==0&&process.exit(u);}else if(t==="contract"){let c=i("contract"),{buildWorkspaceContractGraph:u,readWorkspaceContract:m,verifyWorkspaceContract:d,writeWorkspaceContract:p,WORKSPACE_CONTRACT_PATH:f}=await import('./workspace-contract-OO4GMENV.js'),g=e||"inspect",y=n.output;try{if(g==="init"){let w=await p({workspacePath:c,outputPath:y,force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${w.contractPath}`)),console.log(s.gray(` Projects: ${w.contract.projects.length}`));return}if(g==="inspect"){let w=await m({workspacePath:c,contractPath:y});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${w.contractPath}`)),console.log(s.gray(` Workspace: ${w.contract.workspace.name}`)),console.log(s.gray(` Projects: ${w.contract.projects.length}`)),console.log(s.gray(` Schema: v${w.contract.schemaVersion}`));return}if(g==="verify"){let w=await d({workspacePath:c,contractPath:y,strict:n.strict===true||a("--strict")}),{writeWorkspaceContractVerifyEvidence:P}=await import('./workspace-contract-OO4GMENV.js'),k=await P({workspacePath:c,result:w});if(n.json)console.log(JSON.stringify({...w,evidencePath:k},null,2));else {let h=w.status==="passed"?s.green:s.red;console.log(h(`\u2714 Workspace contract verification ${w.status}: ${w.contractPath}`)),console.log(s.gray(` Projects: ${w.projectCount}`));for(let S of w.checks){let b=S.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${b} ${S.id}: ${S.message}`));}for(let S of w.violations)console.log(s.gray(` Violation: ${S}`));}(w.status==="failed"||w.status!=="passed"&&n.strict)&&process.exit(1);return}if(g==="graph"){let w=await u({workspacePath:c,contractPath:y});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${w.contractPath}`)),console.log(s.gray(` Workspace: ${w.graph.workspace.name}`)),console.log(s.gray(` Projects: ${w.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${w.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${w.graph.summary.eventEdges}`)),console.log(s.gray(` Ports: ${w.graph.summary.portCount}`));for(let P of w.graph.nodes){let k=P.ports.map(h=>`${h.name}:${h.port}`).join(", ")||"none";console.log(s.gray(` \u2022 ${P.id} (${P.runtime||"unknown"}${P.framework?`/${P.framework}`:""}) ports=${k}`));}for(let P of w.graph.edges){let k=P.type==="event"?`event:${P.label}`:P.label;console.log(s.gray(` ${P.from} -> ${P.to} [${k}]`));}return}console.log(s.red(`\u274C Unknown workspace contract action: ${g}`)),console.log(s.white(` npx rapidkit workspace contract init|inspect|verify|graph [--output ${f}]`)),process.exit(1);}catch(w){n.json&&(console.log(JSON.stringify({command:`workspace contract ${g}`,result:"error",workspacePath:c,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${g}.failed`,message:w.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${g} failed: ${w.message}`)),process.exit(1);}}else if(t==="share"){let c=i("share"),u=n.output||e,{createWorkspaceShareBundle:m}=await import('./workspace-IBTKZX7T.js'),d=await m(c,{outputPath:u,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:c,bundlePath:d,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: ${d}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let c=i("export"),{exportWorkspaceArchive:u}=await import('./workspace-archive-EJIGYKSR.js'),m=await u({workspacePath:c,outputPath:n.output||e,includeEnv:n.includeEnv===true||a("--include-env")});if(n.json){console.log(JSON.stringify(m,null,2));return}let d=(m.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${m.archivePath}`)),console.log(s.gray(` Files: ${m.manifest.files.length}`)),console.log(s.gray(` Size: ${d} MB`)),m.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let c=o;c||(console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx rapidkit workspace archive ${e} team.rapidkit-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:u,inspectWorkspaceArchive:m,verifyWorkspaceArchive:d}=await import('./workspace-archive-EJIGYKSR.js');try{if(e==="inspect"){let f=await m({archivePathOrUrl:c});if(n.json){console.log(JSON.stringify(f,null,2));return}let g=(f.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${f.archivePath}`)),console.log(s.gray(` Workspace: ${f.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${f.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${f.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${f.fileCount}`)),console.log(s.gray(` Payload: ${g} MB`));return}if(e==="doctor"){let f=await u({archivePathOrUrl:c,strict:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(f,null,2));else {let g=f.status==="passed"?s.green:f.status==="warning"?s.yellow:s.red;console.log(g(`\u2714 Workspace archive doctor ${f.status}: ${f.archivePath}`)),console.log(s.gray(` Workspace: ${f.workspaceName}`)),console.log(s.gray(` Files: ${f.fileCount}`));for(let y of f.checks){let w=y.status==="passed"?"\u2714":y.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${w} ${y.id}: ${y.message}`));}for(let y of f.recommendedActions)console.log(s.gray(` Next: ${y}`));}(f.status==="failed"||f.status==="warning"&&n.strict)&&process.exit(1);return}let p=await d({archivePathOrUrl:c,requireChecksums:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(p,null,2));else if(p.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${p.archivePath}`)),console.log(s.gray(` Files: ${p.verifiedFiles}/${p.fileCount}`));else {let f=p.status==="failed"?s.red:s.yellow;console.log(f(`\u274C Workspace archive verification ${p.status}: ${p.archivePath}`)),p.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${p.missingArchiveEntries.join(", ")}`)),p.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${p.extraArchiveEntries.join(", ")}`)),p.mismatches.length&&console.log(s.gray(` Mismatches: ${p.mismatches.map(g=>g.path).join(", ")}`)),p.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${p.missingChecksumFiles.join(", ")}`));}(p.status==="failed"||p.status==="warning"&&n.strict)&&process.exit(1);}catch(p){n.json&&(console.log(JSON.stringify({schemaVersion:"workspace-archive-error-v1",command:`workspace archive ${e}`,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:c,error:{code:`workspace.archive.${e}.failed`,message:p.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${p.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let c=e;c||(console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx rapidkit workspace ${t} team.rapidkit-archive.zip --output ./team`)),process.exit(1));let{hydrateWorkspaceArchive:u}=await import('./workspace-archive-EJIGYKSR.js');try{let m=await u({archivePathOrUrl:c,outputPath:n.output,force:n.force===true||a("--force"),dryRun:n.dryRun===true||a("--dry-run"),strict:n.strict===true||a("--strict")});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.dryRun?`\u2714 Workspace archive hydrate preview: ${m.outputPath}`:`\u2714 Workspace archive hydrated: ${m.outputPath}`)),console.log(s.gray(` Files: ${m.files.length}`)),m.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${m.manifest.workspaceName}`));}catch(m){n.json&&(console.log(JSON.stringify({schemaVersion:"workspace-archive-error-v1",command:`workspace ${t}`,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:c,outputPath:n.output??null,dryRun:n.dryRun===true||a("--dry-run"),error:{code:`workspace.${t}.failed`,message:m.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${m.message}`)),process.exit(1);}}else if(t==="run"){let c=i(`run ${e||""}`.trim()),u=new Set(["init","test","build","start"]),m=e?.trim()??"";m||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .rapidkit/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)),u.has(m)||(!/^[a-z][a-z0-9_-]*$/i.test(m)||m==="dev"||m==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${m}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),process.exit(2));let d=Number(n.maxWorkers??""),p=Number.isFinite(d)?Math.max(1,Math.trunc(d)):void 0;if(m==="init"&&n.json!==true){let y=await cn(c);y!==0&&process.exit(y);}let{runWorkspaceStage:f}=await import('./workspace-run-ATFFJCMK.js'),g=await f({workspacePath:c,stage:m,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:p,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(g,null,2)),g.summary.exitCode!==0&&process.exit(g.summary.exitCode);}else if(t==="explain"||t==="why"){let c=i(t),{parseWorkspaceExplainTarget:u}=await import('./workspace-explain-contract-24RQ7KIW.js'),{buildWorkspaceExplain:m,writeWorkspaceExplainReport:d}=await import('./workspace-explain-P2EBRNP6.js'),p=(e??o??"").trim();!p&&n.scope&&(p=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),p||(console.log(s.red(`\u274C workspace ${t} requires a target.`)),console.log(s.gray(" npx rapidkit workspace explain project:<name>|release-blocked [--json] [--write]")),console.log(s.gray(" npx rapidkit workspace why <project>|release-blocked [--json]")),process.exit(1));let f=u(p);f||(console.log(s.red(`\u274C Invalid explain target: ${p}`)),process.exit(1));let g=await m({workspacePath:c,target:f}),y=n.write===true||a("--write"),w;if(y&&(w=await d(g,c,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify({...g,outputPath:w},null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${g.summary}`));for(let P of g.sections)console.log(s.bold(`
330
+ workspace mcp serve \u2014 read-mostly stdio MCP bridge over workspace evidence`).option("--workspace <path>","Workspace root path (defaults to nearest RapidKit workspace)").option("--output <file>","Output file path for workspace share bundle").option("--from <file>","Input workspace model snapshot/report for workspace diff").option("--from-impact <file>","Input workspace impact report for workspace verify (defaults to last-run impact)").option("--include-paths","Include absolute paths in workspace share bundle").option("--write","Write workspace intelligence artifact to .rapidkit/reports").option("--include-evidence","Read status metadata from referenced evidence reports").option("--scan-depth <count>","Observable project discovery depth for large monorepos").option("--cache","Reuse cached workspace model when inputs are unchanged (keyed by inputsHash)").option("--incremental","Rebuild only changed projects and re-infer only their incident graph edges (graph-aware)").option("--once","For workspace watch: do the initial in-memory build and exit (no watcher)").option("--for-agent [agent]","Build an agent-ready workspace context pack").option("--agent-sync","After --write on context, sync cross-tool agent grounding files (AGENTS.md, Copilot, Cursor, Claude)").option("--no-agent-sync","Skip automatic agent grounding sync after context --write").option("--target <targets>","Agent customization targets for agent-sync (all|vscode|agents,copilot,cursor,claude,codex,orca)").option("--preset <preset>","Agent customization pack preset for agent-sync (minimal|enterprise)").option("--refresh-context","Rebuild workspace-context-agent.json during agent-sync").option("--experimental-hooks","Generate advisory VS Code agent hook design files during enterprise agent-sync").option("--hydrate-prompts","Hydrate matching Copilot prompt files with workspace-specific verification steps during agent-sync").option("--scope <scope>","Scope workspace intelligence output, e.g. project:<name>").option("--no-doctor","Exclude doctor evidence in workspace share bundle").option("--no-blueprint","Exclude reproducibility blueprint from workspace share bundle").option("--include-env","Include .env/private key files in workspace export archive").option("--force","Overwrite an existing hydrate output directory").option("--refresh","Publish workspace registry summary before reading status").option("--dry-run","Preview hydrate without writing files").option("--affected","Run only affected projects (requires git diff context)").option("--blast-radius","Include downstream dependents from workspace dependency graph").option("--since <ref>","Git ref for affected calculation (default: HEAD~1)").option("--parallel","Run project stages in parallel").option("--max-workers <count>","Maximum parallel workers (default: min(4, selected))").option("--continue-on-error","Continue running remaining projects after a failure").option("--reuse-passed","Skip projects that already passed this stage in workspace-run-last.json").option("--json","Emit machine-readable JSON output").option("--ci","Build CI-oriented command plans where supported").option("--strict","Return non-zero exit on warn/fail gate outcomes").option("--no-gates","Skip doctor/readiness pre-run gates").action(async function(t,e,o,r){let n=this.opts(),i=c=>{let m=(n.workspace?v.resolve(n.workspace):null)??a$6(process.cwd())??Z(process.cwd());(!m||!We(m))&&(console.log(s.red("\u274C Not inside a RapidKit workspace")),console.log(s.gray("\u{1F4A1} Run from a workspace directory or pass --workspace <path>.")),process.exit(1));let d=v.resolve(process.cwd()),p=v.resolve(m);return d!==p&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${m} for "${c}" (current directory: ${d}).`)),m},a=c=>process.argv.includes(c),l=()=>{if(!n.scanDepth)return;let c=Number.parseInt(n.scanDepth,10);return Number.isFinite(c)?c:void 0};if((Ei(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||a("--json"),strict:n.strict===true||a("--strict")}}),t==="list"){let{listWorkspaces:c}=await import('./workspace-MPKEUHFP.js');await c({json:n.json===true||a("--json")});}else if(t==="model"){let c=i("model"),{buildWorkspaceModelCached:u,buildWorkspaceModelIncremental:m,writeWorkspaceModel:d}=await import('./workspace-model-IDRCH3VI.js'),p=n.incremental===true||a("--incremental"),f=n.cache===true||a("--cache")||p,g={workspacePath:c,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l(),strict:n.strict===true||a("--strict")},y,w;if(p){let h=await m(g);y=h.model,w=h.mode;}else {let h=await u({...g,cache:f});y=h.model,w=h.cache;}let P;(n.write===true||a("--write"))&&(P=await d(y,c));let k=(n.strict===true||a("--strict"))&&y.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...y,...P?{outputPath:P}:{}},null,2)),k&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${y.workspace.name}`)),p?console.log(s.gray(` Build: ${w} (incremental)`)):f&&console.log(s.gray(` Cache: ${w}`)),console.log(s.gray(` Projects: ${y.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${y.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${y.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${y.identity.workspaceType}`)),console.log(s.gray(` Validation: ${y.validation?.status??"unknown"} (${y.validation?.errors??0} error, ${y.validation?.warnings??0} warning)`)),console.log(P?s.gray(` Written: ${P}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-model.json")),k&&process.exit(1);}else if(t==="agent-sync"){let c=i("agent-sync"),{syncWorkspaceAgentGrounding:u,parseAgentGroundingTargets:m}=await import('./workspace-agent-sync-XD32GG5V.js'),d=n.strict===true||a("--strict"),p=n.write===true||a("--write"),f=a("--dry-run"),g=await u({workspacePath:c,scope:n.scope,agent:n.forAgent,write:p&&!f,dryRun:f,strict:d,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||a("--refresh-context")||a("--refresh"),targets:m(n.target),experimentalHooks:n.experimentalHooks===true||a("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||a("--hydrate-prompts"),staleAfterHours:24});if(n.json)console.log(JSON.stringify(g,null,2));else {console.log(s.green(`\u2714 Agent grounding ${p&&!f?"synced":"planned"}`)),console.log(s.gray(` Index: ${g.indexPath}`)),g.contextPath&&console.log(s.gray(` Context: ${g.contextPath}`)),g.blockers.length>0&&console.log(s.yellow(` Blockers: ${g.blockers.slice(0,3).join(" \xB7 ")}`));let y=p&&!f?g.writtenFiles:g.skippedFiles;if(y.length>0&&console.log(s.gray(` Files: ${y.join(", ")}`)),g.strictViolations.length>0)for(let w of g.strictViolations)console.log(s.red(`\u274C ${w}`));}d&&g.strictViolations.length>0&&process.exit(1);}else if(t==="remediation-plan"){let c=i("remediation-plan"),{buildArtifactRemediationPlan:u,writeArtifactRemediationPlan:m}=await import('./artifact-remediation-plan-HRR3WH7T.js'),d=await u({workspacePath:c,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),ciMode:n.ci===true||a("--ci")}),p;if((n.write===true||a("--write"))&&(p=await m(d,c)),n.json===true||a("--json")){console.log(JSON.stringify({...d,...p?{outputPath:p}:{}},null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${d.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${d.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${d.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${d.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${d.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${d.summary.risk.safe}, guarded=${d.summary.risk.guarded}, invasive=${d.summary.risk.invasive}`));for(let f of d.actions.slice(0,8))console.log(s.gray(` \u2022 ${f.cardId}: ${f.title} (${f.mode}, ${f.risk})`));d.actions.length>8&&console.log(s.gray(` \u2026 ${d.actions.length-8} more action(s)`)),console.log(p?s.gray(` Written: ${p}`):s.gray(" Add --write to persist .rapidkit/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let c=i("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx rapidkit workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:u,writeWorkspaceAgentContext:m}=await import('./workspace-context-QFES7YBC.js'),d=n.strict===true||a("--strict"),p=await u({workspacePath:c,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l(),strict:false}),f,g;if((n.write===true||a("--write"))&&(f=await m(p,c),(n.agentSync===true||a("--agent-sync")||n.noAgentSync!==true)&&!a("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:k}=await import('./workspace-agent-sync-XD32GG5V.js');if(g=await P({workspacePath:c,scope:n.scope,agent:p.agent,write:true,refreshContext:false,strict:d,preset:n.preset==="minimal"?"minimal":"enterprise",targets:k(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${g.writtenFiles.length} file(s) updated`)),d&&g.strictViolations.length>0){for(let h of g.strictViolations)console.log(s.red(`\u274C ${h}`));process.exit(1);}}let y=d&&p.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...p,...f?{outputPath:f}:{},...g?{agentGroundingSync:g}:{}},null,2)),y&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${p.workspace.name}`)),console.log(s.gray(` Agent: ${p.agent}`)),console.log(s.gray(` Scope: ${p.scope.activeProject??p.scope.requested}`)),console.log(s.gray(` Projects included: ${p.projects.length}`)),console.log(s.gray(` Safe commands: ${p.safeCommands.length}`)),console.log(s.gray(` Validation: ${p.validation.status} (${p.validation.errors} error, ${p.validation.warnings} warning)`)),console.log(f?s.gray(` Written: ${f}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-context-agent.json")),y){for(let w of p.validation.issues)console.log(s.red(`\u274C ${w.severity}:${w.code}:${w.target}`));process.exit(1);}}else if(t==="snapshot"){let c=i("snapshot"),{buildWorkspaceModelSnapshot:u,writeWorkspaceModelSnapshot:m}=await import('./workspace-intelligence-FJP5ONDB.js'),d=await u({workspacePath:c,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()}),p=await m(d,c);if(n.json){console.log(JSON.stringify({...d,outputPath:p},null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${d.model.workspace.name}`)),console.log(s.gray(` Hash: ${d.modelHash}`)),console.log(s.gray(` Projects: ${d.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${d.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${p}`));}else if(t==="diff"){let c=i("diff"),u=n.from||e;u||((n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-diff-error-v1",command:"workspace diff",status:"error",workspacePath:c,error:{code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>."},examples:["npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json","npx rapidkit workspace diff --from .rapidkit/reports/workspace-model.json --json","npx rapidkit 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 rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx rapidkit workspace diff --from .rapidkit/reports/workspace-model.json --json")),console.log(s.gray(" npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx rapidkit workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:m,writeWorkspaceModelDiff:d}=await import('./workspace-intelligence-FJP5ONDB.js'),p;try{p=await m({workspacePath:c,fromPath:u,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()});}catch(y){throw (n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-diff-error-v1",command:"workspace diff",status:"error",workspacePath:c,fromPath:u,error:{code:"workspace.diff.input_unreadable",message:y.message},nextActions:["npx rapidkit workspace snapshot create --json","npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json"]},null,2)),process.exit(1)),y}let f=await d(p,c);if(n.json){console.log(JSON.stringify({...p,outputPath:f},null,2));return}let g=p.summary.changed?s.yellow:s.green;console.log(g(`\u2714 Workspace model diff: ${p.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${p.fromRef}`)),console.log(s.gray(` Added projects: ${p.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${p.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${p.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${p.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${p.summary.validationChanges}`)),p.git?.available&&console.log(s.gray(` Git: ${p.git.dirty?"dirty":"clean"} (${p.summary.gitChangedFiles} mapped change(s))`));for(let y of p.changes.slice(0,12))console.log(s.gray(` \u2022 ${y.type} ${y.target}: ${y.message}`));p.changes.length>12&&console.log(s.gray(` \u2026 ${p.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="impact"){let c=i("impact"),u=n.from||e;u||((n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-impact-error-v1",command:"workspace impact",status:"error",workspacePath:c,error:{code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>."},examples:["npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json","npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <snapshot-model-or-diff-report>")),console.log(s.gray(" npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:m,writeWorkspaceImpact:d}=await import('./workspace-intelligence-FJP5ONDB.js'),p;try{p=await m({workspacePath:c,fromPath:u,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()});}catch(y){throw (n.json===true||a("--json"))&&(console.log(JSON.stringify({schemaVersion:"workspace-impact-error-v1",command:"workspace impact",status:"error",workspacePath:c,fromPath:u,error:{code:"workspace.impact.input_unreadable",message:y.message},nextActions:["npx rapidkit workspace snapshot create --json","npx rapidkit workspace diff --from .rapidkit/reports/workspace-model-snapshot.json --json","npx rapidkit workspace impact --from .rapidkit/reports/workspace-model-diff-last-run.json --json"]},null,2)),process.exit(1)),y}let f=await d(p,c);if(n.json){console.log(JSON.stringify({...p,outputPath:f},null,2));return}let g=p.summary.risk==="critical"||p.summary.risk==="high"?s.red:p.summary.risk==="medium"?s.yellow:s.green;console.log(g(`\u2714 Workspace impact: ${p.summary.risk}`)),console.log(s.gray(` From: ${p.fromRef}`)),console.log(s.gray(` Affected projects: ${p.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${p.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${p.summary.recommendedCommands}`));for(let y of p.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${y.title}: ${y.summary}`));p.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${p.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="verify"){let c=i("verify"),{buildWorkspaceVerify:u,writeWorkspaceVerify:m,evaluateWorkspaceVerifyGate:d}=await import('./workspace-verify-K4RSQIXT.js'),p=await u({workspacePath:c,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()}),f=await m(p,c),g=d(p,{strict:n.strict===true||a("--strict")}),y=g.exitCode,{recordWorkspaceHistory:w,historyEntryFromVerify:P}=await import('./workspace-history-DSCH7PQZ.js');if(await w(c,P(p,g.passed)),n.json){console.log(JSON.stringify({...p,gate:g,outputPath:f},null,2)),y!==0&&process.exit(y);return}let k=p.summary.verdict==="ready"?s.green:p.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(k(`\u2714 Workspace verify: ${p.summary.verdict}`)),console.log(s.gray(` Freshness: ${p.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${p.impact.risk}`)),console.log(s.gray(` Steps: ${p.steps.length}`)),console.log(s.gray(` Passed ${p.summary.stepsPassed}, warn ${p.summary.stepsWarn}, failed ${p.summary.stepsFailed}, missing ${p.summary.stepsMissing}`));for(let h of p.steps.slice(0,10))console.log(s.gray(` \u2022 ${h.id}: ${h.status} \u2014 ${h.message}`));if(p.steps.length>10&&console.log(s.gray(` \u2026 ${p.steps.length-10} more step(s)`)),p.policyViolations.length>0){console.log(s.gray(` Policy (${p.policyMode}): ${p.policyViolations.length} violation(s)`));for(let h of p.policyViolations.slice(0,5)){let S=h.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${S} [${h.source}] ${h.code}: ${h.message}`);}}console.log(s.gray(` Gate (${g.mode}): ${g.passed?"passed":"blocked"}`));for(let h of g.reasons.slice(0,5))console.log(s.red(` \u2717 ${h}`));console.log(s.gray(` Written: ${f}`)),y!==0&&process.exit(y);}else if(t==="graph"){let c=i("graph"),{buildWorkspaceModel:u}=await import('./workspace-model-IDRCH3VI.js'),{buildGraphEmit:m,renderGraphDot:d,renderGraphMermaid:p,explainGraphNode:f}=await import('./workspace-graph-2A5THUCI.js'),y=(await u({workspacePath:c,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:l()})).graph,w=(e||"emit").toLowerCase();if(y||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:w,result:"error",workspacePath:c,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)),w==="dot"){console.log(d(y));return}if(w==="mermaid"){console.log(p(y));return}if(w==="explain"){let k=(n.scope?.replace(/^project:/,"")||o||"").trim();k||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:c,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx rapidkit workspace graph explain <project> --json","npx rapidkit 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 rapidkit workspace graph explain <project> --json")),console.log(s.gray(" npx rapidkit workspace graph explain --scope project:<name>")),process.exit(1));let h=f(y,k);if(n.json){console.log(JSON.stringify(h,null,2)),h.found||process.exit(1);return}h.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${k}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${h.project}`)),h.centrality&&console.log(s.gray(` Centrality: fanIn ${h.centrality.fanIn}, fanOut ${h.centrality.fanOut}, reach ${h.centrality.reach}, betweenness ${h.centrality.betweenness}${h.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${h.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${h.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${h.transitiveDependents.length}`));for(let S of h.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${S.id} (d${S.distance}, via ${S.via??"\u2014"})`));return}let P=m(y);if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${P.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${P.graph.stats.edgeCount} (inferred ${P.graph.stats.inferredEdges}, contract ${P.graph.stats.contractEdges}, manual ${P.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${P.integrity.ok?"ok":"issues"} (cycles ${P.integrity.stats.cycleCount}, dangling ${P.integrity.stats.danglingCount}, orphans ${P.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${P.hotspots.join(", ")||"none"}`)),console.log(s.gray(" Render: workspace graph dot | workspace graph mermaid"));}else if(t==="watch"){let c=i("watch"),{runWorkspaceWatch:u}=await import('./workspace-watch-PFJDHPXI.js'),m=n.once===true||a("--once"),d=n.json===true,p=new AbortController,f=()=>p.abort();process.once("SIGINT",f),process.once("SIGTERM",f),d||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await u({workspacePath:c,once:m,signal:p.signal,buildOptions:{workspacePath:c,observableScanDepth:l()},onProgress:g=>{d||console.error(s.gray(` ${g}`));},emit:g=>{if(d){console.log(JSON.stringify(g));return}if(g.kind==="ready"){console.log(s.gray(` Ready: ${g.graph.nodeCount} nodes, ${g.graph.edgeCount} edges (hash ${g.modelHash.slice(0,12)})`));return}if(g.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${g.error??"unknown error"}`));return}if(g.kind==="unchanged"){console.log(s.gray(` No structural change (${g.mode}, ${g.durationMs}ms)`));return}let y=[];g.changedProjects.length>0&&y.push(`changed: ${g.changedProjects.join(", ")}`),g.addedProjects.length>0&&y.push(`added: ${g.addedProjects.join(", ")}`),g.removedProjects.length>0&&y.push(`removed: ${g.removedProjects.join(", ")}`),g.graph.edgesAdded.length>0&&y.push(`+${g.graph.edgesAdded.length} edges`),g.graph.edgesRemoved.length>0&&y.push(`-${g.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${g.mode}, ${g.durationMs}ms): ${y.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",f),process.removeListener("SIGTERM",f),!d&&!m&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let c=i("sync"),{syncWorkspaceProjects:u}=await import('./workspace-MPKEUHFP.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${v.basename(c)}`));let m=await u(c,n.json===true);await qe(c,{silent:n.json===true});let{readWorkspaceRegistrySummary:d}=await import('./workspace-registry-summary-X5WRUU3T.js'),p=await d(c);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:c,registry:m,contractSynced:true,registrySummary:p},null,2));}else if(t==="registry"){let c=i("registry"),u=e||"status";u!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${u}`)),console.log(s.gray(" npx rapidkit workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:m,readWorkspaceRegistrySummary:d,resolveWorkspaceRegisteredProjects:p}=await import('./workspace-registry-summary-X5WRUU3T.js'),g=n.refresh===true||a("--refresh")||n.force===true||a("--force")?await m(c):await d(c)||await m(c);if(n.json){console.log(JSON.stringify(g,null,2));return}let y=await p(c);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}`)),y.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let c=i("foundation"),u=e||"ensure";u!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${u}`)),console.log(s.gray(" npx rapidkit workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:m}=await import('./workspace-foundation-2OVUZXPT.js'),d=await m(c,{force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(d,null,2));return}d.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${d.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let c=i("policy"),u=await yd(c,e,o,r,n.json===true||a("--json"));u!==0&&process.exit(u);}else if(t==="contract"){let c=i("contract"),{buildWorkspaceContractGraph:u,readWorkspaceContract:m,verifyWorkspaceContract:d,writeWorkspaceContract:p,WORKSPACE_CONTRACT_PATH:f}=await import('./workspace-contract-OO4GMENV.js'),g=e||"inspect",y=n.output;try{if(g==="init"){let w=await p({workspacePath:c,outputPath:y,force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${w.contractPath}`)),console.log(s.gray(` Projects: ${w.contract.projects.length}`));return}if(g==="inspect"){let w=await m({workspacePath:c,contractPath:y});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${w.contractPath}`)),console.log(s.gray(` Workspace: ${w.contract.workspace.name}`)),console.log(s.gray(` Projects: ${w.contract.projects.length}`)),console.log(s.gray(` Schema: v${w.contract.schemaVersion}`));return}if(g==="verify"){let w=await d({workspacePath:c,contractPath:y,strict:n.strict===true||a("--strict")}),{writeWorkspaceContractVerifyEvidence:P}=await import('./workspace-contract-OO4GMENV.js'),k=await P({workspacePath:c,result:w});if(n.json)console.log(JSON.stringify({...w,evidencePath:k},null,2));else {let h=w.status==="passed"?s.green:s.red;console.log(h(`\u2714 Workspace contract verification ${w.status}: ${w.contractPath}`)),console.log(s.gray(` Projects: ${w.projectCount}`));for(let S of w.checks){let b=S.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${b} ${S.id}: ${S.message}`));}for(let S of w.violations)console.log(s.gray(` Violation: ${S}`));}(w.status==="failed"||w.status!=="passed"&&n.strict)&&process.exit(1);return}if(g==="graph"){let w=await u({workspacePath:c,contractPath:y});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${w.contractPath}`)),console.log(s.gray(` Workspace: ${w.graph.workspace.name}`)),console.log(s.gray(` Projects: ${w.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${w.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${w.graph.summary.eventEdges}`)),console.log(s.gray(` Ports: ${w.graph.summary.portCount}`));for(let P of w.graph.nodes){let k=P.ports.map(h=>`${h.name}:${h.port}`).join(", ")||"none";console.log(s.gray(` \u2022 ${P.id} (${P.runtime||"unknown"}${P.framework?`/${P.framework}`:""}) ports=${k}`));}for(let P of w.graph.edges){let k=P.type==="event"?`event:${P.label}`:P.label;console.log(s.gray(` ${P.from} -> ${P.to} [${k}]`));}return}console.log(s.red(`\u274C Unknown workspace contract action: ${g}`)),console.log(s.white(` npx rapidkit workspace contract init|inspect|verify|graph [--output ${f}]`)),process.exit(1);}catch(w){n.json&&(console.log(JSON.stringify({command:`workspace contract ${g}`,result:"error",workspacePath:c,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${g}.failed`,message:w.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${g} failed: ${w.message}`)),process.exit(1);}}else if(t==="share"){let c=i("share"),u=n.output||e,{createWorkspaceShareBundle:m}=await import('./workspace-MPKEUHFP.js'),d=await m(c,{outputPath:u,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:c,bundlePath:d,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: ${d}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let c=i("export"),{exportWorkspaceArchive:u}=await import('./workspace-archive-EJIGYKSR.js'),m=await u({workspacePath:c,outputPath:n.output||e,includeEnv:n.includeEnv===true||a("--include-env")});if(n.json){console.log(JSON.stringify(m,null,2));return}let d=(m.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${m.archivePath}`)),console.log(s.gray(` Files: ${m.manifest.files.length}`)),console.log(s.gray(` Size: ${d} MB`)),m.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let c=o;c||(console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx rapidkit workspace archive ${e} team.rapidkit-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:u,inspectWorkspaceArchive:m,verifyWorkspaceArchive:d}=await import('./workspace-archive-EJIGYKSR.js');try{if(e==="inspect"){let f=await m({archivePathOrUrl:c});if(n.json){console.log(JSON.stringify(f,null,2));return}let g=(f.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${f.archivePath}`)),console.log(s.gray(` Workspace: ${f.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${f.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${f.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${f.fileCount}`)),console.log(s.gray(` Payload: ${g} MB`));return}if(e==="doctor"){let f=await u({archivePathOrUrl:c,strict:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(f,null,2));else {let g=f.status==="passed"?s.green:f.status==="warning"?s.yellow:s.red;console.log(g(`\u2714 Workspace archive doctor ${f.status}: ${f.archivePath}`)),console.log(s.gray(` Workspace: ${f.workspaceName}`)),console.log(s.gray(` Files: ${f.fileCount}`));for(let y of f.checks){let w=y.status==="passed"?"\u2714":y.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${w} ${y.id}: ${y.message}`));}for(let y of f.recommendedActions)console.log(s.gray(` Next: ${y}`));}(f.status==="failed"||f.status==="warning"&&n.strict)&&process.exit(1);return}let p=await d({archivePathOrUrl:c,requireChecksums:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(p,null,2));else if(p.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${p.archivePath}`)),console.log(s.gray(` Files: ${p.verifiedFiles}/${p.fileCount}`));else {let f=p.status==="failed"?s.red:s.yellow;console.log(f(`\u274C Workspace archive verification ${p.status}: ${p.archivePath}`)),p.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${p.missingArchiveEntries.join(", ")}`)),p.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${p.extraArchiveEntries.join(", ")}`)),p.mismatches.length&&console.log(s.gray(` Mismatches: ${p.mismatches.map(g=>g.path).join(", ")}`)),p.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${p.missingChecksumFiles.join(", ")}`));}(p.status==="failed"||p.status==="warning"&&n.strict)&&process.exit(1);}catch(p){n.json&&(console.log(JSON.stringify({schemaVersion:"workspace-archive-error-v1",command:`workspace archive ${e}`,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:c,error:{code:`workspace.archive.${e}.failed`,message:p.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${p.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let c=e;c||(console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx rapidkit workspace ${t} team.rapidkit-archive.zip --output ./team`)),process.exit(1));let{hydrateWorkspaceArchive:u}=await import('./workspace-archive-EJIGYKSR.js');try{let m=await u({archivePathOrUrl:c,outputPath:n.output,force:n.force===true||a("--force"),dryRun:n.dryRun===true||a("--dry-run"),strict:n.strict===true||a("--strict")});if(n.json){console.log(JSON.stringify(m,null,2));return}console.log(s.green(m.dryRun?`\u2714 Workspace archive hydrate preview: ${m.outputPath}`:`\u2714 Workspace archive hydrated: ${m.outputPath}`)),console.log(s.gray(` Files: ${m.files.length}`)),m.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${m.manifest.workspaceName}`));}catch(m){n.json&&(console.log(JSON.stringify({schemaVersion:"workspace-archive-error-v1",command:`workspace ${t}`,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:c,outputPath:n.output??null,dryRun:n.dryRun===true||a("--dry-run"),error:{code:`workspace.${t}.failed`,message:m.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${m.message}`)),process.exit(1);}}else if(t==="run"){let c=i(`run ${e||""}`.trim()),u=new Set(["init","test","build","start"]),m=e?.trim()??"";m||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .rapidkit/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)),u.has(m)||(!/^[a-z][a-z0-9_-]*$/i.test(m)||m==="dev"||m==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${m}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),process.exit(2));let d=Number(n.maxWorkers??""),p=Number.isFinite(d)?Math.max(1,Math.trunc(d)):void 0;if(m==="init"&&n.json!==true){let y=await cn(c);y!==0&&process.exit(y);}let{runWorkspaceStage:f}=await import('./workspace-run-NULA72JV.js'),g=await f({workspacePath:c,stage:m,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:p,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(g,null,2)),g.summary.exitCode!==0&&process.exit(g.summary.exitCode);}else if(t==="explain"||t==="why"){let c=i(t),{parseWorkspaceExplainTarget:u}=await import('./workspace-explain-contract-24RQ7KIW.js'),{buildWorkspaceExplain:m,writeWorkspaceExplainReport:d}=await import('./workspace-explain-Q7TJCHD5.js'),p=(e??o??"").trim();!p&&n.scope&&(p=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),p||(console.log(s.red(`\u274C workspace ${t} requires a target.`)),console.log(s.gray(" npx rapidkit workspace explain project:<name>|release-blocked [--json] [--write]")),console.log(s.gray(" npx rapidkit workspace why <project>|release-blocked [--json]")),process.exit(1));let f=u(p);f||(console.log(s.red(`\u274C Invalid explain target: ${p}`)),process.exit(1));let g=await m({workspacePath:c,target:f}),y=n.write===true||a("--write"),w;if(y&&(w=await d(g,c,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify({...g,outputPath:w},null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${g.summary}`));for(let P of g.sections)console.log(s.bold(`
331
331
  ${P.title}`)),console.log(P.body);w&&console.log(s.gray(`
332
- Written: ${w}`));}else if(t==="trace"){let c=i("trace"),u=n.from||e;u||(console.log(s.red("\u274C workspace trace requires --from <diff-ref>")),console.log(s.gray(" npx rapidkit workspace trace --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{resolveWorkspaceTraceTarget:m}=await import('./workspace-explain-contract-24RQ7KIW.js'),{buildWorkspaceExplain:d,writeWorkspaceExplainReport:p}=await import('./workspace-explain-P2EBRNP6.js'),f=m(u);(!f||f.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${u}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.rapidkit/reports/workspace-model-diff-last-run.json")),process.exit(1));let g=await d({workspacePath:c,target:f}),y=n.write===true||a("--write"),w;if(y&&(w=await p(g,c,"trace")),n.json){console.log(JSON.stringify({...g,outputPath:w},null,2));return}console.log(s.green(`\u2714 Workspace trace: ${g.summary}`));for(let P of g.sections)console.log(s.bold(`
332
+ Written: ${w}`));}else if(t==="trace"){let c=i("trace"),u=n.from||e;u||(console.log(s.red("\u274C workspace trace requires --from <diff-ref>")),console.log(s.gray(" npx rapidkit workspace trace --from .rapidkit/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{resolveWorkspaceTraceTarget:m}=await import('./workspace-explain-contract-24RQ7KIW.js'),{buildWorkspaceExplain:d,writeWorkspaceExplainReport:p}=await import('./workspace-explain-Q7TJCHD5.js'),f=m(u);(!f||f.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${u}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.rapidkit/reports/workspace-model-diff-last-run.json")),process.exit(1));let g=await d({workspacePath:c,target:f}),y=n.write===true||a("--write"),w;if(y&&(w=await p(g,c,"trace")),n.json){console.log(JSON.stringify({...g,outputPath:w},null,2));return}console.log(s.green(`\u2714 Workspace trace: ${g.summary}`));for(let P of g.sections)console.log(s.bold(`
333
333
  ${P.title}`)),console.log(P.body);w&&console.log(s.gray(`
334
- Written: ${w}`));}else if(t==="feedback"){let c=i("feedback"),u=(e||"record").toLowerCase();u!=="record"&&(console.log(s.red(`Unknown feedback action: ${u}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!a("--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 rapidkit 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 rapidkit workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:m,parseFeedbackStdinPayload:d,readStdinAll:p}=await import('./workspace-feedback-KCDFF7YS.js'),f=await p(),g=d(f);g||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let y=await m({workspacePath:c,payload:g});n.json?console.log(JSON.stringify(y,null,2)):y.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${y.historyPath}`))):console.log(s.red(`\u274C ${y.error??"Failed to record feedback"}`)),y.ok||process.exit(1);}else if(t==="mcp"){let c=i("mcp"),u=(e||"serve").toLowerCase();u!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:u,result:"error",workspacePath:c,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${u}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${u}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:m}=await import('./workspace-mcp-serve-GM7A3IVM.js');n.json||console.error(s.gray("\u2139 RapidKit MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await m({workspacePath:c});}else if(t==="init"){console.log(s.yellow("\u2139 workspace init is an alias of: npx rapidkit workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
334
+ Written: ${w}`));}else if(t==="feedback"){let c=i("feedback"),u=(e||"record").toLowerCase();u!=="record"&&(console.log(s.red(`Unknown feedback action: ${u}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!a("--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 rapidkit 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 rapidkit workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:m,parseFeedbackStdinPayload:d,readStdinAll:p}=await import('./workspace-feedback-KCDFF7YS.js'),f=await p(),g=d(f);g||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let y=await m({workspacePath:c,payload:g});n.json?console.log(JSON.stringify(y,null,2)):y.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${y.historyPath}`))):console.log(s.red(`\u274C ${y.error??"Failed to record feedback"}`)),y.ok||process.exit(1);}else if(t==="mcp"){let c=i("mcp"),u=(e||"serve").toLowerCase();u!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:u,result:"error",workspacePath:c,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${u}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${u}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:m}=await import('./workspace-mcp-serve-DFJIUTL5.js');n.json||console.error(s.gray("\u2139 RapidKit MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await m({workspacePath:c});}else if(t==="init"){console.log(s.yellow("\u2139 workspace init is an alias of: npx rapidkit workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
335
335
  npx rapidkit init | npx rapidkit workspace init | npx rapidkit workspace run init
336
- `));let c=i("init"),u=Number(n.maxWorkers??""),m=Number.isFinite(u)?Math.max(1,Math.trunc(u)):void 0,d=await cn(c);d!==0&&process.exit(d);let{runWorkspaceStage:p}=await import('./workspace-run-ATFFJCMK.js'),f=await p({workspacePath:c,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(f,null,2)),f.summary.exitCode!==0&&process.exit(f.summary.exitCode);}else console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${Ko.join(", ")}`)),process.exit(1);});function Mt(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function Ca(){let t=b$1()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev";console.log(s.white(`Usage:
336
+ `));let c=i("init"),u=Number(n.maxWorkers??""),m=Number.isFinite(u)?Math.max(1,Math.trunc(u)):void 0,d=await cn(c);d!==0&&process.exit(d);let{runWorkspaceStage:p}=await import('./workspace-run-NULA72JV.js'),f=await p({workspacePath:c,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(f,null,2)),f.summary.exitCode!==0&&process.exit(f.summary.exitCode);}else console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${Ko.join(", ")}`)),process.exit(1);});function Mt(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function bd(){console.log(s.yellow("Migration notice: rapidkit is moving to Workspai.")),console.log(s.gray("The rapidkit npm package is in compatibility mode and is planned for deprecation in a future release.")),console.log(s.gray("New installs should use:")),console.log(s.cyan(" npm install -g workspai")),console.log(s.cyan(" npx workspai --help")),console.log(s.gray("Legacy compatibility package: npm install -g rapidkit")),console.log(s.gray("Package: https://www.npmjs.com/package/workspai")),console.log(s.gray(`Repo: https://github.com/rapidkitlabs/workspai
337
+ `));}function Ca(){let t=b$1()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev";bd(),console.log(s.white(`Usage:
337
338
  `)),console.log(s.cyan(` npx rapidkit <workspace-name> [options]
338
339
  `)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems
339
340
  `)),console.log(s.white("Most AI tools understand files.")),console.log(s.white("RapidKit helps developers, CI pipelines, IDEs, and AI agents share the same understanding of a software system.")),console.log(s.dim(`One workspace. One truth. Humans and AI aligned.
@@ -413,7 +414,7 @@ Generate context pack
413
414
  `))):console.log(s.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
414
415
  `));}var la="__rapidkit_signal_handlers_registered__",da=globalThis;da[la]||(da[la]=true,process.on("SIGINT",async()=>{if(!Yo){if(Yo=true,console.log(s.yellow(`
415
416
 
416
- \u26A0\uFE0F Interrupted by user`)),st&&await E__default.pathExists(st)){console.log(s.gray("Cleaning up partial installation..."));try{await E__default.remove(st),console.log(s.green("\u2713 Cleanup complete"));}catch(t){f.debug("Cleanup failed:",t);}}b$6(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!Yo){if(Yo=true,f.debug("Received SIGTERM"),st&&await E__default.pathExists(st))try{await E__default.remove(st);}catch(t){f.debug("Cleanup failed:",t);}b$6(143,"Terminated"),process.exit(143);}}));var bd=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",jd=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),o=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return j.realpathSync(t)===j.realpathSync(fileURLToPath(import.meta.url))||o}catch{return v.resolve(t)===v.resolve(fileURLToPath(import.meta.url))||o}})(),Sd=!bd||jd;function xd(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}function Cd(){for(let t of [process.stdout,process.stderr]){if(t.isTTY)continue;let e=t;if(e.__rapidkitSyncWriteInstalled)continue;let o=t.fd;if(typeof o!="number")continue;let r=t.write.bind(t);e.write=((n,i,a)=>{let l=typeof i=="string"?i:"utf8",c=typeof i=="function"?i:typeof a=="function"?a:void 0;try{let u=typeof n=="string"?Buffer.from(n,l):n instanceof Uint8Array?Buffer.from(n):Buffer.from(String(n),l);return j.writeSync(o,u),c?.(),true}catch{return r(n,l,c)}}),e.__rapidkitSyncWriteInstalled=true;}}async function ne(t){b$6(t),await new Promise(e=>setImmediate(e)),await new Promise(e=>setTimeout(e,25)),await Promise.all([process.stdout,process.stderr].map(e=>new Promise(o=>{e.write("",()=>o());}))),process.exit(t);}async function pa(t,e=0){return j.writeSync(process.stdout.fd??1,t),ne(e)}if(Sd){xd(),Cd(),d$3(),a$3({argv:process.argv,cwd:process.cwd(),rapidkitVersion:b()}),c$1(process.argv);let t=process.argv.slice(2),e$2=t[0],o=process.cwd(),r=We(o),n=j.existsSync(v.join(o,".rapidkit","project.json")),i$2=Ql(),a=Zi(t),l=i$2&&eo(t),c=e$2==="init"&&r&&!n;(t.length===0||t.length===1&&(e$2==="--help"||e$2==="-h"||e$2==="help"))&&(a$1("npm cli"),Ca(),await ne(0)),t.some(m=>m==="--version"||m==="-V"||m==="-v")&&!t.some(m=>m==="--help"||m==="-h"||m==="help")&&(t.includes("--json")?await pa(`${JSON.stringify(Zl(),null,2)}
417
+ \u26A0\uFE0F Interrupted by user`)),st&&await E__default.pathExists(st)){console.log(s.gray("Cleaning up partial installation..."));try{await E__default.remove(st),console.log(s.green("\u2713 Cleanup complete"));}catch(t){f.debug("Cleanup failed:",t);}}b$6(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!Yo){if(Yo=true,f.debug("Received SIGTERM"),st&&await E__default.pathExists(st))try{await E__default.remove(st);}catch(t){f.debug("Cleanup failed:",t);}b$6(143,"Terminated"),process.exit(143);}}));var jd=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Sd=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),o=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return j.realpathSync(t)===j.realpathSync(fileURLToPath(import.meta.url))||o}catch{return v.resolve(t)===v.resolve(fileURLToPath(import.meta.url))||o}})(),xd=!jd||Sd;function Cd(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}function Rd(){for(let t of [process.stdout,process.stderr]){if(t.isTTY)continue;let e=t;if(e.__rapidkitSyncWriteInstalled)continue;let o=t.fd;if(typeof o!="number")continue;let r=t.write.bind(t);e.write=((n,i,a)=>{let l=typeof i=="string"?i:"utf8",c=typeof i=="function"?i:typeof a=="function"?a:void 0;try{let u=typeof n=="string"?Buffer.from(n,l):n instanceof Uint8Array?Buffer.from(n):Buffer.from(String(n),l);return j.writeSync(o,u),c?.(),true}catch{return r(n,l,c)}}),e.__rapidkitSyncWriteInstalled=true;}}async function ne(t){b$6(t),await new Promise(e=>setImmediate(e)),await new Promise(e=>setTimeout(e,25)),await Promise.all([process.stdout,process.stderr].map(e=>new Promise(o=>{e.write("",()=>o());}))),process.exit(t);}async function pa(t,e=0){return j.writeSync(process.stdout.fd??1,t),ne(e)}if(xd){Cd(),Rd(),d$3(),a$3({argv:process.argv,cwd:process.cwd(),rapidkitVersion:b()}),c$1(process.argv);let t=process.argv.slice(2),e$2=t[0],o=process.cwd(),r=We(o),n=j.existsSync(v.join(o,".rapidkit","project.json")),i$2=Ql(),a=Zi(t),l=i$2&&eo(t),c=e$2==="init"&&r&&!n;(t.length===0||t.length===1&&(e$2==="--help"||e$2==="-h"||e$2==="help"))&&(a$1("npm cli"),Ca(),await ne(0)),t.some(m=>m==="--version"||m==="-V"||m==="-v")&&!t.some(m=>m==="--help"||m==="-h"||m==="help")&&(t.includes("--json")?await pa(`${JSON.stringify(Zl(),null,2)}
417
418
  `):await pa(`${b()}
418
419
  `)),nn(t)&&await ne(0),l&&ea(e$2)?(async()=>{e$2==="bootstrap"&&await ne(await na(t)),e$2==="setup"&&await ne(await sa(t)),e$2==="cache"&&await ne(await ia(t)),await ne(await aa(t));})().catch(m=>{process.stderr.write(`RapidKit (npm) failed to run ${e$2}: ${m?.message??m}
419
420
  `),process.exit(1);}):a||l?oe.parseAsync().then(()=>ne(0)).catch(m=>{process.stderr.write(`RapidKit (npm) failed: ${m?.message??m}