rapidkit 0.41.1 → 0.41.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 (28) hide show
  1. package/README.md +76 -6
  2. package/contracts/extension-cli-compatibility.v1.json +1 -1
  3. package/contracts/runtime-command-surface.v1.json +3 -1
  4. package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +24 -0
  5. package/dist/autopilot-release-YDEUKRW6.js +1 -0
  6. package/dist/chunk-DWXRVGOY.js +2 -0
  7. package/dist/{chunk-TJN7G2MA.js → chunk-HYAT2EG7.js} +1 -1
  8. package/dist/{chunk-UQR6G7KH.js → chunk-JNXT6KJV.js} +1 -1
  9. package/dist/{chunk-CDPR2YKL.js → chunk-WCICO7ZB.js} +1 -1
  10. package/dist/{chunk-CKXJR3YT.js → chunk-ZPXMZCYG.js} +1 -1
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.js +8 -8
  13. package/dist/{pipeline-DH6Z47O4.js → pipeline-YD2DO7XY.js} +1 -1
  14. package/dist/{workspace-agent-sync-2HRPM5ZD.js → workspace-agent-sync-BHE2V4KS.js} +1 -1
  15. package/dist/workspace-explain-XJ22ZXJY.js +1 -0
  16. package/dist/{workspace-intelligence-E3KXEZCM.js → workspace-intelligence-EC63CRVF.js} +1 -1
  17. package/dist/{workspace-mcp-serve-RFYDCA2L.js → workspace-mcp-serve-KOM2V35Q.js} +1 -1
  18. package/dist/workspace-run-F5FADRY5.js +1 -0
  19. package/dist/{workspace-verify-NRYH7RNB.js → workspace-verify-IAUHP6Y6.js} +1 -1
  20. package/docs/contracts/ARTIFACT_CATALOG.md +1 -1
  21. package/docs/contracts/README.md +11 -0
  22. package/package.json +1 -1
  23. package/scripts/enterprise-package-smoke.mjs +15 -9
  24. package/dist/autopilot-release-AHMQEUFH.js +0 -1
  25. package/dist/chunk-LKX3L7TE.js +0 -2
  26. package/dist/workspace-explain-3WSJLIJ6.js +0 -1
  27. package/dist/workspace-run-GCIQD73R.js +0 -1
  28. /package/dist/{chunk-JW2FSKT3.js → chunk-VDTAPIHB.js} +0 -0
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$b}from'./chunk-ICGWHIMK.js';import {b as b$5,a as a$5}from'./chunk-ITJ6RKUW.js';import {a as a$6}from'./chunk-KMUWWZRT.js';import {b as b$6,d as d$2,a as a$3,c as c$1,f as f$4,e as e$4}from'./chunk-PCXSTKZ5.js';import {b as b$b,a as a$d,l as l$3}from'./chunk-UQR6G7KH.js';import {a as a$f}from'./chunk-33LR2QEM.js';import {c as c$6,a as a$g}from'./chunk-TJN7G2MA.js';import {e as e$3}from'./chunk-LKX3L7TE.js';import {a as a$e}from'./chunk-VMJA36WD.js';import {g,b as b$2,c,d,m,l,h as h$1,k,a as a$7,j as j$1,f as f$5,i as i$5}from'./chunk-JU3VNLTY.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$c}from'./chunk-AQ4XZZC6.js';import {c as c$4,d as d$5,e as e$2,f as f$3,g as g$2,a as a$h}from'./chunk-EN6YCX36.js';import {j,a as a$4,b as b$7,c as c$2,d as d$3,e as e$1,f as f$2,q as q$1,s as s$2,h as h$2,m as m$1,i,r,t as t$1,g as g$1,p as p$1,k as k$2,o as o$2}from'./chunk-YBS2HGO3.js';export{i as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-YBS2HGO3.js';import {i as i$1}from'./chunk-UZW5QFRW.js';import {f as f$6}from'./chunk-3PTJID76.js';import {h,a as a$2,q,s as s$1,p,t,m as m$2,l as l$1,n as n$1,k as k$1,o as o$1,i as i$4}from'./chunk-E5ZVQL3C.js';import {b as b$9,d as d$6}from'./chunk-RV6HBTFC.js';import {a as a$a}from'./chunk-VKLL63TL.js';import {b,a}from'./chunk-Q2KZIBV4.js';import {f,d as d$1,b as b$8}from'./chunk-OLDPVVSV.js';import {c as c$7}from'./chunk-MIWDCR6I.js';import {f as f$1,e,d as d$4,i as i$2,a as a$8,g as g$4}from'./chunk-FMBSON6H.js';import {b as b$1,n,o,l as l$2,c as c$5,i as i$3,h as h$3,p as p$2,e as e$5,g as g$3}from'./chunk-WRMCPKGA.js';import {c as c$8}from'./chunk-2FIX2MDC.js';import {c as c$3,b as b$a}from'./chunk-HHJAANUC.js';import {Command,Option}from'commander';import s from'chalk';import w from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import*as R from'fs-extra';import R__default from'fs-extra';import b$4,{promises,createWriteStream}from'fs';import Zn,{tmpdir}from'os';import {execa}from'execa';import ar,{createVerify,createHash,createHmac}from'crypto';import di from'http';import pi from'https';function ta(){return i$3()}function oa(t,e){return t==="py"?["-3",...e]:e}function ra(t){return typeof t=="object"&&t!==null}async function na(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 sa(t,e){let o=["-m","rapidkit",...t],r=ta();for(let n of r){let i=await na(n,oa(n,o),e?.cwd,e?.timeoutMs);if(!i.ok)continue;let a=(i.stdout??"").trim();try{let c=JSON.parse(a);return ra(c)?{ok:true,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,data:c}:{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 qn(t,e){let o=await sa(["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 zn=new Set(["create"]),zo=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),ia=new Set(["pip","poetry","venv","pipx","python"]);function Yn(t){return typeof t=="string"&&ia.has(t)}function Yo(t,e){return !t||zn.has(t)?false:a$8.has(t)?true:e?.has(t)??false}function Qo(t,e=null){let o=t[0];return !o||o.startsWith("-")||zn.has(o)||o==="init"?false:Yo(o,e)?true:t.filter(n=>!n.startsWith("-")&&!zo.has(n)).length<=1?false:t.length>1}var mt=w.join(Zn.homedir(),".rapidkitrc.json"),aa=w.join(Zn.homedir(),".rapidkit","config.json");function Qn(t){try{if(!b$4.existsSync(t))return {};let e=b$4.readFileSync(t,"utf-8"),o=JSON.parse(e);return !o||typeof o!="object"||Array.isArray(o)?{}:o}catch{return {}}}function es(t){if(process.platform!=="win32")try{b$4.chmodSync(t,384);}catch{}}function ft(){let t=Qn(mt),e=Qn(aa);return b$4.existsSync(mt)&&es(mt),{...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled,telemetry:t.telemetry??e.telemetry}}function io(t){let o={...ft(),...t};b$4.writeFileSync(mt,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),es(mt);}function Mt(){return process.env.OPENAI_API_KEY||ft().openaiApiKey||null}function Xo(){return ft().aiEnabled!==false}function Zo(){return mt}function ts(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$b}from'./chunk-ICGWHIMK.js';import {b as b$5,a as a$5}from'./chunk-ITJ6RKUW.js';import {a as a$6}from'./chunk-KMUWWZRT.js';import {b as b$6,d as d$2,a as a$3,c as c$1,f as f$4,e as e$4}from'./chunk-PCXSTKZ5.js';import {b as b$b,a as a$d,l as l$3}from'./chunk-JNXT6KJV.js';import {a as a$f}from'./chunk-33LR2QEM.js';import {c as c$6,a as a$g}from'./chunk-HYAT2EG7.js';import {e as e$3}from'./chunk-DWXRVGOY.js';import {a as a$e}from'./chunk-VMJA36WD.js';import {g,b as b$2,c,d,m,l,h as h$1,k,a as a$7,j as j$1,f as f$5,i as i$5}from'./chunk-JU3VNLTY.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$c}from'./chunk-AQ4XZZC6.js';import {c as c$4,d as d$5,e as e$2,f as f$3,g as g$2,a as a$h}from'./chunk-EN6YCX36.js';import {j,a as a$4,b as b$7,c as c$2,d as d$3,e as e$1,f as f$2,q as q$1,s as s$2,h as h$2,m as m$1,i,r,t as t$1,g as g$1,p as p$1,k as k$2,o as o$2}from'./chunk-YBS2HGO3.js';export{i as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-YBS2HGO3.js';import {i as i$1}from'./chunk-UZW5QFRW.js';import {f as f$6}from'./chunk-3PTJID76.js';import {h,a as a$2,q,s as s$1,p,t,m as m$2,l as l$1,n as n$1,k as k$1,o as o$1,i as i$4}from'./chunk-E5ZVQL3C.js';import {b as b$9,d as d$6}from'./chunk-RV6HBTFC.js';import {a as a$a}from'./chunk-VKLL63TL.js';import {b,a}from'./chunk-Q2KZIBV4.js';import {f,d as d$1,b as b$8}from'./chunk-OLDPVVSV.js';import {c as c$7}from'./chunk-MIWDCR6I.js';import {f as f$1,e,d as d$4,i as i$2,a as a$8,g as g$4}from'./chunk-FMBSON6H.js';import {b as b$1,n,o,l as l$2,c as c$5,i as i$3,h as h$3,p as p$2,e as e$5,g as g$3}from'./chunk-WRMCPKGA.js';import {c as c$8}from'./chunk-2FIX2MDC.js';import {c as c$3,b as b$a}from'./chunk-HHJAANUC.js';import {Command,Option}from'commander';import s from'chalk';import w from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import*as R from'fs-extra';import R__default from'fs-extra';import b$4,{promises,createWriteStream}from'fs';import Zn,{tmpdir}from'os';import {execa}from'execa';import ar,{createVerify,createHash,createHmac}from'crypto';import di from'http';import pi from'https';function ta(){return i$3()}function oa(t,e){return t==="py"?["-3",...e]:e}function ra(t){return typeof t=="object"&&t!==null}async function na(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 sa(t,e){let o=["-m","rapidkit",...t],r=ta();for(let n of r){let i=await na(n,oa(n,o),e?.cwd,e?.timeoutMs);if(!i.ok)continue;let a=(i.stdout??"").trim();try{let c=JSON.parse(a);return ra(c)?{ok:true,command:n,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,data:c}:{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 qn(t,e){let o=await sa(["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 zn=new Set(["create"]),zo=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),ia=new Set(["pip","poetry","venv","pipx","python"]);function Yn(t){return typeof t=="string"&&ia.has(t)}function Yo(t,e){return !t||zn.has(t)?false:a$8.has(t)?true:e?.has(t)??false}function Qo(t,e=null){let o=t[0];return !o||o.startsWith("-")||zn.has(o)||o==="init"?false:Yo(o,e)?true:t.filter(n=>!n.startsWith("-")&&!zo.has(n)).length<=1?false:t.length>1}var mt=w.join(Zn.homedir(),".rapidkitrc.json"),aa=w.join(Zn.homedir(),".rapidkit","config.json");function Qn(t){try{if(!b$4.existsSync(t))return {};let e=b$4.readFileSync(t,"utf-8"),o=JSON.parse(e);return !o||typeof o!="object"||Array.isArray(o)?{}:o}catch{return {}}}function es(t){if(process.platform!=="win32")try{b$4.chmodSync(t,384);}catch{}}function ft(){let t=Qn(mt),e=Qn(aa);return b$4.existsSync(mt)&&es(mt),{...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled,telemetry:t.telemetry??e.telemetry}}function io(t){let o={...ft(),...t};b$4.writeFileSync(mt,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),es(mt);}function Mt(){return process.env.OPENAI_API_KEY||ft().openaiApiKey||null}function Xo(){return ft().aiEnabled!==false}function Zo(){return mt}function ts(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,io({openaiApiKey:r}),console.log(s.green(`
5
5
  \u2705 OpenAI API key saved successfully!
@@ -146,7 +146,7 @@ RapidKit infra status
146
146
  \u274C ${r instanceof Error?r.message:String(r)}
147
147
  `)),process.exit(1);}});}function hc(t){try{let e=w.join(t,"Makefile");return b$4.existsSync(e)?b$4.readFileSync(e,"utf8"):""}catch{return ""}}function Ge(t,e){let o=hc(t);return o?new RegExp(`^${e}\\s*:`,"m").test(o):false}var Po=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureDotnetInstalled(e){return (await this.run("dotnet",["--version"],e)).exitCode===0?null:{exitCode:1,message:".NET SDK is not installed or not available on PATH. Install .NET 8+ from https://dotnet.microsoft.com/download and retry."}}findFilesBySuffix(e,o,r=3){let n=[],i=[{dir:e,depth:0}],a=new Set(["bin","obj",".git","node_modules",".rapidkit"]);for(;i.length>0;){let c=i.shift();if(!c||c.depth>r)continue;let l=[];try{l=b$4.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let g of l){let m=w.join(c.dir,g.name);if(g.isDirectory()){a.has(g.name)||i.push({dir:m,depth:c.depth+1});continue}g.name.toLowerCase().endsWith(o.toLowerCase())&&n.push(m);}}return n.sort()}findProjectFile(e){let o=this.findFilesBySuffix(e,".csproj");return o.find(r=>!r.toLowerCase().includes(".tests.csproj"))||o[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(r=>r.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let o=await this.ensureDotnetInstalled(e);return o||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=await this.run("dotnet",r?["restore",r]:["restore"],e);return n.exitCode===0?n:{exitCode:n.exitCode,message:"dotnet restore failed. Check NuGet connectivity, package references, and .NET SDK workload availability, then retry."}}async runDev(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e),n=r?["watch","--project",r,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",r?["test",r]:["test"],e)}async runBuild(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["build",r,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let o=await this.ensureDotnetInstalled(e);if(o)return o;let r=this.findProjectFile(e);return this.run("dotnet",r?["run","--project",r]:["run"],e)}async runLint(e){if(Ge(e,"lint"))return this.run("make",["lint"],e);let o=w.join(e,"Directory.Build.props");if(b$4.existsSync(o)&&b$4.readFileSync(o,"utf-8").includes("EnforceCodeStyleInBuild")){let r=await this.ensureDotnetInstalled(e);if(r)return r;let n=this.findProjectFile(e);return this.run("dotnet",n?["build",n,"-warnaserror"]:["build","-warnaserror"],e)}return {exitCode:1,message:"No .NET lint tooling detected. Add a Makefile lint target or enable EnforceCodeStyleInBuild in Directory.Build.props."}}async runFormat(e){if(Ge(e,"format"))return this.run("make",["format"],e);let o=await this.ensureDotnetInstalled(e);return o||(b$4.existsSync(w.join(e,".editorconfig"))?this.run("dotnet",["format","--verify-no-changes"],e):{exitCode:1,message:"No .NET format tooling detected. Add a Makefile format target or an .editorconfig file for dotnet format."})}async doctorHints(e){return ["Install .NET 8+ SDK and ensure dotnet is on PATH.","Run dotnet restore after changing package references.","Use dotnet format --verify-no-changes in CI for deterministic code style."]}};var bo=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}async ensureGoInstalled(e){return (await this.run("go",["version"],e)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findGoRunTarget(e){let o=w.join(e,"main.go");if(b$4.existsSync(o))return "./main.go";let r=w.join(e,"cmd");try{let n=b$4.readdirSync(r,{withFileTypes:true}).filter(i=>i.isDirectory()).map(i=>i.name).sort();for(let i of n)if(b$4.existsSync(w.join(r,i,"main.go")))return `./cmd/${i}`}catch{}return "./."}findWorkspaceRoot(e){let o=e;for(;;){if(b$4.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$4.existsSync(n))return "isolated";try{let c=b$4.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withGoCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","go"):w.join(e,".rapidkit","cache","go"),a=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=w.join(i,"mod"),process.env.GOCACHE=w.join(i,"build"),o().finally(()=>{typeof a>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=a,typeof c>"u"?delete process.env.GOCACHE:process.env.GOCACHE=c;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(e){return this.withGoCacheEnv(e,async()=>{try{return process.env.GOMODCACHE&&b$4.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&b$4.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let o=await this.ensureGoInstalled(e);if(o)return o;let r=w.join(e,"Makefile");return b$4.existsSync(r)?this.run("make",["run"],e):this.run("go",["run",this.findGoRunTarget(e)],e)})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let r=(b$1()?[w.join(e,"server.exe"),w.join(e,"server")]:[w.join(e,"server")]).find(i=>b$4.existsSync(i));if(r)return this.run(r,[],e);let n=await this.ensureGoInstalled(e);return n||this.run("go",["run",this.findGoRunTarget(e)],e)})}async runLint(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(Ge(e,"lint")?this.run("make",["lint"],e):b$4.existsSync(w.join(e,".golangci.yml"))||b$4.existsSync(w.join(e,".golangci.yaml"))?this.run("golangci-lint",["run","./..."],e):{exitCode:1,message:"No Go lint tooling detected. Add a Makefile lint target or .golangci.yml configuration."})})}async runFormat(e){return this.withGoCacheEnv(e,async()=>{let o=await this.ensureGoInstalled(e);return o||(Ge(e,"fmt")?this.run("make",["fmt"],e):Ge(e,"format")?this.run("make",["format"],e):this.run("go",["fmt","./..."],e))})}async doctorHints(e){return ["Install Go from https://go.dev/dl/ if missing.","Run go mod tidy when dependencies are out of sync.","Use make run for hot-reload if Makefile exists."]}};var jo=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return (b$4.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return b$4.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let o=process.env.JAVA_HOME?.trim();if(!o)return "java";let r=w.join(o,"bin",process.platform==="win32"?"java.exe":"java");return b$4.existsSync(r)?r:"java"}parseMajorJavaVersion(e){if(!e)return null;let r=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(r,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let o=w.join(e,"pom.xml");if(!b$4.existsSync(o))return 21;try{let n=b$4.readFileSync(o,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,o){try{let r=await execa(e,["-version"],{cwd:o,timeout:5e3,reject:false});if(r.exitCode!==0)return null;let n=`${r.stdout||""}
148
148
  ${r.stderr||""}`,i=n.match(/version\s+"([^"]+)"/i);if(i?.[1])return this.parseMajorJavaVersion(i[1]);let a=n.match(/(?:openjdk|java)\s+(\d+(?:[._]\d+)?)/i);return a?.[1]?this.parseMajorJavaVersion(a[1]):null}catch{return null}}parseMavenVersion(e){if(!e)return null;let o=e.match(/Apache Maven\s+(\d+)\.(\d+)\.(\d+)/i);return o?[Number.parseInt(o[1],10),Number.parseInt(o[2],10),Number.parseInt(o[3],10)]:null}isMavenVersionAtLeast(e,o){for(let r=0;r<3;r+=1){if(e[r]>o[r])return true;if(e[r]<o[r])return false}return true}async checkSystemMavenVersion(e){try{let o=await execa("mvn",["-version"],{cwd:e,timeout:5e3,reject:false});if(o.exitCode!==0)return {exitCode:o.exitCode||1,message:"Maven is required and must be available on PATH (3.9+)."};let r=this.parseMavenVersion(`${o.stdout||""}
149
- ${o.stderr||""}`);return r?this.isMavenVersionAtLeast(r,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${r.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let o=b$4.existsSync(w.join(e,"pom.xml")),r=b$4.existsSync(w.join(e,"mvnw"))||b$4.existsSync(w.join(e,"mvnw.cmd")),n=b$4.existsSync(w.join(e,"build.gradle"))||b$4.existsSync(w.join(e,"build.gradle.kts"))||b$4.existsSync(w.join(e,"settings.gradle"))||b$4.existsSync(w.join(e,"settings.gradle.kts")),i=b$4.existsSync(w.join(e,"gradlew"))||b$4.existsSync(w.join(e,"gradlew.bat"));return {hasMavenProject:o||r,hasMavenWrapper:r,hasGradleProject:n||i,hasGradleWrapper:i}}findWorkspaceRoot(e){let o=e;for(;;){if(b$4.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$4.existsSync(n))return "isolated";try{let c=b$4.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let o=w.join(e,"mvnw.cmd");if(process.platform==="win32"&&b$4.existsSync(o))return {command:o,baseArgs:[]};let r=w.join(e,"mvnw");return b$4.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let o=w.join(e,"gradlew.bat");if(process.platform==="win32"&&b$4.existsSync(o))return {command:o,baseArgs:[]};let r=w.join(e,"gradlew");return b$4.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let o=[],r=new Set,n=[e];for(;n.length>0;){let i=n.shift();if(!i||r.has(i))continue;r.add(i);let a=[];try{a=b$4.readdirSync(i,{withFileTypes:true});}catch{continue}for(let c of a){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let l=w.join(i,c.name),g=this.inspectJavaProject(l);(g.hasMavenProject||g.hasGradleProject)&&o.push(l),n.push(l);}}return o}withJavaCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","java","m2"):w.join(e,".rapidkit","cache","java","m2"),a=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","java","gradle"):w.join(e,".rapidkit","cache","java","gradle"),c=process.env.MAVEN_OPTS,l=process.env.GRADLE_USER_HOME,g=`-Dmaven.repo.local=${i}`;return process.env.MAVEN_OPTS=c?`${c} ${g}`:g,process.env.GRADLE_USER_HOME=a,o().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof l>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=l;})}async runBuildTool(e,o,r=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:i}=this.buildToolCommand(e),a=await this.runCommand(n,[...i,...o],e);if(a===0||!r)return {exitCode:a};let c=b$4.existsSync(w.join(e,"pom.xml")),l=b$4.existsSync(w.join(e,"build.gradle"))||b$4.existsSync(w.join(e,"build.gradle.kts"));return {exitCode:a,message:c||l?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let o=[w.join(e,"target"),w.join(e,"build","libs")];for(let r of o){if(!b$4.existsSync(r))continue;let i=b$4.readdirSync(r).filter(a=>a.toLowerCase().endsWith(".jar")).find(a=>!a.toLowerCase().endsWith("-sources.jar")&&!a.toLowerCase().endsWith("-javadoc.jar")&&!a.toLowerCase().endsWith("-plain.jar"));if(i)return w.join(r,i)}return null}commandArgsFor(e,o){if(e==="gradle"){let r=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return o==="init"?[...r,"dependencies"]:o==="dev"?[...r,"bootRun"]:o==="test"?[...r,"test"]:[...r,"bootJar"]}return o==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:o==="dev"?["spring-boot:run"]:o==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),o=this.resolveJavaCommand(e),r=await this.runCommand(o,["-version"],e);if(r!==0)return {exitCode:r,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),l=await this.detectInstalledJavaMajor(o,e);if(l!==null&&l<c)return {exitCode:1,message:`Detected Java ${l}, but project requires Java ${c}+.`};let g=w.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&b$4.existsSync(g))try{let p=b$4.readFileSync(g,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),d=this.parseMajorJavaVersion(p?.[1]);if(d!==null&&d<c)return {exitCode:1,message:`Detected JAVA_HOME version ${d}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),l=c==="gradle"?["--version"]:["-version"],g=await this.runBuildTool(e,l);return g.exitCode!==0?g:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):g}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let l=c.reduce((p,d)=>Math.max(p,this.readRequiredJavaMajor(d)),0);if(l>0){let p=await this.detectInstalledJavaMajor(o,e);if(p!==null&&p<l){let d=c.filter(f=>this.readRequiredJavaMajor(f)>p).map(f=>w.relative(e,f)).join(", ");return {exitCode:1,message:`Detected Java ${p}, but workspace project(s) [${d}] require Java ${l}+.`}}}let g=false,m=false;for(let p of c){let d=this.inspectJavaProject(p);d.hasMavenProject&&!d.hasMavenWrapper&&(g=true),d.hasGradleProject&&!d.hasGradleWrapper&&(m=true);}if(g){let p=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(p!==0)return {exitCode:p,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let d=await this.checkSystemMavenVersion(e);if(d.exitCode!==0)return d}if(m){let p=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(p!==0)return {exitCode:p,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(i===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return a===0?{exitCode:0}:{exitCode:i||a||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let o=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return o&&b$4.mkdirSync(o,{recursive:true}),process.env.GRADLE_USER_HOME&&b$4.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let o=this.resolveJarPath(e);if(o)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",o],e)};let r=await this.runBuild(e);if(r.exitCode!==0)return r;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(Ge(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let o=w.join(e,"pom.xml");return b$4.existsSync(o)&&b$4.readFileSync(o,"utf-8").includes("checkstyle")?this.runBuildTool(e,["checkstyle:check"]):{exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){return Ge(e,"format")?{exitCode:await this.runCommand("make",["format"],e)}:["build.gradle","build.gradle.kts"].map(r=>w.join(e,r)).filter(r=>b$4.existsSync(r)).some(r=>b$4.readFileSync(r,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure spotless in Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run rapidkit init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var xo=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}findWorkspaceRoot(e){let o=e;for(;;){if(b$4.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$4.existsSync(n))return "isolated";try{let c=b$4.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,o,r){let n=this.resolveDependencyMode(e),i=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=n==="isolated"?w.join(e,".rapidkit","cache","node"):w.join(i||e,".rapidkit","cache","node"),c=process.env.npm_config_cache,l=process.env.npm_config_store_dir,g=process.env.RAPIDKIT_DEP_SHARING_MODE,m=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,i&&(process.env.RAPIDKIT_WORKSPACE_PATH=i),o==="pnpm"?(process.env.npm_config_store_dir=w.join(a,"pnpm-store"),process.env.npm_config_cache=w.join(a,"pnpm-cache")):o==="yarn"?process.env.npm_config_cache=w.join(a,"yarn-cache"):process.env.npm_config_cache=w.join(a,"npm-cache"),r().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof l>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=l,typeof g>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=g,typeof m>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=m;})}detectPackageManager(e){if(b$4.existsSync(w.join(e,"package-lock.json")))return "npm";if(b$4.existsSync(w.join(e,"pnpm-lock.yaml")))return "pnpm";if(b$4.existsSync(w.join(e,"yarn.lock")))return "yarn";if(!this.commandAvailable("npm")){if(this.commandAvailable("pnpm"))return "pnpm";if(this.commandAvailable("yarn"))return "yarn"}return "npm"}hasPinnedPackageManager(e){return b$4.existsSync(w.join(e,"package-lock.json"))||b$4.existsSync(w.join(e,"pnpm-lock.yaml"))||b$4.existsSync(w.join(e,"yarn.lock"))}availablePackageManagers(e){let o=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[o]:[o,...["npm","pnpm","yarn"].filter(n=>n!==o&&this.commandAvailable(n))]}commandAvailable(e){let o=e$5(e);return spawnSync(o.command,[...o.prefixArgs,"--version"],{stdio:"ignore",shell:c$5(),env:g$3()}).status===0}scriptArgs(e,o){return e==="npm"?["run",o]:["run",o]}async runScriptWithFallback(e,o){let r={exitCode:1};for(let n of this.availablePackageManagers(e))if(r=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,o),e)),r.exitCode===0)return r;return r}async runLifecycle(e,o){let r=a$4(e),n=i$1(e,r),i=g$1(e,o,{framework:n.key});return i?this.runScriptWithFallback(e,i.scriptName):{exitCode:1,message:`No npm script available for \`${o}\`. Add a "${o}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let o=this.detectPackageManager(e);return this.withDependencyEnv(e,o,async()=>{try{return process.env.npm_config_cache&&b$4.mkdirSync(process.env.npm_config_cache,{recursive:true}),o==="pnpm"&&process.env.npm_config_store_dir&&b$4.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let o=this.detectPackageManager(e),r=this.resolveDependencyMode(e),n=r==="shared-runtime-caches"||r==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,o,()=>this.run(o,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var So=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,o){return {exitCode:await this.withPythonCacheEnv(o,()=>this.runCore(e,o))}}findWorkspaceRoot(e){let o=e;for(;;){if(b$4.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$4.existsSync(n))return "isolated";try{let c=b$4.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","python"):w.join(e,".rapidkit","cache","python"),a=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=w.join(i,"pip"),process.env.POETRY_CACHE_DIR=w.join(i,"poetry"),o().finally(()=>{typeof a>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=a,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),o=await this.run(["doctor","check"],e);return o.exitCode===0?o:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx rapidkit doctor workspace" for a full workspace scan.','Use "npx rapidkit init" after adding or changing modules.','Use workspace launcher "./rapidkit" to avoid environment drift.']}};function wc(){let t={...process.env},e=t.PATH||"";if(e){let o=e.split(w.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(w.delimiter);t.PATH=o;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||h$3(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ve(t,e){return t==="go"?new bo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="node"?new xo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="java"?new jo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="dotnet"?new Po((o,r,n)=>e.runCommandInCwd(o,r,n)):new So((o,r)=>e.runCoreRapidkit(o,{cwd:r,env:wc()}))}var oi=w.join(Zn.homedir(),".rapidkit","cache"),ri=1440*60*1e3;function Er(){let t=process.env.RAPIDKIT_CACHE_DIR?.trim();if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?w.join(oi,`vitest-${e}`):oi}var Ro=class t{static instance;memoryCache=new Map;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getCacheKey(e){return createHash("md5").update(e).digest("hex")}getCachePath(e){return w.join(Er(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let o=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${o}.tmp`}async get(e,o="1.0"){let r=this.memoryCache.get(e);if(r&&r.version===o&&Date.now()-r.timestamp<ri)return f.debug(`Cache hit (memory): ${e}`),r.data;try{let n=this.getCachePath(e),i=await promises.readFile(n,"utf-8"),a=JSON.parse(i);if(a.version===o&&Date.now()-a.timestamp<ri)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,a),a.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,o,r="1.0"){let n={data:o,timestamp:Date.now(),version:r};this.memoryCache.set(e,n);try{await promises.mkdir(Er(),{recursive:true});let i=this.getCachePath(e),a=this.getTempCachePath(i);await promises.writeFile(a,JSON.stringify(n),"utf-8"),await promises.rename(a,i),f.debug(`Cache set: ${e}`);}catch(i){f.debug(`Cache write failed: ${e}`,i);}}async invalidate(e){this.memoryCache.delete(e);try{let o=this.getCachePath(e);await promises.unlink(o),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=Er(),o=await promises.readdir(e);await Promise.all(o.map(r=>promises.unlink(w.join(e,r)))),f.debug("Cache cleared");}catch{}}};var Eo=["list","sync","registry","foundation","model","snapshot","diff","impact","verify","graph","watch","context","agent-sync","explain","why","trace","feedback","mcp","policy","contract","share","export","archive","hydrate","import","run","init"],_o=["model","snapshot","diff","impact","verify","context","agent-sync","explain"];function ni(t){return _o.includes(t)}var si="rapidkit-runtime-command-surface-v1";function Ao(){return {runtimeCommandSurface:si,cliLogEvent:c$7,freshnessMetadata:a$h,blockerResolution:a$g,workspaceModel:g$2,workspaceImpact:e$3,workspaceVerify:c$6,workspaceContext:a$f,workspaceDependencyGraph:f$3,workspaceIntelligenceHistory:a$e,agentCustomizationPack:l$3,workspaceOperationalSkill:a$d,workspaceSkillsIndex:b$b,workspaceExplain:a$c,agentActionOutcome:a$b}}var bc=["catalog","pulse","nova","orbit","atlas","vertex","summit","beacon","ledger","flux","nexus","apex","harbor","forge","spark","portal","studio","canvas","quantum","vault","zenith","compass","vector","catalyst","saas","commerce","radar","stellar","prism","cedar","momentum","signal","cipher","lumen","trail","ridge"],jc={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},xc={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"};function Sc(t){return t[Math.floor(Math.random()*t.length)]}function _r(t){let e=Sc(bc),o=k$1(t);if(o){let i=xc[o.id]??"app";return `${e}-${i}`}let r=p(t),n=r?jc[r.id]??"service":"app";return `${e}-${n}`}async function _c(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function ii(t,e){await R.outputFile(t,`${JSON.stringify(e,null,2)}
149
+ ${o.stderr||""}`);return r?this.isMavenVersionAtLeast(r,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${r.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let o=b$4.existsSync(w.join(e,"pom.xml")),r=b$4.existsSync(w.join(e,"mvnw"))||b$4.existsSync(w.join(e,"mvnw.cmd")),n=b$4.existsSync(w.join(e,"build.gradle"))||b$4.existsSync(w.join(e,"build.gradle.kts"))||b$4.existsSync(w.join(e,"settings.gradle"))||b$4.existsSync(w.join(e,"settings.gradle.kts")),i=b$4.existsSync(w.join(e,"gradlew"))||b$4.existsSync(w.join(e,"gradlew.bat"));return {hasMavenProject:o||r,hasMavenWrapper:r,hasGradleProject:n||i,hasGradleWrapper:i}}findWorkspaceRoot(e){let o=e;for(;;){if(b$4.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$4.existsSync(n))return "isolated";try{let c=b$4.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let o=w.join(e,"mvnw.cmd");if(process.platform==="win32"&&b$4.existsSync(o))return {command:o,baseArgs:[]};let r=w.join(e,"mvnw");return b$4.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let o=w.join(e,"gradlew.bat");if(process.platform==="win32"&&b$4.existsSync(o))return {command:o,baseArgs:[]};let r=w.join(e,"gradlew");return b$4.existsSync(r)?this.ensureWrapperExecutable(r)?{command:r,baseArgs:[]}:{command:"sh",baseArgs:[r]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let o=[],r=new Set,n=[e];for(;n.length>0;){let i=n.shift();if(!i||r.has(i))continue;r.add(i);let a=[];try{a=b$4.readdirSync(i,{withFileTypes:true});}catch{continue}for(let c of a){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let l=w.join(i,c.name),g=this.inspectJavaProject(l);(g.hasMavenProject||g.hasGradleProject)&&o.push(l),n.push(l);}}return o}withJavaCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","java","m2"):w.join(e,".rapidkit","cache","java","m2"),a=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","java","gradle"):w.join(e,".rapidkit","cache","java","gradle"),c=process.env.MAVEN_OPTS,l=process.env.GRADLE_USER_HOME,g=`-Dmaven.repo.local=${i}`;return process.env.MAVEN_OPTS=c?`${c} ${g}`:g,process.env.GRADLE_USER_HOME=a,o().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof l>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=l;})}async runBuildTool(e,o,r=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:i}=this.buildToolCommand(e),a=await this.runCommand(n,[...i,...o],e);if(a===0||!r)return {exitCode:a};let c=b$4.existsSync(w.join(e,"pom.xml")),l=b$4.existsSync(w.join(e,"build.gradle"))||b$4.existsSync(w.join(e,"build.gradle.kts"));return {exitCode:a,message:c||l?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let o=[w.join(e,"target"),w.join(e,"build","libs")];for(let r of o){if(!b$4.existsSync(r))continue;let i=b$4.readdirSync(r).filter(a=>a.toLowerCase().endsWith(".jar")).find(a=>!a.toLowerCase().endsWith("-sources.jar")&&!a.toLowerCase().endsWith("-javadoc.jar")&&!a.toLowerCase().endsWith("-plain.jar"));if(i)return w.join(r,i)}return null}commandArgsFor(e,o){if(e==="gradle"){let r=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return o==="init"?[...r,"dependencies"]:o==="dev"?[...r,"bootRun"]:o==="test"?[...r,"test"]:[...r,"bootJar"]}return o==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:o==="dev"?["spring-boot:run"]:o==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),o=this.resolveJavaCommand(e),r=await this.runCommand(o,["-version"],e);if(r!==0)return {exitCode:r,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),l=await this.detectInstalledJavaMajor(o,e);if(l!==null&&l<c)return {exitCode:1,message:`Detected Java ${l}, but project requires Java ${c}+.`};let g=w.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&b$4.existsSync(g))try{let p=b$4.readFileSync(g,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),d=this.parseMajorJavaVersion(p?.[1]);if(d!==null&&d<c)return {exitCode:1,message:`Detected JAVA_HOME version ${d}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),l=c==="gradle"?["--version"]:["-version"],g=await this.runBuildTool(e,l);return g.exitCode!==0?g:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):g}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let l=c.reduce((p,d)=>Math.max(p,this.readRequiredJavaMajor(d)),0);if(l>0){let p=await this.detectInstalledJavaMajor(o,e);if(p!==null&&p<l){let d=c.filter(f=>this.readRequiredJavaMajor(f)>p).map(f=>w.relative(e,f)).join(", ");return {exitCode:1,message:`Detected Java ${p}, but workspace project(s) [${d}] require Java ${l}+.`}}}let g=false,m=false;for(let p of c){let d=this.inspectJavaProject(p);d.hasMavenProject&&!d.hasMavenWrapper&&(g=true),d.hasGradleProject&&!d.hasGradleWrapper&&(m=true);}if(g){let p=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(p!==0)return {exitCode:p,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let d=await this.checkSystemMavenVersion(e);if(d.exitCode!==0)return d}if(m){let p=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(p!==0)return {exitCode:p,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(i===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return a===0?{exitCode:0}:{exitCode:i||a||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let o=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return o&&b$4.mkdirSync(o,{recursive:true}),process.env.GRADLE_USER_HOME&&b$4.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let o=this.resolveJarPath(e);if(o)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",o],e)};let r=await this.runBuild(e);if(r.exitCode!==0)return r;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(Ge(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let o=w.join(e,"pom.xml");return b$4.existsSync(o)&&b$4.readFileSync(o,"utf-8").includes("checkstyle")?this.runBuildTool(e,["checkstyle:check"]):{exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){return Ge(e,"format")?{exitCode:await this.runCommand("make",["format"],e)}:["build.gradle","build.gradle.kts"].map(r=>w.join(e,r)).filter(r=>b$4.existsSync(r)).some(r=>b$4.readFileSync(r,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure spotless in Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run rapidkit init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var xo=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,o,r){return {exitCode:await this.runCommand(e,o,r)}}findWorkspaceRoot(e){let o=e;for(;;){if(b$4.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$4.existsSync(n))return "isolated";try{let c=b$4.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,o,r){let n=this.resolveDependencyMode(e),i=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=n==="isolated"?w.join(e,".rapidkit","cache","node"):w.join(i||e,".rapidkit","cache","node"),c=process.env.npm_config_cache,l=process.env.npm_config_store_dir,g=process.env.RAPIDKIT_DEP_SHARING_MODE,m=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,i&&(process.env.RAPIDKIT_WORKSPACE_PATH=i),o==="pnpm"?(process.env.npm_config_store_dir=w.join(a,"pnpm-store"),process.env.npm_config_cache=w.join(a,"pnpm-cache")):o==="yarn"?process.env.npm_config_cache=w.join(a,"yarn-cache"):process.env.npm_config_cache=w.join(a,"npm-cache"),r().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof l>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=l,typeof g>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=g,typeof m>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=m;})}detectPackageManager(e){if(b$4.existsSync(w.join(e,"package-lock.json")))return "npm";if(b$4.existsSync(w.join(e,"pnpm-lock.yaml")))return "pnpm";if(b$4.existsSync(w.join(e,"yarn.lock")))return "yarn";if(!this.commandAvailable("npm")){if(this.commandAvailable("pnpm"))return "pnpm";if(this.commandAvailable("yarn"))return "yarn"}return "npm"}hasPinnedPackageManager(e){return b$4.existsSync(w.join(e,"package-lock.json"))||b$4.existsSync(w.join(e,"pnpm-lock.yaml"))||b$4.existsSync(w.join(e,"yarn.lock"))}availablePackageManagers(e){let o=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[o]:[o,...["npm","pnpm","yarn"].filter(n=>n!==o&&this.commandAvailable(n))]}commandAvailable(e){let o=e$5(e);return spawnSync(o.command,[...o.prefixArgs,"--version"],{stdio:"ignore",shell:c$5(),env:g$3()}).status===0}scriptArgs(e,o){return e==="npm"?["run",o]:["run",o]}async runScriptWithFallback(e,o){let r={exitCode:1};for(let n of this.availablePackageManagers(e))if(r=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,o),e)),r.exitCode===0)return r;return r}async runLifecycle(e,o){let r=a$4(e),n=i$1(e,r),i=g$1(e,o,{framework:n.key});return i?this.runScriptWithFallback(e,i.scriptName):{exitCode:1,message:`No npm script available for \`${o}\`. Add a "${o}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let o=this.detectPackageManager(e);return this.withDependencyEnv(e,o,async()=>{try{return process.env.npm_config_cache&&b$4.mkdirSync(process.env.npm_config_cache,{recursive:true}),o==="pnpm"&&process.env.npm_config_store_dir&&b$4.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let o=this.detectPackageManager(e),r=this.resolveDependencyMode(e),n=r==="shared-runtime-caches"||r==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,o,()=>this.run(o,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var So=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,o){return {exitCode:await this.withPythonCacheEnv(o,()=>this.runCore(e,o))}}findWorkspaceRoot(e){let o=e;for(;;){if(b$4.existsSync(w.join(o,".rapidkit-workspace")))return o;let r=w.dirname(o);if(r===o)break;o=r;}return null}resolveDependencyMode(e){let o=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(o==="shared-runtime-caches"||o==="shared-node-deps"||o==="isolated")return o;let r=this.findWorkspaceRoot(e);if(!r)return "isolated";let n=w.join(r,".rapidkit","policies.yml");if(!b$4.existsSync(n))return "isolated";try{let c=b$4.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,o){let r=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=r==="shared-runtime-caches"?w.join(n||e,".rapidkit","cache","python"):w.join(e,".rapidkit","cache","python"),a=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=w.join(i,"pip"),process.env.POETRY_CACHE_DIR=w.join(i,"poetry"),o().finally(()=>{typeof a>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=a,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),o=await this.run(["doctor","check"],e);return o.exitCode===0?o:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx rapidkit doctor workspace" for a full workspace scan.','Use "npx rapidkit init" after adding or changing modules.','Use workspace launcher "./rapidkit" to avoid environment drift.']}};function wc(){let t={...process.env},e=t.PATH||"";if(e){let o=e.split(w.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(w.delimiter);t.PATH=o;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||h$3(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ve(t,e){return t==="go"?new bo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="node"?new xo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="java"?new jo((o,r,n)=>e.runCommandInCwd(o,r,n)):t==="dotnet"?new Po((o,r,n)=>e.runCommandInCwd(o,r,n)):new So((o,r)=>e.runCoreRapidkit(o,{cwd:r,env:wc()}))}var oi=w.join(Zn.homedir(),".rapidkit","cache"),ri=1440*60*1e3;function Er(){let t=process.env.RAPIDKIT_CACHE_DIR?.trim();if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?w.join(oi,`vitest-${e}`):oi}var Ro=class t{static instance;memoryCache=new Map;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getCacheKey(e){return createHash("md5").update(e).digest("hex")}getCachePath(e){return w.join(Er(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let o=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${o}.tmp`}async get(e,o="1.0"){let r=this.memoryCache.get(e);if(r&&r.version===o&&Date.now()-r.timestamp<ri)return f.debug(`Cache hit (memory): ${e}`),r.data;try{let n=this.getCachePath(e),i=await promises.readFile(n,"utf-8"),a=JSON.parse(i);if(a.version===o&&Date.now()-a.timestamp<ri)return f.debug(`Cache hit (disk): ${e}`),this.memoryCache.set(e,a),a.data;await promises.unlink(n).catch(()=>{});}catch{f.debug(`Cache miss: ${e}`);}return null}async set(e,o,r="1.0"){let n={data:o,timestamp:Date.now(),version:r};this.memoryCache.set(e,n);try{await promises.mkdir(Er(),{recursive:true});let i=this.getCachePath(e),a=this.getTempCachePath(i);await promises.writeFile(a,JSON.stringify(n),"utf-8"),await promises.rename(a,i),f.debug(`Cache set: ${e}`);}catch(i){f.debug(`Cache write failed: ${e}`,i);}}async invalidate(e){this.memoryCache.delete(e);try{let o=this.getCachePath(e);await promises.unlink(o),f.debug(`Cache invalidated: ${e}`);}catch{}}async clear(){this.memoryCache.clear();try{let e=Er(),o=await promises.readdir(e);await Promise.all(o.map(r=>promises.unlink(w.join(e,r)))),f.debug("Cache cleared");}catch{}}};var Eo=["list","sync","registry","foundation","model","snapshot","diff","impact","verify","graph","watch","context","agent-sync","explain","why","trace","feedback","mcp","policy","contract","share","export","archive","hydrate","import","run","init"],_o=["model","snapshot","diff","impact","verify","context","agent-sync","explain","why","trace"];function ni(t){return _o.includes(t)}var si="rapidkit-runtime-command-surface-v1";function Ao(){return {runtimeCommandSurface:si,cliLogEvent:c$7,freshnessMetadata:a$h,blockerResolution:a$g,workspaceModel:g$2,workspaceImpact:e$3,workspaceVerify:c$6,workspaceContext:a$f,workspaceDependencyGraph:f$3,workspaceIntelligenceHistory:a$e,agentCustomizationPack:l$3,workspaceOperationalSkill:a$d,workspaceSkillsIndex:b$b,workspaceExplain:a$c,agentActionOutcome:a$b}}var bc=["catalog","pulse","nova","orbit","atlas","vertex","summit","beacon","ledger","flux","nexus","apex","harbor","forge","spark","portal","studio","canvas","quantum","vault","zenith","compass","vector","catalyst","saas","commerce","radar","stellar","prism","cedar","momentum","signal","cipher","lumen","trail","ridge"],jc={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},xc={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"};function Sc(t){return t[Math.floor(Math.random()*t.length)]}function _r(t){let e=Sc(bc),o=k$1(t);if(o){let i=xc[o.id]??"app";return `${e}-${i}`}let r=p(t),n=r?jc[r.id]??"service":"app";return `${e}-${n}`}async function _c(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function ii(t,e){await R.outputFile(t,`${JSON.stringify(e,null,2)}
150
150
  `,"utf-8");}function Te(t,e){return w.isAbsolute(e)?e:w.join(t,e)}function Ac(t,e){if(t.target)return t.target;if(t.source)return w.basename(t.source);if(t.url)try{let o=new URL(t.url).pathname,r=w.basename(o);if(r&&r!=="/")return r}catch{}return `${e}.artifact`}async function Ic(t){let e=w.join(t,".rapidkit","trusted-sources.lock"),o=new Set(["localhost","127.0.0.1"]);if(!await R.pathExists(e))return o;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0&&!i.startsWith("#"));for(let i of n)o.add(i.toLowerCase());}catch{}return o}async function $c(t,e,o){await R.ensureDir(w.dirname(e)),await new Promise((r,n)=>{let a=(t.startsWith("https://")?pi:di).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let l=createWriteStream(e);c.pipe(l),l.on("finish",()=>{l.close(),r();}),l.on("error",g=>{n(g);});});a.setTimeout(o,()=>{a.destroy(new Error(`Request timeout after ${o}ms`));}),a.on("error",c=>{n(c);});});}async function Mc(t,e,o,r,n){let i=new URL(t),a=JSON.stringify(e),c=i.protocol==="https:"?pi:di;await new Promise((l,g)=>{let m=c.request({method:"POST",hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:`${i.pathname}${i.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(a),...r?{Authorization:`Bearer ${r}`}:{},...n||{}}},p=>{if(!p.statusCode||p.statusCode<200||p.statusCode>=300){g(new Error(`HTTP ${p.statusCode||"unknown"}`)),p.resume();return}p.resume(),l();});m.setTimeout(o,()=>{m.destroy(new Error(`Request timeout after ${o}ms`));}),m.on("error",p=>{g(p);}),m.write(a),m.end();});}function ai(t){return new Promise(e=>setTimeout(e,t))}async function Oc(t,e,o,r){let n=Te(t,e||".rapidkit/reports/evidence-export-dead-letter.ndjson");return await R.ensureDir(w.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:r,payload:o})}
151
151
  `,"utf-8"),n}function Nc(t,e){if(!e?.enabled)return {headers:{}};let o=process.env[e.hmacKeyEnv];if(!o)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let r=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",i=createHmac(r,o).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:i,"x-rapidkit-evidence-signature-alg":r}}}async function Tc(t,e,o){let r=(o.algorithm||"sha256").toLowerCase(),n=Te(t,o.publicKeyPath);if(!await R.pathExists(n))return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Public key not found: ${n}`};try{let i=await promises.readFile(n,"utf-8"),a=await promises.readFile(e),c=createVerify(r);c.update(a),c.end();let l=Buffer.from(o.signature,"base64"),g=c.verify(i,l),m=createHash("sha256").update(i).digest("hex");return {verified:g,algorithm:r,publicKeyPath:n,publicKeyFingerprint:m,signature:o.signature,message:g?"Attestation verified.":"Attestation signature verification failed."}}catch(i){return {verified:false,algorithm:r,publicKeyPath:n,publicKeyFingerprint:"",signature:o.signature,message:`Attestation verification error: ${i.message}`}}}async function Dc(t,e,o,r){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:o.signaturePath||null};let i=o.signaturePath?Te(t,o.signaturePath):null;if(!i||!await R.pathExists(i))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:o.bundlePath||null,certificatePath:o.certificatePath||null,signaturePath:i};let a=["verify-blob",e,"--signature",i],c=o.certificatePath?Te(t,o.certificatePath):null;c&&a.push("--certificate",c);let l=o.bundlePath?Te(t,o.bundlePath):null;l&&a.push("--bundle",l);let g=o.keyPath?Te(t,o.keyPath):null;g&&a.push("--key",g),o.identity&&a.push("--certificate-identity",o.identity),o.issuer&&a.push("--certificate-oidc-issuer",o.issuer),o.rekorUrl&&a.push("--rekor-url",o.rekorUrl),r.requireTransparencyLog||a.push("--insecure-ignore-tlog");try{let m=await execa("cosign",a,{reject:false});return m.exitCode===0?{verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed.",identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:i}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${m.stderr||m.stdout||"unknown error"}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:i}}catch(m){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${m.message}`,identity:o.identity||null,issuer:o.issuer||null,rekorUrl:o.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:i}}}async function Wc(t,e){let o=e.algorithm||"sha256",r=Te(t,e.policyPath),n=Te(t,e.signaturePath),i=Te(t,e.publicKeyPath);if(!await R.pathExists(r))return {verified:false,message:`Governance policy bundle not found: ${r}`,policies:null};if(!await R.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await R.pathExists(i))return {verified:false,message:`Governance policy public key not found: ${i}`,policies:null};try{let a=await promises.readFile(r,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),l=await promises.readFile(i,"utf-8"),g=createVerify(o);return g.update(a),g.end(),g.verify(l,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(a).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(a){return {verified:false,message:`Governance policy bundle verification error: ${a.message}`,policies:null}}}async function Ar(t,e){let o=[],r={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=w.join(t,".rapidkit"),i=w.join(n,"mirror-config.json"),a=w.join(n,"mirror.lock"),c=w.join(n,"mirror","artifacts"),l=w.join(n,"reports"),g=await Ic(t);if(!await R.pathExists(i))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .rapidkit/mirror-config.json not found."}),{checks:o,details:r};let m={};try{m=JSON.parse(await promises.readFile(i,"utf-8"));}catch{return o.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:o,details:r}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||m.mode==="offline-only"))return o.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:o,details:r};await R.ensureDir(c);let d=Math.max(0,m.prefetch?.retries??2),f=Math.max(0,m.prefetch?.backoffMs??250),u=Math.max(1e3,m.prefetch?.timeoutMs??15e3),h=m.security?.requireAttestation===true,k=m.security?.requireSigstore===true,P=m.security?.requireTransparencyLog===true,v=m.security?.requireSignedGovernance===true,y=m.security?.evidenceExport,S=(process.env.RAPIDKIT_ENV||m.security?.governance?.environment||"dev").toLowerCase(),x=m.security?.governance?.policies||{};if(m.security?.governanceBundle){let O=await Wc(t,m.security.governanceBundle);if(o.push({id:"governance.bundle.verify",status:O.verified?"passed":"failed",message:O.message}),O.verified&&O.policies)x=O.policies,r.governanceBundleVerified=true;else if(v)return {checks:o,details:r}}let I=x[S],Y=P||I?.requireTransparencyLog===true,H=[],ce=Array.isArray(m.artifacts)?m.artifacts:[],N=[];for(let O=0;O<ce.length;O+=1){let G=ce[O],C=G.id||`artifact-${O+1}`,ee=G.source?Te(t,G.source):null,Re=Ac(G,C),q=w.join(c,Re),X=false,ke={sourceType:"path",source:ee||G.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(ee&&await R.pathExists(ee))await R.ensureDir(w.dirname(q)),await R.copyFile(ee,q),r.syncedArtifacts+=1,X=true,ke={sourceType:"path",source:ee,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},o.push({id:`mirror.sync.${C}`,status:"passed",message:`Mirrored artifact ${C} from source path.`});else if(G.url){let _e="";try{_e=new URL(G.url).hostname.toLowerCase();}catch{o.push({id:`mirror.prefetch.${C}`,status:"failed",message:`Invalid URL for ${C}: ${G.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||g.has(_e))){o.push({id:`mirror.prefetch.trust.${C}`,status:"failed",message:`Untrusted mirror host for ${C}: ${_e}. Add host to .rapidkit/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await R.pathExists(q)?(X=true,ke={sourceType:"url",source:G.url,host:_e,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},o.push({id:`mirror.prefetch.${C}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${C}.`})):o.push({id:`mirror.prefetch.${C}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${C} without an existing mirrored copy.`}),!X))continue;if(!X){let W=null,$e=0;for(let we=1;we<=d+1;we+=1){$e=we;try{await $c(G.url,q,u),r.syncedArtifacts+=1,X=true,ke={sourceType:"url",source:G.url,host:_e,fetchedAt:new Date().toISOString(),attempts:$e,trusted:true},o.push({id:`mirror.prefetch.${C}`,status:"passed",message:$e>1?`Prefetched artifact ${C} from ${_e} after ${$e} attempts.`:`Prefetched artifact ${C} from ${_e}.`});break}catch(Fe){if(W=Fe,we<=d){await ai(f*we);continue}}}if(!X){o.push({id:`mirror.prefetch.${C}`,status:"failed",message:`Failed to prefetch ${C} after ${d+1} attempt(s): ${W?.message||"unknown error"}`});continue}}if(!X){o.push({id:`mirror.prefetch.${C}`,status:"failed",message:`Failed to prefetch ${C}.`});continue}}if(!X){G.required||e.offlineMode?o.push({id:`mirror.sync.${C}`,status:"failed",message:`Mirror source missing for ${C}${ee?`: ${ee}`:""}`}):o.push({id:`mirror.sync.${C}`,status:"skipped",message:`Mirror source not found for optional artifact ${C}.`});continue}let Ee=await _c(q);if(G.sha256&&G.sha256.toLowerCase()!==Ee.toLowerCase()){o.push({id:`mirror.verify.${C}`,status:"failed",message:`Checksum mismatch for ${C}.`});continue}r.verifiedArtifacts+=1,o.push({id:`mirror.verify.${C}`,status:"passed",message:`Checksum verified for ${C}.`});let Pe=G.attestation?await Tc(t,q,G.attestation):null;if(G.attestation){if(o.push({id:`mirror.attest.${C}`,status:Pe?.verified?"passed":"failed",message:Pe?.message||"Attestation verification failed."}),!Pe?.verified)continue}else if(h){o.push({id:`mirror.attest.${C}`,status:"failed",message:`Attestation is required but missing for ${C}.`});continue}else o.push({id:`mirror.attest.${C}`,status:"skipped",message:`No attestation provided for ${C}.`});let xe=G.attestation?.sigstore,V=xe?await Dc(t,q,xe,{requireTransparencyLog:Y}):null;if(xe){if(o.push({id:`mirror.sigstore.${C}`,status:V?.verified?"passed":"failed",message:V?.message||"Sigstore verification failed."}),H.push({artifactId:C,verified:!!V?.verified,tlogVerified:!!V?.tlogVerified,identity:V?.identity||null,issuer:V?.issuer||null,rekorUrl:V?.rekorUrl||null,timestamp:new Date().toISOString(),environment:S}),!V?.verified)continue}else if(k){o.push({id:`mirror.sigstore.${C}`,status:"failed",message:`Sigstore attestation is required but missing for ${C}.`});continue}else o.push({id:`mirror.sigstore.${C}`,status:"skipped",message:`No Sigstore attestation provided for ${C}.`});if(xe&&V?.verified&&I){let _e=I.allowedIdentities||[];if(_e.length>0){let W=!!V.identity&&_e.includes(V.identity);if(o.push({id:`mirror.sigstore.policy.identity.${C}`,status:W?"passed":"failed",message:W?`Sigstore identity policy passed for ${C} in ${S}.`:`Sigstore identity policy failed for ${C} in ${S}.`}),!W)continue}let E=I.allowedIssuers||[];if(E.length>0){let W=!!V.issuer&&E.includes(V.issuer);if(o.push({id:`mirror.sigstore.policy.issuer.${C}`,status:W?"passed":"failed",message:W?`Sigstore issuer policy passed for ${C} in ${S}.`:`Sigstore issuer policy failed for ${C} in ${S}.`}),!W)continue}let M=I.allowedRekorUrls||[];if(M.length>0){let W=!!V.rekorUrl&&M.includes(V.rekorUrl);if(o.push({id:`mirror.sigstore.policy.rekor.${C}`,status:W?"passed":"failed",message:W?`Sigstore Rekor policy passed for ${C} in ${S}.`:`Sigstore Rekor policy failed for ${C} in ${S}.`}),!W)continue}}else I&&o.push({id:`mirror.sigstore.policy.${C}`,status:"skipped",message:`Sigstore governance policy configured for ${S} but no verified Sigstore attestation for ${C}.`});let St=await promises.stat(q);N.push({id:C,path:w.relative(t,q),sha256:Ee,size:St.size,provenance:ke,attestation:{detached:{provided:!!G.attestation,verified:Pe?.verified||false,algorithm:Pe?.algorithm||null,publicKeyPath:Pe?.publicKeyPath||null,publicKeyFingerprint:Pe?.publicKeyFingerprint||null,signature:Pe?.signature||null,verifiedAt:Pe?.verified?new Date().toISOString():null},sigstore:{provided:!!xe,verified:V?.verified||false,tlogVerified:V?.tlogVerified||false,identity:V?.identity||null,issuer:V?.issuer||null,rekorUrl:V?.rekorUrl||null,bundlePath:V?.bundlePath||null,certificatePath:V?.certificatePath||null,signaturePath:V?.signaturePath||null,verifiedAt:V?.verified?new Date().toISOString():null}}});}let D=m.retention?.keepLast;if(typeof D=="number"&&D>0){let G=(await promises.readdir(c,{withFileTypes:true})).filter(C=>C.isFile()).map(C=>w.join(c,C.name));if(G.length>D){let C=await Promise.all(G.map(async Re=>({filePath:Re,stat:await promises.stat(Re)})));C.sort((Re,q)=>q.stat.mtimeMs-Re.stat.mtimeMs);let ee=C.slice(D);for(let Re of ee)await promises.unlink(Re.filePath),r.rotatedFiles+=1;}}o.push({id:"mirror.rotate",status:"passed",message:r.rotatedFiles>0?`Mirror retention rotation removed ${r.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let je={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:m.mode||null,environment:S,artifacts:N};if(await promises.writeFile(a,`${JSON.stringify(je,null,2)}
152
152
  `,"utf-8"),r.lockWritten=true,o.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${w.relative(t,a)}.`}),r.transparencyEvidenceRecords=H.length,H.length>0){let O={schemaVersion:"1.0",generatedAt:new Date().toISOString(),environment:S,records:H},G=new Date().toISOString().replace(/[:.]/g,"-"),C=w.join(l,`transparency-evidence-${G}.json`),ee=w.join(l,"transparency-evidence.latest.json");if(await R.ensureDir(l),await ii(C,O),await ii(ee,O),r.transparencyEvidenceWritten=true,o.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${w.relative(t,ee)}.`}),y?.enabled){let Re=Math.max(1e3,y.timeoutMs??1e4);if(y.target==="file")if(!y.filePath)o.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let q=Te(t,y.filePath);await R.ensureDir(w.dirname(q)),await promises.appendFile(q,`${JSON.stringify(O)}
@@ -214,7 +214,7 @@ Hints:`));for(let p of a)console.log(s.gray(`- ${p}`));}return i.exitCode}functi
214
214
  `),0):(console.log(s.cyan("RapidKit mirror status")),console.log(s.gray(`Workspace: ${r}`)),console.log(s.gray(`Config: ${d?"present":"missing"} (${i})`)),console.log(s.gray(`Lock: ${u?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${h}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let p=await Ar(r,{ciMode:true,offlineMode:e==="verify",forceRun:true}),d=p.checks.filter(h=>h.status==="failed"),f=p.checks.some(h=>h.id.startsWith("mirror.verify.")&&h.status==="failed");if(e==="verify"&&f){let h={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:p.details,checks:p.checks};if(await g(h),o)return process.stdout.write(`${JSON.stringify(h,null,2)}
215
215
  `),1;console.log(s.red("\u274C Mirror verify failed."));for(let k of p.checks.filter(P=>P.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${k.id}: ${k.message}`));return 1}if(d.length>0){let h={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:p.details,checks:p.checks};if(await g(h),o)return process.stdout.write(`${JSON.stringify(h,null,2)}
216
216
  `),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${d.length} issue(s).`));for(let k of d)console.log(s.gray(`- ${k.id}: ${k.message}`));return 1}let u={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:await m(),details:p.details,checks:p.checks};return await g(u),o?(process.stdout.write(`${JSON.stringify(u,null,2)}
217
- `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${p.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${p.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${p.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),1}async function Gr(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 Yi(o,async()=>{let n=re(o),i=Ve("python",{runCommandInCwd:z,runCoreRapidkit:e}),a=Ve("dotnet",{runCommandInCwd:z,runCoreRapidkit:e}),c=t.slice(1).filter(u=>!u.startsWith("-"));if(c.length>0){let u=w.resolve(o,c[0]),h=a$4(u),k=await dt(u);return b$7(h,u)||k==="go"?await Tr(u):d$3(h,u)||k==="java"?await Be("init",u):e$1(h,u)||k==="dotnet"?Z(await a.initProject(u)):c$2(h,u)||k==="node"?await Nr(u):f$2(h,u)||k==="python"?await Or(u,i):await e(t,{cwd:o})}let l=a$4(o),g$1=!!re(o)&&o===re(o);if(!g$1&&b$7(l,o))return await Tr(o);let m=await dt(o);if(!g$1&&(d$3(l,o)||m==="java"))return await Be("init",o);if(!g$1&&(e$1(l,o)||m==="dotnet"))return Z(await a.initProject(o));if(!g$1&&(c$2(l,o)||m==="node"))return await Nr(o);if(!g$1&&(f$2(l,o)||m==="python"))return await Or(o,i);let p=n||re(o),d=Ui(o),f=d?w.dirname(w.dirname(d)):null;if(f&&f!==p){let u=a$4(f),h=await dt(f);return b$7(u,f)||h==="go"?await Tr(f):d$3(u,f)||h==="java"?await Be("init",f):e$1(u,f)||h==="dotnet"?Z(await a.initProject(f)):c$2(u,f)||h==="node"?await Nr(f):f$2(u,f)||h==="python"?await Or(f,i):await e(["init"],{cwd:f})}if(p&&o===p){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 u=await Kr(p);if(u!==0)return u;let{runWorkspaceStage:h}=await import('./workspace-run-GCIQD73R.js');return (await h({workspacePath:p,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!p){let u=await b$2(),h=g(),{name:k}=Il(h);await R__default.ensureDir(h);let{createProject:P}=await import('./create-RNP5ACQL.js');return await P(k,{yes:true,userConfig:u,parentDirectory:h}),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 Oi(t){let e=re(t);if(!e)return [];let o="warn";try{let l=await b$4.promises.readFile(w.join(e,".rapidkit","policies.yml"),"utf-8");(l.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??l.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(o="strict");}catch{return []}if(o!=="strict")return [];let r=[],n=w.join(e,".rapidkit","toolchain.lock");if(!b$4.existsSync(n))return r.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain)."),r;let i={};try{i=JSON.parse(await b$4.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.runtime??{},c=a$4(t);b$7(c,t)&&!a.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."):c$2(c,t)&&!a.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."):d$3(c,t)&&!a.java?.version?r.push("java.version is not pinned in toolchain.lock \u2014 run `rapidkit setup java` first."):e$1(c,t)&&!a.dotnet?.version?r.push("dotnet.version is not pinned in toolchain.lock \u2014 run `rapidkit setup dotnet` first."):f$2(c,t)&&!a.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");try{let g=JSON.parse(await b$4.promises.readFile(w.join(e,".rapidkit","workspace.json"),"utf-8")).profile??"";g==="python-only"&&(b$7(c,t)||c$2(c,t)||d$3(c,t)||e$1(c,t))?r.push('Workspace profile is "python-only" but this project is not Python.'):g==="node-only"&&(b$7(c,t)||f$2(c,t)||d$3(c,t)||e$1(c,t))?r.push('Workspace profile is "node-only" but this project is not Node.'):g==="go-only"&&(c$2(c,t)||f$2(c,t)||d$3(c,t)||e$1(c,t))?r.push('Workspace profile is "go-only" but this project is not Go.'):g==="java-only"&&(f$2(c,t)||c$2(c,t)||b$7(c,t)||e$1(c,t))?r.push('Workspace profile is "java-only" but this project is not Java.'):g==="dotnet-only"&&(f$2(c,t)||c$2(c,t)||b$7(c,t)||d$3(c,t))&&r.push('Workspace profile is "dotnet-only" but this project is not .NET.');}catch{}return r}async function Ol(){let t=async y=>{if(!b$1()||!y.toLowerCase().endsWith(".cmd"))return false;try{let x=(await R__default.readFile(y,"utf8")).replace(/\r\n/g,`
217
+ `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${p.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${p.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${p.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),1}async function Gr(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 Yi(o,async()=>{let n=re(o),i=Ve("python",{runCommandInCwd:z,runCoreRapidkit:e}),a=Ve("dotnet",{runCommandInCwd:z,runCoreRapidkit:e}),c=t.slice(1).filter(u=>!u.startsWith("-"));if(c.length>0){let u=w.resolve(o,c[0]),h=a$4(u),k=await dt(u);return b$7(h,u)||k==="go"?await Tr(u):d$3(h,u)||k==="java"?await Be("init",u):e$1(h,u)||k==="dotnet"?Z(await a.initProject(u)):c$2(h,u)||k==="node"?await Nr(u):f$2(h,u)||k==="python"?await Or(u,i):await e(t,{cwd:o})}let l=a$4(o),g$1=!!re(o)&&o===re(o);if(!g$1&&b$7(l,o))return await Tr(o);let m=await dt(o);if(!g$1&&(d$3(l,o)||m==="java"))return await Be("init",o);if(!g$1&&(e$1(l,o)||m==="dotnet"))return Z(await a.initProject(o));if(!g$1&&(c$2(l,o)||m==="node"))return await Nr(o);if(!g$1&&(f$2(l,o)||m==="python"))return await Or(o,i);let p=n||re(o),d=Ui(o),f=d?w.dirname(w.dirname(d)):null;if(f&&f!==p){let u=a$4(f),h=await dt(f);return b$7(u,f)||h==="go"?await Tr(f):d$3(u,f)||h==="java"?await Be("init",f):e$1(u,f)||h==="dotnet"?Z(await a.initProject(f)):c$2(u,f)||h==="node"?await Nr(f):f$2(u,f)||h==="python"?await Or(f,i):await e(["init"],{cwd:f})}if(p&&o===p){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 u=await Kr(p);if(u!==0)return u;let{runWorkspaceStage:h}=await import('./workspace-run-F5FADRY5.js');return (await h({workspacePath:p,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!p){let u=await b$2(),h=g(),{name:k}=Il(h);await R__default.ensureDir(h);let{createProject:P}=await import('./create-RNP5ACQL.js');return await P(k,{yes:true,userConfig:u,parentDirectory:h}),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 Oi(t){let e=re(t);if(!e)return [];let o="warn";try{let l=await b$4.promises.readFile(w.join(e,".rapidkit","policies.yml"),"utf-8");(l.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??l.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(o="strict");}catch{return []}if(o!=="strict")return [];let r=[],n=w.join(e,".rapidkit","toolchain.lock");if(!b$4.existsSync(n))return r.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain)."),r;let i={};try{i=JSON.parse(await b$4.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.runtime??{},c=a$4(t);b$7(c,t)&&!a.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."):c$2(c,t)&&!a.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."):d$3(c,t)&&!a.java?.version?r.push("java.version is not pinned in toolchain.lock \u2014 run `rapidkit setup java` first."):e$1(c,t)&&!a.dotnet?.version?r.push("dotnet.version is not pinned in toolchain.lock \u2014 run `rapidkit setup dotnet` first."):f$2(c,t)&&!a.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");try{let g=JSON.parse(await b$4.promises.readFile(w.join(e,".rapidkit","workspace.json"),"utf-8")).profile??"";g==="python-only"&&(b$7(c,t)||c$2(c,t)||d$3(c,t)||e$1(c,t))?r.push('Workspace profile is "python-only" but this project is not Python.'):g==="node-only"&&(b$7(c,t)||f$2(c,t)||d$3(c,t)||e$1(c,t))?r.push('Workspace profile is "node-only" but this project is not Node.'):g==="go-only"&&(c$2(c,t)||f$2(c,t)||d$3(c,t)||e$1(c,t))?r.push('Workspace profile is "go-only" but this project is not Go.'):g==="java-only"&&(f$2(c,t)||c$2(c,t)||b$7(c,t)||e$1(c,t))?r.push('Workspace profile is "java-only" but this project is not Java.'):g==="dotnet-only"&&(f$2(c,t)||c$2(c,t)||b$7(c,t)||d$3(c,t))&&r.push('Workspace profile is "dotnet-only" but this project is not .NET.');}catch{}return r}async function Ol(){let t=async y=>{if(!b$1()||!y.toLowerCase().endsWith(".cmd"))return false;try{let x=(await R__default.readFile(y,"utf8")).replace(/\r\n/g,`
218
218
  `).toLowerCase(),I=x.includes("\\.rapidkit\\rapidkit"),Y=x.includes("\\.rapidkit\\rapidkit.cmd")||x.includes("\\.rapidkit\\rapidkit.exe")||x.includes("\\.venv\\scripts\\rapidkit.exe");return I&&!Y}catch{return false}},e$2=process.cwd(),o$1=process.argv.slice(2),r=o$1[0],n=r==="init",i=new Set(h$2),a=!r||r==="--help"||r==="-h"||r==="help",c=We(e$2),l=b$4.existsSync(w.join(e$2,".rapidkit","project.json")),g=a$4(e$2),m=await dt(e$2),p=b$7(g,e$2)||c$2(g,e$2)||f$2(g,e$2)||d$3(g,e$2)||e$1(g,e$2)||m$1(m??void 0),d=!!r&&i.has(r)&&p,f$1=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Lt(o$1)||o$1[0]==="create")return false;if(Fr(o$1))return true;if(o$1[0]==="init"&&c&&!l)return false;if(Lr(o$1))return true;try{let y=r==="shell"&&o$1[1]==="activate",S=r==="create",x=await qn(e$2,{cwd:e$2,timeoutMs:1200});if(x.ok&&x.data?.isRapidkitProject&&x.data.engine==="python"){let I=S||Lt(o$1);if(!a&&!y&&!I&&!n&&!d&&Qo(o$1)){if(r&&ji.includes(r)){let H=await Oi(e$2).catch(()=>[]);if(H.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
219
219
  `);for(let ce of H)process.stderr.write(s.red(` \u2022 ${ce}`)+`
220
220
  `);process.exit(1);}}let Y=await e(process.argv.slice(2),{cwd:e$2});process.exit(Y);}}}catch{}let u=Ui(e$2),h=b$1(),k=f$1?[]:o(e$2),P=null;for(let y of k)if(await R__default.pathExists(y)){if(await t(y)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${y}. Falling back to core bridge.`);continue}P=y;break}let v=r==="create";if(r==="init"&&c&&!l)return false;if(r&&ji.includes(r)){let y=await Oi(e$2);if(y.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
@@ -297,18 +297,18 @@ Use "rapidkit help <command>" for more information.
297
297
  `),f.debug(`Synced Python version ${x.trim()} from workspace to project`);}}catch(x){f.debug("Could not sync Python version from workspace:",x);}}if(!e$1.skipInstall){let v=await e(["init",c$1],{cwd:process.cwd()});if(v!==0&&process.exit(v),P){let y=w.dirname(P),S=w.join(y,".python-version"),x=w.join(c$1,".python-version");try{if(await R__default.pathExists(S)){let I=b$4.readFileSync(S,"utf-8");b$4.writeFileSync(x,I.trim()+`
298
298
  `),f.debug(`Re-synced Python version ${I.trim()} after init`);}}catch(I){f.debug("Could not re-sync Python version after init:",I);}}}}else {let{createProject:l}=await import('./create-RNP5ACQL.js');await l(t,{skipGit:e$1.skipGit,dryRun:e$1.dryRun,yes:e$1.yes,userConfig:n,installMethod:e$1.installMethod,profile:e$1.profile,parentDirectory:w.dirname(c$1)}),console.log(s.gray(`\u2139\uFE0F Workspace root: ${c$1}`)),console.log(s.gray(` Next: ${k(c$1)} && npx rapidkit create project`));}}catch(o){o instanceof a$2?(f.error(`
299
299
  \u274C ${o.message}`),o.details&&f.warn(`\u{1F4A1} ${o.details}`),f.debug("Error code:",o.code)):(f.error(`
300
- \u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{ot=null;}});ks(se);xs(se);Xs(se);se.command("commands").description("Show effective RapidKit command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{Pl({json:t.json});});se.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-QYHMGLSG.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);}});ts(se);se.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(l){let g=l;for(;;){let m=w.join(g,".rapidkit","context.json");if(b$4.existsSync(m))return m;let p=w.dirname(g);if(p===g)break;g=p;}return null}let r=o(e);function n$1(l){let g=l;for(;;){let m=w.join(g,".venv"),p=w.join(g,".rapidkit","activate");if(b$4.existsSync(p)||b$4.existsSync(m))return {venv:m,activateFile:p};let d=w.dirname(g);if(d===g)break;g=d;}return null}let i=n$1(e);!r&&!i&&(console.log(s.yellow("No RapidKit project found in this directory")),process.exit(1));let a;i&&b$4.existsSync(i.activateFile)?a=i.activateFile:i&&b$4.existsSync(i.venv)?a=n(i.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$1();console.log(c?`call "${a}"`:`. "${a}"`);});se.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});});se.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-DH6Z47O4.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});});se.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-AHMQEUFH.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(c){let l=c instanceof Error?c.message:String(c);console.log(s.red(`Autopilot release failed: ${l}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});se.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","Enable Core module/template commands for supported runtimes").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 _l(t,e);o!==0&&process.exit(o);});se.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","Enable Core module/template commands for supported runtimes").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 Al(t,e);o!==0&&process.exit(o);});var No=se.command("snapshot").description("Create, list, and restore RapidKit workspace snapshots");No.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 vt({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);}});No.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 _s({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);}});No.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 Es({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);}});No.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 As({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 Jt=se.command("project").description("Safe workspace project lifecycle operations");Jt.command("commands").description("Show effective commands supported by the current RapidKit project").option("--json","Emit machine-readable JSON output").action(async t=>{Vi({json:t.json});});Jt.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 fr({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);}});Jt.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 gr({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);}});Jt.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 Ns({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);}});Jt.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 Os({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);}});se.command("doctor [scope]").description("\u{1FA7A} Check RapidKit system health by default; use workspace or project for scoped checks").option("--workspace","Check entire workspace (including all projects)").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("--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=await bl({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package rapidkit rapidkit doctor workspace")));let{runDoctor:r}=await import('./doctor-XM6QDTDC.js'),n=await r({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true});n!==0&&process.exit(n);});se.command("workspace <action> [subaction] [key] [value]").description(`Manage RapidKit workspaces (list, sync, policy, share, export, run, intelligence)
300
+ \u274C An unexpected error occurred:`),console.error(o)),process.exit(1);}finally{ot=null;}});ks(se);xs(se);Xs(se);se.command("commands").description("Show effective RapidKit command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{Pl({json:t.json});});se.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-QYHMGLSG.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);}});ts(se);se.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function o(l){let g=l;for(;;){let m=w.join(g,".rapidkit","context.json");if(b$4.existsSync(m))return m;let p=w.dirname(g);if(p===g)break;g=p;}return null}let r=o(e);function n$1(l){let g=l;for(;;){let m=w.join(g,".venv"),p=w.join(g,".rapidkit","activate");if(b$4.existsSync(p)||b$4.existsSync(m))return {venv:m,activateFile:p};let d=w.dirname(g);if(d===g)break;g=d;}return null}let i=n$1(e);!r&&!i&&(console.log(s.yellow("No RapidKit project found in this directory")),process.exit(1));let a;i&&b$4.existsSync(i.activateFile)?a=i.activateFile:i&&b$4.existsSync(i.venv)?a=n(i.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$1();console.log(c?`call "${a}"`:`. "${a}"`);});se.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});});se.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-YD2DO7XY.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});});se.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-YDEUKRW6.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(c){let l=c instanceof Error?c.message:String(c);console.log(s.red(`Autopilot release failed: ${l}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});se.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","Enable Core module/template commands for supported runtimes").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 _l(t,e);o!==0&&process.exit(o);});se.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","Enable Core module/template commands for supported runtimes").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 Al(t,e);o!==0&&process.exit(o);});var No=se.command("snapshot").description("Create, list, and restore RapidKit workspace snapshots");No.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 vt({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);}});No.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 _s({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);}});No.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 Es({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);}});No.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 As({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 Jt=se.command("project").description("Safe workspace project lifecycle operations");Jt.command("commands").description("Show effective commands supported by the current RapidKit project").option("--json","Emit machine-readable JSON output").action(async t=>{Vi({json:t.json});});Jt.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 fr({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);}});Jt.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 gr({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);}});Jt.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 Ns({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);}});Jt.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 Os({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);}});se.command("doctor [scope]").description("\u{1FA7A} Check RapidKit system health by default; use workspace or project for scoped checks").option("--workspace","Check entire workspace (including all projects)").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("--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=await bl({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package rapidkit rapidkit doctor workspace")));let{runDoctor:r}=await import('./doctor-XM6QDTDC.js'),n=await r({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true});n!==0&&process.exit(n);});se.command("workspace <action> [subaction] [key] [value]").description(`Manage RapidKit workspaces (list, sync, policy, share, export, run, intelligence)
301
301
  workspace run <stage> \u2014 fleet stage execution across discovered projects
302
302
  stages: init | test | build | start | <custom-from-context>
303
303
  workspace explain|why \u2014 blocker/project narrative (--write for artifact)
304
304
  workspace trace \u2014 diff \u2192 blast radius \u2192 gates narrative (--from <diff>)
305
- 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("--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=l=>{let m=(n.workspace?w.resolve(n.workspace):null)??a$6(process.cwd())??re(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 p=w.resolve(process.cwd()),d=w.resolve(m);return p!==d&&console.log(s.gray(`\u2139 Using workspace root ${m} for "${l}" (current directory: ${p}).`)),m},a=l=>process.argv.includes(l),c=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0};if((ni(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$1({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:l}=await import('./workspace-E554C5SM.js');await l();}else if(t==="model"){let l=i("model"),{buildWorkspaceModelCached:g,buildWorkspaceModelIncremental:m,writeWorkspaceModel:p}=await import('./workspace-model-YL7W3573.js'),d=n.incremental===true||a("--incremental"),f=n.cache===true||a("--cache")||d,u={workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c(),strict:n.strict===true||a("--strict")},h,k;if(d){let y=await m(u);h=y.model,k=y.mode;}else {let y=await g({...u,cache:f});h=y.model,k=y.cache;}let P;(n.write===true||a("--write"))&&(P=await p(h,l));let v=(n.strict===true||a("--strict"))&&h.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...h,...P?{outputPath:P}:{}},null,2)),v&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${h.workspace.name}`)),d?console.log(s.gray(` Build: ${k} (incremental)`)):f&&console.log(s.gray(` Cache: ${k}`)),console.log(s.gray(` Projects: ${h.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${h.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${h.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${h.identity.workspaceType}`)),console.log(s.gray(` Validation: ${h.validation?.status??"unknown"} (${h.validation?.errors??0} error, ${h.validation?.warnings??0} warning)`)),console.log(P?s.gray(` Written: ${P}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-model.json")),v&&process.exit(1);}else if(t==="agent-sync"){let l=i("agent-sync"),{syncWorkspaceAgentGrounding:g,parseAgentGroundingTargets:m}=await import('./workspace-agent-sync-2HRPM5ZD.js'),p=n.strict===true||a("--strict"),d=n.write===true||a("--write"),f=a("--dry-run"),u=await g({workspacePath:l,scope:n.scope,agent:n.forAgent,write:d&&!f,dryRun:f,strict:p,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(u,null,2));else {console.log(s.green(`\u2714 Agent grounding ${d&&!f?"synced":"planned"}`)),console.log(s.gray(` Index: ${u.indexPath}`)),u.contextPath&&console.log(s.gray(` Context: ${u.contextPath}`)),u.blockers.length>0&&console.log(s.yellow(` Blockers: ${u.blockers.slice(0,3).join(" \xB7 ")}`));let h=d&&!f?u.writtenFiles:u.skippedFiles;if(h.length>0&&console.log(s.gray(` Files: ${h.join(", ")}`)),u.strictViolations.length>0)for(let k of u.strictViolations)console.log(s.red(`\u274C ${k}`));}p&&u.strictViolations.length>0&&process.exit(1);}else if(t==="context"){let l=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:g,writeWorkspaceAgentContext:m}=await import('./workspace-context-VJTXW3K4.js'),p=n.strict===true||a("--strict"),d=await g({workspacePath:l,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c(),strict:false}),f,u;if((n.write===true||a("--write"))&&(f=await m(d,l),(n.agentSync===true||a("--agent-sync")||n.noAgentSync!==true)&&!a("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:v}=await import('./workspace-agent-sync-2HRPM5ZD.js');if(u=await P({workspacePath:l,scope:n.scope,agent:d.agent,write:true,refreshContext:false,strict:p,preset:n.preset==="minimal"?"minimal":"enterprise",targets:v(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${u.writtenFiles.length} file(s) updated`)),p&&u.strictViolations.length>0){for(let y of u.strictViolations)console.log(s.red(`\u274C ${y}`));process.exit(1);}}let h=p&&d.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...d,...f?{outputPath:f}:{},...u?{agentGroundingSync:u}:{}},null,2)),h&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${d.workspace.name}`)),console.log(s.gray(` Agent: ${d.agent}`)),console.log(s.gray(` Scope: ${d.scope.activeProject??d.scope.requested}`)),console.log(s.gray(` Projects included: ${d.projects.length}`)),console.log(s.gray(` Safe commands: ${d.safeCommands.length}`)),console.log(s.gray(` Validation: ${d.validation.status} (${d.validation.errors} error, ${d.validation.warnings} warning)`)),console.log(f?s.gray(` Written: ${f}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-context-agent.json")),h){for(let k of d.validation.issues)console.log(s.red(`\u274C ${k.severity}:${k.code}:${k.target}`));process.exit(1);}}else if(t==="snapshot"){let l=i("snapshot"),{buildWorkspaceModelSnapshot:g,writeWorkspaceModelSnapshot:m}=await import('./workspace-intelligence-E3KXEZCM.js'),p=await g({workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),d=await m(p,l);if(n.json){console.log(JSON.stringify({...p,outputPath:d},null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${p.model.workspace.name}`)),console.log(s.gray(` Hash: ${p.modelHash}`)),console.log(s.gray(` Projects: ${p.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${p.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${d}`));}else if(t==="diff"){let l=i("diff"),g=n.from||e;g||(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:p}=await import('./workspace-intelligence-E3KXEZCM.js'),d=await m({workspacePath:l,fromPath:g,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),f=await p(d,l);if(n.json){console.log(JSON.stringify({...d,outputPath:f},null,2));return}let u=d.summary.changed?s.yellow:s.green;console.log(u(`\u2714 Workspace model diff: ${d.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${d.fromRef}`)),console.log(s.gray(` Added projects: ${d.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${d.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${d.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${d.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${d.summary.validationChanges}`)),d.git?.available&&console.log(s.gray(` Git: ${d.git.dirty?"dirty":"clean"} (${d.summary.gitChangedFiles} mapped change(s))`));for(let h of d.changes.slice(0,12))console.log(s.gray(` \u2022 ${h.type} ${h.target}: ${h.message}`));d.changes.length>12&&console.log(s.gray(` \u2026 ${d.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="impact"){let l=i("impact"),g=n.from||e;g||(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:p}=await import('./workspace-intelligence-E3KXEZCM.js'),d=await m({workspacePath:l,fromPath:g,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),f=await p(d,l);if(n.json){console.log(JSON.stringify({...d,outputPath:f},null,2));return}let u=d.summary.risk==="critical"||d.summary.risk==="high"?s.red:d.summary.risk==="medium"?s.yellow:s.green;console.log(u(`\u2714 Workspace impact: ${d.summary.risk}`)),console.log(s.gray(` From: ${d.fromRef}`)),console.log(s.gray(` Affected projects: ${d.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${d.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${d.summary.recommendedCommands}`));for(let h of d.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${h.title}: ${h.summary}`));d.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${d.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="verify"){let l=i("verify"),{buildWorkspaceVerify:g,writeWorkspaceVerify:m,evaluateWorkspaceVerifyGate:p}=await import('./workspace-verify-NRYH7RNB.js'),d=await g({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),f=await m(d,l),u=p(d,{strict:n.strict===true||a("--strict")}),h=u.exitCode,{recordWorkspaceHistory:k,historyEntryFromVerify:P}=await import('./workspace-history-VPDADQKG.js');if(await k(l,P(d,u.passed)),n.json){console.log(JSON.stringify({...d,gate:u,outputPath:f},null,2)),h!==0&&process.exit(h);return}let v=d.summary.verdict==="ready"?s.green:d.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(v(`\u2714 Workspace verify: ${d.summary.verdict}`)),console.log(s.gray(` Freshness: ${d.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${d.impact.risk}`)),console.log(s.gray(` Steps: ${d.steps.length}`)),console.log(s.gray(` Passed ${d.summary.stepsPassed}, warn ${d.summary.stepsWarn}, failed ${d.summary.stepsFailed}, missing ${d.summary.stepsMissing}`));for(let y of d.steps.slice(0,10))console.log(s.gray(` \u2022 ${y.id}: ${y.status} \u2014 ${y.message}`));if(d.steps.length>10&&console.log(s.gray(` \u2026 ${d.steps.length-10} more step(s)`)),d.policyViolations.length>0){console.log(s.gray(` Policy (${d.policyMode}): ${d.policyViolations.length} violation(s)`));for(let y of d.policyViolations.slice(0,5)){let S=y.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${S} [${y.source}] ${y.code}: ${y.message}`);}}console.log(s.gray(` Gate (${u.mode}): ${u.passed?"passed":"blocked"}`));for(let y of u.reasons.slice(0,5))console.log(s.red(` \u2717 ${y}`));console.log(s.gray(` Written: ${f}`)),h!==0&&process.exit(h);}else if(t==="graph"){let l=i("graph"),{buildWorkspaceModel:g}=await import('./workspace-model-YL7W3573.js'),{buildGraphEmit:m,renderGraphDot:p,renderGraphMermaid:d,explainGraphNode:f}=await import('./workspace-graph-2A5THUCI.js'),h=(await g({workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()})).graph;h||(console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let k=(e||"emit").toLowerCase();if(k==="dot"){console.log(p(h));return}if(k==="mermaid"){console.log(d(h));return}if(k==="explain"){let v=(n.scope?.replace(/^project:/,"")||o||"").trim();v||(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 y=f(h,v);if(n.json){console.log(JSON.stringify(y,null,2)),y.found||process.exit(1);return}y.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${v}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${y.project}`)),y.centrality&&console.log(s.gray(` Centrality: fanIn ${y.centrality.fanIn}, fanOut ${y.centrality.fanOut}, reach ${y.centrality.reach}, betweenness ${y.centrality.betweenness}${y.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${y.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${y.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${y.transitiveDependents.length}`));for(let S of y.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${S.id} (d${S.distance}, via ${S.via??"\u2014"})`));return}let P=m(h);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 l=i("watch"),{runWorkspaceWatch:g}=await import('./workspace-watch-H2AETGFI.js'),m=n.once===true||a("--once"),p=n.json===true,d=new AbortController,f=()=>d.abort();process.once("SIGINT",f),process.once("SIGTERM",f),p||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await g({workspacePath:l,once:m,signal:d.signal,buildOptions:{workspacePath:l,observableScanDepth:c()},onProgress:u=>{p||console.error(s.gray(` ${u}`));},emit:u=>{if(p){console.log(JSON.stringify(u));return}if(u.kind==="ready"){console.log(s.gray(` Ready: ${u.graph.nodeCount} nodes, ${u.graph.edgeCount} edges (hash ${u.modelHash.slice(0,12)})`));return}if(u.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${u.error??"unknown error"}`));return}if(u.kind==="unchanged"){console.log(s.gray(` No structural change (${u.mode}, ${u.durationMs}ms)`));return}let h=[];u.changedProjects.length>0&&h.push(`changed: ${u.changedProjects.join(", ")}`),u.addedProjects.length>0&&h.push(`added: ${u.addedProjects.join(", ")}`),u.removedProjects.length>0&&h.push(`removed: ${u.removedProjects.join(", ")}`),u.graph.edgesAdded.length>0&&h.push(`+${u.graph.edgesAdded.length} edges`),u.graph.edgesRemoved.length>0&&h.push(`-${u.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${u.mode}, ${u.durationMs}ms): ${h.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",f),process.removeListener("SIGTERM",f),!p&&!m&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=i("sync"),{syncWorkspaceProjects:g}=await import('./workspace-E554C5SM.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${w.basename(l)}`));let m=await g(l,n.json===true);await Ue(l,{silent:n.json===true});let{readWorkspaceRegistrySummary:p}=await import('./workspace-registry-summary-X5WRUU3T.js'),d=await p(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:m,contractSynced:true,registrySummary:d},null,2));}else if(t==="registry"){let l=i("registry"),g=e||"status";g!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${g}`)),console.log(s.gray(" npx rapidkit workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:m,readWorkspaceRegistrySummary:p,resolveWorkspaceRegisteredProjects:d}=await import('./workspace-registry-summary-X5WRUU3T.js'),u=n.refresh===true||a("--refresh")||n.force===true||a("--force")?await m(l):await p(l)||await m(l);if(n.json){console.log(JSON.stringify(u,null,2));return}let h=await d(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${u.authority}`)),console.log(s.gray(` Projects: ${u.projectCount}`)),console.log(s.gray(` Summary: ${u.registrySummaryPath}`)),h.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=i("foundation"),g=e||"ensure";g!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${g}`)),console.log(s.gray(" npx rapidkit workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:m}=await import('./workspace-foundation-LISDH53T.js'),p=await m(l,{force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(p,null,2));return}p.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${p.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=i("policy"),g=await Ml(l,e,o,r);g!==0&&process.exit(g);}else if(t==="contract"){let l=i("contract"),{buildWorkspaceContractGraph:g,readWorkspaceContract:m,verifyWorkspaceContract:p,writeWorkspaceContract:d,WORKSPACE_CONTRACT_PATH:f}=await import('./workspace-contract-OO4GMENV.js'),u=e||"inspect",h=n.output;try{if(u==="init"){let k=await d({workspacePath:l,outputPath:h,force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(k,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${k.contractPath}`)),console.log(s.gray(` Projects: ${k.contract.projects.length}`));return}if(u==="inspect"){let k=await m({workspacePath:l,contractPath:h});if(n.json){console.log(JSON.stringify(k,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${k.contractPath}`)),console.log(s.gray(` Workspace: ${k.contract.workspace.name}`)),console.log(s.gray(` Projects: ${k.contract.projects.length}`)),console.log(s.gray(` Schema: v${k.contract.schemaVersion}`));return}if(u==="verify"){let k=await p({workspacePath:l,contractPath:h,strict:n.strict===true||a("--strict")}),{writeWorkspaceContractVerifyEvidence:P}=await import('./workspace-contract-OO4GMENV.js'),v=await P({workspacePath:l,result:k});if(n.json)console.log(JSON.stringify({...k,evidencePath:v},null,2));else {let y=k.status==="passed"?s.green:s.red;console.log(y(`\u2714 Workspace contract verification ${k.status}: ${k.contractPath}`)),console.log(s.gray(` Projects: ${k.projectCount}`));for(let S of k.checks){let x=S.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${x} ${S.id}: ${S.message}`));}for(let S of k.violations)console.log(s.gray(` Violation: ${S}`));}(k.status==="failed"||k.status!=="passed"&&n.strict)&&process.exit(1);return}if(u==="graph"){let k=await g({workspacePath:l,contractPath:h});if(n.json){console.log(JSON.stringify(k,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${k.contractPath}`)),console.log(s.gray(` Workspace: ${k.graph.workspace.name}`)),console.log(s.gray(` Projects: ${k.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${k.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${k.graph.summary.eventEdges}`)),console.log(s.gray(` Ports: ${k.graph.summary.portCount}`));for(let P of k.graph.nodes){let v=P.ports.map(y=>`${y.name}:${y.port}`).join(", ")||"none";console.log(s.gray(` \u2022 ${P.id} (${P.runtime||"unknown"}${P.framework?`/${P.framework}`:""}) ports=${v}`));}for(let P of k.graph.edges){let v=P.type==="event"?`event:${P.label}`:P.label;console.log(s.gray(` ${P.from} -> ${P.to} [${v}]`));}return}console.log(s.red(`\u274C Unknown workspace contract action: ${u}`)),console.log(s.white(` npx rapidkit workspace contract init|inspect|verify|graph [--output ${f}]`)),process.exit(1);}catch(k){console.log(s.red(`\u274C Workspace contract ${u} failed: ${k.message}`)),process.exit(1);}}else if(t==="share"){let l=i("share"),g=n.output||e,{createWorkspaceShareBundle:m}=await import('./workspace-E554C5SM.js'),p=await m(l,{outputPath:g,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});console.log(s.green(`\u2714 Workspace share bundle exported: ${p}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=i("export"),{exportWorkspaceArchive:g}=await import('./workspace-archive-EJIGYKSR.js'),m=await g({workspacePath:l,outputPath:n.output||e,includeEnv:n.includeEnv===true||a("--include-env")});if(n.json){console.log(JSON.stringify(m,null,2));return}let p=(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: ${p} 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 l=o;l||(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:g,inspectWorkspaceArchive:m,verifyWorkspaceArchive:p}=await import('./workspace-archive-EJIGYKSR.js');try{if(e==="inspect"){let f=await m({archivePathOrUrl:l});if(n.json){console.log(JSON.stringify(f,null,2));return}let u=(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: ${u} MB`));return}if(e==="doctor"){let f=await g({archivePathOrUrl:l,strict:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(f,null,2));else {let u=f.status==="passed"?s.green:f.status==="warning"?s.yellow:s.red;console.log(u(`\u2714 Workspace archive doctor ${f.status}: ${f.archivePath}`)),console.log(s.gray(` Workspace: ${f.workspaceName}`)),console.log(s.gray(` Files: ${f.fileCount}`));for(let h of f.checks){let k=h.status==="passed"?"\u2714":h.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${k} ${h.id}: ${h.message}`));}for(let h of f.recommendedActions)console.log(s.gray(` Next: ${h}`));}(f.status==="failed"||f.status==="warning"&&n.strict)&&process.exit(1);return}let d=await p({archivePathOrUrl:l,requireChecksums:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(d,null,2));else if(d.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${d.archivePath}`)),console.log(s.gray(` Files: ${d.verifiedFiles}/${d.fileCount}`));else {let f=d.status==="failed"?s.red:s.yellow;console.log(f(`\u274C Workspace archive verification ${d.status}: ${d.archivePath}`)),d.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${d.missingArchiveEntries.join(", ")}`)),d.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${d.extraArchiveEntries.join(", ")}`)),d.mismatches.length&&console.log(s.gray(` Mismatches: ${d.mismatches.map(u=>u.path).join(", ")}`)),d.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${d.missingChecksumFiles.join(", ")}`));}(d.status==="failed"||d.status==="warning"&&n.strict)&&process.exit(1);}catch(d){console.log(s.red(`\u274C Workspace archive ${e} failed: ${d.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(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:g}=await import('./workspace-archive-EJIGYKSR.js');try{let m=await g({archivePathOrUrl:l,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){console.log(s.red(`\u274C Workspace ${t} failed: ${m.message}`)),process.exit(1);}}else if(t==="run"){let l=i(`run ${e||""}`.trim()),g=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)),g.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 p=Number(n.maxWorkers??""),d=Number.isFinite(p)?Math.max(1,Math.trunc(p)):void 0;if(m==="init"){let h=await Kr(l);h!==0&&process.exit(h);}let{runWorkspaceStage:f}=await import('./workspace-run-GCIQD73R.js'),u=await f({workspacePath:l,stage:m,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:d,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(u,null,2)),u.summary.exitCode!==0&&process.exit(u.summary.exitCode);}else if(t==="explain"||t==="why"){let l=i(t),{parseWorkspaceExplainTarget:g}=await import('./workspace-explain-contract-24RQ7KIW.js'),{buildWorkspaceExplain:m,writeWorkspaceExplainReport:p}=await import('./workspace-explain-3WSJLIJ6.js'),d=(e??o??"").trim();!d&&n.scope&&(d=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),d||(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=g(d);f||(console.log(s.red(`\u274C Invalid explain target: ${d}`)),process.exit(1));let u=await m({workspacePath:l,target:f}),h=n.write===true||a("--write"),k;if(h&&(k=await p(u,l,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify({...u,outputPath:k},null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${u.summary}`));for(let P of u.sections)console.log(s.bold(`
305
+ 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("--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=l=>{let m=(n.workspace?w.resolve(n.workspace):null)??a$6(process.cwd())??re(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 p=w.resolve(process.cwd()),d=w.resolve(m);return p!==d&&console.log(s.gray(`\u2139 Using workspace root ${m} for "${l}" (current directory: ${p}).`)),m},a=l=>process.argv.includes(l),c=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0};if((ni(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$1({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:l}=await import('./workspace-E554C5SM.js');await l();}else if(t==="model"){let l=i("model"),{buildWorkspaceModelCached:g,buildWorkspaceModelIncremental:m,writeWorkspaceModel:p}=await import('./workspace-model-YL7W3573.js'),d=n.incremental===true||a("--incremental"),f=n.cache===true||a("--cache")||d,u={workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c(),strict:n.strict===true||a("--strict")},h,k;if(d){let y=await m(u);h=y.model,k=y.mode;}else {let y=await g({...u,cache:f});h=y.model,k=y.cache;}let P;(n.write===true||a("--write"))&&(P=await p(h,l));let v=(n.strict===true||a("--strict"))&&h.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...h,...P?{outputPath:P}:{}},null,2)),v&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${h.workspace.name}`)),d?console.log(s.gray(` Build: ${k} (incremental)`)):f&&console.log(s.gray(` Cache: ${k}`)),console.log(s.gray(` Projects: ${h.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${h.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${h.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${h.identity.workspaceType}`)),console.log(s.gray(` Validation: ${h.validation?.status??"unknown"} (${h.validation?.errors??0} error, ${h.validation?.warnings??0} warning)`)),console.log(P?s.gray(` Written: ${P}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-model.json")),v&&process.exit(1);}else if(t==="agent-sync"){let l=i("agent-sync"),{syncWorkspaceAgentGrounding:g,parseAgentGroundingTargets:m}=await import('./workspace-agent-sync-BHE2V4KS.js'),p=n.strict===true||a("--strict"),d=n.write===true||a("--write"),f=a("--dry-run"),u=await g({workspacePath:l,scope:n.scope,agent:n.forAgent,write:d&&!f,dryRun:f,strict:p,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(u,null,2));else {console.log(s.green(`\u2714 Agent grounding ${d&&!f?"synced":"planned"}`)),console.log(s.gray(` Index: ${u.indexPath}`)),u.contextPath&&console.log(s.gray(` Context: ${u.contextPath}`)),u.blockers.length>0&&console.log(s.yellow(` Blockers: ${u.blockers.slice(0,3).join(" \xB7 ")}`));let h=d&&!f?u.writtenFiles:u.skippedFiles;if(h.length>0&&console.log(s.gray(` Files: ${h.join(", ")}`)),u.strictViolations.length>0)for(let k of u.strictViolations)console.log(s.red(`\u274C ${k}`));}p&&u.strictViolations.length>0&&process.exit(1);}else if(t==="context"){let l=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:g,writeWorkspaceAgentContext:m}=await import('./workspace-context-VJTXW3K4.js'),p=n.strict===true||a("--strict"),d=await g({workspacePath:l,agent:n.forAgent||o||e,scope:n.scope,includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c(),strict:false}),f,u;if((n.write===true||a("--write"))&&(f=await m(d,l),(n.agentSync===true||a("--agent-sync")||n.noAgentSync!==true)&&!a("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:v}=await import('./workspace-agent-sync-BHE2V4KS.js');if(u=await P({workspacePath:l,scope:n.scope,agent:d.agent,write:true,refreshContext:false,strict:p,preset:n.preset==="minimal"?"minimal":"enterprise",targets:v(n.target)}),n.json||console.log(s.gray(` Agent grounding synced: ${u.writtenFiles.length} file(s) updated`)),p&&u.strictViolations.length>0){for(let y of u.strictViolations)console.log(s.red(`\u274C ${y}`));process.exit(1);}}let h=p&&d.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...d,...f?{outputPath:f}:{},...u?{agentGroundingSync:u}:{}},null,2)),h&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${d.workspace.name}`)),console.log(s.gray(` Agent: ${d.agent}`)),console.log(s.gray(` Scope: ${d.scope.activeProject??d.scope.requested}`)),console.log(s.gray(` Projects included: ${d.projects.length}`)),console.log(s.gray(` Safe commands: ${d.safeCommands.length}`)),console.log(s.gray(` Validation: ${d.validation.status} (${d.validation.errors} error, ${d.validation.warnings} warning)`)),console.log(f?s.gray(` Written: ${f}`):s.gray(" Add --write to persist .rapidkit/reports/workspace-context-agent.json")),h){for(let k of d.validation.issues)console.log(s.red(`\u274C ${k.severity}:${k.code}:${k.target}`));process.exit(1);}}else if(t==="snapshot"){let l=i("snapshot"),{buildWorkspaceModelSnapshot:g,writeWorkspaceModelSnapshot:m}=await import('./workspace-intelligence-EC63CRVF.js'),p=await g({workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),d=await m(p,l);if(n.json){console.log(JSON.stringify({...p,outputPath:d},null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${p.model.workspace.name}`)),console.log(s.gray(` Hash: ${p.modelHash}`)),console.log(s.gray(` Projects: ${p.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${p.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${d}`));}else if(t==="diff"){let l=i("diff"),g=n.from||e;g||(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:p}=await import('./workspace-intelligence-EC63CRVF.js'),d=await m({workspacePath:l,fromPath:g,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),f=await p(d,l);if(n.json){console.log(JSON.stringify({...d,outputPath:f},null,2));return}let u=d.summary.changed?s.yellow:s.green;console.log(u(`\u2714 Workspace model diff: ${d.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${d.fromRef}`)),console.log(s.gray(` Added projects: ${d.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${d.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${d.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${d.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${d.summary.validationChanges}`)),d.git?.available&&console.log(s.gray(` Git: ${d.git.dirty?"dirty":"clean"} (${d.summary.gitChangedFiles} mapped change(s))`));for(let h of d.changes.slice(0,12))console.log(s.gray(` \u2022 ${h.type} ${h.target}: ${h.message}`));d.changes.length>12&&console.log(s.gray(` \u2026 ${d.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="impact"){let l=i("impact"),g=n.from||e;g||(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:p}=await import('./workspace-intelligence-EC63CRVF.js'),d=await m({workspacePath:l,fromPath:g,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),f=await p(d,l);if(n.json){console.log(JSON.stringify({...d,outputPath:f},null,2));return}let u=d.summary.risk==="critical"||d.summary.risk==="high"?s.red:d.summary.risk==="medium"?s.yellow:s.green;console.log(u(`\u2714 Workspace impact: ${d.summary.risk}`)),console.log(s.gray(` From: ${d.fromRef}`)),console.log(s.gray(` Affected projects: ${d.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${d.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${d.summary.recommendedCommands}`));for(let h of d.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${h.title}: ${h.summary}`));d.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${d.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${f}`));}else if(t==="verify"){let l=i("verify"),{buildWorkspaceVerify:g,writeWorkspaceVerify:m,evaluateWorkspaceVerifyGate:p}=await import('./workspace-verify-IAUHP6Y6.js'),d=await g({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()}),f=await m(d,l),u=p(d,{strict:n.strict===true||a("--strict")}),h=u.exitCode,{recordWorkspaceHistory:k,historyEntryFromVerify:P}=await import('./workspace-history-VPDADQKG.js');if(await k(l,P(d,u.passed)),n.json){console.log(JSON.stringify({...d,gate:u,outputPath:f},null,2)),h!==0&&process.exit(h);return}let v=d.summary.verdict==="ready"?s.green:d.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(v(`\u2714 Workspace verify: ${d.summary.verdict}`)),console.log(s.gray(` Freshness: ${d.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${d.impact.risk}`)),console.log(s.gray(` Steps: ${d.steps.length}`)),console.log(s.gray(` Passed ${d.summary.stepsPassed}, warn ${d.summary.stepsWarn}, failed ${d.summary.stepsFailed}, missing ${d.summary.stepsMissing}`));for(let y of d.steps.slice(0,10))console.log(s.gray(` \u2022 ${y.id}: ${y.status} \u2014 ${y.message}`));if(d.steps.length>10&&console.log(s.gray(` \u2026 ${d.steps.length-10} more step(s)`)),d.policyViolations.length>0){console.log(s.gray(` Policy (${d.policyMode}): ${d.policyViolations.length} violation(s)`));for(let y of d.policyViolations.slice(0,5)){let S=y.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${S} [${y.source}] ${y.code}: ${y.message}`);}}console.log(s.gray(` Gate (${u.mode}): ${u.passed?"passed":"blocked"}`));for(let y of u.reasons.slice(0,5))console.log(s.red(` \u2717 ${y}`));console.log(s.gray(` Written: ${f}`)),h!==0&&process.exit(h);}else if(t==="graph"){let l=i("graph"),{buildWorkspaceModel:g}=await import('./workspace-model-YL7W3573.js'),{buildGraphEmit:m,renderGraphDot:p,renderGraphMermaid:d,explainGraphNode:f}=await import('./workspace-graph-2A5THUCI.js'),h=(await g({workspacePath:l,includeAbsolutePaths:n.includePaths===true||a("--include-paths"),includeEvidence:n.includeEvidence===true||a("--include-evidence"),observableScanDepth:c()})).graph;h||(console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let k=(e||"emit").toLowerCase();if(k==="dot"){console.log(p(h));return}if(k==="mermaid"){console.log(d(h));return}if(k==="explain"){let v=(n.scope?.replace(/^project:/,"")||o||"").trim();v||(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 y=f(h,v);if(n.json){console.log(JSON.stringify(y,null,2)),y.found||process.exit(1);return}y.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${v}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${y.project}`)),y.centrality&&console.log(s.gray(` Centrality: fanIn ${y.centrality.fanIn}, fanOut ${y.centrality.fanOut}, reach ${y.centrality.reach}, betweenness ${y.centrality.betweenness}${y.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${y.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${y.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${y.transitiveDependents.length}`));for(let S of y.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${S.id} (d${S.distance}, via ${S.via??"\u2014"})`));return}let P=m(h);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 l=i("watch"),{runWorkspaceWatch:g}=await import('./workspace-watch-H2AETGFI.js'),m=n.once===true||a("--once"),p=n.json===true,d=new AbortController,f=()=>d.abort();process.once("SIGINT",f),process.once("SIGTERM",f),p||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await g({workspacePath:l,once:m,signal:d.signal,buildOptions:{workspacePath:l,observableScanDepth:c()},onProgress:u=>{p||console.error(s.gray(` ${u}`));},emit:u=>{if(p){console.log(JSON.stringify(u));return}if(u.kind==="ready"){console.log(s.gray(` Ready: ${u.graph.nodeCount} nodes, ${u.graph.edgeCount} edges (hash ${u.modelHash.slice(0,12)})`));return}if(u.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${u.error??"unknown error"}`));return}if(u.kind==="unchanged"){console.log(s.gray(` No structural change (${u.mode}, ${u.durationMs}ms)`));return}let h=[];u.changedProjects.length>0&&h.push(`changed: ${u.changedProjects.join(", ")}`),u.addedProjects.length>0&&h.push(`added: ${u.addedProjects.join(", ")}`),u.removedProjects.length>0&&h.push(`removed: ${u.removedProjects.join(", ")}`),u.graph.edgesAdded.length>0&&h.push(`+${u.graph.edgesAdded.length} edges`),u.graph.edgesRemoved.length>0&&h.push(`-${u.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${u.mode}, ${u.durationMs}ms): ${h.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",f),process.removeListener("SIGTERM",f),!p&&!m&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=i("sync"),{syncWorkspaceProjects:g}=await import('./workspace-E554C5SM.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${w.basename(l)}`));let m=await g(l,n.json===true);await Ue(l,{silent:n.json===true});let{readWorkspaceRegistrySummary:p}=await import('./workspace-registry-summary-X5WRUU3T.js'),d=await p(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:m,contractSynced:true,registrySummary:d},null,2));}else if(t==="registry"){let l=i("registry"),g=e||"status";g!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${g}`)),console.log(s.gray(" npx rapidkit workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:m,readWorkspaceRegistrySummary:p,resolveWorkspaceRegisteredProjects:d}=await import('./workspace-registry-summary-X5WRUU3T.js'),u=n.refresh===true||a("--refresh")||n.force===true||a("--force")?await m(l):await p(l)||await m(l);if(n.json){console.log(JSON.stringify(u,null,2));return}let h=await d(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${u.authority}`)),console.log(s.gray(` Projects: ${u.projectCount}`)),console.log(s.gray(` Summary: ${u.registrySummaryPath}`)),h.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=i("foundation"),g=e||"ensure";g!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${g}`)),console.log(s.gray(" npx rapidkit workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:m}=await import('./workspace-foundation-LISDH53T.js'),p=await m(l,{force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(p,null,2));return}p.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${p.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=i("policy"),g=await Ml(l,e,o,r);g!==0&&process.exit(g);}else if(t==="contract"){let l=i("contract"),{buildWorkspaceContractGraph:g,readWorkspaceContract:m,verifyWorkspaceContract:p,writeWorkspaceContract:d,WORKSPACE_CONTRACT_PATH:f}=await import('./workspace-contract-OO4GMENV.js'),u=e||"inspect",h=n.output;try{if(u==="init"){let k=await d({workspacePath:l,outputPath:h,force:n.force===true||a("--force")});if(n.json){console.log(JSON.stringify(k,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${k.contractPath}`)),console.log(s.gray(` Projects: ${k.contract.projects.length}`));return}if(u==="inspect"){let k=await m({workspacePath:l,contractPath:h});if(n.json){console.log(JSON.stringify(k,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${k.contractPath}`)),console.log(s.gray(` Workspace: ${k.contract.workspace.name}`)),console.log(s.gray(` Projects: ${k.contract.projects.length}`)),console.log(s.gray(` Schema: v${k.contract.schemaVersion}`));return}if(u==="verify"){let k=await p({workspacePath:l,contractPath:h,strict:n.strict===true||a("--strict")}),{writeWorkspaceContractVerifyEvidence:P}=await import('./workspace-contract-OO4GMENV.js'),v=await P({workspacePath:l,result:k});if(n.json)console.log(JSON.stringify({...k,evidencePath:v},null,2));else {let y=k.status==="passed"?s.green:s.red;console.log(y(`\u2714 Workspace contract verification ${k.status}: ${k.contractPath}`)),console.log(s.gray(` Projects: ${k.projectCount}`));for(let S of k.checks){let x=S.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${x} ${S.id}: ${S.message}`));}for(let S of k.violations)console.log(s.gray(` Violation: ${S}`));}(k.status==="failed"||k.status!=="passed"&&n.strict)&&process.exit(1);return}if(u==="graph"){let k=await g({workspacePath:l,contractPath:h});if(n.json){console.log(JSON.stringify(k,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${k.contractPath}`)),console.log(s.gray(` Workspace: ${k.graph.workspace.name}`)),console.log(s.gray(` Projects: ${k.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${k.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${k.graph.summary.eventEdges}`)),console.log(s.gray(` Ports: ${k.graph.summary.portCount}`));for(let P of k.graph.nodes){let v=P.ports.map(y=>`${y.name}:${y.port}`).join(", ")||"none";console.log(s.gray(` \u2022 ${P.id} (${P.runtime||"unknown"}${P.framework?`/${P.framework}`:""}) ports=${v}`));}for(let P of k.graph.edges){let v=P.type==="event"?`event:${P.label}`:P.label;console.log(s.gray(` ${P.from} -> ${P.to} [${v}]`));}return}console.log(s.red(`\u274C Unknown workspace contract action: ${u}`)),console.log(s.white(` npx rapidkit workspace contract init|inspect|verify|graph [--output ${f}]`)),process.exit(1);}catch(k){console.log(s.red(`\u274C Workspace contract ${u} failed: ${k.message}`)),process.exit(1);}}else if(t==="share"){let l=i("share"),g=n.output||e,{createWorkspaceShareBundle:m}=await import('./workspace-E554C5SM.js'),p=await m(l,{outputPath:g,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});console.log(s.green(`\u2714 Workspace share bundle exported: ${p}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=i("export"),{exportWorkspaceArchive:g}=await import('./workspace-archive-EJIGYKSR.js'),m=await g({workspacePath:l,outputPath:n.output||e,includeEnv:n.includeEnv===true||a("--include-env")});if(n.json){console.log(JSON.stringify(m,null,2));return}let p=(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: ${p} 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 l=o;l||(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:g,inspectWorkspaceArchive:m,verifyWorkspaceArchive:p}=await import('./workspace-archive-EJIGYKSR.js');try{if(e==="inspect"){let f=await m({archivePathOrUrl:l});if(n.json){console.log(JSON.stringify(f,null,2));return}let u=(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: ${u} MB`));return}if(e==="doctor"){let f=await g({archivePathOrUrl:l,strict:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(f,null,2));else {let u=f.status==="passed"?s.green:f.status==="warning"?s.yellow:s.red;console.log(u(`\u2714 Workspace archive doctor ${f.status}: ${f.archivePath}`)),console.log(s.gray(` Workspace: ${f.workspaceName}`)),console.log(s.gray(` Files: ${f.fileCount}`));for(let h of f.checks){let k=h.status==="passed"?"\u2714":h.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${k} ${h.id}: ${h.message}`));}for(let h of f.recommendedActions)console.log(s.gray(` Next: ${h}`));}(f.status==="failed"||f.status==="warning"&&n.strict)&&process.exit(1);return}let d=await p({archivePathOrUrl:l,requireChecksums:n.strict===true||a("--strict")});if(n.json)console.log(JSON.stringify(d,null,2));else if(d.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${d.archivePath}`)),console.log(s.gray(` Files: ${d.verifiedFiles}/${d.fileCount}`));else {let f=d.status==="failed"?s.red:s.yellow;console.log(f(`\u274C Workspace archive verification ${d.status}: ${d.archivePath}`)),d.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${d.missingArchiveEntries.join(", ")}`)),d.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${d.extraArchiveEntries.join(", ")}`)),d.mismatches.length&&console.log(s.gray(` Mismatches: ${d.mismatches.map(u=>u.path).join(", ")}`)),d.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${d.missingChecksumFiles.join(", ")}`));}(d.status==="failed"||d.status==="warning"&&n.strict)&&process.exit(1);}catch(d){console.log(s.red(`\u274C Workspace archive ${e} failed: ${d.message}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(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:g}=await import('./workspace-archive-EJIGYKSR.js');try{let m=await g({archivePathOrUrl:l,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){console.log(s.red(`\u274C Workspace ${t} failed: ${m.message}`)),process.exit(1);}}else if(t==="run"){let l=i(`run ${e||""}`.trim()),g=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)),g.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 p=Number(n.maxWorkers??""),d=Number.isFinite(p)?Math.max(1,Math.trunc(p)):void 0;if(m==="init"){let h=await Kr(l);h!==0&&process.exit(h);}let{runWorkspaceStage:f}=await import('./workspace-run-F5FADRY5.js'),u=await f({workspacePath:l,stage:m,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:d,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(u,null,2)),u.summary.exitCode!==0&&process.exit(u.summary.exitCode);}else if(t==="explain"||t==="why"){let l=i(t),{parseWorkspaceExplainTarget:g}=await import('./workspace-explain-contract-24RQ7KIW.js'),{buildWorkspaceExplain:m,writeWorkspaceExplainReport:p}=await import('./workspace-explain-XJ22ZXJY.js'),d=(e??o??"").trim();!d&&n.scope&&(d=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),d||(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=g(d);f||(console.log(s.red(`\u274C Invalid explain target: ${d}`)),process.exit(1));let u=await m({workspacePath:l,target:f}),h=n.write===true||a("--write"),k;if(h&&(k=await p(u,l,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify({...u,outputPath:k},null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${u.summary}`));for(let P of u.sections)console.log(s.bold(`
306
306
  ${P.title}`)),console.log(P.body);k&&console.log(s.gray(`
307
- Written: ${k}`));}else if(t==="trace"){let l=i("trace"),g=n.from||e;g||(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:p,writeWorkspaceExplainReport:d}=await import('./workspace-explain-3WSJLIJ6.js'),f=m(g);(!f||f.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${g}`)),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 u=await p({workspacePath:l,target:f}),h=n.write===true||a("--write"),k;if(h&&(k=await d(u,l,"trace")),n.json){console.log(JSON.stringify({...u,outputPath:k},null,2));return}console.log(s.green(`\u2714 Workspace trace: ${u.summary}`));for(let P of u.sections)console.log(s.bold(`
307
+ Written: ${k}`));}else if(t==="trace"){let l=i("trace"),g=n.from||e;g||(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:p,writeWorkspaceExplainReport:d}=await import('./workspace-explain-XJ22ZXJY.js'),f=m(g);(!f||f.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${g}`)),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 u=await p({workspacePath:l,target:f}),h=n.write===true||a("--write"),k;if(h&&(k=await d(u,l,"trace")),n.json){console.log(JSON.stringify({...u,outputPath:k},null,2));return}console.log(s.green(`\u2714 Workspace trace: ${u.summary}`));for(let P of u.sections)console.log(s.bold(`
308
308
  ${P.title}`)),console.log(P.body);k&&console.log(s.gray(`
309
- Written: ${k}`));}else if(t==="feedback"){let l=i("feedback"),g=(e||"record").toLowerCase();g!=="record"&&(console.log(s.red(`Unknown feedback action: ${g}`)),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:p,readStdinAll:d}=await import('./workspace-feedback-65NR3EZH.js'),f=await d(),u=p(f);u||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let h=await m({workspacePath:l,payload:u});n.json?console.log(JSON.stringify(h,null,2)):h.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${h.historyPath}`))):console.log(s.red(`\u274C ${h.error??"Failed to record feedback"}`)),h.ok||process.exit(1);}else if(t==="mcp"){let l=i("mcp"),g=(e||"serve").toLowerCase();g!=="serve"&&(console.log(s.red(`Unknown mcp action: ${g}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:m}=await import('./workspace-mcp-serve-RFYDCA2L.js');n.json||console.error(s.gray("\u2139 RapidKit MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await m({workspacePath:l});}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:
309
+ Written: ${k}`));}else if(t==="feedback"){let l=i("feedback"),g=(e||"record").toLowerCase();g!=="record"&&(console.log(s.red(`Unknown feedback action: ${g}`)),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:p,readStdinAll:d}=await import('./workspace-feedback-65NR3EZH.js'),f=await d(),u=p(f);u||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let h=await m({workspacePath:l,payload:u});n.json?console.log(JSON.stringify(h,null,2)):h.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${h.historyPath}`))):console.log(s.red(`\u274C ${h.error??"Failed to record feedback"}`)),h.ok||process.exit(1);}else if(t==="mcp"){let l=i("mcp"),g=(e||"serve").toLowerCase();g!=="serve"&&(console.log(s.red(`Unknown mcp action: ${g}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:m}=await import('./workspace-mcp-serve-KOM2V35Q.js');n.json||console.error(s.gray("\u2139 RapidKit MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await m({workspacePath:l});}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:
310
310
  npx rapidkit init | npx rapidkit workspace init | npx rapidkit workspace run init
311
- `));let l=i("init"),g=Number(n.maxWorkers??""),m=Number.isFinite(g)?Math.max(1,Math.trunc(g)):void 0,p=await Kr(l);p!==0&&process.exit(p);let{runWorkspaceStage:d}=await import('./workspace-run-GCIQD73R.js'),f=await d({workspacePath:l,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:m,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(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: ${Eo.join(", ")}`)),process.exit(1);});function xt(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function Qi(){let t=b$1()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev";console.log(s.white(`Usage:
311
+ `));let l=i("init"),g=Number(n.maxWorkers??""),m=Number.isFinite(g)?Math.max(1,Math.trunc(g)):void 0,p=await Kr(l);p!==0&&process.exit(p);let{runWorkspaceStage:d}=await import('./workspace-run-F5FADRY5.js'),f=await d({workspacePath:l,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:m,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(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: ${Eo.join(", ")}`)),process.exit(1);});function xt(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function Qi(){let t=b$1()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev";console.log(s.white(`Usage:
312
312
  `)),console.log(s.cyan(` npx rapidkit <workspace-name> [options]
313
313
  `)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems
314
314
  `)),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.