workspai 0.53.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/contracts/artifact-remediation-plan.v1.json +22 -3
  2. package/contracts/doctor-project-evidence.v1.json +21 -2
  3. package/contracts/doctor-remediation-plan.v1.json +22 -3
  4. package/contracts/doctor-workspace-evidence.v1.json +21 -2
  5. package/contracts/extension-cli-compatibility.v1.json +1 -1
  6. package/contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json +52 -13
  7. package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +56 -6
  8. package/contracts/workspace-repair-capabilities.v1.json +48 -0
  9. package/dist/{artifact-remediation-plan-CJSPCMWA.js → artifact-remediation-plan-A2PRCUNA.js} +1 -1
  10. package/dist/autopilot-release-63XHNGR6.js +1 -0
  11. package/dist/{chunk-T6JI7GYZ.js → chunk-4HTSZGEU.js} +50 -50
  12. package/dist/{chunk-HOVJUP7K.js → chunk-BPACED27.js} +1 -1
  13. package/dist/{chunk-E5YYVFM2.js → chunk-I5CGTCP5.js} +1 -1
  14. package/dist/chunk-IQQWQ3II.js +3 -0
  15. package/dist/chunk-UFOCUHG3.js +1 -0
  16. package/dist/{chunk-27AXFTKW.js → chunk-ZLYEYHMH.js} +1 -1
  17. package/dist/{doctor-KNIYGDM7.js → doctor-HJ3O7SAO.js} +1 -1
  18. package/dist/index.js +7 -7
  19. package/dist/{pipeline-PVCLAQDI.js → pipeline-TDQK5QYQ.js} +1 -1
  20. package/dist/{verified-goal-MCSNMA3P.js → verified-goal-S2PEBJUV.js} +1 -1
  21. package/dist/{workspace-intelligence-runner-JNCQLUH7.js → workspace-intelligence-runner-EQFLRVRL.js} +1 -1
  22. package/dist/workspace-repair-engine-OZXOXVVV.js +3 -0
  23. package/dist/workspace-run-VPXRRHDK.js +1 -0
  24. package/docs/doctor-command.md +6 -0
  25. package/docs/workspace-repair-engine.md +17 -8
  26. package/package.json +1 -1
  27. package/dist/autopilot-release-LZWNQQLY.js +0 -1
  28. package/dist/chunk-SUV7Y2FH.js +0 -3
  29. package/dist/chunk-ZTKIBREF.js +0 -1
  30. package/dist/workspace-repair-engine-SRWECKZO.js +0 -3
  31. package/dist/workspace-run-3U77TMKX.js +0 -1
  32. /package/dist/{chunk-USMLRNZ7.js → chunk-3LVJBH7V.js} +0 -0
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {c as c$9,b as b$h,a as a$q}from'./chunk-NYHVCFBT.js';import {a as a$m}from'./chunk-ICGWHIMK.js';import {a as a$k,f as f$4,d as d$c}from'./chunk-E5YYVFM2.js';import {a as a$l}from'./chunk-5XDPQ3CB.js';import {a as a$t}from'./chunk-FB7SCXAZ.js';import {c as c$1,b as b$7,a as a$A}from'./chunk-FPJNWPKU.js';import {b as b$5,a as a$7}from'./chunk-RMXXK64P.js';import {a as a$j,d as d$d}from'./chunk-KFKZOPZC.js';import {b as b$9,d as d$7,a as a$6,c as c$5,f as f$7,e as e$8}from'./chunk-T3GJ7YVG.js';import {b as b$1,c,d,j,h as h$2,i as i$1,a as a$i}from'./chunk-M5ICGR55.js';import {a,b as b$2}from'./chunk-KVSYBHUR.js';import {c as c$4,d as d$6,e as e$4,b as b$f,g as g$3}from'./chunk-HRN5J6PW.js';import {a as a$y,b as b$i}from'./chunk-QZ7PNMVP.js';import {a as a$n}from'./chunk-EBKYSDCX.js';import {a as a$p}from'./chunk-GDU7VP6G.js';import {a as a$r}from'./chunk-7T4TSV5C.js';import {a as a$s}from'./chunk-PS5F4DCT.js';import {d as d$3,c as c$2,p as p$2,b as b$j,a as a$z}from'./chunk-HY3RMPW5.js';import {b as b$g,a as a$o,c as c$8}from'./chunk-OUBBBC7T.js';import {b as b$b,a as a$a}from'./chunk-THIOE2PB.js';import {e as e$2,d as d$4}from'./chunk-AMB42V2F.js';import {a as a$v}from'./chunk-P7K5RHJC.js';import {a as a$x}from'./chunk-RA24WQLF.js';import {c as c$a,a as a$w}from'./chunk-XVRJVKOX.js';import {f as f$5}from'./chunk-S7Z4DP3P.js';import {f as f$3}from'./chunk-H7P7SSUW.js';import {b as b$6,a as a$2,d as d$2}from'./chunk-FQLB4BIC.js';import {a as a$h}from'./chunk-2FJW6GSW.js';import {a as a$c}from'./chunk-3DONU3DU.js';import {a as a$8}from'./chunk-A5FBGRJA.js';import {a as a$u}from'./chunk-7KKP7RNB.js';import {b as b$d,a as a$e,c as c$6,d as d$a,j as j$4,g as g$5,e as e$7}from'./chunk-7AR5PDLD.js';import {h as h$1,a as a$1,l as l$1,k as k$1,m as m$2,q as q$1,j as j$5,p as p$4,n as n$1,s as s$3,r as r$2}from'./chunk-WJVB6SSD.js';import {a as a$g}from'./chunk-27UR373Z.js';import {c as c$3,g as g$1,b as b$e,l as l$2,e as e$6,a as a$C}from'./chunk-MQ73VS4E.js';import {b as b$3,d as d$1,a as a$4,e as e$3,w,i as i$2,p as p$3,j as j$2,l,m as m$1,n,k,s as s$2,o as o$2,y,q as q$2,h as h$4,r as r$1,x,z,t as t$1,v as v$1,f as f$6,u as u$1}from'./chunk-6HJJHEL6.js';export{r as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-6HJJHEL6.js';import {j as j$3}from'./chunk-2PY65U6X.js';import {a as a$f}from'./chunk-GR6442P7.js';import {d as d$8,a as a$b,b as b$c}from'./chunk-WIO6L24E.js';import {b as b$l}from'./chunk-BYVTHIC3.js';import {a as a$5}from'./chunk-AFIFZTOY.js';import {g,e as e$1,a as a$3,b as b$8,d as d$9,c as c$7,h as h$5}from'./chunk-44VJHNZB.js';import {i,f,h,d as d$5,b as b$a,g as g$4}from'./chunk-VRW6KXNK.js';import {a as a$d}from'./chunk-TQEMLBAG.js';import {c as c$b}from'./chunk-RO73VVHW.js';import {f as f$1,e,a as a$9,d as d$b,i as i$4,g as g$6}from'./chunk-3GRKUP5W.js';import {m,f as f$2,t,o as o$1,v,p,j as j$1,s as s$1,u,i as i$3,g as g$2,h as h$3,e as e$5,a as a$B,b as b$k,k as k$2,n as n$2}from'./chunk-MOSXTVPU.js';import {o,b as b$4,p as p$1,q,r,m as m$3,i as i$5,j as j$6,e as e$9,g as g$7,c as c$c}from'./chunk-RJIYCDVC.js';import {c as c$d}from'./chunk-2FIX2MDC.js';import {Command,Option}from'commander';import s from'chalk';import b from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Mu from'vm';import*as O from'fs-extra';import O__default from'fs-extra';import A,{existsSync,promises,createWriteStream}from'fs';import $n,{tmpdir,homedir}from'os';import {execa}from'execa';import Pt,{randomUUID,createVerify,createHash,createHmac}from'crypto';import ul from'http';import ml from'https';function op(){return j$6()}function np(t,e){return t==="py"?["-3",...e]:e}function sp(t){return typeof t=="object"&&t!==null}async function ap(t,e,r,o=c$d()){try{let n=await execa(t,e,{cwd:r,timeout:o,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function ip(t,e){let r=["-m","rapidkit",...t],o=op();for(let n of o){let a=await ap(n,np(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return sp(c)?{ok:true,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr,data:c}:{ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}catch{return {ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}}return {ok:false}}async function Ri(t,e){let r=await ip(["project","detect","--path",t,"--json"],e);return !r.ok||!r.data||r.data.schema_version!==1?{ok:false,command:r.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:r}var Ai=new Set(["create"]),Rn=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),cp=new Set(["pip","poetry","venv","pipx","python"]);function _i(t){return typeof t=="string"&&cp.has(t)}function An(t,e){return !t||Ai.has(t)?false:a$9.has(t)?true:e?.has(t)??false}function _n(t,e=null){let r=t[0];return !r||r.startsWith("-")||Ai.has(r)||r==="init"?false:An(r,e)?true:t.filter(n=>!n.startsWith("-")&&!Rn.has(n)).length<=1?false:t.length>1}var Ut=b.join($n.homedir(),".workspairc.json"),lp=b.join($n.homedir(),".rapidkitrc.json"),pp=b.join($n.homedir(),".rapidkit","config.json");function In(t){try{if(!A.existsSync(t))return {};let e=A.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Ii(t){if(process.platform!=="win32")try{A.chmodSync(t,384);}catch{}}function Ht(){let t=In(Ut),e=In(lp),r=In(pp);return A.existsSync(Ut)&&Ii(Ut),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function fo(t){let r={...Ht(),...t};A.writeFileSync(Ut,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Ii(Ut);}function Cr(){return process.env.OPENAI_API_KEY||Ht().openaiApiKey||null}function Nn(){return Ht().aiEnabled!==false}function Tn(){return Ut}function Oi(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async r=>{let o=r.key;o?o.startsWith("sk-")||(console.log(s.red(`
2
+ import {c as c$9,b as b$h,a as a$q}from'./chunk-NYHVCFBT.js';import {a as a$m}from'./chunk-ICGWHIMK.js';import {a as a$k,f as f$4,d as d$c}from'./chunk-I5CGTCP5.js';import {a as a$l}from'./chunk-5XDPQ3CB.js';import {a as a$t}from'./chunk-FB7SCXAZ.js';import {c as c$1,b as b$7,a as a$A}from'./chunk-FPJNWPKU.js';import {b as b$5,a as a$7}from'./chunk-RMXXK64P.js';import {a as a$j,d as d$d}from'./chunk-KFKZOPZC.js';import {b as b$9,d as d$7,a as a$6,c as c$5,f as f$7,e as e$8}from'./chunk-T3GJ7YVG.js';import {b as b$1,c,d,j,h as h$2,i as i$1,a as a$i}from'./chunk-M5ICGR55.js';import {a,b as b$2}from'./chunk-KVSYBHUR.js';import {c as c$4,d as d$6,e as e$4,b as b$f,g as g$3}from'./chunk-HRN5J6PW.js';import {a as a$y,b as b$i}from'./chunk-QZ7PNMVP.js';import {a as a$n}from'./chunk-EBKYSDCX.js';import {a as a$p}from'./chunk-GDU7VP6G.js';import {a as a$r}from'./chunk-7T4TSV5C.js';import {a as a$s}from'./chunk-PS5F4DCT.js';import {d as d$3,c as c$2,p as p$2,b as b$j,a as a$z}from'./chunk-HY3RMPW5.js';import {b as b$g,a as a$o,c as c$8}from'./chunk-OUBBBC7T.js';import {b as b$b,a as a$a}from'./chunk-THIOE2PB.js';import {e as e$2,d as d$4}from'./chunk-AMB42V2F.js';import {a as a$v}from'./chunk-P7K5RHJC.js';import {a as a$x}from'./chunk-RA24WQLF.js';import {c as c$a,a as a$w}from'./chunk-XVRJVKOX.js';import {f as f$5}from'./chunk-S7Z4DP3P.js';import {f as f$3}from'./chunk-H7P7SSUW.js';import {b as b$6,a as a$2,d as d$2}from'./chunk-FQLB4BIC.js';import {a as a$h}from'./chunk-2FJW6GSW.js';import {a as a$c}from'./chunk-3DONU3DU.js';import {a as a$8}from'./chunk-A5FBGRJA.js';import {a as a$u}from'./chunk-7KKP7RNB.js';import {b as b$d,a as a$e,c as c$6,d as d$a,j as j$4,g as g$5,e as e$7}from'./chunk-7AR5PDLD.js';import {h as h$1,a as a$1,l as l$1,k as k$1,m as m$2,q as q$1,j as j$5,p as p$4,n as n$1,s as s$3,r as r$2}from'./chunk-WJVB6SSD.js';import {a as a$g}from'./chunk-27UR373Z.js';import {c as c$3,g as g$1,b as b$e,l as l$2,e as e$6,a as a$C}from'./chunk-MQ73VS4E.js';import {b as b$3,d as d$1,a as a$4,e as e$3,w,i as i$2,p as p$3,j as j$2,l,m as m$1,n,k,s as s$2,o as o$2,y,q as q$2,h as h$4,r as r$1,x,z,t as t$1,v as v$1,f as f$6,u as u$1}from'./chunk-6HJJHEL6.js';export{r as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-6HJJHEL6.js';import {j as j$3}from'./chunk-2PY65U6X.js';import {a as a$f}from'./chunk-GR6442P7.js';import {d as d$8,a as a$b,b as b$c}from'./chunk-WIO6L24E.js';import {b as b$l}from'./chunk-BYVTHIC3.js';import {a as a$5}from'./chunk-AFIFZTOY.js';import {g,e as e$1,a as a$3,b as b$8,d as d$9,c as c$7,h as h$5}from'./chunk-44VJHNZB.js';import {i,f,h,d as d$5,b as b$a,g as g$4}from'./chunk-VRW6KXNK.js';import {a as a$d}from'./chunk-TQEMLBAG.js';import {c as c$b}from'./chunk-RO73VVHW.js';import {f as f$1,e,a as a$9,d as d$b,i as i$4,g as g$6}from'./chunk-3GRKUP5W.js';import {m,f as f$2,t,o as o$1,v,p,j as j$1,s as s$1,u,i as i$3,g as g$2,h as h$3,e as e$5,a as a$B,b as b$k,k as k$2,n as n$2}from'./chunk-MOSXTVPU.js';import {o,b as b$4,p as p$1,q,r,m as m$3,i as i$5,j as j$6,e as e$9,g as g$7,c as c$c}from'./chunk-RJIYCDVC.js';import {c as c$d}from'./chunk-2FIX2MDC.js';import {Command,Option}from'commander';import s from'chalk';import b from'path';import {fileURLToPath}from'url';import {spawn,spawnSync}from'child_process';import Mu from'vm';import*as O from'fs-extra';import O__default from'fs-extra';import A,{existsSync,promises,createWriteStream}from'fs';import $n,{tmpdir,homedir}from'os';import {execa}from'execa';import Pt,{randomUUID,createVerify,createHash,createHmac}from'crypto';import ul from'http';import ml from'https';function op(){return j$6()}function np(t,e){return t==="py"?["-3",...e]:e}function sp(t){return typeof t=="object"&&t!==null}async function ap(t,e,r,o=c$d()){try{let n=await execa(t,e,{cwd:r,timeout:o,reject:false,stdio:"pipe"});return {ok:n.exitCode===0,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch(n){return {ok:false,exitCode:void 0,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}async function ip(t,e){let r=["-m","rapidkit",...t],o=op();for(let n of o){let a=await ap(n,np(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return sp(c)?{ok:true,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr,data:c}:{ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}catch{return {ok:false,command:n,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}}return {ok:false}}async function Ri(t,e){let r=await ip(["project","detect","--path",t,"--json"],e);return !r.ok||!r.data||r.data.schema_version!==1?{ok:false,command:r.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}:r}var Ai=new Set(["create"]),Rn=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),cp=new Set(["pip","poetry","venv","pipx","python"]);function _i(t){return typeof t=="string"&&cp.has(t)}function An(t,e){return !t||Ai.has(t)?false:a$9.has(t)?true:e?.has(t)??false}function _n(t,e=null){let r=t[0];return !r||r.startsWith("-")||Ai.has(r)||r==="init"?false:An(r,e)?true:t.filter(n=>!n.startsWith("-")&&!Rn.has(n)).length<=1?false:t.length>1}var Ut=b.join($n.homedir(),".workspairc.json"),lp=b.join($n.homedir(),".rapidkitrc.json"),pp=b.join($n.homedir(),".rapidkit","config.json");function In(t){try{if(!A.existsSync(t))return {};let e=A.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Ii(t){if(process.platform!=="win32")try{A.chmodSync(t,384);}catch{}}function Ht(){let t=In(Ut),e=In(lp),r=In(pp);return A.existsSync(Ut)&&Ii(Ut),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function fo(t){let r={...Ht(),...t};A.writeFileSync(Ut,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Ii(Ut);}function Cr(){return process.env.OPENAI_API_KEY||Ht().openaiApiKey||null}function Nn(){return Ht().aiEnabled!==false}function Tn(){return Ut}function Oi(t){let e=t.command("config").description("Configure Workspai settings");e.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async r=>{let o=r.key;o?o.startsWith("sk-")||(console.log(s.red(`
3
3
  \u274C Invalid API key format (should start with sk-)
4
4
  `)),process.exit(1)):o=(await b$2([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:a=>a?a.startsWith("sk-")?a.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,fo({openaiApiKey:o}),console.log(s.green(`
5
5
  \u2705 OpenAI API key saved successfully!
@@ -323,7 +323,7 @@ Hints:`));for(let w of p$1)console.log(s.gray(`- ${w}`));}return c.exitCode}func
323
323
  `),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Config: ${m?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${k?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${w}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let m=await ms(o,{ciMode:true,offlineMode:e==="verify",forceRun:true}),k=m.checks.filter(x=>x.status==="failed"),w=m.checks.some(x=>x.id.startsWith("mirror.verify.")&&x.status==="failed");if(e==="verify"&&w){let x={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await g(),details:m.details,checks:m.checks};if(await d(x),r)return process.stdout.write(`${JSON.stringify(x,null,2)}
324
324
  `),1;console.log(s.red("\u274C Mirror verify failed."));for(let l of m.checks.filter(P=>P.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${l.id}: ${l.message}`));return 1}if(k.length>0){let x={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await g(),details:m.details,checks:m.checks};if(await d(x),r)return process.stdout.write(`${JSON.stringify(x,null,2)}
325
325
  `),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${k.length} issue(s).`));for(let l of k)console.log(s.gray(`- ${l.id}: ${l.message}`));return 1}let j={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:await g(),details:m.details,checks:m.checks};return await d(j),r?(process.stdout.write(`${JSON.stringify(j,null,2)}
326
- `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${m.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${m.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${m.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Js(t){let e$1=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$1>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await Zl(r,async()=>{let n$1=Pe(r),a=Ke("python",{runCommandInCwd:je,runCoreRapidkit:e}),i=Ke("dotnet",{runCommandInCwd:je,runCoreRapidkit:e}),c=Ke("rust",{runCommandInCwd:je,runCoreRapidkit:e}),p=Ke("php",{runCommandInCwd:je,runCoreRapidkit:e}),d=t.slice(1).filter(l=>!l.startsWith("-"));if(d.length>0){let l$1=b.resolve(r,d[0]),P=i$2(l$1),u=await Wt(l$1);return j$2(P,l$1)||u==="go"?await Ss(l$1):l(P,l$1)||u==="java"?await ht("init",l$1):m$1(P,l$1)||u==="dotnet"?Q(await i.initProject(l$1)):k(P,l$1)||u==="node"?await Cs(l$1):n(P,l$1)||u==="python"?await bs(l$1,a):u==="rust"?Q(await c.initProject(l$1)):u==="php"?Q(await p.initProject(l$1)):await e(t,{cwd:r})}let g=i$2(r),m=!!Pe(r)&&r===Pe(r);if(!m&&j$2(g,r))return await Ss(r);let k$1=await Wt(r);if(!m&&(l(g,r)||k$1==="java"))return await ht("init",r);if(!m&&(m$1(g,r)||k$1==="dotnet"))return Q(await i.initProject(r));if(!m&&(k(g,r)||k$1==="node"))return await Cs(r);if(!m&&(n(g,r)||k$1==="python"))return await bs(r,a);if(!m&&k$1==="rust")return Q(await c.initProject(r));if(!m&&k$1==="php")return Q(await p.initProject(r));let w=n$1||Pe(r),j=ql(r),x=j?b.dirname(b.dirname(j)):null;if(x&&x!==w){let l$1=i$2(x),P=await Wt(x);return j$2(l$1,x)||P==="go"?await Ss(x):l(l$1,x)||P==="java"?await ht("init",x):m$1(l$1,x)||P==="dotnet"?Q(await i.initProject(x)):k(l$1,x)||P==="node"?await Cs(x):n(l$1,x)||P==="python"?await bs(x,a):P==="rust"?Q(await c.initProject(x)):P==="php"?Q(await p.initProject(x)):await e(["init"],{cwd:x})}if(w&&r===w){console.log(s.yellow("\u26A0\uFE0F Running `npx workspai init` at workspace root.")),console.log(s.gray(" Root `init`, `workspace init`, and `workspace run init` now share the same full-init flow:\n workspace-profile dependencies first, then project dependency initialization.\n"));let l=await Ls(w);if(l!==0)return l;let{runWorkspaceStage:P}=await import('./workspace-run-3U77TMKX.js');return (await P({workspacePath:w,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!w){let l=await b$1(),P=k$2(),{name:u}=vm(P);await O__default.ensureDir(P);let{createProject:h}=await import('./create-R6A7EHQZ.js');return await h(u,{yes:true,userConfig:l,parentDirectory:P}),0}return await e(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e$1>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$1;}}async function Kl(t){let e=Pe(t);if(!e)return [];let r="warn";try{let p=s$1(e,"policies.yml").find(m=>A.existsSync(m));if(!p)return [];let d=await A.promises.readFile(p,"utf-8");(d.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??d.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n$1=s$1(e,"toolchain.lock").find(p=>A.existsSync(p));if(!n$1||!A.existsSync(n$1))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await A.promises.readFile(n$1,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=i$2(t);j$2(c,t)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):k(c,t)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):l(c,t)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):m$1(c,t)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):n(c,t)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let p=s$1(e,"workspace.json").find(w=>A.existsSync(w));if(!p)throw new Error("workspace manifest missing");let g=JSON.parse(await A.promises.readFile(p,"utf-8")).profile??"",m=j$3(t,c),k=St({profile:g,runtime:m.runtime,subjectLabel:b.basename(t),mode:"strict"});k.ok||o.push(`${k.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function Em(){let t$1=async h=>{if(!b$4()||!h.toLowerCase().endsWith(".cmd"))return false;try{let v=(await O__default.readFile(h,"utf8")).replace(/\r\n/g,`
326
+ `),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${m.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${m.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${m.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function Js(t){let e$1=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e$1>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await Zl(r,async()=>{let n$1=Pe(r),a=Ke("python",{runCommandInCwd:je,runCoreRapidkit:e}),i=Ke("dotnet",{runCommandInCwd:je,runCoreRapidkit:e}),c=Ke("rust",{runCommandInCwd:je,runCoreRapidkit:e}),p=Ke("php",{runCommandInCwd:je,runCoreRapidkit:e}),d=t.slice(1).filter(l=>!l.startsWith("-"));if(d.length>0){let l$1=b.resolve(r,d[0]),P=i$2(l$1),u=await Wt(l$1);return j$2(P,l$1)||u==="go"?await Ss(l$1):l(P,l$1)||u==="java"?await ht("init",l$1):m$1(P,l$1)||u==="dotnet"?Q(await i.initProject(l$1)):k(P,l$1)||u==="node"?await Cs(l$1):n(P,l$1)||u==="python"?await bs(l$1,a):u==="rust"?Q(await c.initProject(l$1)):u==="php"?Q(await p.initProject(l$1)):await e(t,{cwd:r})}let g=i$2(r),m=!!Pe(r)&&r===Pe(r);if(!m&&j$2(g,r))return await Ss(r);let k$1=await Wt(r);if(!m&&(l(g,r)||k$1==="java"))return await ht("init",r);if(!m&&(m$1(g,r)||k$1==="dotnet"))return Q(await i.initProject(r));if(!m&&(k(g,r)||k$1==="node"))return await Cs(r);if(!m&&(n(g,r)||k$1==="python"))return await bs(r,a);if(!m&&k$1==="rust")return Q(await c.initProject(r));if(!m&&k$1==="php")return Q(await p.initProject(r));let w=n$1||Pe(r),j=ql(r),x=j?b.dirname(b.dirname(j)):null;if(x&&x!==w){let l$1=i$2(x),P=await Wt(x);return j$2(l$1,x)||P==="go"?await Ss(x):l(l$1,x)||P==="java"?await ht("init",x):m$1(l$1,x)||P==="dotnet"?Q(await i.initProject(x)):k(l$1,x)||P==="node"?await Cs(x):n(l$1,x)||P==="python"?await bs(x,a):P==="rust"?Q(await c.initProject(x)):P==="php"?Q(await p.initProject(x)):await e(["init"],{cwd:x})}if(w&&r===w){console.log(s.yellow("\u26A0\uFE0F Running `npx workspai init` at workspace root.")),console.log(s.gray(" Root `init`, `workspace init`, and `workspace run init` now share the same full-init flow:\n workspace-profile dependencies first, then project dependency initialization.\n"));let l=await Ls(w);if(l!==0)return l;let{runWorkspaceStage:P}=await import('./workspace-run-VPXRRHDK.js');return (await P({workspacePath:w,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:false,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!w){let l=await b$1(),P=k$2(),{name:u}=vm(P);await O__default.ensureDir(P);let{createProject:h}=await import('./create-R6A7EHQZ.js');return await h(u,{yes:true,userConfig:l,parentDirectory:P}),0}return await e(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e$1>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e$1;}}async function Kl(t){let e=Pe(t);if(!e)return [];let r="warn";try{let p=s$1(e,"policies.yml").find(m=>A.existsSync(m));if(!p)return [];let d=await A.promises.readFile(p,"utf-8");(d.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??d.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n$1=s$1(e,"toolchain.lock").find(p=>A.existsSync(p));if(!n$1||!A.existsSync(n$1))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await A.promises.readFile(n$1,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=i$2(t);j$2(c,t)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):k(c,t)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):l(c,t)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):m$1(c,t)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):n(c,t)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let p=s$1(e,"workspace.json").find(w=>A.existsSync(w));if(!p)throw new Error("workspace manifest missing");let g=JSON.parse(await A.promises.readFile(p,"utf-8")).profile??"",m=j$3(t,c),k=St({profile:g,runtime:m.runtime,subjectLabel:b.basename(t),mode:"strict"});k.ok||o.push(`${k.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function Em(){let t$1=async h=>{if(!b$4()||!h.toLowerCase().endsWith(".cmd"))return false;try{let v=(await O__default.readFile(h,"utf8")).replace(/\r\n/g,`
327
327
  `).toLowerCase(),C=v.includes("\\.rapidkit\\rapidkit"),R=v.includes("\\.rapidkit\\rapidkit.cmd")||v.includes("\\.rapidkit\\rapidkit.exe")||v.includes("\\.venv\\scripts\\rapidkit.exe");return C&&!R}catch{return false}},e$1=process.cwd(),r=process.argv.slice(2),o=r[0],n$1=o==="init",a=new Set(q$2),i=!o||o==="--help"||o==="-h"||o==="help",c=Ye(e$1),p=t(e$1,"project.json").some(h=>A.existsSync(h)),d=i$2(e$1),g=await Wt(e$1),m=j$2(d,e$1)||k(d,e$1)||n(d,e$1)||l(d,e$1)||m$1(d,e$1)||h$4(g??void 0),k$1=!!o&&a.has(o)&&m,w=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Jr(r)||r[0]==="create")return false;if(Ts(r))return true;if(r[0]==="init"&&c&&!p)return false;if(Ms(r))return true;try{let h=o==="shell"&&r[1]==="activate",f=o==="create",v=await Ri(e$1,{cwd:e$1,timeoutMs:1200});if(v.ok&&v.data?.isRapidkitProject&&v.data.engine==="python"){let C=f||Jr(r);if(!i&&!h&&!C&&!n$1&&!k$1&&_n(r)){if(o&&Ml.includes(o)){let y=await Kl(e$1).catch(()=>[]);if(y.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
328
328
  `);for(let E of y)process.stderr.write(s.red(` \u2022 ${E}`)+`
329
329
  `);process.exit(1);}}let R=await e(process.argv.slice(2),{cwd:e$1});process.exit(R);}}}catch{}let j=ql(e$1),x=b$4(),l$1=w?[]:p$1(e$1),P=null;for(let h of l$1)if(await O__default.pathExists(h)){if(await t$1(h)){f.warn(`Skipping legacy/broken Windows launcher candidate: ${h}. Falling back to core bridge.`);continue}P=h;break}let u=o==="create";if(o==="init"&&c&&!p)return false;if(o&&Ml.includes(o)){let h=await Kl(e$1);if(h.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
@@ -370,7 +370,7 @@ Discover more:
370
370
  `),f.debug(`Synced Python version ${v.trim()} from workspace to project`);}}catch(v){f.debug("Could not sync Python version from workspace:",v);}}if(!e$1.skipInstall){let u=await e(["init",c$1],{cwd:process.cwd()});if(u!==0&&process.exit(u),P){let h=b.dirname(P),f$1=b.join(h,".python-version"),v=b.join(c$1,".python-version");try{if(await O__default.pathExists(f$1)){let C=A.readFileSync(f$1,"utf-8");A.writeFileSync(v,C.trim()+`
371
371
  `),f.debug(`Re-synced Python version ${C.trim()} after init`);}}catch(C){f.debug("Could not re-sync Python version after init:",C);}}}}else {let{createProject:p}=await import('./create-R6A7EHQZ.js');await p(t,{skipGit:e$1.skipGit,skipPythonEngine:e$1.skipPythonEngine,dryRun:e$1.dryRun,yes:e$1.yes,userConfig:n,installMethod:e$1.installMethod,profile:e$1.profile,parentDirectory:b.dirname(c$1)});}}catch(r){r instanceof a$1?(f.error(`
372
372
  \u274C ${r.message}`),r.details&&f.warn(`\u{1F4A1} ${r.details}`),f.debug("Error code:",r.code)):(f.error(`
373
- \u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Et=null;}});Yi(de);rc(de);Mc(de);de.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{im({json:t.json});});de.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:r}=await import('./analyze-AAZEJ4FC.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});Oi(de);de.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t$1=>{t$1!=="activate"&&(console.log(s.red(`Unknown shell command: ${t$1}`)),process.exit(1));let e=process.cwd();function r(p){let d=p;for(;;){let g=t(d,"context.json").find(k=>A.existsSync(k));if(g)return g;let m=b.dirname(d);if(m===d)break;d=m;}return null}let o$1=r(e);function n(p){let d=p;for(;;){let g=b.join(d,".venv"),m=[b.join(d,".workspai","activate"),b.join(d,".rapidkit","activate")].find(w=>A.existsSync(w))??b.join(d,".workspai","activate");if(A.existsSync(m)||A.existsSync(g))return {venv:g,activateFile:m};let k=b.dirname(d);if(k===d)break;d=k;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&A.existsSync(a.activateFile)?i=a.activateFile:a&&A.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$4();console.log(c?`call "${i}"`:`. "${i}"`);});de.command(g.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$5({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});de.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:r}=await import('./pipeline-PVCLAQDI.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});de.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Is({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-LZWNQQLY.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});de.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ds(t,e);r!==0&&process.exit(r);});de.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await ep(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});var sn=de.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");sn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await xo({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});sn.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await dc({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});sn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await pc({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});sn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await mc({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});var Dt=de.command("project").description("Safe workspace project lifecycle operations");Dt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{Bl({json:t.json});});Dt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$6({startPath:b.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??b.join(o.projectPath,f$2),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json"};if(el(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});Dt.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-44ZPCOPV.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let p of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${p.path}: ${p.percent===null?"unknown":`${p.percent}%`} (${p.uncovered} uncovered)`));}for(let p of o.diagnostics)console.log(s.gray(` ${p}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});Dt.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Hn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Dt.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Bn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});Dt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await kc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});Dt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await yc({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});de.command(g.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await cm({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-KNIYGDM7.js'),a=await n({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});de.command(g.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
373
+ \u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Et=null;}});Yi(de);rc(de);Mc(de);de.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{im({json:t.json});});de.command("analyze").description("Analyze workspace/project health and generate enterprise-ready evidence").option("--workspace <path>","Workspace/root path to analyze").option("--json","Output as JSON").option("--output <file>","Write JSON report to a file").option("--strict","Treat warnings as blocking in the verdict").action(async t=>{try{let{runAnalyze:e,printAnalyzeReport:r}=await import('./analyze-AAZEJ4FC.js'),o=await e({workspacePath:t.workspace,json:t.json===true,output:t.output,strict:t.strict===true});t.json?console.log(JSON.stringify(o,null,2)):r(o),o.summary.verdict==="blocked"&&process.exit(2);}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:"analyze",code:"analyze.failed",message:r}),null,2)):console.error(s.red(`Analyze failed: ${r}`)),process.exit(1);}});Oi(de);de.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t$1=>{t$1!=="activate"&&(console.log(s.red(`Unknown shell command: ${t$1}`)),process.exit(1));let e=process.cwd();function r(p){let d=p;for(;;){let g=t(d,"context.json").find(k=>A.existsSync(k));if(g)return g;let m=b.dirname(d);if(m===d)break;d=m;}return null}let o$1=r(e);function n(p){let d=p;for(;;){let g=b.join(d,".venv"),m=[b.join(d,".workspai","activate"),b.join(d,".rapidkit","activate")].find(w=>A.existsSync(w))??b.join(d,".workspai","activate");if(A.existsSync(m)||A.existsSync(g))return {venv:g,activateFile:m};let k=b.dirname(d);if(k===d)break;d=k;}return null}let a=n(e);!o$1&&!a&&(console.log(s.yellow("No Workspai project found in this directory")),process.exit(1));let i;a&&A.existsSync(a.activateFile)?i=a.activateFile:a&&A.existsSync(a.venv)?i=o(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$4();console.log(c?`call "${i}"`:`. "${i}"`);});de.command(g.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$5({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});de.command("pipeline").description("\u{1F517} Run governance pipeline: sync \u2192 doctor \u2192 analyze \u2192 readiness \u2192 autopilot (writes pipeline-last-run.json)").option("--json","Output pipeline report as JSON").option("--strict","Treat warnings as blocking and propagate non-zero exit codes").option("--skip-verify","Skip readiness verify gate").option("--skip-analyze","Skip analyze stage").option("--skip-autopilot","Skip autopilot release stage").option("--autopilot-mode <mode>","Autopilot mode when stage is enabled: audit | safe-fix | enforce","audit").option("--no-agent-sync","Skip cross-tool agent grounding sync after pipeline evidence write").option("--agent-sync","Force agent grounding sync after pipeline (default when report is written)").action(async t=>{let e=String(t.autopilotMode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(e)||(console.log(s.red(`Invalid autopilot mode: ${t.autopilotMode}`)),process.exit(1));let{runPipelineCommand:r}=await import('./pipeline-TDQK5QYQ.js');await r({json:t.json===true,strict:t.strict===true,skipVerify:t.skipVerify===true,skipAnalyze:t.skipAnalyze===true,skipAutopilot:t.skipAutopilot===true,autopilotMode:e,noAgentSync:t.agentSync===false,agentSync:t.agentSync});});de.command("autopilot <action>").description("Run end-to-end release autopilot workflows").option("--mode <mode>","Autopilot mode: audit | safe-fix | enforce","audit").option("--json","Emit machine-readable JSON output").option("--output <file>","Write autopilot report to an additional output path").option("--since <ref>","Git ref for affected project selection (default: HEAD~1)").option("--parallel","Run workspace stage execution in parallel").option("--max-workers <count>","Maximum parallel workers").action(async(t,e)=>{t!=="release"&&(console.log(s.red(`Unknown autopilot action: ${t}`)),console.log(s.gray("Available: release")),process.exit(1));let r=String(e.mode||"audit").trim().toLowerCase();["audit","safe-fix","enforce"].includes(r)||(console.log(s.red(`Invalid autopilot mode: ${e.mode}`)),console.log(s.gray("Allowed modes: audit | safe-fix | enforce")),process.exit(1));let o=Is({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-63XHNGR6.js'),a;try{a=await n({workspacePath:process.cwd(),mode:r,since:e.since,parallel:e.parallel===true,maxWorkers:o,json:e.json===true,output:e.output});}catch(i){let c=i instanceof Error?i.message:String(i);console.log(s.red(`Autopilot release failed: ${c}`)),process.exit(3);}e.json&&console.log(JSON.stringify(a,null,2)),a.summary.exitCode!==0&&process.exit(a.summary.exitCode);});de.command("import <source>").description("Import a local project folder or clone a git repository into the current workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Override imported project folder name").option("--enable-modules","Preserve Core module/template commands only when imported RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--git","Force source to be treated as a git repository URL").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await Ds(t,e);r!==0&&process.exit(r);});de.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (defaults to nearest or managed default)").option("--name <projectName>","Override adopted project name").option("--enable-modules","Preserve Core module/template commands only when adopted RapidKit metadata already supports them").addOption(new Option("--project-grounding <mode>","Project entrypoint policy: managed, local, or off").choices(["managed","local","off"]).default("managed")).option("--dry-run","Preview adoption without writing project or registry metadata").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=await ep(t,{...e,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),enableModules:e.enableModules===true||process.argv.includes("--enable-modules")});r!==0&&process.exit(r);});var sn=de.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");sn.command("create [name]").description("Create a recoverable workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the snapshot manifest").option("--include-projects","Include project source files in the snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await xo({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});sn.command("list").description("List workspace snapshots").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await dc({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});sn.command("inspect <name>").description("Inspect snapshot manifest and estimated payload size").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await pc({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});sn.command("restore <name>").description("Restore a workspace snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the audit log").option("--dry-run","Show what would be restored without changing files").option("--force","Required to apply a restore").option("--no-safety-snapshot","Do not create a pre-restore metadata snapshot").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await mc({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});var Dt=de.command("project").description("Safe workspace project lifecycle operations");Dt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{Bl({json:t.json});});Dt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$6({startPath:b.resolve(e.project??process.cwd()),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!o||!o.projectPath)throw new a$2("project.workspace.unlinked","No Workspai project metadata was found from the requested path.");let n=r==="relink"||o.source==="registry"||o.recovered?await d$2(o):null,a={schemaVersion:"project-workspace-resolution.v1",status:"resolved",workspacePath:o.workspacePath,projectPath:o.projectPath,source:n?"local-link":o.source,recovered:o.recovered||n!==null,linkPath:n?.linkPath??o.linkPath??b.join(o.projectPath,f$2),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json"};if(el(a),e.json){console.log(JSON.stringify(a,null,2));return}console.log(s.green("\u2714 Project workspace resolved")),console.log(s.gray(` Workspace: ${a.workspacePath}`)),console.log(s.gray(` Project: ${a.projectPath}`)),console.log(s.gray(` Resolution: ${a.source}`)),n&&console.log(s.gray(` Local link repaired: ${n.linkPath}`));}catch(o){let n=o instanceof a$2?o:null,a=o instanceof Error?o.message:String(o);e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:n?.code??"project.workspace.resolve.failed",message:a,context:n?.context}),null,2)):console.log(s.red(`\u274C ${a}`)),process.exit(1);}});Dt.command("coverage").description("Inspect or run runtime-native test coverage and publish normalized project evidence").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--target <percent>","Required coverage target from 0 to 100","80").option("--run","Run the detected runtime-native coverage command before reading evidence").option("--strict","Return exit 2 when coverage is unavailable or below the selected target").option("--json","Emit machine-readable JSON output").action(async t=>{let e=Number(t.target??80);if(!Number.isFinite(e)||e<0||e>100){let r="--target must be a number from 0 to 100.";t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.target.invalid",message:r}),null,2)):console.log(s.red(`\u274C ${r}`)),process.exit(1);}try{let{collectProjectTestCoverage:r}=await import('./project-test-coverage-44ZPCOPV.js'),o=await r({projectPath:t.project,target:e,run:t.run===true});if(t.json)console.log(JSON.stringify(o,null,2));else {let a=o.metrics[o.target.metric]?.percent,i=a==null?"unavailable":`${a}%`,c=o.status==="passed"?s.green:o.status==="failed"?s.red:s.yellow;if(console.log(c(`Project coverage: ${o.status}`)),console.log(s.gray(` Project: ${o.project.name}`)),console.log(s.gray(` Runtime: ${o.runtime}`)),console.log(s.gray(` ${o.target.metric}: ${i} \xB7 target ${o.target.percent}%`)),console.log(s.gray(` Evidence: ${o.artifactPaths.project}`)),o.lowCoverageFiles.length>0){console.log(s.gray(" Lowest coverage files:"));for(let p of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${p.path}: ${p.percent===null?"unknown":`${p.percent}%`} (${p.uncovered} uncovered)`));}for(let p of o.diagnostics)console.log(s.gray(` ${p}`));}o.status==="failed"&&process.exit(1),t.strict&&(o.status==="below-target"||o.status==="unavailable")&&process.exit(2);}catch(r){let o=r.message;t.json?console.log(JSON.stringify(c$1({operation:"project coverage",code:"project.coverage.failed",message:o}),null,2)):console.log(s.red(`\u274C Project coverage failed: ${o}`)),process.exit(1);}});Dt.command("archives").description("List archived workspace projects").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--json","Emit machine-readable JSON output").action(async t=>{try{let e=await Hn({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({archives:e},null,2));return}if(e.length===0){console.log(s.yellow("No archived projects found."));return}for(let r of e)console.log(s.cyan(r.projectName)),console.log(s.gray(` Archived: ${r.archivedAt}`)),console.log(s.gray(` Path: ${r.archivePath}`)),r.reason&&console.log(s.gray(` Reason: ${r.reason}`));}catch(e){console.log(s.red(`\u274C Project archive list failed: ${e.message}`)),process.exit(1);}});Dt.command("archive <project>").description("Move a project into .workspai/archive with a safety snapshot").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the archive manifest").option("--dry-run","Show what would be archived without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await Bn({workspacePath:e.workspace,project:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project archive dry-run: ${r.projectName}`):s.green(`\u2714 Project archived: ${r.projectName}`)),console.log(s.gray(` From: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` To: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project archive",code:"project.archive.failed",message:o}),null,2)):console.log(s.red(`\u274C Project archive failed: ${o}`)),process.exit(1);}});Dt.command("restore <archive>").description("Restore an archived project back into the workspace").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--name <projectName>","Restore using a new project folder name").option("--reason <text>","Reason recorded in the audit log").option("--force","Overwrite an existing restore target").option("--dry-run","Show what would be restored without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await kc({workspacePath:e.workspace,archive:t,targetName:e.name,reason:e.reason,force:e.force===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(r.dryRun?s.cyan(`Project restore dry-run: ${r.projectName}`):s.green(`\u2714 Project restored: ${r.projectName}`)),console.log(s.gray(` From: ${r.archivePath}`)),console.log(s.gray(` To: ${r.projectPath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project restore",code:"project.restore.failed",message:o}),null,2)):console.log(s.red(`\u274C Project restore failed: ${o}`)),process.exit(1);}});Dt.command("delete <project>").description("Archive by default; permanently delete only with --permanent and exact --confirm").option("--workspace <path>","Workspace root path (defaults to nearest Workspai workspace)").option("--reason <text>","Reason recorded in the safety snapshot/archive manifest").option("--permanent","Permanently delete the project directory").option("--confirm <projectName>","Required exact project name for --permanent").option("--dry-run","Show what would be deleted without changing files").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let r=await yc({workspacePath:e.workspace,project:t,reason:e.reason,permanent:e.permanent===true,confirm:e.confirm,dryRun:e.dryRun===true||process.argv.includes("--dry-run")});if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.action==="archive"?"archived":"deleted";console.log(r.dryRun?s.cyan(`Project ${o} dry-run: ${r.projectName}`):s.green(`\u2714 Project ${o}: ${r.projectName}`)),console.log(s.gray(` Path: ${r.projectPath}`)),r.archivePath&&console.log(s.gray(` Archive: ${r.archivePath}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){let o=r.message;e.json?console.log(JSON.stringify(c$1({operation:"project delete",code:"project.delete.failed",message:o}),null,2)):console.log(s.red(`\u274C Project delete failed: ${o}`)),process.exit(1);}});de.command(g.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json","Output results in JSON format (for CI/CD pipelines)").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate remediation plan without applying changes").option("--apply","Apply remediation plan non-interactively").action(async(t,e)=>{t&&t!=="workspace"&&t!=="project"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project")),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await cm({scope:t,workspaceFlag:e.workspace});o.detected&&!e.json&&(console.log(s.yellow("\u26A0\uFE0F Local launcher shadow detected for doctor workspace checks.")),o.candidatePath&&console.log(s.gray(` Candidate: ${o.candidatePath}`)),console.log(s.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution.")),console.log(s.gray(" If this happens in a shell call, run: npx --yes --package workspai workspai doctor workspace")));let{runDoctor:n}=await import('./doctor-HJ3O7SAO.js'),a=await n({...e,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});de.command(g.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
374
374
  workspace run <stage> \u2014 fleet stage execution across discovered projects
375
375
  stages: init | test | build | start | <custom-from-context>
376
376
  workspace explain|why \u2014 blocker/project narrative (--write for artifact)
@@ -386,16 +386,16 @@ Workspace Actions:
386
386
  Fleet lifecycle run | init
387
387
 
388
388
  Use "workspai commands --json" for the contract-backed runtime inventory.
389
- See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=l=>{let P=n.workspace?b.resolve(n.workspace):null,u=null,h=null;try{u=b$6({startPath:process.cwd(),explicitWorkspacePath:P,strict:true})?.workspacePath??null;}catch(C){if(C instanceof a$2)h=C;else throw C}if(!u||!Ye(u)){let C=h?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${l}`,code:h?.code??"workspace.root.required",message:C,context:{cwd:b.resolve(process.cwd()),...P?{requestedWorkspace:P}:{},...h?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${C}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let f=b.resolve(process.cwd()),v=b.resolve(u);return f!==v&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${u} for "${l}" (current directory: ${f}).`)),u},i=l=>process.argv.includes(l),c=l=>Ie(process.argv,l),p=()=>n.output||c("--output"),d=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0},g=(l,P)=>{if(!l)return;let u=l.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!u)throw new Error(`${P} must be a byte size such as 500gb or 2tb.`);let h={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},f=Number(u[1])*h[u[2]||"b"];if(!Number.isSafeInteger(Math.floor(f))||f<=0)throw new Error(`${P} is outside the supported numeric range.`);return Math.floor(f)},m=()=>{let l=n.downloadTimeoutMs,P=l===void 0?void 0:Number.parseInt(l,10);if(P!==void 0&&(!Number.isFinite(P)||P<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:g(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:g(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:P,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},k=new Set(Object.values(Nr).flatMap(l=>[...l.flags])),w=new Set(process.argv.slice(2).filter(l=>l.startsWith("--")).map(l=>l.split("=",1)[0]).filter(l=>k.has(l))),j=Nr[t]?.flags,x=j?[...w].filter(l=>!j.includes(l)):[];if(x.length>0){let l=`${x.join(", ")} ${x.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||w.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:l,exitCode:2,context:{action:t,unsupportedFlags:x,allowedFlags:j}}),null,2)):(console.log(s.red(`\u274C ${l}`)),console.log(s.gray(` Allowed flags: ${j.join(", ")||"none"}`))),process.exit(2);}if((Gc(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$5({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:l}=await import('./workspace-B53XH35L.js');await l({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let l=a("intelligence"),{runWorkspaceIntelligenceChain:P}=await import('./workspace-intelligence-runner-JNCQLUH7.js'),u=await P({workspacePath:l,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(u,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${u.status}`));for(let h of u.stages)console.log(s.gray(` ${h.id}: ${h.status} \u2014 ${h.message}`));console.log(s.gray(` Evidence: ${u.artifactPath}`));}u.exitCode!==0&&process.exit(u.exitCode);}else if(t==="model"){let l=a("model"),{buildWorkspaceModelCached:P,buildWorkspaceModelIncremental:u,createWorkspaceModelBuildProvenance:h,writeWorkspaceModel:f}=await import('./workspace-model-MNJOGBPP.js'),v=n.incremental===true||i("--incremental"),C=n.cache===true||i("--cache")||v,R={workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:n.strict===true||i("--strict")},y,E;if(v){let M=await u(R);y=M.model,E=M.mode;}else {let M=await P({...R,cache:C});y=M.model,E=M.cache;}y={...y,build:h({mode:v?"incremental":C?"cache":"full",engineStatus:E})};let $;(n.write===true||i("--write"))&&($=await f(y,l));let N=(n.strict===true||i("--strict"))&&y.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...y,...$?{outputPath:$}:{}},null,2)),N&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${y.workspace.name}`)),v?console.log(s.gray(` Build: ${E} (incremental)`)):C&&console.log(s.gray(` Cache: ${E}`)),console.log(s.gray(` Projects: ${y.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${y.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${y.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${y.identity.workspaceType}`)),console.log(s.gray(` Validation: ${y.validation?.status??"unknown"} (${y.validation?.errors??0} error, ${y.validation?.warnings??0} warning)`)),console.log($?s.gray(` Written: ${$}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),N&&process.exit(1);}else if(t==="agent-sync"){let l=a("agent-sync"),{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:u}=await import('./workspace-agent-sync-446AXPHJ.js'),h=n.strict===true||i("--strict"),f=n.write===true||i("--write"),v=i("--dry-run"),C=await P({workspacePath:l,scope:n.scope,agent:n.forAgent,write:f&&!v,dryRun:v,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:u(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(C,null,2));else {console.log(s.green(`\u2714 Agent grounding ${f&&!v?"synced":"planned"}`)),console.log(s.gray(` Index: ${C.indexPath}`)),C.contextPath&&console.log(s.gray(` Context: ${C.contextPath}`)),C.blockers.length>0&&console.log(s.yellow(` Blockers: ${C.blockers.slice(0,3).join(" \xB7 ")}`));let R=f&&!v?C.writtenFiles:C.skippedFiles;if(R.length>0&&console.log(s.gray(` Files: ${R.join(", ")}`)),C.strictViolations.length>0)for(let y of C.strictViolations)console.log(s.red(`\u274C ${y}`));}h&&C.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let l=e??"status",{approveWorkspaceRepair:P,cancelWorkspaceRepair:u,decideWorkspaceRepair:h,executeWorkspaceRepair:f,inspectWorkspaceRepairCapabilities:v,listWorkspaceRepairTransactions:C,planWorkspaceRepair:R,planWorkspaceRepairProposal:y,readWorkspaceRepairTransaction:E,rollbackWorkspaceRepair:$}=await import('./workspace-repair-engine-SRWECKZO.js');if(l==="capabilities"){let F;if(n.workspace)F=a("repair capabilities");else try{let G=b$6({startPath:process.cwd(),strict:false})?.workspacePath;G&&Ye(G)&&(F=G);}catch{}let W=await v(F?{workspacePath:F}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(W,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${W.adapters.length}`));for(let G of W.adapters)console.log(s.gray(` ${G.id.padEnd(14)} ${G.support.padEnd(11)} ${G.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let N=a("repair"),M=n.transaction??(["plan","propose","capabilities"].includes(l)?void 0:r),_=()=>{if(!M?.trim())throw new Error(`workspace repair ${l} requires --transaction <id> (or the id as the next positional argument).`);return M.trim()},S;if(l==="plan"){let F=n.card??r;if(!F?.trim())throw new Error("workspace repair plan requires --card <id>.");S=await R({workspacePath:N,cardId:F.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="propose"){let F=n.proposal??r;if(!F?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let W=b.resolve(N,F.trim()),G=b.relative(N,W);if(G.startsWith("..")||b.isAbsolute(G))throw new Error("The repair proposal file must be inside the canonical workspace.");let H=await O__default.lstat(W).catch(()=>{});if(!H?.isFile()||H.isSymbolicLink()||H.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");S=await y({workspacePath:N,proposal:await O__default.readJson(W),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="approve")S=await P({workspacePath:N,transactionId:_(),approvedBy:n.approvedBy});else if(l==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");S=await h({workspacePath:N,transactionId:_(),decision:n.decision});}else if(l==="execute"||l==="resume")S=await f({workspacePath:N,transactionId:_()});else if(l==="status")S=await E({workspacePath:N,transactionId:_()});else if(l==="list")S=await C(N);else if(l==="rollback")S=await $({workspacePath:N,transactionId:_()});else if(l==="cancel")S=await u({workspacePath:N,transactionId:_()});else throw new Error(`Unknown workspace repair action: ${l}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let J=b.join(N,a$3.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$7(`workspace repair ${l}`,S,J),null,2));else if(Array.isArray(S)){console.log(s.green(`\u2714 Workspace repair transactions: ${S.length}`));for(let F of S.slice(0,20))console.log(s.gray(` ${F.transactionId} \xB7 ${F.target.cardId} \xB7 ${F.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${S.state}`)),console.log(s.gray(` Transaction: ${S.transactionId}`)),console.log(s.gray(` Target: ${S.target.cardId}`));for(let F of S.stages)console.log(s.gray(` ${F.status.padEnd(8)} ${F.kind}: ${F.summary}`));S.decision&&console.log(s.yellow(` Decision: ${S.decision.reason}`)),console.log(s.gray(` Evidence: ${a$3.repairTransaction}`));}Array.isArray(S)||(S.state==="decision-required"&&process.exit(2),(S.state==="rolled-back"||S.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let l=a("remediation-plan"),{buildArtifactRemediationPlan:P,writeArtifactRemediationPlan:u}=await import('./artifact-remediation-plan-CJSPCMWA.js'),h=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),f;if((n.write===true||i("--write"))&&(f=await u(h,l)),n.json===true||i("--json")){console.log(JSON.stringify(b$7("workspace remediation-plan",h,f),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${h.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${h.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${h.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${h.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${h.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${h.summary.risk.safe}, guarded=${h.summary.risk.guarded}, invasive=${h.summary.risk.invasive}`));for(let v of h.actions.slice(0,8))console.log(s.gray(` \u2022 ${v.cardId}: ${v.title} (${v.mode}, ${v.risk})`));h.actions.length>8&&console.log(s.gray(` \u2026 ${h.actions.length-8} more action(s)`)),console.log(f?s.gray(` Written: ${f}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let l=a("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:P,writeWorkspaceAgentContext:u}=await import('./workspace-context-XSECHC7O.js'),h=n.strict===true||i("--strict"),f=await P({workspacePath:l,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:false}),v,C;if((n.write===true||i("--write"))&&(v=await u(f,l),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:E,parseAgentGroundingTargets:$}=await import('./workspace-agent-sync-446AXPHJ.js');if(C=await E({workspacePath:l,scope:n.scope,agent:f.agent,write:true,refreshContext:false,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",targets:$(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${C.writtenFiles.length} file(s) updated`)),h&&C.strictViolations.length>0){for(let N of C.strictViolations)console.log(s.red(`\u274C ${N}`));process.exit(1);}}let R=h&&f.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...f,...v?{outputPath:v}:{},...C?{agentGroundingSync:C}:{}},null,2)),R&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${f.workspace.name}`)),console.log(s.gray(` Agent: ${f.agent}`)),console.log(s.gray(` Scope: ${f.scope.activeProject??f.scope.requested}`)),console.log(s.gray(` Projects included: ${f.projects.length}`)),console.log(s.gray(` Safe commands: ${f.safeCommands.length}`)),console.log(s.gray(` Validation: ${f.validation.status} (${f.validation.errors} error, ${f.validation.warnings} warning)`)),console.log(v?s.gray(` Written: ${v}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),R){for(let y of f.validation.issues)console.log(s.red(`\u274C ${y.severity}:${y.code}:${y.target}`));process.exit(1);}}else if(t==="snapshot"){let l=a("snapshot"),{buildWorkspaceModelSnapshot:P,writeWorkspaceModelSnapshot:u}=await import('./workspace-intelligence-FWRB47EJ.js'),h=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),f=await u(h,l);if(n.json){console.log(JSON.stringify(b$7("workspace snapshot",h,f),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${h.model.workspace.name}`)),console.log(s.gray(` Hash: ${h.modelHash}`)),console.log(s.gray(` Projects: ${h.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${h.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${f}`));}else if(t==="diff"){let l=a("diff"),P=n.from||e;P||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:u,writeWorkspaceModelDiff:h}=await import('./workspace-intelligence-FWRB47EJ.js'),f;try{f=await u({workspacePath:l,fromPath:P,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:P},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),R}let v=await h(f,l);if(n.json){console.log(JSON.stringify(b$7("workspace diff",f,v),null,2));return}let C=f.summary.changed?s.yellow:s.green;console.log(C(`\u2714 Workspace model diff: ${f.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${f.fromRef}`)),console.log(s.gray(` Added projects: ${f.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${f.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${f.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${f.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${f.summary.validationChanges}`)),f.git?.available&&console.log(s.gray(` Git: ${f.git.dirty?"dirty":"clean"} (${f.summary.gitChangedFiles} mapped change(s))`));for(let R of f.changes.slice(0,12))console.log(s.gray(` \u2022 ${R.type} ${R.target}: ${R.message}`));f.changes.length>12&&console.log(s.gray(` \u2026 ${f.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="impact"){let l=a("impact"),P=n.from||e;P||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:u,writeWorkspaceImpact:h}=await import('./workspace-intelligence-FWRB47EJ.js'),f;try{f=await u({workspacePath:l,fromPath:P,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:P},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),R}let v=await h(f,l);if(n.json){console.log(JSON.stringify(b$7("workspace impact",f,v),null,2));return}let C=f.summary.risk==="critical"||f.summary.risk==="high"?s.red:f.summary.risk==="medium"?s.yellow:s.green;console.log(C(`\u2714 Workspace impact: ${f.summary.risk}`)),console.log(s.gray(` From: ${f.fromRef}`)),console.log(s.gray(` Affected projects: ${f.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${f.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${f.summary.recommendedCommands}`));for(let R of f.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${R.title}: ${R.summary}`));f.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${f.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="verify"){let l=a("verify"),{buildWorkspaceVerify:P,writeWorkspaceVerify:u,evaluateWorkspaceVerifyGate:h}=await import('./workspace-verify-C6HWHRLJ.js'),f=await P({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),v=await u(f,l),C=h(f,{strict:n.strict===true||i("--strict")}),R=C.exitCode,{recordWorkspaceHistory:y,historyEntryFromVerify:E}=await import('./workspace-history-YY7YRDOH.js');if(await y(l,E(f,C.passed)),n.json){console.log(JSON.stringify(b$7("workspace verify",{...f,gate:C},v),null,2)),R!==0&&process.exit(R);return}let $=f.summary.verdict==="ready"?s.green:f.summary.verdict==="needs-attention"?s.yellow:s.red;console.log($(`\u2714 Workspace verify: ${f.summary.verdict}`)),console.log(s.gray(` Freshness: ${f.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${f.impact.risk}`)),console.log(s.gray(` Steps: ${f.steps.length}`)),console.log(s.gray(` Passed ${f.summary.stepsPassed}, warn ${f.summary.stepsWarn}, failed ${f.summary.stepsFailed}, missing ${f.summary.stepsMissing}`));for(let N of f.steps.slice(0,10))console.log(s.gray(` \u2022 ${N.id}: ${N.status} \u2014 ${N.message}`));if(f.steps.length>10&&console.log(s.gray(` \u2026 ${f.steps.length-10} more step(s)`)),f.policyViolations.length>0){console.log(s.gray(` Policy (${f.policyMode}): ${f.policyViolations.length} violation(s)`));for(let N of f.policyViolations.slice(0,5)){let M=N.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${M} [${N.source}] ${N.code}: ${N.message}`);}}console.log(s.gray(` Gate (${C.mode}): ${C.passed?"passed":"blocked"}`));for(let N of C.reasons.slice(0,5))console.log(s.red(` \u2717 ${N}`));console.log(s.gray(` Written: ${v}`)),R!==0&&process.exit(R);}else if(t==="graph"){let l=a("graph"),{buildWorkspaceModel:P,workspaceModelProjectTopology:u}=await import('./workspace-model-MNJOGBPP.js'),{buildGraphEmit:h,renderGraphDot:f,renderGraphMermaid:v,explainGraphNode:C}=await import('./workspace-graph-2A5THUCI.js'),R=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),y=u(R),E=(e||"emit").toLowerCase();y||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:E,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let $=async()=>{let{buildWorkspaceKnowledgeGraph:_}=await import('./workspace-knowledge-graph-BMMM2FUE.js'),{hashWorkspaceModel:S}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:J}=await import('./workspace-contract-AYFTZIKM.js'),F=null;try{F=(await J({workspacePath:l})).contract;}catch{}return _({workspacePath:l,workspace:{name:R.workspace.name,...R.workspace.profile?{profile:R.workspace.profile}:{}},projects:R.projects.map(W=>({id:W.name,path:W.path,...W.absolutePath?{absolutePath:W.absolutePath}:{},runtime:W.runtime,runtimeCandidates:W.runtimeCandidates,framework:W.framework,...W.kit?{kit:W.kit}:{}})),projectTopology:y,contract:F,now:new Date(R.generatedAt),source:{kind:"workspace-model",artifact:a$3.model,hashAlgorithm:"sha256",hash:S(R)}})};if(E==="dot"||E==="mermaid"){let _=E==="dot"?f(y):v(y),S=p();if(S){let J=b.resolve(l,S);await O__default.outputFile(J,`${_}
389
+ See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=l=>{let P=n.workspace?b.resolve(n.workspace):null,u=null,h=null;try{u=b$6({startPath:process.cwd(),explicitWorkspacePath:P,strict:true})?.workspacePath??null;}catch(C){if(C instanceof a$2)h=C;else throw C}if(!u||!Ye(u)){let C=h?.message??"Not inside a Workspai workspace. Run from a workspace/project directory or pass --workspace <path>.";(n.json===true||process.argv.includes("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${l}`,code:h?.code??"workspace.root.required",message:C,context:{cwd:b.resolve(process.cwd()),...P?{requestedWorkspace:P}:{},...h?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${C}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let f=b.resolve(process.cwd()),v=b.resolve(u);return f!==v&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${u} for "${l}" (current directory: ${f}).`)),u},i=l=>process.argv.includes(l),c=l=>Ie(process.argv,l),p=()=>n.output||c("--output"),d=()=>{if(!n.scanDepth)return;let l=Number.parseInt(n.scanDepth,10);return Number.isFinite(l)?l:void 0},g=(l,P)=>{if(!l)return;let u=l.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!u)throw new Error(`${P} must be a byte size such as 500gb or 2tb.`);let h={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},f=Number(u[1])*h[u[2]||"b"];if(!Number.isSafeInteger(Math.floor(f))||f<=0)throw new Error(`${P} is outside the supported numeric range.`);return Math.floor(f)},m=()=>{let l=n.downloadTimeoutMs,P=l===void 0?void 0:Number.parseInt(l,10);if(P!==void 0&&(!Number.isFinite(P)||P<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:g(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:g(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:P,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},k=new Set(Object.values(Nr).flatMap(l=>[...l.flags])),w=new Set(process.argv.slice(2).filter(l=>l.startsWith("--")).map(l=>l.split("=",1)[0]).filter(l=>k.has(l))),j=Nr[t]?.flags,x=j?[...w].filter(l=>!j.includes(l)):[];if(x.length>0){let l=`${x.join(", ")} ${x.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||w.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:l,exitCode:2,context:{action:t,unsupportedFlags:x,allowedFlags:j}}),null,2)):(console.log(s.red(`\u274C ${l}`)),console.log(s.gray(` Allowed flags: ${j.join(", ")||"none"}`))),process.exit(2);}if((Gc(t)||t==="trace"||t==="feedback"||t==="mcp")&&d$5({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:l}=await import('./workspace-B53XH35L.js');await l({json:n.json===true||i("--json")});}else if(t==="intelligence"){e&&e!=="run"&&(console.log(s.red(`\u274C Unknown workspace intelligence action: ${e}`)),console.log(s.gray(" npx workspai workspace intelligence run [--strict] [--json]")),process.exit(2));let l=a("intelligence"),{runWorkspaceIntelligenceChain:P}=await import('./workspace-intelligence-runner-EQFLRVRL.js'),u=await P({workspacePath:l,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(u,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${u.status}`));for(let h of u.stages)console.log(s.gray(` ${h.id}: ${h.status} \u2014 ${h.message}`));console.log(s.gray(` Evidence: ${u.artifactPath}`));}u.exitCode!==0&&process.exit(u.exitCode);}else if(t==="model"){let l=a("model"),{buildWorkspaceModelCached:P,buildWorkspaceModelIncremental:u,createWorkspaceModelBuildProvenance:h,writeWorkspaceModel:f}=await import('./workspace-model-MNJOGBPP.js'),v=n.incremental===true||i("--incremental"),C=n.cache===true||i("--cache")||v,R={workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:n.strict===true||i("--strict")},y,E;if(v){let M=await u(R);y=M.model,E=M.mode;}else {let M=await P({...R,cache:C});y=M.model,E=M.cache;}y={...y,build:h({mode:v?"incremental":C?"cache":"full",engineStatus:E})};let $;(n.write===true||i("--write"))&&($=await f(y,l));let N=(n.strict===true||i("--strict"))&&y.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...y,...$?{outputPath:$}:{}},null,2)),N&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${y.workspace.name}`)),v?console.log(s.gray(` Build: ${E} (incremental)`)):C&&console.log(s.gray(` Cache: ${E}`)),console.log(s.gray(` Projects: ${y.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${y.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${y.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${y.identity.workspaceType}`)),console.log(s.gray(` Validation: ${y.validation?.status??"unknown"} (${y.validation?.errors??0} error, ${y.validation?.warnings??0} warning)`)),console.log($?s.gray(` Written: ${$}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),N&&process.exit(1);}else if(t==="agent-sync"){let l=a("agent-sync"),{syncWorkspaceAgentGrounding:P,parseAgentGroundingTargets:u}=await import('./workspace-agent-sync-446AXPHJ.js'),h=n.strict===true||i("--strict"),f=n.write===true||i("--write"),v=i("--dry-run"),C=await P({workspacePath:l,scope:n.scope,agent:n.forAgent,write:f&&!v,dryRun:v,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:u(n.target),experimentalHooks:n.experimentalHooks===true||i("--experimental-hooks"),hydratePrompts:n.hydratePrompts===true||i("--hydrate-prompts"),projectGrounding:n.projectGrounding??"managed",staleAfterHours:24});if(n.json)console.log(JSON.stringify(C,null,2));else {console.log(s.green(`\u2714 Agent grounding ${f&&!v?"synced":"planned"}`)),console.log(s.gray(` Index: ${C.indexPath}`)),C.contextPath&&console.log(s.gray(` Context: ${C.contextPath}`)),C.blockers.length>0&&console.log(s.yellow(` Blockers: ${C.blockers.slice(0,3).join(" \xB7 ")}`));let R=f&&!v?C.writtenFiles:C.skippedFiles;if(R.length>0&&console.log(s.gray(` Files: ${R.join(", ")}`)),C.strictViolations.length>0)for(let y of C.strictViolations)console.log(s.red(`\u274C ${y}`));}h&&C.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let l=e??"status",{approveWorkspaceRepair:P,cancelWorkspaceRepair:u,decideWorkspaceRepair:h,executeWorkspaceRepair:f,inspectWorkspaceRepairCapabilities:v,listWorkspaceRepairTransactions:C,planWorkspaceRepair:R,planWorkspaceRepairProposal:y,readWorkspaceRepairTransaction:E,rollbackWorkspaceRepair:$}=await import('./workspace-repair-engine-OZXOXVVV.js');if(l==="capabilities"){let F;if(n.workspace)F=a("repair capabilities");else try{let G=b$6({startPath:process.cwd(),strict:false})?.workspacePath;G&&Ye(G)&&(F=G);}catch{}let W=await v(F?{workspacePath:F}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(W,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${W.adapters.length}`));for(let G of W.adapters)console.log(s.gray(` ${G.id.padEnd(14)} ${G.support.padEnd(11)} ${G.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let N=a("repair"),M=n.transaction??(["plan","propose","capabilities"].includes(l)?void 0:r),_=()=>{if(!M?.trim())throw new Error(`workspace repair ${l} requires --transaction <id> (or the id as the next positional argument).`);return M.trim()},S;if(l==="plan"){let F=n.card??r;if(!F?.trim())throw new Error("workspace repair plan requires --card <id>.");S=await R({workspacePath:N,cardId:F.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="propose"){let F=n.proposal??r;if(!F?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let W=b.resolve(N,F.trim()),G=b.relative(N,W);if(G.startsWith("..")||b.isAbsolute(G))throw new Error("The repair proposal file must be inside the canonical workspace.");let H=await O__default.lstat(W).catch(()=>{});if(!H?.isFile()||H.isSymbolicLink()||H.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");S=await y({workspacePath:N,proposal:await O__default.readJson(W),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(l==="approve")S=await P({workspacePath:N,transactionId:_(),approvedBy:n.approvedBy});else if(l==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");S=await h({workspacePath:N,transactionId:_(),decision:n.decision});}else if(l==="execute"||l==="resume")S=await f({workspacePath:N,transactionId:_()});else if(l==="status")S=await E({workspacePath:N,transactionId:_()});else if(l==="list")S=await C(N);else if(l==="rollback")S=await $({workspacePath:N,transactionId:_()});else if(l==="cancel")S=await u({workspacePath:N,transactionId:_()});else throw new Error(`Unknown workspace repair action: ${l}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let J=b.join(N,a$3.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$7(`workspace repair ${l}`,S,J),null,2));else if(Array.isArray(S)){console.log(s.green(`\u2714 Workspace repair transactions: ${S.length}`));for(let F of S.slice(0,20))console.log(s.gray(` ${F.transactionId} \xB7 ${F.target.cardId} \xB7 ${F.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${S.state}`)),console.log(s.gray(` Transaction: ${S.transactionId}`)),console.log(s.gray(` Target: ${S.target.cardId}`));for(let F of S.stages)console.log(s.gray(` ${F.status.padEnd(8)} ${F.kind}: ${F.summary}`));S.decision&&console.log(s.yellow(` Decision: ${S.decision.reason}`)),console.log(s.gray(` Evidence: ${a$3.repairTransaction}`));}Array.isArray(S)||(S.state==="decision-required"&&process.exit(2),(S.state==="rolled-back"||S.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let l=a("remediation-plan"),{buildArtifactRemediationPlan:P,writeArtifactRemediationPlan:u}=await import('./artifact-remediation-plan-A2PRCUNA.js'),h=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),f;if((n.write===true||i("--write"))&&(f=await u(h,l)),n.json===true||i("--json")){console.log(JSON.stringify(b$7("workspace remediation-plan",h,f),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${h.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${h.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${h.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${h.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${h.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${h.summary.risk.safe}, guarded=${h.summary.risk.guarded}, invasive=${h.summary.risk.invasive}`));for(let v of h.actions.slice(0,8))console.log(s.gray(` \u2022 ${v.cardId}: ${v.title} (${v.mode}, ${v.risk})`));h.actions.length>8&&console.log(s.gray(` \u2026 ${h.actions.length-8} more action(s)`)),console.log(f?s.gray(` Written: ${f}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let l=a("context");n.forAgent!==true&&typeof n.forAgent!="string"&&e!=="agent"&&(console.log(s.red("\u274C workspace context currently requires --for-agent")),console.log(s.gray(" npx workspai workspace context --for-agent --json [--scope project:<name>]")),process.exit(1));let{buildWorkspaceAgentContext:P,writeWorkspaceAgentContext:u}=await import('./workspace-context-XSECHC7O.js'),h=n.strict===true||i("--strict"),f=await P({workspacePath:l,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d(),strict:false}),v,C;if((n.write===true||i("--write"))&&(v=await u(f,l),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:E,parseAgentGroundingTargets:$}=await import('./workspace-agent-sync-446AXPHJ.js');if(C=await E({workspacePath:l,scope:n.scope,agent:f.agent,write:true,refreshContext:false,strict:h,preset:n.preset==="minimal"?"minimal":"enterprise",targets:$(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${C.writtenFiles.length} file(s) updated`)),h&&C.strictViolations.length>0){for(let N of C.strictViolations)console.log(s.red(`\u274C ${N}`));process.exit(1);}}let R=h&&f.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...f,...v?{outputPath:v}:{},...C?{agentGroundingSync:C}:{}},null,2)),R&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${f.workspace.name}`)),console.log(s.gray(` Agent: ${f.agent}`)),console.log(s.gray(` Scope: ${f.scope.activeProject??f.scope.requested}`)),console.log(s.gray(` Projects included: ${f.projects.length}`)),console.log(s.gray(` Safe commands: ${f.safeCommands.length}`)),console.log(s.gray(` Validation: ${f.validation.status} (${f.validation.errors} error, ${f.validation.warnings} warning)`)),console.log(v?s.gray(` Written: ${v}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),R){for(let y of f.validation.issues)console.log(s.red(`\u274C ${y.severity}:${y.code}:${y.target}`));process.exit(1);}}else if(t==="snapshot"){let l=a("snapshot"),{buildWorkspaceModelSnapshot:P,writeWorkspaceModelSnapshot:u}=await import('./workspace-intelligence-FWRB47EJ.js'),h=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),f=await u(h,l);if(n.json){console.log(JSON.stringify(b$7("workspace snapshot",h,f),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${h.model.workspace.name}`)),console.log(s.gray(` Hash: ${h.modelHash}`)),console.log(s.gray(` Projects: ${h.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${h.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${f}`));}else if(t==="diff"){let l=a("diff"),P=n.from||e;P||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.from.required",message:"workspace diff requires --from <snapshot-or-model-report|git[:ref]>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace diff --from .workspai/reports/workspace-model.json --json","npx workspai workspace diff --from git --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace diff requires --from <snapshot-or-model-report|git[:ref]>")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json")),console.log(s.gray(" npx workspai workspace diff --from .workspai/reports/workspace-model.json --json")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),console.log(s.gray(" npx workspai workspace diff --from git --json (uses snapshot baseline + git working tree)")),process.exit(1));let{diffWorkspaceModel:u,writeWorkspaceModelDiff:h}=await import('./workspace-intelligence-FWRB47EJ.js'),f;try{f=await u({workspacePath:l,fromPath:P,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:P},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),R}let v=await h(f,l);if(n.json){console.log(JSON.stringify(b$7("workspace diff",f,v),null,2));return}let C=f.summary.changed?s.yellow:s.green;console.log(C(`\u2714 Workspace model diff: ${f.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${f.fromRef}`)),console.log(s.gray(` Added projects: ${f.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${f.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${f.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${f.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${f.summary.validationChanges}`)),f.git?.available&&console.log(s.gray(` Git: ${f.git.dirty?"dirty":"clean"} (${f.summary.gitChangedFiles} mapped change(s))`));for(let R of f.changes.slice(0,12))console.log(s.gray(` \u2022 ${R.type} ${R.target}: ${R.message}`));f.changes.length>12&&console.log(s.gray(` \u2026 ${f.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="impact"){let l=a("impact"),P=n.from||e;P||((n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.from.required",message:"workspace impact requires --from <workspace-diff-report>.",context:{workspacePath:l},examples:["npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),console.log(s.red("\u274C workspace impact requires --from <workspace-diff-report>")),console.log(s.gray(" npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{buildWorkspaceImpact:u,writeWorkspaceImpact:h}=await import('./workspace-intelligence-FWRB47EJ.js'),f;try{f=await u({workspacePath:l,fromPath:P,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()});}catch(R){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:R.message,context:{workspacePath:l,fromPath:P},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json"]}),null,2)),process.exit(1)),R}let v=await h(f,l);if(n.json){console.log(JSON.stringify(b$7("workspace impact",f,v),null,2));return}let C=f.summary.risk==="critical"||f.summary.risk==="high"?s.red:f.summary.risk==="medium"?s.yellow:s.green;console.log(C(`\u2714 Workspace impact: ${f.summary.risk}`)),console.log(s.gray(` From: ${f.fromRef}`)),console.log(s.gray(` Affected projects: ${f.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${f.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${f.summary.recommendedCommands}`));for(let R of f.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${R.title}: ${R.summary}`));f.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${f.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="verify"){let l=a("verify"),{buildWorkspaceVerify:P,writeWorkspaceVerify:u,evaluateWorkspaceVerifyGate:h}=await import('./workspace-verify-C6HWHRLJ.js'),f=await P({workspacePath:l,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),v=await u(f,l),C=h(f,{strict:n.strict===true||i("--strict")}),R=C.exitCode,{recordWorkspaceHistory:y,historyEntryFromVerify:E}=await import('./workspace-history-YY7YRDOH.js');if(await y(l,E(f,C.passed)),n.json){console.log(JSON.stringify(b$7("workspace verify",{...f,gate:C},v),null,2)),R!==0&&process.exit(R);return}let $=f.summary.verdict==="ready"?s.green:f.summary.verdict==="needs-attention"?s.yellow:s.red;console.log($(`\u2714 Workspace verify: ${f.summary.verdict}`)),console.log(s.gray(` Freshness: ${f.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${f.impact.risk}`)),console.log(s.gray(` Steps: ${f.steps.length}`)),console.log(s.gray(` Passed ${f.summary.stepsPassed}, warn ${f.summary.stepsWarn}, failed ${f.summary.stepsFailed}, missing ${f.summary.stepsMissing}`));for(let N of f.steps.slice(0,10))console.log(s.gray(` \u2022 ${N.id}: ${N.status} \u2014 ${N.message}`));if(f.steps.length>10&&console.log(s.gray(` \u2026 ${f.steps.length-10} more step(s)`)),f.policyViolations.length>0){console.log(s.gray(` Policy (${f.policyMode}): ${f.policyViolations.length} violation(s)`));for(let N of f.policyViolations.slice(0,5)){let M=N.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${M} [${N.source}] ${N.code}: ${N.message}`);}}console.log(s.gray(` Gate (${C.mode}): ${C.passed?"passed":"blocked"}`));for(let N of C.reasons.slice(0,5))console.log(s.red(` \u2717 ${N}`));console.log(s.gray(` Written: ${v}`)),R!==0&&process.exit(R);}else if(t==="graph"){let l=a("graph"),{buildWorkspaceModel:P,workspaceModelProjectTopology:u}=await import('./workspace-model-MNJOGBPP.js'),{buildGraphEmit:h,renderGraphDot:f,renderGraphMermaid:v,explainGraphNode:C}=await import('./workspace-graph-2A5THUCI.js'),R=await P({workspacePath:l,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:d()}),y=u(R),E=(e||"emit").toLowerCase();y||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:E,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.missing",message:"Workspace model did not produce a dependency graph."}},null,2)),process.exit(1)),console.log(s.red("\u274C Workspace model did not produce a dependency graph.")),process.exit(1));let $=async()=>{let{buildWorkspaceKnowledgeGraph:_}=await import('./workspace-knowledge-graph-BMMM2FUE.js'),{hashWorkspaceModel:S}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:J}=await import('./workspace-contract-AYFTZIKM.js'),F=null;try{F=(await J({workspacePath:l})).contract;}catch{}return _({workspacePath:l,workspace:{name:R.workspace.name,...R.workspace.profile?{profile:R.workspace.profile}:{}},projects:R.projects.map(W=>({id:W.name,path:W.path,...W.absolutePath?{absolutePath:W.absolutePath}:{},runtime:W.runtime,runtimeCandidates:W.runtimeCandidates,framework:W.framework,...W.kit?{kit:W.kit}:{}})),projectTopology:y,contract:F,now:new Date(R.generatedAt),source:{kind:"workspace-model",artifact:a$3.model,hashAlgorithm:"sha256",hash:S(R)}})};if(E==="dot"||E==="mermaid"){let _=E==="dot"?f(y):v(y),S=p();if(S){let J=b.resolve(l,S);await O__default.outputFile(J,`${_}
390
390
  `,"utf8"),n.json?console.log(JSON.stringify(b$7(`workspace graph ${E}`,{format:E,nodeCount:y.stats.nodeCount,edgeCount:y.stats.edgeCount},J),null,2)):(console.log(s.green(`\u2714 Workspace dependency graph exported as ${E}`)),console.log(s.gray(` Written: ${J}`)));return}console.log(_);return}if(E==="jsonld"||E==="graphml"||E==="gexf"){let _=await $(),{renderWorkspaceKnowledgeGraphGexf:S,renderWorkspaceKnowledgeGraphGraphMl:J,renderWorkspaceKnowledgeGraphJsonLd:F}=await import('./workspace-knowledge-graph-export-UYAYFTWX.js'),W=E==="jsonld"?F(_):E==="graphml"?J(_):S(_),G=p();if(G){let H=b.resolve(l,G);await O__default.outputFile(H,`${W}
391
- `,"utf8"),n.json?console.log(JSON.stringify(b$7(`workspace graph ${E}`,{format:E,entityCount:_.entities.length,relationCount:_.relations.length,proofCount:_.proofs.length},H),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${E}`)),console.log(s.gray(` Written: ${H}`)));return}console.log(W);return}if(E==="explain"){let _=(n.scope?.replace(/^project:/,"")||r||"").trim();_||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let S=C(y,_);if(n.json){console.log(JSON.stringify(S,null,2)),S.found||process.exit(1);return}S.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${_}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${S.project}`)),S.centrality&&console.log(s.gray(` Centrality: fanIn ${S.centrality.fanIn}, fanOut ${S.centrality.fanOut}, reach ${S.centrality.reach}, betweenness ${S.centrality.betweenness}${S.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${S.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${S.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${S.transitiveDependents.length}`));for(let J of S.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${J.id} (d${J.distance}, via ${J.via??"\u2014"})`));return}if(E==="entities"){let _=await $(),{queryKnowledgeEntities:S}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),J=S(_,r);if(n.json){console.log(JSON.stringify({schemaVersion:_.schemaVersion,generatedAt:_.generatedAt,kind:r??null,count:J.length,entities:J},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${r?`: ${r}`:""}`)),console.log(s.gray(` Count: ${J.length}`));for(let F of J)console.log(s.gray(` \u2022 ${F.kind}: ${F.label} [${F.id}]`));return}if(E==="search"||E==="benchmark"){let _=(r||"").trim();_||(console.log(s.red(`\u274C workspace graph ${E} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${E} "authentication endpoint" --json`)),process.exit(1));let S=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(S)||S<1||S>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let J=await $();if(E==="benchmark"){let{buildWorkspaceGraphTokenEfficiencyReport:G}=await import('./workspace-graph-token-efficiency-5FNH4JZ5.js'),H=await G({workspacePath:l,graph:J,query:_,limit:S});n.json?console.log(JSON.stringify(H,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${_}`)),console.log(s.gray(` Estimated tokens: ${H.corpus.estimatedTokens} corpus \u2192 ${H.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${H.savings.reductionRatio}\xD7 (${H.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${H.retrieval.matchCount}`)),console.log(s.yellow(` ${H.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:F}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),W=F(J,{query:_,limit:S});if(n.json)console.log(JSON.stringify(W,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${_}`)),console.log(s.gray(` ${W.entities.length}/${W.totalMatches} match(es)${W.truncated?" (bounded)":""}`));for(let G of W.entities)console.log(s.gray(` \u2022 ${G.kind}: ${G.label} [${G.id}]`));}return}if(E==="evidence"){let _=(r||"").trim();_||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let S=await $(),{queryKnowledgeEvidence:J}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),F=J(S,_);if(n.json)console.log(JSON.stringify(F,null,2));else if(F.found){console.log(s.green(`\u2714 Graph evidence: ${_}`));for(let W of F.proofs)console.log(s.gray(` \u2022 ${W.artifact}${W.pointer?`#${W.pointer}`:""} [${W.provider}/${W.trust}/${W.confidence}]`));}else {console.log(s.red(F.candidates.length>0?`\u274C Graph query is ambiguous: ${_}`:`\u274C Graph entity or relation not found: ${_}`));for(let W of F.candidates.slice(0,10))console.log(s.gray(` \u2022 ${W}`));}F.found||process.exit(1);return}if(E==="path"){let _=(r||"").trim(),S=(o||"").trim();(!_||!S)&&(console.log(s.red("\u274C workspace graph path requires <from> and <to>.")),console.log(s.gray(" npx workspai workspace graph path <from> <to> --json")),process.exit(1));let J=await $(),{queryKnowledgePath:F}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),W=F(J,_,S);if(n.json)console.log(JSON.stringify(W,null,2));else if(W.found){console.log(s.green(`\u2714 Graph proof path: ${_} \u2192 ${S}`));for(let G of W.hops)console.log(s.gray(` \u2022 ${G.from} ${G.direction==="forward"?"\u2192":"\u2190"} ${G.to} [${G.kind}]`));console.log(s.gray(` Proofs: ${W.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${_} and ${S}.`));W.found||process.exit(1);return}if(E==="overlay"){let _=(n.from||r||"").trim();_||(console.log(s.red("\u274C workspace graph overlay requires --from <graph.json>.")),console.log(s.gray(" npx workspai workspace graph overlay --from <graph.json> --json")),process.exit(1));let S=b.resolve(l,_),J;try{J=JSON.parse(await O__default.readFile(S,"utf8"));}catch(Me){console.log(s.red(`\u274C Could not read the base knowledge graph: ${Me instanceof Error?Me.message:String(Me)}`)),process.exit(1);}let F=J&&typeof J=="object"?J:{},W=F.graph,G=W&&typeof W=="object"?W:{},H=F.schemaVersion===b$8.knowledgeGraph?F:F.knowledgeGraph??G.knowledgeGraph;(!H||typeof H!="object"||H.schemaVersion!==b$8.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${b$8.knowledgeGraph} document.`)),process.exit(1));let Te=await $(),{buildWorkspaceKnowledgeGraphChangeOverlay:we}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),ie=we(H,Te);if(n.json){console.log(JSON.stringify(ie,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${_}`)),console.log(s.gray(` Risk: ${ie.summary.risk}`)),console.log(s.gray(` Entities: +${ie.summary.entityAdds} -${ie.summary.entityRemovals} ~${ie.summary.entityChanges}`)),console.log(s.gray(` Relations: +${ie.summary.relationAdds} -${ie.summary.relationRemovals} ~${ie.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${ie.summary.proofAdds} -${ie.summary.proofRemovals} ~${ie.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${ie.summary.impactedEntities} entities \xB7 ${ie.summary.changedArtifacts} proof artifacts`));return}let N=h(y),M=await $();if(n.json){console.log(JSON.stringify({...N,knowledgeGraph:M},null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${N.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${N.graph.stats.edgeCount} (inferred ${N.graph.stats.inferredEdges}, contract ${N.graph.stats.contractEdges}, manual ${N.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${N.integrity.ok?"ok":"issues"} (cycles ${N.integrity.stats.cycleCount}, dangling ${N.integrity.stats.danglingCount}, orphans ${N.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${N.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${M.quality.entityCount} entities \xB7 ${M.quality.relationCount} relations \xB7 ${M.quality.proofCount} proofs \xB7 ${M.providers.length} providers`)),console.log(s.gray(" Query: workspace graph search <query> | entities [kind] | path <from> <to> | evidence <entity-or-relation> | overlay --from <graph.json>")),console.log(s.gray(" Render: workspace graph dot | mermaid | jsonld | graphml | gexf [--output <file>]"));}else if(t==="watch"){let l=a("watch"),{runWorkspaceWatch:P}=await import('./workspace-watch-DLPHLF5R.js'),u=n.once===true||i("--once"),h=n.graphStream===true||i("--graph-stream"),f=n.json===true||h,v=h?new(await import('./workspace-graph-stream-AJPS45FD.js')).WorkspaceGraphStreamPublisher({workspacePath:l}):null,C=new AbortController,R=()=>C.abort();process.once("SIGINT",R),process.once("SIGTERM",R),f||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await P({workspacePath:l,once:u,signal:C.signal,buildOptions:{workspacePath:l,observableScanDepth:d()},onProgress:y=>{f||console.error(s.gray(` ${y}`));},onModel:v?async y=>{let E=(await import('./workspace-model-MNJOGBPP.js')).workspaceModelProjectTopology(y);if(!E)return;let{buildWorkspaceKnowledgeGraph:$}=await import('./workspace-knowledge-graph-BMMM2FUE.js'),{readWorkspaceContract:N}=await import('./workspace-contract-AYFTZIKM.js'),M=null;try{M=(await N({workspacePath:l})).contract;}catch{}let _=await $({workspacePath:l,workspace:{name:y.workspace.name,...y.workspace.profile?{profile:y.workspace.profile}:{}},projects:y.projects.map(S=>({id:S.name,path:S.path,...S.absolutePath?{absolutePath:S.absolutePath}:{},runtime:S.runtime,runtimeCandidates:S.runtimeCandidates,framework:S.framework,...S.kit?{kit:S.kit}:{}})),projectTopology:E,contract:M,now:new Date(y.generatedAt),source:{kind:"workspace-model",artifact:a$3.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(y)}});console.log(JSON.stringify(v.publish(y,_)));}:void 0,emit:y=>{if(h)return;if(f){console.log(JSON.stringify(y));return}if(y.kind==="ready"){console.log(s.gray(` Ready: ${y.graph.nodeCount} nodes, ${y.graph.edgeCount} edges (hash ${y.modelHash.slice(0,12)})`));return}if(y.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${y.error??"unknown error"}`));return}if(y.kind==="unchanged"){console.log(s.gray(` No structural change (${y.mode}, ${y.durationMs}ms)`));return}let E=[];y.changedProjects.length>0&&E.push(`changed: ${y.changedProjects.join(", ")}`),y.addedProjects.length>0&&E.push(`added: ${y.addedProjects.join(", ")}`),y.removedProjects.length>0&&E.push(`removed: ${y.removedProjects.join(", ")}`),y.graph.edgesAdded.length>0&&E.push(`+${y.graph.edgesAdded.length} edges`),y.graph.edgesRemoved.length>0&&E.push(`-${y.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${y.mode}, ${y.durationMs}ms): ${E.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R),!f&&!u&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=a("sync"),{syncWorkspaceProjects:P}=await import('./workspace-B53XH35L.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${b.basename(l)}`));let u=await P(l,n.json===true);await Kr(l,{silent:n.json===true});let{syncWorkspaceProjectLenses:h}=await import('./project-intelligence-lens-ZOAWXYC5.js'),f=await h({workspacePath:l,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:v}=await import('./workspace-registry-summary-GPJEL7K7.js'),C=await v(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:u,contractSynced:true,projectLenses:{synced:f.projects.length,skipped:f.skipped},registrySummary:C},null,2));}else if(t==="registry"){let l=a("registry"),P=e||"status";P!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${P}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:u,resolveWorkspaceRegisteredProjects:h}=await import('./workspace-registry-summary-GPJEL7K7.js'),f=await u(l);if(n.json){console.log(JSON.stringify(f,null,2));return}let v=await h(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${f.authority}`)),console.log(s.gray(` Projects: ${f.projectCount}`)),console.log(s.gray(` Summary: ${f.registrySummaryPath}`)),v.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=a("foundation"),P=e||"ensure";P!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${P}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:u}=await import('./workspace-foundation-FFNCK5ZD.js'),h=await u(l,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(h,null,2));return}h.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${h.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=a("policy"),P=await Sm(l,e,r,o,n.json===true||i("--json"));P!==0&&process.exit(P);}else if(t==="contract"){let l=a("contract"),{buildWorkspaceContractGraph:P,readWorkspaceContract:u,verifyWorkspaceContract:h,writeWorkspaceContract:f,WORKSPACE_CONTRACT_PATH:v}=await import('./workspace-contract-AYFTZIKM.js'),C=e||"inspect",R=p();try{if(C==="init"){let y=await f({workspacePath:l,outputPath:R,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${y.contractPath}`)),console.log(s.gray(` Projects: ${y.contract.projects.length}`));return}if(C==="inspect"){let y=await u({workspacePath:l,contractPath:R});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${y.contractPath}`)),console.log(s.gray(` Workspace: ${y.contract.workspace.name}`)),console.log(s.gray(` Projects: ${y.contract.projects.length}`)),console.log(s.gray(` Schema: v${y.contract.schemaVersion}`));return}if(C==="verify"){let y=await h({workspacePath:l,contractPath:R,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:E}=await import('./workspace-contract-AYFTZIKM.js'),$=await E({workspacePath:l,result:y});if(n.json)console.log(JSON.stringify({...y,evidencePath:$},null,2));else {let N=y.status==="passed"?s.green:s.red;console.log(N(`\u2714 Workspace contract verification ${y.status}: ${y.contractPath}`)),console.log(s.gray(` Projects: ${y.projectCount}`));for(let M of y.checks){let _=M.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${_} ${M.id}: ${M.message}`));}for(let M of y.violations)console.log(s.gray(` Violation: ${M}`));}(y.status==="failed"||y.status!=="passed"&&n.strict)&&process.exit(1);return}if(C==="graph"){let y=await P({workspacePath:l,contractPath:R});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${y.contractPath}`)),console.log(s.gray(` Workspace: ${y.graph.workspace.name}`)),console.log(s.gray(` Projects: ${y.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${y.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${y.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${y.graph.summary.relationshipEdges} (${y.graph.summary.inferredEdges} inferred, ${y.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${y.graph.summary.connectedProjects}/${y.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(y.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(y.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${y.graph.summary.orphanProjects} \xB7 Hotspots: ${y.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${y.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${y.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${y.graph.summary.entityCount} entities \xB7 ${y.graph.summary.knowledgeRelations} relations \xB7 ${y.graph.summary.proofCount} proofs \xB7 ${y.graph.summary.providerCount} providers \xB7 ${y.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${y.graph.summary.portCount}`));for(let E of y.graph.nodes){let $=E.ports.map(M=>`${M.name}:${M.port}`).join(", ")||"none",N=E.operationalProfile?` risk=${E.operationalProfile.weight}/${E.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${E.id} (${E.runtime||"unknown"}${E.framework?`/${E.framework}`:""}) ports=${$} manifests=${E.files.manifests.length}${N}`));}for(let E of y.graph.edges){let $=E.type==="event"?`event:${E.label}`:E.label;console.log(s.gray(` ${E.from} -> ${E.to} [${$}]`));}if(y.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let E of y.graph.dependencyGraph.edges)console.log(s.gray(` ${E.from} -> ${E.to} [${E.kind}/${E.source}/${E.confidence}] evidence=${E.evidence.length}`));}for(let E of y.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${E.severity}: ${E.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${C}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${v}]`)),process.exit(1);}catch(y){n.json&&(console.log(JSON.stringify({command:`workspace contract ${C}`,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${C}.failed`,message:y.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${C} failed: ${y.message}`)),process.exit(1);}}else if(t==="share"){let l=a("share"),P=p()||e,{createWorkspaceShareBundle:u}=await import('./workspace-B53XH35L.js'),h=await u(l,{outputPath:P,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:l,bundlePath:h,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${h}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=a("export");try{let{exportWorkspaceArchive:P}=await import('./workspace-archive-VHUPOBAV.js'),u=n.archiveCompression?.trim().toLowerCase()??"store";if(u!=="store"&&u!=="deflate")throw new Error("--archive-compression must be store or deflate.");let h=await P({workspacePath:l,outputPath:p()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:u});if(n.json){console.log(JSON.stringify(h,null,2));return}let f=(h.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.manifest.files.length}`)),console.log(s.gray(` Size: ${f} MB`)),h.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(P){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:P.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${P.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let l=r;l||(n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:P,inspectWorkspaceArchive:u,verifyWorkspaceArchive:h}=await import('./workspace-archive-VHUPOBAV.js');try{if(e==="inspect"){let v=await u({archivePathOrUrl:l,safety:m()});if(n.json){console.log(JSON.stringify(v,null,2));return}let C=(v.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${v.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${v.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${v.fileCount}`)),console.log(s.gray(` Payload: ${C} MB`));return}if(e==="doctor"){let v=await P({archivePathOrUrl:l,strict:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(v,null,2));else {let C=v.status==="passed"?s.green:v.status==="warning"?s.yellow:s.red;console.log(C(`\u2714 Workspace archive doctor ${v.status}: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.workspaceName}`)),console.log(s.gray(` Files: ${v.fileCount}`));for(let R of v.checks){let y=R.status==="passed"?"\u2714":R.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${y} ${R.id}: ${R.message}`));}for(let R of v.recommendedActions)console.log(s.gray(` Next: ${R}`));}(v.status==="failed"||v.status==="warning"&&n.strict)&&process.exit(1);return}let f=await h({archivePathOrUrl:l,requireChecksums:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(f,null,2));else if(f.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${f.archivePath}`)),console.log(s.gray(` Files: ${f.verifiedFiles}/${f.fileCount}`));else {let v=f.status==="failed"?s.red:s.yellow;console.log(v(`\u274C Workspace archive verification ${f.status}: ${f.archivePath}`)),f.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${f.missingArchiveEntries.join(", ")}`)),f.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${f.extraArchiveEntries.join(", ")}`)),f.mismatches.length&&console.log(s.gray(` Mismatches: ${f.mismatches.map(C=>C.path).join(", ")}`)),f.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${f.missingChecksumFiles.join(", ")}`));}(f.status==="failed"||f.status==="warning"&&n.strict)&&process.exit(1);}catch(f){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,error:{code:`workspace.archive.${e}.failed`,message:f.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${f.message}`)),process.exit(1);}}else if(t==="connect"){let l=b.resolve(e||process.cwd());try{let P=await ks({workspacePath:l,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green(P.status==="preview"?`\u2714 Workspace connection preview: ${l}`:`\u2714 Workspace connected: ${l}`));for(let u of P.warnings)console.log(s.yellow(` \u26A0 ${u}`));}catch(P){let u=P instanceof Error?P.message:String(P);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:u}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${u}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let P=await vs({archivePathOrUrl:l,outputPath:p(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:m()});if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green(P.status==="preview"?`\u2714 Workspace import preview: ${P.workspacePath}`:`\u2714 Workspace imported and registered: ${P.workspacePath}`));for(let u of P.warnings)console.log(s.yellow(` \u26A0 ${u}`));}else {let{hydrateWorkspaceArchive:P}=await import('./workspace-archive-VHUPOBAV.js'),u=await P({archivePathOrUrl:l,outputPath:p(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:m()});if(n.json){console.log(JSON.stringify(u,null,2));return}console.log(s.green(u.dryRun?`\u2714 Workspace archive hydrate preview: ${u.outputPath}`:`\u2714 Workspace archive hydrated: ${u.outputPath}`)),console.log(s.gray(` Files: ${u.files.length}`)),u.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${u.manifest.workspaceName}`));}}catch(P){let u=P instanceof Error?P.message:String(P);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:u,context:{archivePathOrUrl:l,...p()?{outputPath:p()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,...p()?{outputPath:p()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:u}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${u}`)),process.exit(1);}}else if(t==="run"){let l=a(`run ${e||""}`.trim()),P=new Set(["init","test","build","start"]),u=e?.trim()??"";u||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .workspai/context.json commands")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2)),P.has(u)||(!/^[a-z][a-z0-9_-]*$/i.test(u)||u==="dev"||u==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${u}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),u==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let h=Is({raw:n.maxWorkers,operation:`workspace run ${u}`,json:n.json===true||i("--json")});if(u==="init"&&n.json!==true){let C=await Ls(l);C!==0&&process.exit(C);}let{runWorkspaceStage:f}=await import('./workspace-run-3U77TMKX.js'),v=await f({workspacePath:l,stage:u,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:h,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(v,null,2)),v.summary.exitCode!==0&&process.exit(v.summary.exitCode);}else if(t==="explain"||t==="why"){let l=a(t),{parseWorkspaceExplainTarget:P}=await import('./workspace-explain-contract-N2XQHAPM.js'),{buildWorkspaceExplain:u,writeWorkspaceExplainReport:h}=await import('./workspace-explain-SZI2WAAD.js'),f=(e??r??"").trim();!f&&n.scope&&(f=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),f||(f="release-blocked");let v=P(f);v||(console.log(s.red(`\u274C Invalid explain target: ${f}`)),process.exit(1));let C=await u({workspacePath:l,target:v}),R=n.write===true||i("--write"),y;if(R&&(y=await h(C,l,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$7(`workspace ${t}`,C,y),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${C.summary}`));for(let E of C.sections)console.log(s.bold(`
391
+ `,"utf8"),n.json?console.log(JSON.stringify(b$7(`workspace graph ${E}`,{format:E,entityCount:_.entities.length,relationCount:_.relations.length,proofCount:_.proofs.length},H),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${E}`)),console.log(s.gray(` Written: ${H}`)));return}console.log(W);return}if(E==="explain"){let _=(n.scope?.replace(/^project:/,"")||r||"").trim();_||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let S=C(y,_);if(n.json){console.log(JSON.stringify(S,null,2)),S.found||process.exit(1);return}S.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${_}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${S.project}`)),S.centrality&&console.log(s.gray(` Centrality: fanIn ${S.centrality.fanIn}, fanOut ${S.centrality.fanOut}, reach ${S.centrality.reach}, betweenness ${S.centrality.betweenness}${S.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${S.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${S.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${S.transitiveDependents.length}`));for(let J of S.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${J.id} (d${J.distance}, via ${J.via??"\u2014"})`));return}if(E==="entities"){let _=await $(),{queryKnowledgeEntities:S}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),J=S(_,r);if(n.json){console.log(JSON.stringify({schemaVersion:_.schemaVersion,generatedAt:_.generatedAt,kind:r??null,count:J.length,entities:J},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${r?`: ${r}`:""}`)),console.log(s.gray(` Count: ${J.length}`));for(let F of J)console.log(s.gray(` \u2022 ${F.kind}: ${F.label} [${F.id}]`));return}if(E==="search"||E==="benchmark"){let _=(r||"").trim();_||(console.log(s.red(`\u274C workspace graph ${E} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${E} "authentication endpoint" --json`)),process.exit(1));let S=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(S)||S<1||S>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let J=await $();if(E==="benchmark"){let{buildWorkspaceGraphTokenEfficiencyReport:G}=await import('./workspace-graph-token-efficiency-5FNH4JZ5.js'),H=await G({workspacePath:l,graph:J,query:_,limit:S});n.json?console.log(JSON.stringify(H,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${_}`)),console.log(s.gray(` Estimated tokens: ${H.corpus.estimatedTokens} corpus \u2192 ${H.retrieval.estimatedTokens} bounded retrieval`)),console.log(s.gray(` Estimated payload reduction: ${H.savings.reductionRatio}\xD7 (${H.savings.reductionPercent}%)`)),console.log(s.gray(` Matches: ${H.retrieval.matchCount}`)),console.log(s.yellow(` ${H.methodology.claimBoundary}`)));return}let{searchKnowledgeGraph:F}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),W=F(J,{query:_,limit:S});if(n.json)console.log(JSON.stringify(W,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${_}`)),console.log(s.gray(` ${W.entities.length}/${W.totalMatches} match(es)${W.truncated?" (bounded)":""}`));for(let G of W.entities)console.log(s.gray(` \u2022 ${G.kind}: ${G.label} [${G.id}]`));}return}if(E==="evidence"){let _=(r||"").trim();_||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let S=await $(),{queryKnowledgeEvidence:J}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),F=J(S,_);if(n.json)console.log(JSON.stringify(F,null,2));else if(F.found){console.log(s.green(`\u2714 Graph evidence: ${_}`));for(let W of F.proofs)console.log(s.gray(` \u2022 ${W.artifact}${W.pointer?`#${W.pointer}`:""} [${W.provider}/${W.trust}/${W.confidence}]`));}else {console.log(s.red(F.candidates.length>0?`\u274C Graph query is ambiguous: ${_}`:`\u274C Graph entity or relation not found: ${_}`));for(let W of F.candidates.slice(0,10))console.log(s.gray(` \u2022 ${W}`));}F.found||process.exit(1);return}if(E==="path"){let _=(r||"").trim(),S=(o||"").trim();(!_||!S)&&(console.log(s.red("\u274C workspace graph path requires <from> and <to>.")),console.log(s.gray(" npx workspai workspace graph path <from> <to> --json")),process.exit(1));let J=await $(),{queryKnowledgePath:F}=await import('./workspace-knowledge-graph-query-EKHIE3E2.js'),W=F(J,_,S);if(n.json)console.log(JSON.stringify(W,null,2));else if(W.found){console.log(s.green(`\u2714 Graph proof path: ${_} \u2192 ${S}`));for(let G of W.hops)console.log(s.gray(` \u2022 ${G.from} ${G.direction==="forward"?"\u2192":"\u2190"} ${G.to} [${G.kind}]`));console.log(s.gray(` Proofs: ${W.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${_} and ${S}.`));W.found||process.exit(1);return}if(E==="overlay"){let _=(n.from||r||"").trim();_||(console.log(s.red("\u274C workspace graph overlay requires --from <graph.json>.")),console.log(s.gray(" npx workspai workspace graph overlay --from <graph.json> --json")),process.exit(1));let S=b.resolve(l,_),J;try{J=JSON.parse(await O__default.readFile(S,"utf8"));}catch(Me){console.log(s.red(`\u274C Could not read the base knowledge graph: ${Me instanceof Error?Me.message:String(Me)}`)),process.exit(1);}let F=J&&typeof J=="object"?J:{},W=F.graph,G=W&&typeof W=="object"?W:{},H=F.schemaVersion===b$8.knowledgeGraph?F:F.knowledgeGraph??G.knowledgeGraph;(!H||typeof H!="object"||H.schemaVersion!==b$8.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${b$8.knowledgeGraph} document.`)),process.exit(1));let Te=await $(),{buildWorkspaceKnowledgeGraphChangeOverlay:we}=await import('./workspace-knowledge-graph-change-overlay-XG6FC4IX.js'),ie=we(H,Te);if(n.json){console.log(JSON.stringify(ie,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${_}`)),console.log(s.gray(` Risk: ${ie.summary.risk}`)),console.log(s.gray(` Entities: +${ie.summary.entityAdds} -${ie.summary.entityRemovals} ~${ie.summary.entityChanges}`)),console.log(s.gray(` Relations: +${ie.summary.relationAdds} -${ie.summary.relationRemovals} ~${ie.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${ie.summary.proofAdds} -${ie.summary.proofRemovals} ~${ie.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${ie.summary.impactedEntities} entities \xB7 ${ie.summary.changedArtifacts} proof artifacts`));return}let N=h(y),M=await $();if(n.json){console.log(JSON.stringify({...N,knowledgeGraph:M},null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${N.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${N.graph.stats.edgeCount} (inferred ${N.graph.stats.inferredEdges}, contract ${N.graph.stats.contractEdges}, manual ${N.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${N.integrity.ok?"ok":"issues"} (cycles ${N.integrity.stats.cycleCount}, dangling ${N.integrity.stats.danglingCount}, orphans ${N.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${N.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${M.quality.entityCount} entities \xB7 ${M.quality.relationCount} relations \xB7 ${M.quality.proofCount} proofs \xB7 ${M.providers.length} providers`)),console.log(s.gray(" Query: workspace graph search <query> | entities [kind] | path <from> <to> | evidence <entity-or-relation> | overlay --from <graph.json>")),console.log(s.gray(" Render: workspace graph dot | mermaid | jsonld | graphml | gexf [--output <file>]"));}else if(t==="watch"){let l=a("watch"),{runWorkspaceWatch:P}=await import('./workspace-watch-DLPHLF5R.js'),u=n.once===true||i("--once"),h=n.graphStream===true||i("--graph-stream"),f=n.json===true||h,v=h?new(await import('./workspace-graph-stream-AJPS45FD.js')).WorkspaceGraphStreamPublisher({workspacePath:l}):null,C=new AbortController,R=()=>C.abort();process.once("SIGINT",R),process.once("SIGTERM",R),f||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await P({workspacePath:l,once:u,signal:C.signal,buildOptions:{workspacePath:l,observableScanDepth:d()},onProgress:y=>{f||console.error(s.gray(` ${y}`));},onModel:v?async y=>{let E=(await import('./workspace-model-MNJOGBPP.js')).workspaceModelProjectTopology(y);if(!E)return;let{buildWorkspaceKnowledgeGraph:$}=await import('./workspace-knowledge-graph-BMMM2FUE.js'),{readWorkspaceContract:N}=await import('./workspace-contract-AYFTZIKM.js'),M=null;try{M=(await N({workspacePath:l})).contract;}catch{}let _=await $({workspacePath:l,workspace:{name:y.workspace.name,...y.workspace.profile?{profile:y.workspace.profile}:{}},projects:y.projects.map(S=>({id:S.name,path:S.path,...S.absolutePath?{absolutePath:S.absolutePath}:{},runtime:S.runtime,runtimeCandidates:S.runtimeCandidates,framework:S.framework,...S.kit?{kit:S.kit}:{}})),projectTopology:E,contract:M,now:new Date(y.generatedAt),source:{kind:"workspace-model",artifact:a$3.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(y)}});console.log(JSON.stringify(v.publish(y,_)));}:void 0,emit:y=>{if(h)return;if(f){console.log(JSON.stringify(y));return}if(y.kind==="ready"){console.log(s.gray(` Ready: ${y.graph.nodeCount} nodes, ${y.graph.edgeCount} edges (hash ${y.modelHash.slice(0,12)})`));return}if(y.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${y.error??"unknown error"}`));return}if(y.kind==="unchanged"){console.log(s.gray(` No structural change (${y.mode}, ${y.durationMs}ms)`));return}let E=[];y.changedProjects.length>0&&E.push(`changed: ${y.changedProjects.join(", ")}`),y.addedProjects.length>0&&E.push(`added: ${y.addedProjects.join(", ")}`),y.removedProjects.length>0&&E.push(`removed: ${y.removedProjects.join(", ")}`),y.graph.edgesAdded.length>0&&E.push(`+${y.graph.edgesAdded.length} edges`),y.graph.edgesRemoved.length>0&&E.push(`-${y.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${y.mode}, ${y.durationMs}ms): ${E.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R),!f&&!u&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let l=a("sync"),{syncWorkspaceProjects:P}=await import('./workspace-B53XH35L.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${b.basename(l)}`));let u=await P(l,n.json===true);await Kr(l,{silent:n.json===true});let{syncWorkspaceProjectLenses:h}=await import('./project-intelligence-lens-ZOAWXYC5.js'),f=await h({workspacePath:l,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:v}=await import('./workspace-registry-summary-GPJEL7K7.js'),C=await v(l);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:l,registry:u,contractSynced:true,projectLenses:{synced:f.projects.length,skipped:f.skipped},registrySummary:C},null,2));}else if(t==="registry"){let l=a("registry"),P=e||"status";P!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${P}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:u,resolveWorkspaceRegisteredProjects:h}=await import('./workspace-registry-summary-GPJEL7K7.js'),f=await u(l);if(n.json){console.log(JSON.stringify(f,null,2));return}let v=await h(l);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${f.authority}`)),console.log(s.gray(` Projects: ${f.projectCount}`)),console.log(s.gray(` Summary: ${f.registrySummaryPath}`)),v.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let l=a("foundation"),P=e||"ensure";P!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${P}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:u}=await import('./workspace-foundation-FFNCK5ZD.js'),h=await u(l,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(h,null,2));return}h.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${h.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let l=a("policy"),P=await Sm(l,e,r,o,n.json===true||i("--json"));P!==0&&process.exit(P);}else if(t==="contract"){let l=a("contract"),{buildWorkspaceContractGraph:P,readWorkspaceContract:u,verifyWorkspaceContract:h,writeWorkspaceContract:f,WORKSPACE_CONTRACT_PATH:v}=await import('./workspace-contract-AYFTZIKM.js'),C=e||"inspect",R=p();try{if(C==="init"){let y=await f({workspacePath:l,outputPath:R,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${y.contractPath}`)),console.log(s.gray(` Projects: ${y.contract.projects.length}`));return}if(C==="inspect"){let y=await u({workspacePath:l,contractPath:R});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${y.contractPath}`)),console.log(s.gray(` Workspace: ${y.contract.workspace.name}`)),console.log(s.gray(` Projects: ${y.contract.projects.length}`)),console.log(s.gray(` Schema: v${y.contract.schemaVersion}`));return}if(C==="verify"){let y=await h({workspacePath:l,contractPath:R,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:E}=await import('./workspace-contract-AYFTZIKM.js'),$=await E({workspacePath:l,result:y});if(n.json)console.log(JSON.stringify({...y,evidencePath:$},null,2));else {let N=y.status==="passed"?s.green:s.red;console.log(N(`\u2714 Workspace contract verification ${y.status}: ${y.contractPath}`)),console.log(s.gray(` Projects: ${y.projectCount}`));for(let M of y.checks){let _=M.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${_} ${M.id}: ${M.message}`));}for(let M of y.violations)console.log(s.gray(` Violation: ${M}`));}(y.status==="failed"||y.status!=="passed"&&n.strict)&&process.exit(1);return}if(C==="graph"){let y=await P({workspacePath:l,contractPath:R});if(n.json){console.log(JSON.stringify(y,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${y.contractPath}`)),console.log(s.gray(` Workspace: ${y.graph.workspace.name}`)),console.log(s.gray(` Projects: ${y.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${y.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${y.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${y.graph.summary.relationshipEdges} (${y.graph.summary.inferredEdges} inferred, ${y.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${y.graph.summary.connectedProjects}/${y.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(y.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(y.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${y.graph.summary.orphanProjects} \xB7 Hotspots: ${y.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${y.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${y.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${y.graph.summary.entityCount} entities \xB7 ${y.graph.summary.knowledgeRelations} relations \xB7 ${y.graph.summary.proofCount} proofs \xB7 ${y.graph.summary.providerCount} providers \xB7 ${y.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${y.graph.summary.portCount}`));for(let E of y.graph.nodes){let $=E.ports.map(M=>`${M.name}:${M.port}`).join(", ")||"none",N=E.operationalProfile?` risk=${E.operationalProfile.weight}/${E.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${E.id} (${E.runtime||"unknown"}${E.framework?`/${E.framework}`:""}) ports=${$} manifests=${E.files.manifests.length}${N}`));}for(let E of y.graph.edges){let $=E.type==="event"?`event:${E.label}`:E.label;console.log(s.gray(` ${E.from} -> ${E.to} [${$}]`));}if(y.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let E of y.graph.dependencyGraph.edges)console.log(s.gray(` ${E.from} -> ${E.to} [${E.kind}/${E.source}/${E.confidence}] evidence=${E.evidence.length}`));}for(let E of y.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${E.severity}: ${E.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${C}`)),console.log(s.white(` npx workspai workspace contract init|inspect|verify|graph [--output ${v}]`)),process.exit(1);}catch(y){n.json&&(console.log(JSON.stringify({command:`workspace contract ${C}`,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${C}.failed`,message:y.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${C} failed: ${y.message}`)),process.exit(1);}}else if(t==="share"){let l=a("share"),P=p()||e,{createWorkspaceShareBundle:u}=await import('./workspace-B53XH35L.js'),h=await u(l,{outputPath:P,includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false});if(n.json){console.log(JSON.stringify({command:"workspace share",result:"ok",timestamp:new Date().toISOString(),workspacePath:l,bundlePath:h,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${h}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let l=a("export");try{let{exportWorkspaceArchive:P}=await import('./workspace-archive-VHUPOBAV.js'),u=n.archiveCompression?.trim().toLowerCase()??"store";if(u!=="store"&&u!=="deflate")throw new Error("--archive-compression must be store or deflate.");let h=await P({workspacePath:l,outputPath:p()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:u});if(n.json){console.log(JSON.stringify(h,null,2));return}let f=(h.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.manifest.files.length}`)),console.log(s.gray(` Size: ${f} MB`)),h.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(P){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:P.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${P.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let l=r;l||(n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:P,inspectWorkspaceArchive:u,verifyWorkspaceArchive:h}=await import('./workspace-archive-VHUPOBAV.js');try{if(e==="inspect"){let v=await u({archivePathOrUrl:l,safety:m()});if(n.json){console.log(JSON.stringify(v,null,2));return}let C=(v.totalBytes/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.manifest.workspaceName}`)),console.log(s.gray(` Exported: ${v.manifest.exportedAt}`)),console.log(s.gray(` Exporter: ${v.manifest.exportedBy||"unknown"}`)),console.log(s.gray(` Files: ${v.fileCount}`)),console.log(s.gray(` Payload: ${C} MB`));return}if(e==="doctor"){let v=await P({archivePathOrUrl:l,strict:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(v,null,2));else {let C=v.status==="passed"?s.green:v.status==="warning"?s.yellow:s.red;console.log(C(`\u2714 Workspace archive doctor ${v.status}: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.workspaceName}`)),console.log(s.gray(` Files: ${v.fileCount}`));for(let R of v.checks){let y=R.status==="passed"?"\u2714":R.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${y} ${R.id}: ${R.message}`));}for(let R of v.recommendedActions)console.log(s.gray(` Next: ${R}`));}(v.status==="failed"||v.status==="warning"&&n.strict)&&process.exit(1);return}let f=await h({archivePathOrUrl:l,requireChecksums:n.strict===true||i("--strict"),safety:m()});if(n.json)console.log(JSON.stringify(f,null,2));else if(f.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${f.archivePath}`)),console.log(s.gray(` Files: ${f.verifiedFiles}/${f.fileCount}`));else {let v=f.status==="failed"?s.red:s.yellow;console.log(v(`\u274C Workspace archive verification ${f.status}: ${f.archivePath}`)),f.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${f.missingArchiveEntries.join(", ")}`)),f.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${f.extraArchiveEntries.join(", ")}`)),f.mismatches.length&&console.log(s.gray(` Mismatches: ${f.mismatches.map(C=>C.path).join(", ")}`)),f.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${f.missingChecksumFiles.join(", ")}`));}(f.status==="failed"||f.status==="warning"&&n.strict)&&process.exit(1);}catch(f){n.json&&(console.log(JSON.stringify({schemaVersion:c$2,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,error:{code:`workspace.archive.${e}.failed`,message:f.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${f.message}`)),process.exit(1);}}else if(t==="connect"){let l=b.resolve(e||process.cwd());try{let P=await ks({workspacePath:l,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green(P.status==="preview"?`\u2714 Workspace connection preview: ${l}`:`\u2714 Workspace connected: ${l}`));for(let u of P.warnings)console.log(s.yellow(` \u26A0 ${u}`));}catch(P){let u=P instanceof Error?P.message:String(P);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:u}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${u}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let l=e;l||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let P=await vs({archivePathOrUrl:l,outputPath:p(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:m()});if(n.json){console.log(JSON.stringify(P,null,2));return}console.log(s.green(P.status==="preview"?`\u2714 Workspace import preview: ${P.workspacePath}`:`\u2714 Workspace imported and registered: ${P.workspacePath}`));for(let u of P.warnings)console.log(s.yellow(` \u26A0 ${u}`));}else {let{hydrateWorkspaceArchive:P}=await import('./workspace-archive-VHUPOBAV.js'),u=await P({archivePathOrUrl:l,outputPath:p(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:m()});if(n.json){console.log(JSON.stringify(u,null,2));return}console.log(s.green(u.dryRun?`\u2714 Workspace archive hydrate preview: ${u.outputPath}`:`\u2714 Workspace archive hydrated: ${u.outputPath}`)),console.log(s.gray(` Files: ${u.files.length}`)),u.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${u.manifest.workspaceName}`));}}catch(P){let u=P instanceof Error?P.message:String(P);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:u,context:{archivePathOrUrl:l,...p()?{outputPath:p()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$2,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:l,...p()?{outputPath:p()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:u}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${u}`)),process.exit(1);}}else if(t==="run"){let l=a(`run ${e||""}`.trim()),P=new Set(["init","test","build","start"]),u=e?.trim()??"";u||(console.log(s.red(`Unknown workspace run stage: ${e||"(none provided)"}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),console.log(s.gray(" \u2022 init \u2014 run install/bootstrap across the project fleet")),console.log(s.gray(" \u2022 test \u2014 run test suite across selected projects")),console.log(s.gray(" \u2022 build \u2014 compile/package across selected projects")),console.log(s.gray(" \u2022 start \u2014 start services (smoke/e2e scenarios)")),console.log(s.gray(" \u2022 custom \u2014 any stage key declared in .workspai/context.json commands")),console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2)),P.has(u)||(!/^[a-z][a-z0-9_-]*$/i.test(u)||u==="dev"||u==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${u}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),u==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let h=Is({raw:n.maxWorkers,operation:`workspace run ${u}`,json:n.json===true||i("--json")});if(u==="init"&&n.json!==true){let C=await Ls(l);C!==0&&process.exit(C);}let{runWorkspaceStage:f}=await import('./workspace-run-VPXRRHDK.js'),v=await f({workspacePath:l,stage:u,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:h,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true});n.json&&console.log(JSON.stringify(v,null,2)),v.summary.exitCode!==0&&process.exit(v.summary.exitCode);}else if(t==="explain"||t==="why"){let l=a(t),{parseWorkspaceExplainTarget:P}=await import('./workspace-explain-contract-N2XQHAPM.js'),{buildWorkspaceExplain:u,writeWorkspaceExplainReport:h}=await import('./workspace-explain-SZI2WAAD.js'),f=(e??r??"").trim();!f&&n.scope&&(f=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),f||(f="release-blocked");let v=P(f);v||(console.log(s.red(`\u274C Invalid explain target: ${f}`)),process.exit(1));let C=await u({workspacePath:l,target:v}),R=n.write===true||i("--write"),y;if(R&&(y=await h(C,l,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$7(`workspace ${t}`,C,y),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${C.summary}`));for(let E of C.sections)console.log(s.bold(`
392
392
  ${E.title}`)),console.log(E.body);y&&console.log(s.gray(`
393
393
  Written: ${y}`));}else if(t==="trace"){let l=a("trace"),P=n.from||e;P||(console.log(s.red("\u274C workspace trace requires --from <diff-ref>")),console.log(s.gray(" npx workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --json")),process.exit(1));let{resolveWorkspaceTraceTarget:u}=await import('./workspace-explain-contract-N2XQHAPM.js'),{buildWorkspaceExplain:h,writeWorkspaceExplainReport:f}=await import('./workspace-explain-SZI2WAAD.js'),v=u(P);(!v||v.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${P}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.workspai/reports/workspace-model-diff-last-run.json")),process.exit(1));let C=await h({workspacePath:l,target:v}),R=n.write===true||i("--write"),y;if(R&&(y=await f(C,l,"trace")),n.json){console.log(JSON.stringify(b$7("workspace trace",C,y),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${C.summary}`));for(let E of C.sections)console.log(s.bold(`
394
394
  ${E.title}`)),console.log(E.body);y&&console.log(s.gray(`
395
395
  Written: ${y}`));}else if(t==="eval"){let l=a("eval"),P=(e||"status").toLowerCase(),{WORKSPACE_EVALUATION_LAST_RUN_PATH:u,WORKSPACE_EVALUATION_LIVE_PATH:h,appendWorkspaceEvaluationEvent:f,compareWorkspaceEvaluations:v,createWorkspaceEvaluation:C,finalizeWorkspaceEvaluation:R,readWorkspaceEvaluation:y,writeWorkspaceEvaluation:E}=await import('./workspace-intelligence-evaluation-UP2K3L35.js');if(P==="init"){let $=(r||"").trim(),N=(o||"workspace-intelligence").trim(),M=["full-corpus","grep","vector","graph","workspace-intelligence","custom"];(!$||!M.includes(N))&&(console.log(s.red("\u274C workspace eval init requires <task> and an optional valid strategy.")),console.log(s.gray(` Strategies: ${M.join(" | ")}
396
- npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:_}=await import('./workspace-marker-7NHMDIRL.js'),S=await _(l),J=C({workspacePath:l,workspaceName:S?.name,taskId:$,strategy:N}),F=await E(l,J);if(n.json){console.log(JSON.stringify(b$7("workspace eval init",J,F),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${$}`)),console.log(s.gray(` Run: ${J.runId}`)),console.log(s.gray(` Strategy: ${J.configuration.strategy}`)),console.log(s.gray(` Live: ${F}`));return}if(P==="record"){!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace eval record requires --json and a stdin event.")),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace eval record requires piped JSON on stdin.")),process.exit(1));let{parseFeedbackStdinPayload:$,readStdinAll:N}=await import('./workspace-feedback-WXE7NVMV.js'),M=$(await N());M||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let _=await f({workspacePath:l,payload:M});console.log(JSON.stringify(_,null,2));}catch(_){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:_ instanceof Error?_.message:String(_),context:{workspacePath:l}}),null,2)),process.exit(1);}return}if(P==="report"){let $=await R({workspacePath:l}),N=p(),M=$.outputPath;if(N){let _=b.resolve(l,N);b.resolve($.outputPath)!==_&&await O__default.copy($.outputPath,_,{overwrite:true}),M=_;}if(n.json){console.log(JSON.stringify(b$7("workspace eval report",$.report,M),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${$.report.runId}`)),console.log(s.gray(` Tokens: ${$.report.summary.tokens.observedTotal} \xB7 model calls ${$.report.summary.modelCalls} \xB7 tool calls ${$.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${$.report.summary.outcome.status}${$.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${M}`));return}if(P==="compare"){let $=(n.from||r||"").trim();$||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let N=await y(l,u),M=await y(l,$),_=v(N,M);if(n.json){console.log(JSON.stringify(_,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${_.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${_.delta.tokens}`)),console.log(s.gray(` Reduction: ${_.delta.reductionPercent===null?"unavailable":`${_.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${_.comparableOutcome?"yes":"no"}`));return}if(P==="status"){let $;try{$=await y(l,h);}catch{$=await y(l,u);}if(n.json){console.log(JSON.stringify($,null,2));return}console.log(s.green(`\u2714 Evaluation ${$.status}: ${$.configuration.taskId}`)),console.log(s.gray(` Run: ${$.runId}`)),console.log(s.gray(` Events: ${$.events.length}`)),console.log(s.gray(` Tokens: ${$.summary.tokens.observedTotal} (${$.summary.tokenSources.providerReported} provider-reported calls, ${$.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${P}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let l=a("feedback"),P=(e||"record").toLowerCase();P!=="record"&&(console.log(s.red(`Unknown feedback action: ${P}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace feedback record requires --json (stdin payload)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace feedback record requires piped JSON on stdin (not a TTY)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:u,parseFeedbackStdinPayload:h,readStdinAll:f}=await import('./workspace-feedback-WXE7NVMV.js'),v=await f(),C=h(v);C||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let R=await u({workspacePath:l,payload:C});n.json?console.log(JSON.stringify(R,null,2)):R.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${R.historyPath}`))):console.log(s.red(`\u274C ${R.error??"Failed to record feedback"}`)),R.ok||process.exit(1);}else if(t==="goal"){let l=a("goal"),P=(e||"status").toLowerCase(),u=r?.trim(),{planVerifiedGoal:h,readVerifiedGoal:f,verifyVerifiedGoal:v,VERIFIED_GOAL_SCHEMA_VERSION:C}=await import('./verified-goal-MCSNMA3P.js'),R=y=>{if(n.json){console.log(JSON.stringify(y,null,2));return}let E=y.goal;console.log(y.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(y.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),E&&console.log(s.bold(` ${E.summary}`)),console.log(s.gray(` Goal: ${y.status.goalId}`)),console.log(s.gray(` Progress: ${y.status.progress.message}`)),console.log(s.gray(` State: ${y.status.state}`)),y.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${y.status.blockingReasons[0]}`)),y.status.nextActions.length>0&&console.log(s.gray(` Next: ${y.status.nextActions[0]}`)),console.log(s.gray(` Status: ${y.status.artifactPath}`));};if(P==="plan"){if(!u||!["release-readiness","dependency-security","test-coverage"].includes(u)){let N="Goal kind must be release-readiness, dependency-security, or test-coverage.";n.json?console.log(JSON.stringify(c$1({operation:"workspace goal plan",code:"workspace.goal.kind.invalid",message:N}),null,2)):console.log(s.red(`\u274C ${N}`)),process.exit(1);}let E=Number(n.target??80);if(!Number.isFinite(E)||E<0||E>100)throw new Error("--target must be a number from 0 to 100.");let $=await h({workspacePath:l,kind:u,scope:n.scope,target:E,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});R($);}else if(P==="status"){if(!u)throw new Error("workspace goal status requires a goal id.");let y=await f(l,u);R({...y,resumed:y.status.state!=="verified"});}else if(P==="verify"){if(!u)throw new Error("workspace goal verify requires a goal id.");let y=await f(l,u),E=await v({workspacePath:l,goalId:u,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});R({goal:y.goal,status:E}),E.state!=="verified"&&process.exit(2);}else {let y=`Unknown workspace goal action: ${P}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:y,context:{schemaVersion:C,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${y}`)),process.exit(1);}}else if(t==="mcp"){let l=a("mcp"),P=(e||"serve").toLowerCase();P!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:P,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${P}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${P}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:u}=await import('./workspace-mcp-serve-COA4FMCA.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await u({workspacePath:l});}else if(t==="init"){n.json||(console.log(s.yellow("\u2139 workspace init is an alias of: npx workspai workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
396
+ npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:_}=await import('./workspace-marker-7NHMDIRL.js'),S=await _(l),J=C({workspacePath:l,workspaceName:S?.name,taskId:$,strategy:N}),F=await E(l,J);if(n.json){console.log(JSON.stringify(b$7("workspace eval init",J,F),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${$}`)),console.log(s.gray(` Run: ${J.runId}`)),console.log(s.gray(` Strategy: ${J.configuration.strategy}`)),console.log(s.gray(` Live: ${F}`));return}if(P==="record"){!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace eval record requires --json and a stdin event.")),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace eval record requires piped JSON on stdin.")),process.exit(1));let{parseFeedbackStdinPayload:$,readStdinAll:N}=await import('./workspace-feedback-WXE7NVMV.js'),M=$(await N());M||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let _=await f({workspacePath:l,payload:M});console.log(JSON.stringify(_,null,2));}catch(_){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:_ instanceof Error?_.message:String(_),context:{workspacePath:l}}),null,2)),process.exit(1);}return}if(P==="report"){let $=await R({workspacePath:l}),N=p(),M=$.outputPath;if(N){let _=b.resolve(l,N);b.resolve($.outputPath)!==_&&await O__default.copy($.outputPath,_,{overwrite:true}),M=_;}if(n.json){console.log(JSON.stringify(b$7("workspace eval report",$.report,M),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${$.report.runId}`)),console.log(s.gray(` Tokens: ${$.report.summary.tokens.observedTotal} \xB7 model calls ${$.report.summary.modelCalls} \xB7 tool calls ${$.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${$.report.summary.outcome.status}${$.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${M}`));return}if(P==="compare"){let $=(n.from||r||"").trim();$||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let N=await y(l,u),M=await y(l,$),_=v(N,M);if(n.json){console.log(JSON.stringify(_,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${_.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${_.delta.tokens}`)),console.log(s.gray(` Reduction: ${_.delta.reductionPercent===null?"unavailable":`${_.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${_.comparableOutcome?"yes":"no"}`));return}if(P==="status"){let $;try{$=await y(l,h);}catch{$=await y(l,u);}if(n.json){console.log(JSON.stringify($,null,2));return}console.log(s.green(`\u2714 Evaluation ${$.status}: ${$.configuration.taskId}`)),console.log(s.gray(` Run: ${$.runId}`)),console.log(s.gray(` Events: ${$.events.length}`)),console.log(s.gray(` Tokens: ${$.summary.tokens.observedTotal} (${$.summary.tokenSources.providerReported} provider-reported calls, ${$.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${P}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let l=a("feedback"),P=(e||"record").toLowerCase();P!=="record"&&(console.log(s.red(`Unknown feedback action: ${P}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!i("--json")&&(console.log(s.red("\u274C workspace feedback record requires --json (stdin payload)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1)),process.stdin.isTTY&&(console.log(s.red("\u274C workspace feedback record requires piped JSON on stdin (not a TTY)")),console.log(s.gray(` echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | npx workspai workspace feedback record --json`)),process.exit(1));let{recordWorkspaceFeedback:u,parseFeedbackStdinPayload:h,readStdinAll:f}=await import('./workspace-feedback-WXE7NVMV.js'),v=await f(),C=h(v);C||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let R=await u({workspacePath:l,payload:C});n.json?console.log(JSON.stringify(R,null,2)):R.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${R.historyPath}`))):console.log(s.red(`\u274C ${R.error??"Failed to record feedback"}`)),R.ok||process.exit(1);}else if(t==="goal"){let l=a("goal"),P=(e||"status").toLowerCase(),u=r?.trim(),{planVerifiedGoal:h,readVerifiedGoal:f,verifyVerifiedGoal:v,VERIFIED_GOAL_SCHEMA_VERSION:C}=await import('./verified-goal-S2PEBJUV.js'),R=y=>{if(n.json){console.log(JSON.stringify(y,null,2));return}let E=y.goal;console.log(y.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(y.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),E&&console.log(s.bold(` ${E.summary}`)),console.log(s.gray(` Goal: ${y.status.goalId}`)),console.log(s.gray(` Progress: ${y.status.progress.message}`)),console.log(s.gray(` State: ${y.status.state}`)),y.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${y.status.blockingReasons[0]}`)),y.status.nextActions.length>0&&console.log(s.gray(` Next: ${y.status.nextActions[0]}`)),console.log(s.gray(` Status: ${y.status.artifactPath}`));};if(P==="plan"){if(!u||!["release-readiness","dependency-security","test-coverage"].includes(u)){let N="Goal kind must be release-readiness, dependency-security, or test-coverage.";n.json?console.log(JSON.stringify(c$1({operation:"workspace goal plan",code:"workspace.goal.kind.invalid",message:N}),null,2)):console.log(s.red(`\u274C ${N}`)),process.exit(1);}let E=Number(n.target??80);if(!Number.isFinite(E)||E<0||E>100)throw new Error("--target must be a number from 0 to 100.");let $=await h({workspacePath:l,kind:u,scope:n.scope,target:E,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});R($);}else if(P==="status"){if(!u)throw new Error("workspace goal status requires a goal id.");let y=await f(l,u);R({...y,resumed:y.status.state!=="verified"});}else if(P==="verify"){if(!u)throw new Error("workspace goal verify requires a goal id.");let y=await f(l,u),E=await v({workspacePath:l,goalId:u,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});R({goal:y.goal,status:E}),E.state!=="verified"&&process.exit(2);}else {let y=`Unknown workspace goal action: ${P}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:y,context:{schemaVersion:C,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${y}`)),process.exit(1);}}else if(t==="mcp"){let l=a("mcp"),P=(e||"serve").toLowerCase();P!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:P,result:"error",workspacePath:l,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${P}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${P}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:u}=await import('./workspace-mcp-serve-COA4FMCA.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await u({workspacePath:l});}else if(t==="init"){n.json||(console.log(s.yellow("\u2139 workspace init is an alias of: npx workspai workspace run init")),console.log(s.gray(` Equivalent full-init aliases at workspace root:
397
397
  npx workspai init | npx workspai workspace init | npx workspai workspace run init
398
- `)));let l=a("init"),P=Is({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let f=await Ls(l);f!==0&&process.exit(f);}let{runWorkspaceStage:u}=await import('./workspace-run-3U77TMKX.js'),h=await u({workspacePath:l,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:P,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(h,null,2)),h.summary.exitCode!==0&&process.exit(h.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:$r}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${$r.join(", ")}`)),process.exit(1);});function Rs(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function tp(){let t=r=>r.replace(/\bnpx (?:rapidkit|workspai)\b/g,Es),e=(r,o)=>{console.log(s.cyan(` ${t(r).padEnd(67)} `)+s.gray(o));};console.log(s.white(`Usage:
398
+ `)));let l=a("init"),P=Is({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let f=await Ls(l);f!==0&&process.exit(f);}let{runWorkspaceStage:u}=await import('./workspace-run-VPXRRHDK.js'),h=await u({workspacePath:l,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:P,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(h,null,2)),h.summary.exitCode!==0&&process.exit(h.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:$r}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${$r.join(", ")}`)),process.exit(1);});function Rs(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function tp(){let t=r=>r.replace(/\bnpx (?:rapidkit|workspai)\b/g,Es),e=(r,o)=>{console.log(s.cyan(` ${t(r).padEnd(67)} `)+s.gray(o));};console.log(s.white(`Usage:
399
399
  `)),console.log(s.cyan(` ${Es} <command> [options]
400
400
  `)),Rm==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${Es}.
401
401
  `)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems