workspai 0.77.0 → 0.79.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.
- package/contracts/create-planner-capabilities.v1.json +27 -3
- package/contracts/runtime-command-surface.v1.json +2 -0
- package/contracts/workspace-intelligence-architecture.v1.json +2 -0
- package/dist/analyze-SKOIUD6F.js +1 -0
- package/dist/autopilot-release-MDMVMU67.js +1 -0
- package/dist/{chunk-UP3UWAJV.js → chunk-2ZVE7VE2.js} +1 -1
- package/dist/{chunk-47UR6ZH4.js → chunk-3O344BX3.js} +1 -1
- package/dist/{chunk-IDETNYCF.js → chunk-4H3VNKOJ.js} +1 -1
- package/dist/{chunk-LUPKDFQ3.js → chunk-7EMG3C3H.js} +2 -2
- package/dist/{chunk-O3TVVQ6X.js → chunk-7HV4U2OV.js} +1 -1
- package/dist/{chunk-DWKCFHHL.js → chunk-7MIOAM4A.js} +1 -1
- package/dist/{chunk-E7WJ2QX7.js → chunk-7SN4V3RC.js} +1 -1
- package/dist/{chunk-X5XFT5UZ.js → chunk-BGUCDG5N.js} +1 -1
- package/dist/{chunk-IAXRGH4Q.js → chunk-CJBDYDVC.js} +1 -1
- package/dist/{chunk-UTIK3K3M.js → chunk-EPFEUMYF.js} +1 -1
- package/dist/{chunk-4CXV3PPV.js → chunk-ETTZXKAS.js} +1 -1
- package/dist/{chunk-V6HVDVKJ.js → chunk-FVG5FBA4.js} +5 -5
- package/dist/{chunk-J2MPBSQJ.js → chunk-GUCZOQUS.js} +1 -1
- package/dist/{chunk-SC43A6LH.js → chunk-H24MEOML.js} +50 -50
- package/dist/{chunk-ZIWWE4BQ.js → chunk-HXTNPR3M.js} +1 -1
- package/dist/chunk-ICPL4WNK.js +2 -0
- package/dist/{chunk-475GQJ2D.js → chunk-KRTVIBPC.js} +1 -1
- package/dist/{chunk-GLBFY7AB.js → chunk-KTOKU6HQ.js} +2 -2
- package/dist/{chunk-QCX6BO2M.js → chunk-MNZAJ6PP.js} +1 -1
- package/dist/chunk-O4TZKLEC.js +1 -0
- package/dist/{chunk-HRVHQBTA.js → chunk-R7R5FX4B.js} +1 -1
- package/dist/chunk-RQXZF7BZ.js +1 -0
- package/dist/{chunk-UNEK3VVR.js → chunk-RRZQPFFR.js} +2171 -109
- package/dist/{chunk-3EPR3D5Q.js → chunk-SKHRUHXO.js} +1 -1
- package/dist/{chunk-WC2K5QFI.js → chunk-SV7X5LJW.js} +1 -1
- package/dist/{chunk-TGNPMOM6.js → chunk-TQW2SZHH.js} +1 -1
- package/dist/{chunk-JVZA35OL.js → chunk-U5WP4HDH.js} +1 -1
- package/dist/{chunk-223SWPTL.js → chunk-VT4WPXTO.js} +1 -1
- package/dist/chunk-WU5M6UP7.js +2 -0
- package/dist/{chunk-3EMAC3MF.js → chunk-ZDLF77IS.js} +1 -1
- package/dist/{chunk-3SQIV3F4.js → chunk-ZONAHZBG.js} +1 -1
- package/dist/{create-YPAZJYCE.js → create-M3TWRHV6.js} +1 -1
- package/dist/{doctor-W5PXJ5FL.js → doctor-FF3WLJSP.js} +1 -1
- package/dist/{goal-lifecycle-5R55CA7H.js → goal-lifecycle-O4MYYTRU.js} +1 -1
- package/dist/{goal-pack-IS6GGJPH.js → goal-pack-NUDKANPM.js} +1 -1
- package/dist/index.js +92 -91
- package/dist/{pipeline-LW3SW2WT.js → pipeline-V5P2FX2P.js} +1 -1
- package/dist/{project-agent-entry-5TYKK5IV.js → project-agent-entry-6O7FKWSL.js} +1 -1
- package/dist/{project-intelligence-lens-TEOSTKNU.js → project-intelligence-lens-OQTZ4K7L.js} +1 -1
- package/dist/{project-test-coverage-T4TIWGKN.js → project-test-coverage-EJ3MBSZ3.js} +1 -1
- package/dist/{proof-carrying-change-2TKRADCW.js → proof-carrying-change-GV37YLDQ.js} +1 -1
- package/dist/{verified-goal-RN4TOV34.js → verified-goal-VB7IOTNO.js} +1 -1
- package/dist/{workspace-A33YMF2N.js → workspace-AXU6ODER.js} +1 -1
- package/dist/{workspace-agent-sync-VCA4G4DT.js → workspace-agent-sync-6427FNME.js} +1 -1
- package/dist/{workspace-context-YBWLSKR6.js → workspace-context-VVZARI5K.js} +1 -1
- package/dist/{workspace-contract-3QUZDBMM.js → workspace-contract-N2BJCAJ7.js} +1 -1
- package/dist/{workspace-explain-NXYRAQFI.js → workspace-explain-5WKK6ENK.js} +1 -1
- package/dist/{workspace-foundation-DZ52PECX.js → workspace-foundation-GYL3D7TW.js} +1 -1
- package/dist/{workspace-graph-stream-4VT46HZ7.js → workspace-graph-stream-26ME2JJS.js} +1 -1
- package/dist/{workspace-intelligence-FKYQQDJ6.js → workspace-intelligence-ZTET7JHS.js} +1 -1
- package/dist/{workspace-intelligence-runner-3K2JZH6Q.js → workspace-intelligence-runner-2EJ7GXG5.js} +1 -1
- package/dist/{workspace-knowledge-graph-CPBKNXQI.js → workspace-knowledge-graph-4RSZTEFJ.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-UTJHALST.js +1 -0
- package/dist/{workspace-mcp-serve-UXPKX7K6.js → workspace-mcp-serve-BSA6Q4EB.js} +1 -1
- package/dist/{workspace-model-POCPMNRT.js → workspace-model-LBICKRVI.js} +1 -1
- package/dist/{workspace-onboarding-KLG3GG7S.js → workspace-onboarding-NH4WFJ5N.js} +1 -1
- package/dist/{workspace-registry-summary-M4WMFDQ4.js → workspace-registry-summary-3PXZENLC.js} +1 -1
- package/dist/{workspace-repair-engine-2VGN42QD.js → workspace-repair-engine-ODTFFM6O.js} +1 -1
- package/dist/workspace-run-VDQ6BYLS.js +1 -0
- package/dist/{workspace-verify-PLAKTF3J.js → workspace-verify-UQWAFGNQ.js} +1 -1
- package/dist/{workspace-watch-VNU4KVYN.js → workspace-watch-BKIZQ2SM.js} +1 -1
- package/docs/agent-framework-adapters.md +88 -32
- package/docs/ci-workflows.md +10 -7
- package/docs/commands-reference.md +13 -9
- package/docs/create-planner-capabilities.md +1 -1
- package/docs/creating-workspaces-and-projects.md +24 -20
- package/docs/doctor-command.md +5 -3
- package/docs/model-gateways.md +23 -23
- package/docs/native-kit-baselines.md +2 -2
- package/package.json +4 -1
- package/scripts/enterprise-package-smoke.mjs +50 -0
- package/dist/analyze-TJM66CPF.js +0 -1
- package/dist/autopilot-release-C7Q4OTPY.js +0 -1
- package/dist/chunk-5KXOV7W4.js +0 -1
- package/dist/chunk-IHWS3ALP.js +0 -2
- package/dist/chunk-N7DOKE7V.js +0 -2
- package/dist/chunk-SEZTSMRR.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-67XDXUOT.js +0 -1
- package/dist/workspace-run-5YQR7GEZ.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$r}from'./chunk-ICGWHIMK.js';import {a as a$w}from'./chunk-UHIN3RS6.js';import {c as c$a,b as b$h,a as a$v}from'./chunk-ZS7JHATN.js';import {d as d$3,c as c$3,p as p$3,b as b$m,a as a$M}from'./chunk-NLRZFIC6.js';import {h as h$2,b as b$i,a as a$D}from'./chunk-LDBULT2T.js';import {c,d,e as e$1,k,i,j as j$1,b as b$n,a as a$O}from'./chunk-
|
|
2
|
+
import {a as a$r}from'./chunk-ICGWHIMK.js';import {a as a$w}from'./chunk-UHIN3RS6.js';import {c as c$a,b as b$h,a as a$v}from'./chunk-ZS7JHATN.js';import {d as d$3,c as c$3,p as p$3,b as b$m,a as a$M}from'./chunk-NLRZFIC6.js';import {h as h$2,b as b$i,a as a$D}from'./chunk-LDBULT2T.js';import {c,d,e as e$1,k,i,j as j$1,b as b$n,a as a$O}from'./chunk-ICPL4WNK.js';import {a as a$n}from'./chunk-EPFEUMYF.js';import {a as a$l}from'./chunk-BGUCDG5N.js';import {a as a$x}from'./chunk-XHUM372O.js';import {m,o,p as p$1,c as c$8,n as n$2,f as f$2,d as d$9,e as e$d,a as a$R,h as h$6,q as q$2,g as g$b,r as r$3,i as i$5,s as s$4,l as l$7,k as k$6}from'./chunk-ZDLF77IS.js';import {d as d$4,a as a$p,g as g$6,e as e$8,j as j$6}from'./chunk-V4LCPLV6.js';import {c as c$1,b as b$6,a as a$N}from'./chunk-LPCWROQ3.js';import {b as b$4,a as a$7}from'./chunk-TQW2SZHH.js';import {b as b$g,a as a$t,c as c$9}from'./chunk-GUCZOQUS.js';import {j as j$4,a as a$d,k as k$3}from'./chunk-CJBDYDVC.js';import {b as b$a,g as g$4,c as c$g,a as a$L}from'./chunk-HXTNPR3M.js';import {b as b$9,a as a$a}from'./chunk-D5LLTUTY.js';import {c as c$5,d as d$6,e as e$5,b as b$f,g as g$5}from'./chunk-KTOKU6HQ.js';import {a as a$q}from'./chunk-2DZLCINC.js';import {m as m$3,g as g$8,e as e$c,c as c$d,b as b$j,a as a$H}from'./chunk-4H3VNKOJ.js';import {a as a$o,c as c$e,b as b$k}from'./chunk-H24MEOML.js';import {a,b as b$1}from'./chunk-B6FJ6RG6.js';import {b as b$7,d as d$7,c as c$6,a as a$6,f as f$7,e as e$e}from'./chunk-XF65LQ6M.js';import {a as a$u}from'./chunk-RU3UT7GJ.js';import {a as a$y}from'./chunk-5HNQIMGW.js';import {a as a$s}from'./chunk-IVYPC36J.js';import {e as e$3,d as d$5}from'./chunk-QYEQVNBF.js';import {a as a$B}from'./chunk-U5WP4HDH.js';import {a as a$G}from'./chunk-COICGD62.js';import {c as c$b,a as a$C}from'./chunk-ZONAHZBG.js';import {a as a$K,b as b$l}from'./chunk-N4B2M44I.js';import {a as a$J}from'./chunk-NS53IPAC.js';import {f as f$4}from'./chunk-SKHRUHXO.js';import {a as a$k}from'./chunk-ETTZXKAS.js';import {b as b$5,a as a$2,d as d$2}from'./chunk-DWDYLKVW.js';import {f,e as e$2,a as a$5,d as d$8,i as i$3,g as g$9}from'./chunk-4BPZJR4Z.js';import {a as a$c}from'./chunk-MNZAJ6PP.js';import {a as a$9}from'./chunk-A5FBGRJA.js';import {a as a$A}from'./chunk-HCFOVANQ.js';import {l as l$2,e as e$a,c as c$c,a as a$P,b as b$o,m as m$7,k as k$5}from'./chunk-O4TZKLEC.js';import {j,a as a$1,_,F,U,W,Y,X,V,Z,D as D$1,A,z,y,x as x$1,w as w$2,v as v$3,n as n$4,m as m$5,o as o$3,K,R,s as s$2,B,C as C$1,G as G$1,I,l as l$5,r as r$2,Q,J,L,S,p as p$5,u as u$3,t as t$3,T,E as E$1}from'./chunk-RRZQPFFR.js';import {b as b$c,a as a$h}from'./chunk-RQXZF7BZ.js';import {a as a$j}from'./chunk-NMXGSVMD.js';import {c as c$4,g as g$2,b as b$e,a as a$m,e as e$9,l as l$4}from'./chunk-WU5M6UP7.js';import {b as b$2,d as d$1,a as a$3,e as e$4,D,C,j as j$2,k as k$2,m as m$1,n as n$1,o as o$1,l,t as t$2,p as p$4,F as F$1,r as r$1,h as h$4,s as s$3,E,G,u as u$2,f as f$6,x as x$2,w as w$4,v as v$4,z as z$1}from'./chunk-7HV4U2OV.js';export{s as PROJECT_COMMANDS_CORE_FALLBACK}from'./chunk-7HV4U2OV.js';import {a as a$g}from'./chunk-ROOPODG6.js';import {m as m$2,j as j$5,l as l$1}from'./chunk-7EMG3C3H.js';import {a as a$i}from'./chunk-GR6442P7.js';import {g as g$1,a as a$b,e as e$6,b as b$p,h as h$5}from'./chunk-BLEIUQL6.js';import {b as b$q}from'./chunk-VN2MKTQO.js';import {a as a$4}from'./chunk-AFIFZTOY.js';import {a as a$Q}from'./chunk-XWKGZRHN.js';import {b as b$d}from'./chunk-252EKOR6.js';import {c as c$h}from'./chunk-EWZZUQBR.js';import {u,b as b$3,v as v$1,w as w$1,x,m as m$6,i as i$4,j as j$8,e as e$f,g as g$a,c as c$i}from'./chunk-6BO4QHKA.js';import {h,e,g,c as c$2,b as b$8,a as a$8,f as f$3}from'./chunk-EFHSRPW7.js';import {a as a$f}from'./chunk-TQEMLBAG.js';import {c as c$k}from'./chunk-2FIX2MDC.js';import {a as a$F}from'./chunk-64XWHDZ3.js';import {c as c$7}from'./chunk-25AWHAB5.js';import {a as a$E}from'./chunk-W37NOQVG.js';import {n,f as f$1,u as u$1,p as p$2,w,q as q$1,k as k$1,t as t$1,v as v$2,j as j$3,g as g$3,h as h$1,i as i$1,a as a$e,b as b$b,e as e$7,l as l$6,o as o$4,c as c$j,d as d$a}from'./chunk-VQZ5PI5J.js';import {v,t,p,q,s as s$1,r,o as o$2,n as n$3,m as m$4,k as k$4,j as j$7,i as i$2,h as h$3,l as l$3,g as g$7,e as e$b,f as f$5,c as c$f,a as a$I,w as w$3}from'./chunk-ODK4LCEL.js';import {a as a$z}from'./chunk-FB7SCXAZ.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 Jf from'vm';import*as M from'fs-extra';import M__default from'fs-extra';import $,{existsSync,promises,createWriteStream}from'fs';import Ma,{tmpdir,homedir}from'os';import {execa}from'execa';import Wt,{createHash,randomUUID,createVerify,createHmac}from'crypto';import Hd from'http';import qd from'https';function Vu(){return j$8()}function Ju(t,e){return t==="py"?["-3",...e]:e}function Ku(t){return typeof t=="object"&&t!==null}async function Uu(t,e,r,o=c$k()){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 Bu(t,e){let r=["-m","rapidkit",...t],o=Vu();for(let n of o){let a=await Uu(n,Ju(n,r),e?.cwd,e?.timeoutMs);if(!a.ok)continue;let i=(a.stdout??"").trim();try{let c=JSON.parse(i);return Ku(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 Kl(t,e){let r=await Bu(["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 Ul=new Set(["create"]),_a=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]),Hu=new Set(["pip","poetry","venv","pipx","python","uv"]);function ro(t){return typeof t=="string"&&Hu.has(t)}function Oa(t,e){return !t||Ul.has(t)?false:a$5.has(t)?true:e?.has(t)??false}function Na(t,e=null){let r=t[0];return !r||r.startsWith("-")||Ul.has(r)||r==="init"?false:Oa(r,e)?true:t.filter(n=>!n.startsWith("-")&&!_a.has(n)).length<=1?false:t.length>1}var kr=b.join(Ma.homedir(),".workspairc.json"),qu=b.join(Ma.homedir(),".rapidkitrc.json"),zu=b.join(Ma.homedir(),".rapidkit","config.json");function $a(t){try{if(!$.existsSync(t))return {};let e=$.readFileSync(t,"utf-8"),r=JSON.parse(e);return !r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return {}}}function Bl(t){if(process.platform!=="win32")try{$.chmodSync(t,384);}catch{}}function vr(){let t=$a(kr),e=$a(qu),r=$a(zu);return $.existsSync(kr)&&Bl(kr),{...e,...t,openaiApiKey:t.openaiApiKey??e.openaiApiKey??r.openaiApiKey,aiEnabled:t.aiEnabled??e.aiEnabled??r.aiEnabled,telemetry:t.telemetry??e.telemetry??r.telemetry}}function an(t){let r={...vr(),...t};$.writeFileSync(kr,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),Bl(kr);}function no(){return process.env.OPENAI_API_KEY||vr().openaiApiKey||null}function Wa(){return vr().aiEnabled!==false}function Da(){return kr}function Hl(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
|
-
`)),process.exit(1)):o=(await b$1([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:a=>a?a.startsWith("sk-")?a.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,
|
|
4
|
+
`)),process.exit(1)):o=(await b$1([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:a=>a?a.startsWith("sk-")?a.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,an({openaiApiKey:o}),console.log(s.green(`
|
|
5
5
|
\u2705 OpenAI API key saved successfully!
|
|
6
|
-
`)),console.log(s.gray(`Stored in: ${
|
|
6
|
+
`)),console.log(s.gray(`Stored in: ${Da()}`)),console.log(s.cyan(`
|
|
7
7
|
\u{1F389} You can now use AI features:`)),console.log(s.white(' workspai ai recommend "I need user authentication"')),console.log(s.gray(`
|
|
8
8
|
\u{1F4A1} To generate module embeddings (one-time):`)),console.log(s.white(" cd packages/cli")),console.log(s.white(` npx tsx src/ai/generate-embeddings.ts
|
|
9
9
|
`));}),e.command("show").description("Show current configuration").action(()=>{let r=vr();if(console.log(s.bold(`
|
|
10
10
|
\u2699\uFE0F Workspai Configuration
|
|
11
11
|
`)),r.openaiApiKey){let o=r.openaiApiKey.substring(0,8)+"..."+r.openaiApiKey.slice(-4);console.log(s.cyan("OpenAI API Key:"),s.white(o));}else console.log(s.cyan("OpenAI API Key:"),s.red("Not set")),console.log(s.gray(" Set with: workspai config set-api-key"));console.log(s.cyan("AI Features:"),r.aiEnabled!==false?s.green("Enabled"):s.red("Disabled")),console.log(s.gray(`
|
|
12
|
-
\u{1F4C1} Config file: ${
|
|
12
|
+
\u{1F4C1} Config file: ${Da()}
|
|
13
13
|
`));}),e.command("remove-api-key").description("Remove stored OpenAI API key").option("--yes","Remove without an interactive confirmation prompt").action(async r=>{if(!vr().openaiApiKey){console.log(s.yellow(`
|
|
14
14
|
\u26A0\uFE0F No API key is currently stored
|
|
15
|
-
`));return}let n=r.yes===true||process.argv.includes("--yes");!n&&(!process.stdin.isTTY||!process.stdout.isTTY)&&(console.error(s.red("Cannot confirm API key removal in a non-interactive session. Use --yes.")),process.exit(1)),(n?{confirm:true}:await b$1([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(
|
|
15
|
+
`));return}let n=r.yes===true||process.argv.includes("--yes");!n&&(!process.stdin.isTTY||!process.stdout.isTTY)&&(console.error(s.red("Cannot confirm API key removal in a non-interactive session. Use --yes.")),process.exit(1)),(n?{confirm:true}:await b$1([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(an({openaiApiKey:void 0}),console.log(s.green(`
|
|
16
16
|
\u2705 API key removed successfully
|
|
17
17
|
`))):console.log(s.gray(`
|
|
18
18
|
Cancelled
|
|
19
19
|
`));}),e.command("ai <action>").description("Enable or disable AI features (enable|disable)").action(r=>{r!=="enable"&&r!=="disable"&&(console.log(s.red(`
|
|
20
20
|
\u274C Invalid action: ${r}`)),console.log(s.gray(`Use: workspai config ai enable|disable
|
|
21
|
-
`)),process.exit(1));let o=r==="enable";
|
|
21
|
+
`)),process.exit(1));let o=r==="enable";an({aiEnabled:o}),console.log(s.green(`
|
|
22
22
|
\u2705 AI features ${o?"enabled":"disabled"}
|
|
23
|
-
`));});}var ao=null,an=false,Wa=null;async function Yu(){return Wa||(Wa=(await import('openai')).default),Wa}function ql(){an=true;}function zl(t){let r=new Array(1536),o=0;for(let a=0;a<t.length;a++)o=(o<<5)-o+t.charCodeAt(a),o=o&o;for(let a=0;a<1536;a++)o=o*1664525+1013904223&4294967295,r[a]=o/4294967295*2-1;let n=Math.sqrt(r.reduce((a,i)=>a+i*i,0));return r.map(a=>a/n)}async function sn(t){if(!t.trim()){ao=null;return}let e=await Yu();ao=new e({apiKey:t});}function Yl(){if(!ao)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return ao}async function Da(t){return an?zl(t):(await Yl().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function Xl(t){return an?t.map(zl):(await Yl().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(o=>o.embedding)}function Ql(){return ao!==null}function Pr(){return an}function La(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Xu(t){return !t||typeof t!="object"?{}:t}var Ga=[{id:"authentication-core",name:"Authentication Core",category:"auth",description:"Complete authentication system with password hashing, JWT tokens, OAuth 2.0, and secure session management",longDescription:"Production-ready authentication with bcrypt password hashing, JWT access/refresh tokens, OAuth 2.0 providers (Google, GitHub, etc), rate limiting, and security best practices.",keywords:["auth","login","password","jwt","oauth","token","authentication","security","signin","signup"],framework:"both",dependencies:[],useCases:["User login and logout","Password reset flow","OAuth social login (Google, GitHub)","JWT authentication","Secure session management","Token refresh","Rate limiting"]},{id:"users-core",name:"Users Core",category:"auth",description:"User management system with profiles, roles, permissions, and user CRUD operations",longDescription:"Complete user management with user profiles, role-based access control (RBAC), permissions, user search, soft delete, and audit trails.",keywords:["user","profile","role","permission","rbac","management","admin","accounts"],framework:"both",dependencies:["authentication-core"],useCases:["User registration","User profile management","Role management (admin, user, etc)","Permission system","User administration dashboard","Soft delete users"]},{id:"session-management",name:"Session Management",category:"auth",description:"Secure session handling with Redis storage, session rotation, and device tracking",longDescription:"Advanced session management with Redis-backed storage, automatic session rotation, device fingerprinting, IP tracking, and session revocation.",keywords:["session","redis","cookie","storage","device","tracking"],framework:"both",dependencies:["authentication-core","redis-cache"],useCases:["User session management","Remember me functionality","Device tracking","Session security","Logout from all devices","Session expiration"]},{id:"db-postgres",name:"PostgreSQL",category:"database",description:"PostgreSQL integration with async SQLAlchemy, migrations, connection pooling, and query optimization",longDescription:"Production-ready PostgreSQL with async SQLAlchemy 2.0, Alembic migrations, connection pooling, query optimization, JSON support, and full-text search.",keywords:["postgres","postgresql","database","sql","sqlalchemy","migration","orm","relational"],framework:"both",dependencies:[],useCases:["Relational database","Complex SQL queries","Database transactions","Data integrity","Production-grade database","ACID compliance"]},{id:"db-mongodb",name:"MongoDB",category:"database",description:"MongoDB integration with Motor async driver, schema validation, and aggregation pipelines",longDescription:"Async MongoDB with Motor driver, Pydantic schema validation, aggregation pipelines, indexes, and Atlas integration.",keywords:["mongodb","mongo","nosql","document","database","motor"],framework:"both",dependencies:[],useCases:["Document storage","Flexible schema","Real-time data","JSON documents","Unstructured data","Analytics"]},{id:"stripe-payment",name:"Stripe Payment",category:"payment",description:"Stripe integration with payment intents, subscriptions, webhooks, and customer portal",longDescription:"Complete Stripe integration with Payment Intents API, subscription management, automatic webhooks, customer portal, refunds, and SCA compliance.",keywords:["stripe","payment","subscription","billing","checkout","webhook","credit card"],framework:"both",dependencies:[],useCases:["Accept credit card payments","Subscription billing","One-time payments","Checkout flow","Payment webhooks","Refunds and disputes"]},{id:"email",name:"Email",category:"communication",description:"Email sending with templates, SMTP/SendGrid/AWS SES support, and queue management",longDescription:"Production email system with Jinja2 templates, multiple providers (SMTP, SendGrid, AWS SES), queue management, retry logic, and bounce handling.",keywords:["email","mail","smtp","sendgrid","ses","template","notification"],framework:"both",dependencies:[],useCases:["Welcome emails","Password reset emails","Notifications","Marketing emails","Transactional emails","Email templates"]},{id:"sms",name:"SMS",category:"communication",description:"SMS sending with Twilio, verification codes, and delivery tracking",longDescription:"SMS integration with Twilio, verification codes, two-factor authentication, delivery tracking, and international support.",keywords:["sms","twilio","text","message","2fa","verification","otp"],framework:"both",dependencies:[],useCases:["2FA verification codes","SMS notifications","Phone verification","OTP generation","SMS alerts"]},{id:"redis-cache",name:"Redis Cache",category:"infrastructure",description:"Redis caching with decorators, TTL management, and cache invalidation patterns",longDescription:"Redis integration with async client, caching decorators, TTL management, cache invalidation, pub/sub, and rate limiting.",keywords:["redis","cache","memory","performance","speed","pubsub"],framework:"both",dependencies:[],useCases:["API response caching","Session storage","Rate limiting","Real-time features","Performance optimization","Pub/sub messaging"]},{id:"celery",name:"Celery",category:"infrastructure",description:"Background task processing with Celery, periodic tasks, and monitoring",longDescription:"Celery task queue with Redis/RabbitMQ backend, periodic tasks (cron), task monitoring, retry logic, and failure handling.",keywords:["celery","task","background","queue","async","worker","job","cron"],framework:"fastapi",dependencies:["redis-cache"],useCases:["Background email sending","Data processing","Report generation","Scheduled tasks","Long-running jobs"]},{id:"storage",name:"Storage",category:"infrastructure",description:"File storage with S3, local filesystem, and image processing",longDescription:"Unified storage interface for AWS S3, local files, image resizing, format conversion, CDN integration, and presigned URLs.",keywords:["storage","s3","file","upload","image","cdn","aws"],framework:"both",dependencies:[],useCases:["File uploads","Image storage","Document management","Profile pictures","Media files","CDN integration"]}],Tt=null,Fa=0,Qu=300*1e3;function Zu(t){let e=Xu(t),r=e.slug||e.name||e.id||e.module_id||"",o=La(e.keywords??e.tags);return {id:r,name:e.display_name||e.name||"",category:em(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:o.map(n=>n.toLowerCase()),framework:tm(e.framework),dependencies:La(e.dependencies),useCases:La(e.use_cases??e.useCases)}}function em(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function tm(t){if(!t)return "both";if(typeof t=="string"){if(t.toLowerCase().includes("fastapi"))return "fastapi";if(t.toLowerCase().includes("nest"))return "nestjs"}return "both"}async function rm(){try{let t=await g$9(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.trim(),r;try{r=JSON.parse(e);}catch{let n=e.indexOf("{"),a=e.indexOf("["),i=[n,a].filter(m=>m>=0);if(i.length===0)throw new Error("Python Core modules response did not contain JSON");let c=Math.min(...i),l=e[c]==="["?"]":"}",p=e.lastIndexOf(l);if(p<c)throw new Error("Python Core modules response contained incomplete JSON");r=JSON.parse(e.slice(c,p+1));}let o=[];if(Array.isArray(r))o=r;else if(r&&typeof r=="object"){let n=r;Array.isArray(n.modules)?o=n.modules:Array.isArray(n.data)&&(o=n.data);}return o.map(Zu).filter(n=>n.id&&n.name)}catch(t){return console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",t.message),console.warn(" Using fallback module catalog (11 modules)"),Ga}}async function cn(){let t=Date.now();return Pr()?(Tt=Ga,Fa=t,Tt):(Tt&&t-Fa<Qu||(Tt=await rm(),Fa=t,Tt.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),Tt=Ga)),Tt)}var nm=fileURLToPath(import.meta.url),ep=b.dirname(nm),br=null,tp=new Map;function am(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function sm(t){let e=tp.get(t.id);if(e)return e;let r=await Da(am(t));return tp.set(t.id,r),r}function im(){if(br)return br;let t=[b.join(ep,"../../data/modules-embeddings.json"),b.join(ep,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if($.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let r=$.readFileSync(e,"utf-8"),o=JSON.parse(r);if(Array.isArray(o)?br={model:"mock-or-text-embedding-3-small",dimension:o[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:o}:br=o,!br)throw new Error("failed to load embeddings data");return br}function rp(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let r=0,o=0,n=0;for(let i=0;i<t.length;i++)r+=t[i]*e[i],o+=t[i]*t[i],n+=e[i]*e[i];let a=Math.sqrt(o)*Math.sqrt(n);return a===0?0:r/a}function op(t,e){let r=e.toLowerCase(),o=t.keywords.filter(n=>r.includes(n)||n.includes(r));return o.length>0?`Matches: ${o.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function np(t,e=5){let r=await cn(),o=await Da(t);if(Pr()){let i=await Promise.all(r.map(async c=>{let l=await sm(c);return {module:c,score:rp(o,l),reason:op(c,t)}}));return i.sort((c,l)=>l.score-c.score),i.slice(0,e)}let a=im().modules.map(i=>{let c=r.find(p=>p.id===i.id);if(!c)return null;let l=rp(o,i.embedding);return {module:c,score:l,reason:op(c,t)}}).filter(i=>i!==null);return a.sort((i,c)=>c.score-i.score),a.slice(0,e)}var lm=fileURLToPath(import.meta.url),ap=b.dirname(lm);function sp(t){return t instanceof Error?t.message:String(t)}function pm(){return [b.join(ap,"../../data/modules-embeddings.json"),b.join(ap,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")]}function ip(){let t=pm();for(let e of t)if($.existsSync(e))try{let r=JSON.parse($.readFileSync(e,"utf-8")),o=Array.isArray(r)?r:r.modules||[];return {exists:true,path:e,moduleCount:o.length,generatedAt:r.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function pn(t=true,e){try{if(!Ql()&&!Pr())return console.log(s.red(`
|
|
23
|
+
`));});}var ao=null,sn=false,La=null;async function Yu(){return La||(La=(await import('openai')).default),La}function ql(){sn=true;}function zl(t){let r=new Array(1536),o=0;for(let a=0;a<t.length;a++)o=(o<<5)-o+t.charCodeAt(a),o=o&o;for(let a=0;a<1536;a++)o=o*1664525+1013904223&4294967295,r[a]=o/4294967295*2-1;let n=Math.sqrt(r.reduce((a,i)=>a+i*i,0));return r.map(a=>a/n)}async function cn(t){if(!t.trim()){ao=null;return}let e=await Yu();ao=new e({apiKey:t});}function Yl(){if(!ao)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return ao}async function Fa(t){return sn?zl(t):(await Yl().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data[0].embedding}async function Xl(t){return sn?t.map(zl):(await Yl().embeddings.create({model:"text-embedding-3-small",input:t,encoding_format:"float"})).data.map(o=>o.embedding)}function Ql(){return ao!==null}function Pr(){return sn}function Ga(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Xu(t){return !t||typeof t!="object"?{}:t}var Ja=[{id:"authentication-core",name:"Authentication Core",category:"auth",description:"Complete authentication system with password hashing, JWT tokens, OAuth 2.0, and secure session management",longDescription:"Production-ready authentication with bcrypt password hashing, JWT access/refresh tokens, OAuth 2.0 providers (Google, GitHub, etc), rate limiting, and security best practices.",keywords:["auth","login","password","jwt","oauth","token","authentication","security","signin","signup"],framework:"both",dependencies:[],useCases:["User login and logout","Password reset flow","OAuth social login (Google, GitHub)","JWT authentication","Secure session management","Token refresh","Rate limiting"]},{id:"users-core",name:"Users Core",category:"auth",description:"User management system with profiles, roles, permissions, and user CRUD operations",longDescription:"Complete user management with user profiles, role-based access control (RBAC), permissions, user search, soft delete, and audit trails.",keywords:["user","profile","role","permission","rbac","management","admin","accounts"],framework:"both",dependencies:["authentication-core"],useCases:["User registration","User profile management","Role management (admin, user, etc)","Permission system","User administration dashboard","Soft delete users"]},{id:"session-management",name:"Session Management",category:"auth",description:"Secure session handling with Redis storage, session rotation, and device tracking",longDescription:"Advanced session management with Redis-backed storage, automatic session rotation, device fingerprinting, IP tracking, and session revocation.",keywords:["session","redis","cookie","storage","device","tracking"],framework:"both",dependencies:["authentication-core","redis-cache"],useCases:["User session management","Remember me functionality","Device tracking","Session security","Logout from all devices","Session expiration"]},{id:"db-postgres",name:"PostgreSQL",category:"database",description:"PostgreSQL integration with async SQLAlchemy, migrations, connection pooling, and query optimization",longDescription:"Production-ready PostgreSQL with async SQLAlchemy 2.0, Alembic migrations, connection pooling, query optimization, JSON support, and full-text search.",keywords:["postgres","postgresql","database","sql","sqlalchemy","migration","orm","relational"],framework:"both",dependencies:[],useCases:["Relational database","Complex SQL queries","Database transactions","Data integrity","Production-grade database","ACID compliance"]},{id:"db-mongodb",name:"MongoDB",category:"database",description:"MongoDB integration with Motor async driver, schema validation, and aggregation pipelines",longDescription:"Async MongoDB with Motor driver, Pydantic schema validation, aggregation pipelines, indexes, and Atlas integration.",keywords:["mongodb","mongo","nosql","document","database","motor"],framework:"both",dependencies:[],useCases:["Document storage","Flexible schema","Real-time data","JSON documents","Unstructured data","Analytics"]},{id:"stripe-payment",name:"Stripe Payment",category:"payment",description:"Stripe integration with payment intents, subscriptions, webhooks, and customer portal",longDescription:"Complete Stripe integration with Payment Intents API, subscription management, automatic webhooks, customer portal, refunds, and SCA compliance.",keywords:["stripe","payment","subscription","billing","checkout","webhook","credit card"],framework:"both",dependencies:[],useCases:["Accept credit card payments","Subscription billing","One-time payments","Checkout flow","Payment webhooks","Refunds and disputes"]},{id:"email",name:"Email",category:"communication",description:"Email sending with templates, SMTP/SendGrid/AWS SES support, and queue management",longDescription:"Production email system with Jinja2 templates, multiple providers (SMTP, SendGrid, AWS SES), queue management, retry logic, and bounce handling.",keywords:["email","mail","smtp","sendgrid","ses","template","notification"],framework:"both",dependencies:[],useCases:["Welcome emails","Password reset emails","Notifications","Marketing emails","Transactional emails","Email templates"]},{id:"sms",name:"SMS",category:"communication",description:"SMS sending with Twilio, verification codes, and delivery tracking",longDescription:"SMS integration with Twilio, verification codes, two-factor authentication, delivery tracking, and international support.",keywords:["sms","twilio","text","message","2fa","verification","otp"],framework:"both",dependencies:[],useCases:["2FA verification codes","SMS notifications","Phone verification","OTP generation","SMS alerts"]},{id:"redis-cache",name:"Redis Cache",category:"infrastructure",description:"Redis caching with decorators, TTL management, and cache invalidation patterns",longDescription:"Redis integration with async client, caching decorators, TTL management, cache invalidation, pub/sub, and rate limiting.",keywords:["redis","cache","memory","performance","speed","pubsub"],framework:"both",dependencies:[],useCases:["API response caching","Session storage","Rate limiting","Real-time features","Performance optimization","Pub/sub messaging"]},{id:"celery",name:"Celery",category:"infrastructure",description:"Background task processing with Celery, periodic tasks, and monitoring",longDescription:"Celery task queue with Redis/RabbitMQ backend, periodic tasks (cron), task monitoring, retry logic, and failure handling.",keywords:["celery","task","background","queue","async","worker","job","cron"],framework:"fastapi",dependencies:["redis-cache"],useCases:["Background email sending","Data processing","Report generation","Scheduled tasks","Long-running jobs"]},{id:"storage",name:"Storage",category:"infrastructure",description:"File storage with S3, local filesystem, and image processing",longDescription:"Unified storage interface for AWS S3, local files, image resizing, format conversion, CDN integration, and presigned URLs.",keywords:["storage","s3","file","upload","image","cdn","aws"],framework:"both",dependencies:[],useCases:["File uploads","Image storage","Document management","Profile pictures","Media files","CDN integration"]}],Tt=null,Va=0,Qu=300*1e3;function Zu(t){let e=Xu(t),r=e.slug||e.name||e.id||e.module_id||"",o=Ga(e.keywords??e.tags);return {id:r,name:e.display_name||e.name||"",category:em(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:o.map(n=>n.toLowerCase()),framework:tm(e.framework),dependencies:Ga(e.dependencies),useCases:Ga(e.use_cases??e.useCases)}}function em(t){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[t.toLowerCase()]||"infrastructure"}function tm(t){if(!t)return "both";if(typeof t=="string"){if(t.toLowerCase().includes("fastapi"))return "fastapi";if(t.toLowerCase().includes("nest"))return "nestjs"}return "both"}async function rm(){try{let t=await g$9(["modules","list","--json-schema","1"],{cwd:process.cwd()});if(t.exitCode!==0)throw new Error(t.stderr.trim()||"Python Core modules command failed");let e=t.stdout.trim(),r;try{r=JSON.parse(e);}catch{let n=e.indexOf("{"),a=e.indexOf("["),i=[n,a].filter(m=>m>=0);if(i.length===0)throw new Error("Python Core modules response did not contain JSON");let c=Math.min(...i),l=e[c]==="["?"]":"}",p=e.lastIndexOf(l);if(p<c)throw new Error("Python Core modules response contained incomplete JSON");r=JSON.parse(e.slice(c,p+1));}let o=[];if(Array.isArray(r))o=r;else if(r&&typeof r=="object"){let n=r;Array.isArray(n.modules)?o=n.modules:Array.isArray(n.data)&&(o=n.data);}return o.map(Zu).filter(n=>n.id&&n.name)}catch(t){return console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",t.message),console.warn(" Using fallback module catalog (11 modules)"),Ja}}async function ln(){let t=Date.now();return Pr()?(Tt=Ja,Va=t,Tt):(Tt&&t-Va<Qu||(Tt=await rm(),Va=t,Tt.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),Tt=Ja)),Tt)}var nm=fileURLToPath(import.meta.url),ep=b.dirname(nm),br=null,tp=new Map;function am(t){return [t.name,t.description,t.longDescription,...t.keywords,...t.useCases].filter(Boolean).join(" ")}async function sm(t){let e=tp.get(t.id);if(e)return e;let r=await Fa(am(t));return tp.set(t.id,r),r}function im(){if(br)return br;let t=[b.join(ep,"../../data/modules-embeddings.json"),b.join(ep,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")],e=null;for(let n of t)if($.existsSync(n)){e=n;break}if(!e)throw new Error("embeddings file not found");let r=$.readFileSync(e,"utf-8"),o=JSON.parse(r);if(Array.isArray(o)?br={model:"mock-or-text-embedding-3-small",dimension:o[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:o}:br=o,!br)throw new Error("failed to load embeddings data");return br}function rp(t,e){if(t.length!==e.length)throw new Error("Vectors must have the same length");let r=0,o=0,n=0;for(let i=0;i<t.length;i++)r+=t[i]*e[i],o+=t[i]*t[i],n+=e[i]*e[i];let a=Math.sqrt(o)*Math.sqrt(n);return a===0?0:r/a}function op(t,e){let r=e.toLowerCase(),o=t.keywords.filter(n=>r.includes(n)||n.includes(r));return o.length>0?`Matches: ${o.slice(0,3).join(", ")}`:`Relevant for: ${t.useCases[0]}`}async function np(t,e=5){let r=await ln(),o=await Fa(t);if(Pr()){let i=await Promise.all(r.map(async c=>{let l=await sm(c);return {module:c,score:rp(o,l),reason:op(c,t)}}));return i.sort((c,l)=>l.score-c.score),i.slice(0,e)}let a=im().modules.map(i=>{let c=r.find(p=>p.id===i.id);if(!c)return null;let l=rp(o,i.embedding);return {module:c,score:l,reason:op(c,t)}}).filter(i=>i!==null);return a.sort((i,c)=>c.score-i.score),a.slice(0,e)}var lm=fileURLToPath(import.meta.url),ap=b.dirname(lm);function sp(t){return t instanceof Error?t.message:String(t)}function pm(){return [b.join(ap,"../../data/modules-embeddings.json"),b.join(ap,"../data/modules-embeddings.json"),b.join(process.cwd(),"data/modules-embeddings.json")]}function ip(){let t=pm();for(let e of t)if($.existsSync(e))try{let r=JSON.parse($.readFileSync(e,"utf-8")),o=Array.isArray(r)?r:r.modules||[];return {exists:true,path:e,moduleCount:o.length,generatedAt:r.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function dn(t=true,e){try{if(!Ql()&&!Pr())return console.log(s.red(`
|
|
24
24
|
\u274C OpenAI not initialized`)),console.log(s.yellow("Please set your API key:")),console.log(s.white(" workspai config set-api-key")),console.log(s.gray(` OR set: export OPENAI_API_KEY="sk-..."
|
|
25
25
|
`)),false;console.log(s.blue(`
|
|
26
26
|
\u{1F916} Generating AI embeddings for Workspai modules...
|
|
27
|
-
`)),console.log(s.gray("\u{1F4E1} Fetching modules from Workspai..."));let r=await
|
|
27
|
+
`)),console.log(s.gray("\u{1F4E1} Fetching modules from Workspai..."));let r=await ln();console.log(s.green(`\u2713 Found ${r.length} modules
|
|
28
28
|
`));let o=r.length*50/1e6*.02;if(console.log(s.cyan(`\u{1F4B0} Estimated cost: ~$${o.toFixed(3)}`)),console.log(s.gray(` (Based on ${r.length} modules at $0.02/1M tokens)
|
|
29
29
|
`)),t){let{confirm:i}=await b$1([{type:"confirm",name:"confirm",message:"Generate embeddings now?",default:true}]);if(!i)return console.log(s.yellow(`
|
|
30
30
|
\u26A0\uFE0F Embeddings generation cancelled
|
|
@@ -41,18 +41,18 @@ Cancelled
|
|
|
41
41
|
`)),false}}async function cp(t=true){if(ip().exists)return true;if(console.log(s.yellow(`
|
|
42
42
|
\u26A0\uFE0F Module embeddings not found`)),console.log(s.gray(`AI recommendations require embeddings to be generated.
|
|
43
43
|
`)),!t)return console.log(s.red("\u274C Cannot generate embeddings in non-interactive mode")),console.log(s.white(`Run: workspai ai generate-embeddings
|
|
44
|
-
`)),false;let{action:r}=await b$1([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"\u{1F680} Generate embeddings now (OpenAI key for production, or mock mode for testing)",value:"generate"},{name:"\u{1F4DD} Show me how to generate them manually",value:"manual"},{name:"\u274C Cancel",value:"cancel"}]}]);return r==="generate"?await
|
|
44
|
+
`)),false;let{action:r}=await b$1([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"\u{1F680} Generate embeddings now (OpenAI key for production, or mock mode for testing)",value:"generate"},{name:"\u{1F4DD} Show me how to generate them manually",value:"manual"},{name:"\u274C Cancel",value:"cancel"}]}]);return r==="generate"?await dn(true):(r==="manual"&&(console.log(s.cyan(`
|
|
45
45
|
\u{1F4DD} To generate embeddings manually:
|
|
46
46
|
`)),console.log(s.white("1. Get OpenAI API key from: https://platform.openai.com/api-keys")),console.log(s.white("2. Set the API key:")),console.log(s.gray(" workspai config set-api-key")),console.log(s.gray(` OR: export OPENAI_API_KEY="sk-..."
|
|
47
47
|
`)),console.log(s.white("3. Generate embeddings:")),console.log(s.gray(` workspai ai generate-embeddings
|
|
48
48
|
`)),console.log(s.cyan(`\u{1F4B0} Cost: ~$0.50 one-time
|
|
49
49
|
`))),false)}async function lp(){let t=ip();return t.exists?(console.log(s.blue(`
|
|
50
50
|
\u{1F504} Updating embeddings...`)),console.log(s.gray(`Current: ${t.moduleCount} modules`)),console.log(s.gray(`Generated: ${t.generatedAt||"unknown"}
|
|
51
|
-
`)),t.path?await
|
|
51
|
+
`)),t.path?await dn(true,t.path):false):(console.log(s.yellow(`
|
|
52
52
|
\u26A0\uFE0F No existing embeddings found`)),console.log(s.gray(`Use: workspai ai generate-embeddings
|
|
53
|
-
`)),false)}function
|
|
53
|
+
`)),false)}function Ka(t){if(t&&typeof t=="object"){let e=t;return {message:typeof e.message=="string"?e.message:String(t),code:typeof e.code=="string"?e.code:void 0}}return {message:String(t)}}function pp(t,e=0){console.log(JSON.stringify(t,null,2)),e!==0&&process.exit(e);}function dp(t){let e$1=t.command("ai").description("AI-powered features");e$1.command("recommend").description("Get AI-powered module recommendations").argument("[query]",'What do you want to build? (e.g., "user authentication with email")').option("-n, --number <count>","Number of recommendations","5").option("--json","Output as JSON").action(async(r,o)=>{try{Wa()||(o.json&&pp({ok:false,error:{code:"AI_DISABLED",message:"AI features are disabled",remediation:"workspai config ai enable"}},1),console.log(s.yellow(`
|
|
54
54
|
\u26A0\uFE0F AI features are disabled`)),console.log(s.gray(`Enable with: workspai config ai enable
|
|
55
|
-
`)),process.exit(1));let n=no();n?await
|
|
55
|
+
`)),process.exit(1));let n=no();n?await cn(n):(o.json||(console.log(s.yellow(`
|
|
56
56
|
\u26A0\uFE0F OpenAI API key not configured - using MOCK MODE for testing
|
|
57
57
|
`)),console.log(s.gray("\u{1F4DD} Note: Mock embeddings provide approximate results for testing.")),console.log(s.gray(` For production, configure your OpenAI API key:
|
|
58
58
|
`)),console.log(s.white(" 1. Get your key from: https://platform.openai.com/api-keys")),console.log(s.white(" 2. Configure it: workspai config set-api-key")),console.log(s.gray(` OR set: export OPENAI_API_KEY="sk-proj-..."
|
|
@@ -79,12 +79,12 @@ Cancelled
|
|
|
79
79
|
\u274C Module installation failed (exit code: ${E})
|
|
80
80
|
`));}else console.log(s.gray(`
|
|
81
81
|
No modules selected
|
|
82
|
-
`));}}catch(n){let a=
|
|
82
|
+
`));}}catch(n){let a=Ka(n);e.error(`
|
|
83
83
|
\u274C Error:`,a.message),a.code==="invalid_api_key"?(console.log(s.yellow(`
|
|
84
84
|
\u{1F4A1} Your API key may be invalid or expired`)),console.log(s.cyan(` Update it: workspai config set-api-key
|
|
85
85
|
`))):a.message.includes("embeddings file not found")&&(console.log(s.yellow(`
|
|
86
86
|
\u{1F4A1} Module embeddings not generated yet`)),console.log(s.cyan(" Generate them (one-time):")),console.log(s.white(" cd packages/cli")),console.log(s.white(' export OPENAI_API_KEY="sk-proj-..."')),console.log(s.white(` npx tsx src/ai/generate-embeddings.ts
|
|
87
|
-
`))),process.exit(1);}}),e$1.command("info").description("Show AI features information").action(()=>{let r=no(),o=
|
|
87
|
+
`))),process.exit(1);}}),e$1.command("info").description("Show AI features information").action(()=>{let r=no(),o=Wa();console.log(s.bold(`
|
|
88
88
|
\u{1F916} Workspai AI Features
|
|
89
89
|
`)),console.log(s.cyan("Status:"),o?s.green("Enabled"):s.red("Disabled")),console.log(s.cyan("API Key:"),r?s.green("Configured \u2713"):s.red("Not configured \u2717")),console.log(s.bold(`
|
|
90
90
|
\u{1F4E6} Available Features:
|
|
@@ -97,11 +97,11 @@ No modules selected
|
|
|
97
97
|
`)),console.log(s.cyan(`To generate embeddings, you need an OpenAI API key:
|
|
98
98
|
`)),console.log(s.white("1. Get your key from: https://platform.openai.com/api-keys")),console.log(s.white("2. Configure it: workspai config set-api-key")),console.log(s.gray(`
|
|
99
99
|
OR set environment variable:`)),console.log(s.white(` export OPENAI_API_KEY="sk-proj-..."
|
|
100
|
-
`)),process.exit(1)),
|
|
101
|
-
`))),process.exit(o?0:1);}catch(r){let o=
|
|
100
|
+
`)),process.exit(1)),cn(r);let o=await dn(true);o&&(console.log(s.green("\u2705 Ready to use AI recommendations!")),console.log(s.cyan(`Try: workspai ai recommend "authentication"
|
|
101
|
+
`))),process.exit(o?0:1);}catch(r){let o=Ka(r);e.error("Failed to generate embeddings:",o.message),process.exit(1);}}),e$1.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let r=no();r||(console.log(s.red(`
|
|
102
102
|
\u274C OpenAI API key not configured
|
|
103
103
|
`)),console.log(s.white(`Set your API key: workspai config set-api-key
|
|
104
|
-
`)),process.exit(1)),
|
|
104
|
+
`)),process.exit(1)),cn(r);let o=await lp();process.exit(o?0:1);}catch(r){let o=Ka(r);e.error("Failed to update embeddings:",o.message),process.exit(1);}});}var um="rapidkit.product-factory-plan.v1",mm="rapidkit.private-product-manifest.v1";function up(t){let e=process.argv;for(let r=0;r<e.length;r+=1){let o=e[r];if(o===t){let n=e[r+1];return n&&!n.startsWith("-")?n:void 0}if(o.startsWith(`${t}=`))return o.slice(t.length+1)}}function io(t,e=""){return typeof t=="string"&&t.trim()?t.trim():e}function Ua(t){return typeof t=="string"&&t.trim()?t.trim():null}function gm(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function mp(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function fp(t){if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(t))throw new Error(`Invalid product slug "${t}". Use lowercase letters, numbers, and hyphens.`)}function fm(t,e,r){let o=io(t.slug);if(!o)throw new Error(`Backlog product at index ${e} is missing slug.`);fp(o);let n=mp(t.modules),a=mp(t.moduleGaps);return {rank:gm(t.rank,e+1),slug:o,title:io(t.title,o),category:io(t.category,"Uncategorized"),tier:io(t.tier,"pro"),summary:io(t.summary),modules:n,moduleGaps:a,recommendedKit:r,workspaceProfile:"enterprise",readiness:{status:a.length>0?"blocked-by-module-gaps":"ready-for-private-manifest",blockingGaps:a}}}function hm(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Backlog must be a JSON object.");return t}async function wm(t){let e=b.resolve(process.cwd(),t),r=hm(await M__default.readJson(e));if(!Array.isArray(r.products))throw new Error("Backlog must contain a products array.");return {absolutePath:e,payload:r}}function ym(t,e){let r=[...t];if(e.tier){let o=e.tier.toLowerCase();r=r.filter(n=>n.tier.toLowerCase()===o);}if(e.category){let o=e.category.toLowerCase();r=r.filter(n=>n.category.toLowerCase()===o);}if(e.limit){let o=Number.parseInt(e.limit,10);if(!Number.isInteger(o)||o<1)throw new Error("--limit must be a positive integer.");r=r.slice(0,o);}return r}async function hp(t){let e=t.kit?.trim()||"fastapi.standard",{absolutePath:r,payload:o}=await wm(t.backlogPath),n=o.products,a=n.map((m,u)=>fm(m,u,e)),i=ym(a,t),c=new Set(i.flatMap(m=>m.modules)),l=i.flatMap(m=>m.moduleGaps),p=i.filter(m=>m.readiness.status==="ready-for-private-manifest").length;return {schemaVersion:um,generatedAt:(t.now??new Date).toISOString(),source:{backlogPath:r,backlogSchemaVersion:Ua(o.schemaVersion),purpose:Ua(o.purpose),publicationRule:Ua(o.publicationRule)},defaults:{kit:e,workspaceProfile:"enterprise",projectSlug:"api"},stats:{totalProducts:n.length,plannedProducts:i.length,readyProducts:p,blockedProducts:i.length-p,uniqueModules:c.size,knownModuleGaps:l.length},products:i}}function Cr(t){return JSON.stringify(t,null,2)}function km(t){return `sha256:${Wt.createHash("sha256").update(Cr(t)).digest("hex")}`}function vm(t){return t.replace(/\\/g,"/")}async function Pm(t){let e=await hp({backlogPath:t.backlogPath,kit:t.kit,now:t.now}),r=e.products.find(a=>a.slug===t.slug);if(!r)throw new Error(`Product "${t.slug}" was not found in backlog.`);let o=t.outputRoot||"../workspai-examples-pro",n={schemaVersion:mm,generatedAt:e.generatedAt,product:{rank:r.rank,slug:r.slug,title:r.title,category:r.category,tier:r.tier,summary:r.summary},workspace:{name:r.slug,profile:"enterprise",outputHint:vm(b.join(o,r.slug))},projects:[{slug:"api",kit:r.recommendedKit,runtime:"python",framework:"fastapi",modules:r.modules,moduleGaps:r.moduleGaps}],factory:{sourceBacklogPath:e.source.backlogPath,manifestChecksum:"",requiredCommands:[`npx workspai create workspace ${r.slug} --yes --profile enterprise`,`npx workspai create project ${r.recommendedKit} api --yes --skip-install`,"npx workspai init","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"],releaseEvidencePath:`.workspai/product-factory/${r.slug}/release-evidence.json`}};return {...n,factory:{...n.factory,manifestChecksum:km({...n,factory:{...n.factory,manifestChecksum:""}})}}}async function gp(t,e,r=false){let o=b.resolve(process.cwd(),t);if(!r&&await M__default.pathExists(o))throw new Error(`Refusing to overwrite existing file: ${o}. Use --force.`);await M__default.ensureDir(b.dirname(o)),await M__default.writeFile(o,`${Cr(e)}
|
|
105
105
|
`,"utf-8");}function bm(t,e){let r=b.join(".workspai","product-factory","manifests",`${e}.manifest.json`);return t?t.endsWith(".json")?t:b.join(t,`${e}.manifest.json`):r}function jm(t,e){console.log(s.bold(`
|
|
106
106
|
Workspai Product Factory Plan
|
|
107
107
|
`)),console.log(s.cyan("Products:"),s.white(String(t.stats.plannedProducts))),console.log(s.cyan("Ready:"),s.green(String(t.stats.readyProducts))),console.log(s.cyan("Blocked:"),s.yellow(String(t.stats.blockedProducts))),console.log(s.cyan("Unique modules:"),s.white(String(t.stats.uniqueModules))),console.log(s.cyan("Known gaps:"),s.yellow(String(t.stats.knownModuleGaps))),e&&console.log(s.gray(`
|
|
@@ -111,71 +111,71 @@ Next: npx workspai product manifest create <slug> --from-backlog <file>
|
|
|
111
111
|
Workspai Private Product Manifest
|
|
112
112
|
`)),console.log(s.cyan("Product:"),s.white(t.product.slug)),console.log(s.cyan("Kit:"),s.white(t.projects[0].kit)),console.log(s.cyan("Modules:"),s.white(String(t.projects[0].modules.length))),console.log(s.cyan("Module gaps:"),s.yellow(String(t.projects[0].moduleGaps.length))),console.log(s.cyan("Checksum:"),s.white(t.factory.manifestChecksum)),console.log(s.gray(`
|
|
113
113
|
Wrote manifest: ${b.resolve(process.cwd(),e)}
|
|
114
|
-
`));}function wp(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(r,o)=>{try{let n=o.output||up("--output"),a=await hp({backlogPath:r,kit:o.kit,tier:o.tier,category:o.category,limit:o.limit});a$4(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await gp(n,a,true),o.json?console.log(Cr(a)):jm(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Cr({ok:false,error:{message:a}})):console.error(s.red(`Product plan failed: ${a}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(r,o)=>{try{let n=o.output||up("--output");fp(r);let a=await Pm({backlogPath:o.fromBacklog,slug:r,kit:o.kit,outputRoot:o.workspaceOutput});a$4(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=bm(n,r);await gp(i,a,o.force===true),o.json?console.log(Cr(a)):Cm(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Cr({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var kp="rapidkit-workspace-snapshot-v1",lo="rapidkit-workspace-snapshot-v2",Em=kp,vp="rapidkit-project-archive-v1",bt="workspai-archive.json",
|
|
115
|
-
`,"utf-8"),r}async function gn(t,e,r){let o=await xm(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function Ua(t=process.cwd()){let e=b.resolve(t),r=b.resolve($a.tmpdir());for(;;){if(e!==r&&k$1(e))return e;let o=b.dirname(e);if(o===e)return null;e=o;}}function Dt(t){let e=t?b.resolve(t):Ua(process.cwd())??b$5({startPath:process.cwd()})?.workspacePath??null;if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!k$1(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function bp(t){let e=await Pp(t$1(t,"workspace.json").find(o=>existsSync(o))??q$1(t,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():b$d(t)}function Ar(t){return q$1(t,"snapshots")}function po(t){return q$1(t,"archive","projects")}function Er(t){return b.join(t,"files")}function _m(t){return b.join($a.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${Wt.randomBytes(4).toString("hex")}`)}function Om(t,e){return b.join(Ar(t),`.tmp-${process.pid}-${e}-${Wt.randomBytes(4).toString("hex")}`)}function fn(t,e){let r=b.relative(t,e);if(!r)return true;let o=r.split(b.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>Am.has(n)||a$i(n))}async function Nm(t){let e=await a$j(t,{descendIntoMatchedProjects:false}),r=new Map;for(let n of e){let a=b.relative(t,n).replace(/\\/g,"/");r.set(a,{name:b.basename(n),relativePath:a});}let o=await Pp(t$1(t,"workspace.contract.json").find(n=>existsSync(n))??q$1(t,"workspace.contract.json"));if(Array.isArray(o?.projects))for(let n of o.projects){if(!n||typeof n!="object")continue;let a=n,i=typeof a.relativePath=="string"?a.relativePath.replace(/\\/g,"/"):"",c=typeof a.slug=="string"?a.slug.trim():"";!i||!c||i.startsWith("../")||b.isAbsolute(i)||r.set(i,{name:c,relativePath:i});}return [...r.values()].sort((n,a)=>n.relativePath.localeCompare(a.relativePath))}async function $m(t,e){let r=[],o=new Set;for(let n of Sm){let a=b.join(t,n);if(!await M__default.pathExists(a))continue;let i=w(n);if(o.has(i))continue;let c=b.join(e,i);await M__default.copy(a,c,{filter:l=>fn(t,l)}),r.push(i),o.add(i);}return r}async function jp(t){let e=[];async function r(o){let n=[];try{n=await M__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=b.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=b.join(b.dirname(o),b.basename(w(b.basename(o))));await M__default.copy(o,n,{overwrite:false,errorOnExist:false}),await M__default.remove(o);}}async function Cp(t,e){let r=e.schema===lo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,r,"Workspace snapshot manifest"),await M__default.writeJson(b.join(t,"snapshot.json"),e,{spaces:2});}async function Ba(t){let e=b.join(t,"snapshot.json"),r=await M__default.readJson(e);if(!r||typeof r!="object"||![kp,lo].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===lo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==lo||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function Tm(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await M__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=b.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let l=await M__default.stat(c);e+=1,r+=l.size;}catch{}}}return {files:e,bytes:r}}async function hn(t={}){let e=Dt(t.workspacePath),r=t.name?t.name:`snapshot-${Sr()}`,o=mn(r),n=b.join(Ar(e),o),a=_m(o);if(await M__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=Er(a);try{await M__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",l=c==="full"?["."]:await $m(e,i);c==="full"&&(await M__default.copy(e,i,{filter:m=>fn(e,m)}),await jp(i));let p={schema:Em,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await bp(e),workspacePath:e,copiedPaths:l,projects:await Nm(e)};return await Cp(a,p),await M__default.ensureDir(b.dirname(n)),await M__default.move(a,n,{overwrite:false}),await lt(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:l,snapshotPath:n,projectCount:p.projects.length}}),{manifest:p,snapshotPath:n}}catch(c){throw await M__default.remove(a),await lt(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function wn(t){let e=b.resolve(t.workspacePath),r=b.resolve(t.projectPath),o=b.relative(e,r);if(!o||o.startsWith("..")||b.isAbsolute(o)||o.split(b.sep).some(m=>m===".workspai"||m===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=b.basename(r),a=mn(`${t.namePrefix}-${n}-${Sr()}-${Wt.randomBytes(3).toString("hex")}`),i=b.join(Ar(e),a),c=Om(e,a),l=b.join(Er(c),o),p=false;try{await M__default.ensureDir(b.dirname(l)),t.moveSource?(await M__default.move(r,l,{overwrite:false}),p=true):await M__default.copy(r,l,{overwrite:false,errorOnExist:true,filter:u=>fn(r,u)});let m={schema:lo,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await bp(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await Cp(c,m),await M__default.move(c,i,{overwrite:false}),await lt(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:m,snapshotPath:i}}catch(m){if(p&&!await M__default.pathExists(r)){let u=await M__default.pathExists(l)?l:b.join(Er(i),o);await M__default.pathExists(u)&&(await M__default.ensureDir(b.dirname(r)),await M__default.move(u,r,{overwrite:false}));}throw await M__default.remove(c),await M__default.remove(i),await lt(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:m instanceof Error?m.message:String(m)}}),m}}async function Ep(t){let e=Dt(t.workspacePath),r=b.join(Ar(e),mn(t.name));if(!await M__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Ba(r),n=Er(r),a=await Tm(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function Sp(t={}){let e=Dt(t.workspacePath),r=Ar(e);if(!await M__default.pathExists(r))return [];let o=await M__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=b.join(r,a.name);try{n.push({...await Ba(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var Mm=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function Wm(t){let e=b.dirname(t.workspacePath),r=b.basename(t.workspacePath),o=`${Sr()}-${Wt.randomBytes(4).toString("hex")}`,n=b.join(e,`.${r}.restore-staging-${o}`),a=b.join(e,`.${r}.pre-restore-${o}`),i=b.join(e,`.${r}.restore-failed-${o}`),c=[],l=false,p=false;try{await M__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:m=>fn(t.filesRoot,m)}),await jp(n),await M__default.rename(t.workspacePath,a),l=true,await M__default.rename(n,t.workspacePath),p=true;for(let m of Mm){let u=b.join(a,m);if(!await M__default.pathExists(u))continue;let f=b.join(t.workspacePath,m);if(await M__default.pathExists(f))throw new Error(`Full restore operational path collision: ${m}`);await M__default.ensureDir(b.dirname(f)),await M__default.rename(u,f),c.push(m);}return a}catch(m){for(let u of [...c].reverse()){let f=b.join(t.workspacePath,u),P=b.join(a,u);await M__default.pathExists(f)&&(await M__default.ensureDir(b.dirname(P)),await M__default.rename(f,P));}throw p&&await M__default.pathExists(t.workspacePath)&&await M__default.rename(t.workspacePath,i),l&&await M__default.pathExists(a)&&await M__default.rename(a,t.workspacePath),await M__default.remove(i),await M__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${m instanceof Error?m.message:String(m)}`)}}async function Ap(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=b.join(Er(t.snapshotPath),r),n=b.join(e,r);await M__default.pathExists(o)&&!await M__default.pathExists(n)&&(await M__default.ensureDir(b.dirname(n)),await M__default.move(o,n,{overwrite:false})),await M__default.remove(t.snapshotPath);}async function Rp(t){let e=Dt(t.workspacePath),r=b.join(Ar(e),mn(t.name));if(!await M__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await Ba(r),n=Er(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(l=>{let p=w(l);return p.startsWith(".workspai/")?".workspai":p})));if(t.dryRun)return await lt(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await gn(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await Wm({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let l=o.recoveryScope?.relativePath;if(!l)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let p=b.join(n,l),m=b.join(e,l),u=await M__default.pathExists(m),f,P=b.join(b.dirname(m),`.${b.basename(m)}.pre-restore-${process.pid}-${Wt.randomBytes(4).toString("hex")}`),y=false;u&&t.safetySnapshot!==false?(f=await wn({workspacePath:e,projectPath:m,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=f.snapshotPath):u&&(await M__default.rename(m,P),y=true);let E=b.join(b.dirname(m),`.${b.basename(m)}.restore-${process.pid}-${Wt.randomBytes(4).toString("hex")}`);try{await M__default.copy(p,E,{overwrite:false,errorOnExist:true}),await M__default.rename(E,m),y&&await M__default.remove(P);}catch(A){throw await M__default.remove(E),y&&await M__default.pathExists(P)&&(await M__default.remove(m),await M__default.rename(P,m)),f&&await Ap(f,e),A}}else t.safetySnapshot!==false&&(i=(await hn({workspacePath:e,name:`pre-restore-${o.name}-${Sr()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let l=new Set;for(let p of o.copiedPaths){let m=w(p);l.has(m)||(await M__default.copy(b.join(n,p),b.join(e,m),{overwrite:true,errorOnExist:false}),l.add(m));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await lt(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function xp(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function Ip(t,e){let r=xp(e),o=b.isAbsolute(r)?b.resolve(r):b.resolve(t,r),n=async c=>{let[l,p,m]=await Promise.all([M__default.realpath(t),M__default.realpath(c),M__default.stat(c)]),u=b.relative(l,p);if(!m.isDirectory()||!u||u===".."||u.startsWith(`..${b.sep}`)||b.isAbsolute(u))throw new Error(`Project ${e} is not a directory contained by the workspace.`);return c};if(o.startsWith(`${b.resolve(t)}${b.sep}`)&&await M__default.pathExists(o))return n(o);let i=(await a$j(t,{descendIntoMatchedProjects:false})).filter(c=>{let l=b.relative(t,c);return b.basename(c)===r||l===r});if(i.length===0){let l=(await a$m(t)).filter(u=>{let f=u.relativePath?.replace(/\\/g,"/");return u.name===r||f===r.replace(/\\/g,"/")||b.resolve(t,u.path)===o}),p=[...new Set(l.map(u=>b.resolve(t,u.path)))];if(p.length>1)throw new Error(`Project reference is ambiguous: ${e}`);let m=p[0];if(m&&!m.startsWith(`${b.resolve(t)}${b.sep}`))throw new Error(`Project ${e} is a linked external project and cannot be archived or deleted by workspace lifecycle commands. Only managed projects contained by the workspace support archive/delete; manage the external source or its workspace registration explicitly.`);if(m&&await M__default.pathExists(m))return n(m);throw new Error(`Project not found in workspace: ${e}`)}if(i.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return n(i[0])}async function Ha(t){let{syncWorkspaceProjects:e}=await import('./workspace-A33YMF2N.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-3QUZDBMM.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-TEOSTKNU.js');await o({workspacePath:t,mode:"managed"});}function Dm(t,e){let r=Wt.randomBytes(4).toString("hex");return b.join(po(t),`${e}-${Sr()}-${r}`)}async function _p(t){let e=Op(t),r=await M__default.readJson(e);if(!r||typeof r!="object"||r.schema!==vp)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function Op(t){return [bt,un].map(e=>b.join(t,e)).find(e=>M__default.existsSync(e))??b.join(t,bt)}async function qa(t={}){let e=Dt(t.workspacePath),r=po(e);if(!await M__default.pathExists(r))return [];let o=await M__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=b.join(r,a.name),c=[bt,un].map(l=>b.join(i,l)).find(l=>M__default.existsSync(l))??b.join(i,bt);try{n.push({...await _p(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function Lm(t,e){let r=xp(e),o=b.isAbsolute(r)?b.resolve(r):b.resolve(po(t),r);if(o.startsWith(`${b.resolve(po(t))}${b.sep}`)&&(await M__default.pathExists(b.join(o,bt))||await M__default.pathExists(b.join(o,un))))return o;let a=(await qa({workspacePath:t})).filter(i=>b.basename(i.archivePath)===r||i.projectName===r||b.relative(po(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function za(t){let e=Dt(t.workspacePath),r=await Ip(e,t.project),o=b.basename(r),n=Dm(e,o),a=b.join(n,bt),i=`${n}.tmp-${process.pid}`,c=b.join(i,bt);for(let u of [bt,un])if(await M__default.pathExists(b.join(r,u)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${u}`);if(t.dryRun)return await lt(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await gn(e,"project.archive",{reason:t.reason,safetySnapshot:true});let l=await wn({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),p={schema:vp,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:l.snapshotPath};a$4(p,"contracts/project-archive.v1.json","Project archive manifest");let m=false;try{await M__default.ensureDir(b.dirname(n)),await M__default.move(r,i,{overwrite:false}),m=true,await M__default.writeJson(c,p,{spaces:2}),await M__default.rename(i,n);}catch(u){if(m&&!await M__default.pathExists(r)){let f=await M__default.pathExists(i)?i:n;await M__default.pathExists(f)&&(await M__default.remove(b.join(f,bt)),await M__default.move(f,r,{overwrite:false}));}throw await M__default.remove(i),u}return await c$4(e,[r]),await Ha(e),await lt(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath,dryRun:false}}async function Np(t){if(!t.permanent)return za(t);let e=Dt(t.workspacePath),r=await Ip(e,t.project),o=b.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await lt(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await gn(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await wn({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$4(e,[r]),await Ha(e),await lt(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function $p(t){let e=Dt(t.workspacePath),r=await Lm(e,t.archive),o=await _p(r),n=t.targetName?.trim()||o.projectName,a=b.join(e,n);if(!a.startsWith(`${b.resolve(e)}${b.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await M__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await lt(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:b.join(r,bt),dryRun:true};await gn(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await M__default.pathExists(a),c=i?await wn({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await hn({workspacePath:e,name:`pre-restore-project-${n}-${Sr()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),l=Op(r),p=q$1(e,"audit","restores",`${b.basename(r)}.json`);try{await M__default.move(r,a,{overwrite:false}),await M__default.ensureDir(b.dirname(p)),await M__default.move(b.join(a,b.basename(l)),p,{overwrite:false});}catch(m){throw await M__default.pathExists(a)&&(await M__default.pathExists(p)&&await M__default.move(p,b.join(a,b.basename(l)),{overwrite:false}),await M__default.pathExists(r)||await M__default.move(a,r,{overwrite:false})),i&&await Ap(c,e),m}return await Ha(e),await lt(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:p,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:p,safetySnapshotPath:c.snapshotPath,dryRun:false}}var Gm="rapidkit.infra-stack.v1",Mp=s$1.infraPlan.schemaVersion,Rr=".workspai/infra/docker-compose.yml",xr=t.infraPlan,Qa=".workspai/infra/.env.example";function Vm(){let t=b.dirname(fileURLToPath(import.meta.url)),e=[b.join(t,"../../contracts/infra-stack.v1.json"),b.join(t,"../contracts/infra-stack.v1.json")];for(let r of e)if($.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var Xa=null;function zt(t){if(Xa)return Xa;let e=Vm(),r=$.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==Gm)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return Jm(o),(Xa=o),o}function Jm(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function Wp(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function Ir(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Dp(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function Um(t){let e=b.join(t,"registry.json");if(!await M__default.pathExists(e))return [];try{let o=(await M__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function Bm(t){let e=b.join(t,".env.example");if(!await M__default.pathExists(e))return [];try{let r=await M__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
|
|
116
|
-
`)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&o.push(i[1]);}return o}catch{return []}}async function Hm(t){let e=t$1(t,"infra","overrides.json").find(r=>existsSync(r));if(!e)return [];try{let r=await M__default.readJson(e);return Array.isArray(r.services)?[...new Set(r.services.filter(o=>typeof o=="string"&&o.trim().length>0))]:[]}catch{return []}}async function qm(t$1){let e=await g$1(t$1,t.workspaceContract);if(!e)return [];try{let r=await M__default.readJson(e),o=[];for(let n of r.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&o.push({project:a,env:i.trim().toUpperCase()});}return o}catch{return []}}function
|
|
114
|
+
`));}function wp(t){let e=t.command("product",{hidden:true}).description("Product Factory commands for private workspace product manifests");e.command("plan <backlog>").description("Build a deterministic Product Factory plan from a workspace backlog JSON").option("--output <file>","Write plan JSON to file").option("--kit <kit>","Default API kit for generated product manifests","fastapi.standard").option("--tier <tier>","Filter products by tier").option("--category <category>","Filter products by category").option("--limit <count>","Limit planned products").option("--json","Print JSON to stdout").action(async(r,o)=>{try{let n=o.output||up("--output"),a=await hp({backlogPath:r,kit:o.kit,tier:o.tier,category:o.category,limit:o.limit});a$4(a,"contracts/product-factory-plan.v1.json","Product Factory plan"),n&&await gp(n,a,true),o.json?console.log(Cr(a)):jm(a,n);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Cr({ok:false,error:{message:a}})):console.error(s.red(`Product plan failed: ${a}`)),process.exit(1);}}),e.command("manifest").description("Create or inspect private product manifests").command("create <slug>").description("Create a private product manifest from a backlog product slug").requiredOption("--from-backlog <file>","Source workspace backlog JSON").option("--output <fileOrDir>","Manifest output file or directory").option("--kit <kit>","API kit for the generated workspace product","fastapi.standard").option("--workspace-output <dir>","Suggested root for generated product workspaces").option("--json","Print JSON to stdout").option("--force","Overwrite existing manifest file").action(async(r,o)=>{try{let n=o.output||up("--output");fp(r);let a=await Pm({backlogPath:o.fromBacklog,slug:r,kit:o.kit,outputRoot:o.workspaceOutput});a$4(a,"contracts/private-product-manifest.v1.json","Private product manifest");let i=bm(n,r);await gp(i,a,o.force===true),o.json?console.log(Cr(a)):Cm(a,i);}catch(n){let a=n instanceof Error?n.message:String(n);o.json?console.log(Cr({ok:false,error:{message:a}})):console.error(s.red(`Product manifest create failed: ${a}`)),process.exit(1);}});}var kp="rapidkit-workspace-snapshot-v1",lo="rapidkit-workspace-snapshot-v2",Em=kp,vp="rapidkit-project-archive-v1",bt="workspai-archive.json",mn="rapidkit-archive.json",Sm=[".workspai/workspace.json",t.workspaceContract,t.workspaceRegistry,".workspai/imported-projects.json",".workspai/policies.yml",".workspai/toolchain.lock",".workspai/cache-config.yml",".workspai-workspace","workspai.config.json","workspai.config.js","workspai.config.cjs","workspai.config.mjs",".rapidkit/workspace.json",".rapidkit-workspace","rapidkit.config.json","rapidkit.config.js","rapidkit.config.cjs","rapidkit.config.mjs","package.json"],Am=new Set([".git","node_modules",".venv","dist","build","target","coverage","htmlcov",".next"]),co={requireReasonForDestructiveOps:false,requireSafetySnapshotForDestructiveOps:true,allowPermanentDelete:true};function Sr(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function gn(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!e)throw new Error("Snapshot name must contain at least one letter or number.");return e.slice(0,120)}async function Pp(t){try{let e=await M__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Rm(t,e){if(!t)return e;let r=t.trim().toLowerCase();return ["true","yes","1","on"].includes(r)?true:["false","no","0","off"].includes(r)?false:e}async function xm(t){let e=t$1(t,"policies.yml").find(r=>existsSync(r))??q$1(t,"policies.yml");if(!await M__default.pathExists(e))return {...co};try{let r=await M__default.readFile(e,"utf-8"),o=(n,a)=>{let i=r.match(new RegExp(`^\\s*${n}:\\s*([^#\\n]+)`,"m"));return Rm(i?.[1],a)};return {requireReasonForDestructiveOps:o("require_reason_for_destructive_ops",co.requireReasonForDestructiveOps),requireSafetySnapshotForDestructiveOps:o("require_safety_snapshot_for_destructive_ops",co.requireSafetySnapshotForDestructiveOps),allowPermanentDelete:o("allow_permanent_delete",co.allowPermanentDelete)}}catch{return {...co}}}function Im(t){return q$1(t,"audit","events.jsonl")}async function lt(t,e){let r={schema:"rapidkit-workspace-audit-event-v1",id:Wt.randomUUID(),timestamp:new Date().toISOString(),workspacePath:t,...e},o=Im(t);return await M__default.ensureDir(b.dirname(o)),await M__default.appendFile(o,`${JSON.stringify(r)}
|
|
115
|
+
`,"utf-8"),r}async function fn(t,e,r){let o=await xm(t);if(o.requireReasonForDestructiveOps&&!r.reason?.trim())throw new Error(`${e} requires --reason by workspace policy.`);if(o.requireSafetySnapshotForDestructiveOps&&r.safetySnapshot===false)throw new Error(`${e} requires a safety snapshot by workspace policy.`);if(r.permanent&&!o.allowPermanentDelete)throw new Error("Permanent project delete is disabled by workspace policy.");return o}function Ha(t=process.cwd()){let e=b.resolve(t),r=b.resolve(Ma.tmpdir());for(;;){if(e!==r&&k$1(e))return e;let o=b.dirname(e);if(o===e)return null;e=o;}}function Dt(t){let e=t?b.resolve(t):Ha(process.cwd())??b$5({startPath:process.cwd()})?.workspacePath??null;if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");if(!k$1(e))throw new Error(`Workspace path is not a Workspai workspace: ${e}`);return e}async function bp(t){let e=await Pp(t$1(t,"workspace.json").find(o=>existsSync(o))??q$1(t,"workspace.json")),r=e?.workspace_name??e?.name;return typeof r=="string"&&r.trim()?r.trim():b$d(t)}function Ar(t){return q$1(t,"snapshots")}function po(t){return q$1(t,"archive","projects")}function Er(t){return b.join(t,"files")}function _m(t){return b.join(Ma.tmpdir(),`rapidkit-workspace-snapshot-${process.pid}-${t}-${Wt.randomBytes(4).toString("hex")}`)}function Om(t,e){return b.join(Ar(t),`.tmp-${process.pid}-${e}-${Wt.randomBytes(4).toString("hex")}`)}function hn(t,e){let r=b.relative(t,e);if(!r)return true;let o=r.split(b.sep);return (o[0]===".workspai"||o[0]===".rapidkit")&&["snapshots","archive","audit"].includes(o[1]||"")?false:!o.some(n=>Am.has(n)||a$i(n))}async function Nm(t){let e=await a$j(t,{descendIntoMatchedProjects:false}),r=new Map;for(let n of e){let a=b.relative(t,n).replace(/\\/g,"/");r.set(a,{name:b.basename(n),relativePath:a});}let o=await Pp(t$1(t,"workspace.contract.json").find(n=>existsSync(n))??q$1(t,"workspace.contract.json"));if(Array.isArray(o?.projects))for(let n of o.projects){if(!n||typeof n!="object")continue;let a=n,i=typeof a.relativePath=="string"?a.relativePath.replace(/\\/g,"/"):"",c=typeof a.slug=="string"?a.slug.trim():"";!i||!c||i.startsWith("../")||b.isAbsolute(i)||r.set(i,{name:c,relativePath:i});}return [...r.values()].sort((n,a)=>n.relativePath.localeCompare(a.relativePath))}async function $m(t,e){let r=[],o=new Set;for(let n of Sm){let a=b.join(t,n);if(!await M__default.pathExists(a))continue;let i=w(n);if(o.has(i))continue;let c=b.join(e,i);await M__default.copy(a,c,{filter:l=>hn(t,l)}),r.push(i),o.add(i);}return r}async function jp(t){let e=[];async function r(o){let n=[];try{n=await M__default.readdir(o,{withFileTypes:true});}catch{return}for(let a of n){let i=b.join(o,a.name);a.isDirectory()?a.name===".rapidkit"?e.push(i):await r(i):a.isFile()&&a.name===".rapidkit-workspace"&&e.push(i);}}await r(t),e.sort((o,n)=>n.length-o.length);for(let o of e){let n=b.join(b.dirname(o),b.basename(w(b.basename(o))));await M__default.copy(o,n,{overwrite:false,errorOnExist:false}),await M__default.remove(o);}}async function Cp(t,e){let r=e.schema===lo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";a$4(e,r,"Workspace snapshot manifest"),await M__default.writeJson(b.join(t,"snapshot.json"),e,{spaces:2});}async function qa(t){let e=b.join(t,"snapshot.json"),r=await M__default.readJson(e);if(!r||typeof r!="object"||![kp,lo].includes(r.schema))throw new Error(`Invalid Workspai workspace snapshot manifest: ${e}`);let o=r,n=o.schema===lo?"contracts/workspace-snapshot.v2.json":"contracts/workspace-snapshot.v1.json";if(a$4(o,n,"Workspace snapshot manifest"),o.mode==="project"&&(o.schema!==lo||o.recoveryScope?.kind!=="project"||!o.recoveryScope.relativePath))throw new Error(`Invalid project recovery snapshot manifest: ${e}`);return o}async function Tm(t){let e=0,r=0,o=[t];for(;o.length>0;){let n=o.shift();if(!n)continue;let a=[];try{a=await M__default.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){let c=b.join(n,i.name);if(i.isDirectory()){o.push(c);continue}if(i.isFile())try{let l=await M__default.stat(c);e+=1,r+=l.size;}catch{}}}return {files:e,bytes:r}}async function wn(t={}){let e=Dt(t.workspacePath),r=t.name?t.name:`snapshot-${Sr()}`,o=gn(r),n=b.join(Ar(e),o),a=_m(o);if(await M__default.pathExists(n))throw new Error(`Snapshot already exists: ${o}`);let i=Er(a);try{await M__default.ensureDir(i);let c=t.includeProjects?"full":"metadata",l=c==="full"?["."]:await $m(e,i);c==="full"&&(await M__default.copy(e,i,{filter:m=>hn(e,m)}),await jp(i));let p={schema:Em,name:o,mode:c,reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await bp(e),workspacePath:e,copiedPaths:l,projects:await Nm(e)};return await Cp(a,p),await M__default.ensureDir(b.dirname(n)),await M__default.move(a,n,{overwrite:false}),await lt(e,{action:"snapshot.create",target:o,status:"succeeded",reason:t.reason,details:{mode:c,copiedPaths:l,snapshotPath:n,projectCount:p.projects.length}}),{manifest:p,snapshotPath:n}}catch(c){throw await M__default.remove(a),await lt(e,{action:"snapshot.create",target:o,status:"failed",reason:t.reason,details:{error:c instanceof Error?c.message:String(c)}}),c}}async function yn(t){let e=b.resolve(t.workspacePath),r=b.resolve(t.projectPath),o=b.relative(e,r);if(!o||o.startsWith("..")||b.isAbsolute(o)||o.split(b.sep).some(m=>m===".workspai"||m===".rapidkit"))throw new Error(`Project recovery path must be a project inside the workspace: ${r}`);let n=b.basename(r),a=gn(`${t.namePrefix}-${n}-${Sr()}-${Wt.randomBytes(3).toString("hex")}`),i=b.join(Ar(e),a),c=Om(e,a),l=b.join(Er(c),o),p=false;try{await M__default.ensureDir(b.dirname(l)),t.moveSource?(await M__default.move(r,l,{overwrite:false}),p=true):await M__default.copy(r,l,{overwrite:false,errorOnExist:true,filter:u=>hn(r,u)});let m={schema:lo,name:a,mode:"project",reason:t.reason,createdAt:new Date().toISOString(),workspaceName:await bp(e),workspacePath:e,copiedPaths:[o],projects:[{name:n,relativePath:o}],recoveryScope:{kind:"project",projectName:n,relativePath:o}};return await Cp(c,m),await M__default.move(c,i,{overwrite:false}),await lt(e,{action:"snapshot.create",target:a,status:"succeeded",reason:t.reason,details:{mode:"project",copiedPaths:[o],snapshotPath:i,projectCount:1}}),{manifest:m,snapshotPath:i}}catch(m){if(p&&!await M__default.pathExists(r)){let u=await M__default.pathExists(l)?l:b.join(Er(i),o);await M__default.pathExists(u)&&(await M__default.ensureDir(b.dirname(r)),await M__default.move(u,r,{overwrite:false}));}throw await M__default.remove(c),await M__default.remove(i),await lt(e,{action:"snapshot.create",target:a,status:"failed",reason:t.reason,details:{mode:"project",error:m instanceof Error?m.message:String(m)}}),m}}async function Ep(t){let e=Dt(t.workspacePath),r=b.join(Ar(e),gn(t.name));if(!await M__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await qa(r),n=Er(r),a=await Tm(n);return {manifest:o,snapshotPath:r,filesRoot:n,estimatedFileCount:a.files,estimatedBytes:a.bytes}}async function Sp(t={}){let e=Dt(t.workspacePath),r=Ar(e);if(!await M__default.pathExists(r))return [];let o=await M__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=b.join(r,a.name);try{n.push({...await qa(i),snapshotPath:i});}catch{}}return n.sort((a,i)=>i.createdAt.localeCompare(a.createdAt))}var Mm=[".workspai/snapshots",".workspai/archive",".workspai/audit",".rapidkit/snapshots",".rapidkit/archive",".rapidkit/audit"];async function Wm(t){let e=b.dirname(t.workspacePath),r=b.basename(t.workspacePath),o=`${Sr()}-${Wt.randomBytes(4).toString("hex")}`,n=b.join(e,`.${r}.restore-staging-${o}`),a=b.join(e,`.${r}.pre-restore-${o}`),i=b.join(e,`.${r}.restore-failed-${o}`),c=[],l=false,p=false;try{await M__default.copy(t.filesRoot,n,{overwrite:false,errorOnExist:true,filter:m=>hn(t.filesRoot,m)}),await jp(n),await M__default.rename(t.workspacePath,a),l=true,await M__default.rename(n,t.workspacePath),p=true;for(let m of Mm){let u=b.join(a,m);if(!await M__default.pathExists(u))continue;let f=b.join(t.workspacePath,m);if(await M__default.pathExists(f))throw new Error(`Full restore operational path collision: ${m}`);await M__default.ensureDir(b.dirname(f)),await M__default.rename(u,f),c.push(m);}return a}catch(m){for(let u of [...c].reverse()){let f=b.join(t.workspacePath,u),P=b.join(a,u);await M__default.pathExists(f)&&(await M__default.ensureDir(b.dirname(P)),await M__default.rename(f,P));}throw p&&await M__default.pathExists(t.workspacePath)&&await M__default.rename(t.workspacePath,i),l&&await M__default.pathExists(a)&&await M__default.rename(a,t.workspacePath),await M__default.remove(i),await M__default.remove(n),new Error(`Atomic full restore failed for ${t.snapshotName}: ${m instanceof Error?m.message:String(m)}`)}}async function Ap(t,e){let r=t.manifest.recoveryScope?.relativePath;if(!r)return;let o=b.join(Er(t.snapshotPath),r),n=b.join(e,r);await M__default.pathExists(o)&&!await M__default.pathExists(n)&&(await M__default.ensureDir(b.dirname(n)),await M__default.move(o,n,{overwrite:false})),await M__default.remove(t.snapshotPath);}async function Rp(t){let e=Dt(t.workspacePath),r=b.join(Ar(e),gn(t.name));if(!await M__default.pathExists(r))throw new Error(`Snapshot not found: ${t.name}`);let o=await qa(r),n=Er(r),a=o.mode==="full"?["."]:Array.from(new Set(o.copiedPaths.map(l=>{let p=w(l);return p.startsWith(".workspai/")?".workspai":p})));if(t.dryRun)return await lt(e,{action:"snapshot.restore",target:o.name,status:"planned",reason:t.reason,details:{restoredPaths:a}}),{workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:true};if(!t.force)throw new Error("Restore is destructive. Re-run with --force after reviewing --dry-run output.");await fn(e,"snapshot.restore",{reason:t.reason,safetySnapshot:t.safetySnapshot});let i;if(o.mode==="full")i=await Wm({workspacePath:e,filesRoot:n,snapshotName:o.name});else if(o.mode==="project"){let l=o.recoveryScope?.relativePath;if(!l)throw new Error(`Project recovery snapshot is missing recoveryScope: ${o.name}`);let p=b.join(n,l),m=b.join(e,l),u=await M__default.pathExists(m),f,P=b.join(b.dirname(m),`.${b.basename(m)}.pre-restore-${process.pid}-${Wt.randomBytes(4).toString("hex")}`),y=false;u&&t.safetySnapshot!==false?(f=await yn({workspacePath:e,projectPath:m,namePrefix:`pre-restore-${o.name}`,reason:`Automatic project recovery snapshot before restoring ${o.name}`,moveSource:true}),i=f.snapshotPath):u&&(await M__default.rename(m,P),y=true);let E=b.join(b.dirname(m),`.${b.basename(m)}.restore-${process.pid}-${Wt.randomBytes(4).toString("hex")}`);try{await M__default.copy(p,E,{overwrite:false,errorOnExist:true}),await M__default.rename(E,m),y&&await M__default.remove(P);}catch(A){throw await M__default.remove(E),y&&await M__default.pathExists(P)&&(await M__default.remove(m),await M__default.rename(P,m)),f&&await Ap(f,e),A}}else t.safetySnapshot!==false&&(i=(await wn({workspacePath:e,name:`pre-restore-${o.name}-${Sr()}`,reason:`Automatic safety snapshot before restoring ${o.name}`,includeProjects:false})).snapshotPath);if(o.mode==="metadata"){let l=new Set;for(let p of o.copiedPaths){let m=w(p);l.has(m)||(await M__default.copy(b.join(n,p),b.join(e,m),{overwrite:true,errorOnExist:false}),l.add(m));}}let c={workspacePath:e,snapshotPath:r,restoredPaths:a,dryRun:false,safetySnapshotPath:i};return await lt(e,{action:"snapshot.restore",target:o.name,status:"succeeded",reason:t.reason,details:{restoredPaths:a,safetySnapshotPath:i}}),c}function xp(t){let e=t.trim();if(!e)throw new Error("Project name/path is required.");return e}async function Ip(t,e){let r=xp(e),o=b.isAbsolute(r)?b.resolve(r):b.resolve(t,r),n=async c=>{let[l,p,m]=await Promise.all([M__default.realpath(t),M__default.realpath(c),M__default.stat(c)]),u=b.relative(l,p);if(!m.isDirectory()||!u||u===".."||u.startsWith(`..${b.sep}`)||b.isAbsolute(u))throw new Error(`Project ${e} is not a directory contained by the workspace.`);return c};if(o.startsWith(`${b.resolve(t)}${b.sep}`)&&await M__default.pathExists(o))return n(o);let i=(await a$j(t,{descendIntoMatchedProjects:false})).filter(c=>{let l=b.relative(t,c);return b.basename(c)===r||l===r});if(i.length===0){let l=(await a$m(t)).filter(u=>{let f=u.relativePath?.replace(/\\/g,"/");return u.name===r||f===r.replace(/\\/g,"/")||b.resolve(t,u.path)===o}),p=[...new Set(l.map(u=>b.resolve(t,u.path)))];if(p.length>1)throw new Error(`Project reference is ambiguous: ${e}`);let m=p[0];if(m&&!m.startsWith(`${b.resolve(t)}${b.sep}`))throw new Error(`Project ${e} is a linked external project and cannot be archived or deleted by workspace lifecycle commands. Only managed projects contained by the workspace support archive/delete; manage the external source or its workspace registration explicitly.`);if(m&&await M__default.pathExists(m))return n(m);throw new Error(`Project not found in workspace: ${e}`)}if(i.length>1)throw new Error(`Project reference is ambiguous: ${e}`);return n(i[0])}async function za(t){let{syncWorkspaceProjects:e}=await import('./workspace-AXU6ODER.js');await e(t,true);let{syncWorkspaceContract:r}=await import('./workspace-contract-N2BJCAJ7.js');await r({workspacePath:t,strict:true});let{syncWorkspaceProjectLenses:o}=await import('./project-intelligence-lens-OQTZ4K7L.js');await o({workspacePath:t,mode:"managed"});}function Dm(t,e){let r=Wt.randomBytes(4).toString("hex");return b.join(po(t),`${e}-${Sr()}-${r}`)}async function _p(t){let e=Op(t),r=await M__default.readJson(e);if(!r||typeof r!="object"||r.schema!==vp)throw new Error(`Invalid Workspai archive manifest: ${e}`);return a$4(r,"contracts/project-archive.v1.json","Project archive manifest"),r}function Op(t){return [bt,mn].map(e=>b.join(t,e)).find(e=>M__default.existsSync(e))??b.join(t,bt)}async function Ya(t={}){let e=Dt(t.workspacePath),r=po(e);if(!await M__default.pathExists(r))return [];let o=await M__default.readdir(r,{withFileTypes:true}),n=[];for(let a of o){if(!a.isDirectory())continue;let i=b.join(r,a.name),c=[bt,mn].map(l=>b.join(i,l)).find(l=>M__default.existsSync(l))??b.join(i,bt);try{n.push({...await _p(i),archivePath:i,manifestPath:c});}catch{}}return n.sort((a,i)=>i.archivedAt.localeCompare(a.archivedAt))}async function Lm(t,e){let r=xp(e),o=b.isAbsolute(r)?b.resolve(r):b.resolve(po(t),r);if(o.startsWith(`${b.resolve(po(t))}${b.sep}`)&&(await M__default.pathExists(b.join(o,bt))||await M__default.pathExists(b.join(o,mn))))return o;let a=(await Ya({workspacePath:t})).filter(i=>b.basename(i.archivePath)===r||i.projectName===r||b.relative(po(t),i.archivePath)===r);if(a.length===0)throw new Error(`Archived project not found: ${e}`);if(a.length>1)throw new Error(`Archive reference is ambiguous: ${e}`);return a[0].archivePath}async function Xa(t){let e=Dt(t.workspacePath),r=await Ip(e,t.project),o=b.basename(r),n=Dm(e,o),a=b.join(n,bt),i=`${n}.tmp-${process.pid}`,c=b.join(i,bt);for(let u of [bt,mn])if(await M__default.pathExists(b.join(r,u)))throw new Error(`Project contains reserved archive manifest path and cannot be archived safely: ${u}`);if(t.dryRun)return await lt(e,{action:"project.archive",target:o,status:"planned",reason:t.reason,details:{projectPath:r,archivePath:n}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,dryRun:true};await fn(e,"project.archive",{reason:t.reason,safetySnapshot:true});let l=await yn({workspacePath:e,projectPath:r,namePrefix:"pre-archive",reason:t.reason||`Automatic safety snapshot before archiving ${o}`,moveSource:false}),p={schema:vp,projectName:o,originalPath:r,archivedPath:n,reason:t.reason,archivedAt:new Date().toISOString(),safetySnapshotPath:l.snapshotPath};a$4(p,"contracts/project-archive.v1.json","Project archive manifest");let m=false;try{await M__default.ensureDir(b.dirname(n)),await M__default.move(r,i,{overwrite:false}),m=true,await M__default.writeJson(c,p,{spaces:2}),await M__default.rename(i,n);}catch(u){if(m&&!await M__default.pathExists(r)){let f=await M__default.pathExists(i)?i:n;await M__default.pathExists(f)&&(await M__default.remove(b.join(f,bt)),await M__default.move(f,r,{overwrite:false}));}throw await M__default.remove(i),u}return await c$4(e,[r]),await za(e),await lt(e,{action:"project.archive",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"archive",archivePath:n,manifestPath:a,safetySnapshotPath:l.snapshotPath,dryRun:false}}async function Np(t){if(!t.permanent)return Xa(t);let e=Dt(t.workspacePath),r=await Ip(e,t.project),o=b.basename(r);if(t.confirm!==o)throw new Error(`Permanent delete requires --confirm ${o}`);if(t.dryRun)return await lt(e,{action:"project.delete",target:o,status:"planned",reason:t.reason,details:{projectPath:r,permanent:true}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",dryRun:true};await fn(e,"project.delete",{reason:t.reason,permanent:true,safetySnapshot:true});let n=await yn({workspacePath:e,projectPath:r,namePrefix:"pre-delete",reason:t.reason||`Automatic safety snapshot before deleting ${o}`,moveSource:true});return await c$4(e,[r]),await za(e),await lt(e,{action:"project.delete",target:o,status:"succeeded",reason:t.reason,details:{projectPath:r,permanent:true,safetySnapshotPath:n.snapshotPath}}),{workspacePath:e,projectName:o,projectPath:r,action:"delete",safetySnapshotPath:n.snapshotPath,dryRun:false}}async function $p(t){let e=Dt(t.workspacePath),r=await Lm(e,t.archive),o=await _p(r),n=t.targetName?.trim()||o.projectName,a=b.join(e,n);if(!a.startsWith(`${b.resolve(e)}${b.sep}`))throw new Error(`Archive restore target escapes workspace: ${n}`);if(await M__default.pathExists(a)&&!t.force)throw new Error(`Project path already exists. Re-run with --force to overwrite: ${a}`);if(t.dryRun)return await lt(e,{action:"project.restore",target:n,status:"planned",reason:t.reason,details:{archivePath:r,projectPath:a}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:b.join(r,bt),dryRun:true};await fn(e,"project.restore",{reason:t.reason,safetySnapshot:true});let i=await M__default.pathExists(a),c=i?await yn({workspacePath:e,projectPath:a,namePrefix:"pre-restore-project",reason:t.reason||`Automatic safety snapshot before restoring ${n}`,moveSource:true}):await wn({workspacePath:e,name:`pre-restore-project-${n}-${Sr()}`,reason:t.reason||`Automatic safety snapshot before restoring ${n}`,includeProjects:false}),l=Op(r),p=q$1(e,"audit","restores",`${b.basename(r)}.json`);try{await M__default.move(r,a,{overwrite:false}),await M__default.ensureDir(b.dirname(p)),await M__default.move(b.join(a,b.basename(l)),p,{overwrite:false});}catch(m){throw await M__default.pathExists(a)&&(await M__default.pathExists(p)&&await M__default.move(p,b.join(a,b.basename(l)),{overwrite:false}),await M__default.pathExists(r)||await M__default.move(a,r,{overwrite:false})),i&&await Ap(c,e),m}return await za(e),await lt(e,{action:"project.restore",target:n,status:"succeeded",reason:t.reason,details:{archivePath:r,projectPath:a,restoreReceiptPath:p,safetySnapshotPath:c.snapshotPath}}),{workspacePath:e,projectName:n,projectPath:a,action:"restore",archivePath:r,manifestPath:p,safetySnapshotPath:c.snapshotPath,dryRun:false}}var Gm="rapidkit.infra-stack.v1",Mp=s$1.infraPlan.schemaVersion,Rr=".workspai/infra/docker-compose.yml",xr=t.infraPlan,es=".workspai/infra/.env.example";function Vm(){let t=b.dirname(fileURLToPath(import.meta.url)),e=[b.join(t,"../../contracts/infra-stack.v1.json"),b.join(t,"../contracts/infra-stack.v1.json")];for(let r of e)if($.existsSync(r))return r;throw new Error(`Infra stack contract not found. Expected contracts/infra-stack.v1.json beside the rapidkit package root. Checked: ${e.join(", ")}`)}var Za=null;function zt(t){if(Za)return Za;let e=Vm(),r=$.readFileSync(e,"utf-8"),o=JSON.parse(r);if(o.schemaVersion!==Gm)throw new Error(`Unsupported infra stack schema: ${o.schemaVersion}`);return Jm(o),(Za=o),o}function Jm(t){let e=new Set(Object.keys(t.services));for(let[r,o]of Object.entries(t.moduleMappings)){if(!Array.isArray(o))throw new Error(`Invalid moduleMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`moduleMappings/${r} references unknown service '${n}'`)}for(let[r,o]of Object.entries(t.envVarMappings)){if(!Array.isArray(o))throw new Error(`Invalid envVarMappings entry for ${r}`);for(let n of o)if(!e.has(n))throw new Error(`envVarMappings/${r} references unknown service '${n}'`)}}function Wp(t,e){let r=e.startsWith("free/")?e:`free/${e}`;return t.moduleMappings[r]||[]}function Ir(t,e){return t.envVarMappings[e.toUpperCase()]||[]}function Dp(t,e){let r={};for(let o of e){let n=t.services[o];n&&Object.assign(r,n.connectionEnv);}return r}async function Um(t){let e=b.join(t,"registry.json");if(!await M__default.pathExists(e))return [];try{let o=(await M__default.readJson(e)).installed_modules||[];return [...new Set(o.map(n=>typeof n.slug=="string"?n.slug.trim():"").filter(Boolean))]}catch{return []}}async function Bm(t){let e=b.join(t,".env.example");if(!await M__default.pathExists(e))return [];try{let r=await M__default.readFile(e,"utf-8"),o=[];for(let n of r.split(`
|
|
116
|
+
`)){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=a.match(/^([A-Z0-9_]+)=/);i?.[1]&&o.push(i[1]);}return o}catch{return []}}async function Hm(t){let e=t$1(t,"infra","overrides.json").find(r=>existsSync(r));if(!e)return [];try{let r=await M__default.readJson(e);return Array.isArray(r.services)?[...new Set(r.services.filter(o=>typeof o=="string"&&o.trim().length>0))]:[]}catch{return []}}async function qm(t$1){let e=await g$1(t$1,t.workspaceContract);if(!e)return [];try{let r=await M__default.readJson(e),o=[];for(let n of r.projects||[]){let a=typeof n.slug=="string"?n.slug:"unknown";for(let i of n.contracts?.env||[])typeof i=="string"&&i.trim()&&o.push({project:a,env:i.trim().toUpperCase()});}return o}catch{return []}}function kn(t,e,r,o){t.add(r),e.push(o);}async function Lp(t){let e=b.resolve(t.workspacePath),r=t.contract||zt(),o=new Set,n=[],a=new Set,i=new Set,c=new Set,l=await l$4(e);for(let p of l){let m=b.dirname(b.dirname(p)),u=b.basename(m);for(let f of await Um(m)){a.add(f);for(let P of Wp(r,f))kn(o,n,P,{kind:"module",value:f,project:u});}for(let f of await Bm(m)){i.add(f);for(let P of Ir(r,f))kn(o,n,P,{kind:"env-var",value:f,project:u});}}for(let p of await qm(e)){i.add(p.env);for(let m of Ir(r,p.env))kn(o,n,m,{kind:"contract-env",value:p.env,project:p.project});}for(let p of await Hm(e))c.add(p),kn(o,n,p,{kind:"override",value:p});return {modules:[...a].sort(),envVars:[...i].sort(),overrides:[...c].sort(),sources:n,serviceIds:[...o].sort()}}function zm(t){let e=t.trim();if(!e||e.startsWith("#"))return null;let r=e.indexOf("=");if(r<=0)return null;let o=e.slice(0,r).trim();if(!/^[A-Z0-9_]+$/.test(o))return null;let n=e.slice(r+1).trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1));let a=n.match(/^\$\{[A-Z0-9_]+:-([^}]+)\}$/),i=(a?a[1]:n).trim();return i?{key:o,value:i}:null}async function Ym(t){if(!await M__default.pathExists(t))return {};try{let e=await M__default.readFile(t,"utf-8"),r={};for(let o of e.split(`
|
|
117
117
|
`)){let n=zm(o);n&&(r[n.key]=n.value);}return r}catch{return {}}}async function Gp(t){let e={},r=await l$4(t.workspacePath);for(let o of r){let n=b.dirname(b.dirname(o)),a=await Ym(b.join(n,".env.example"));for(let[i,c]of Object.entries(a))Ir(t.contract,i).length>0&&(e[i]=c);}return e}function Vp(t,e){return t.filter(r=>Ir(e,r).length>0).sort()}function Jp(t){let e=t.RAPIDKIT_DB_POSTGRES_URL||t.DATABASE_URL;if(e?.startsWith("postgresql://"))try{let r=new URL(e),o=r.pathname.replace(/^\//,"");return {POSTGRES_USER:decodeURIComponent(r.username||"postgres"),POSTGRES_PASSWORD:decodeURIComponent(r.password||"postgres"),POSTGRES_DB:o||"postgres"}}catch{return}}function Kp(t){let e=t.POSTGRES_USER||"postgres",r=t.POSTGRES_DB||"postgres";return ["CMD-SHELL",`pg_isready -U ${e} -d ${r}`]}function Xm(t){return /[:#{}[\],&*!|>'"%@`]/.test(t)||t.includes(`
|
|
118
118
|
`)?JSON.stringify(t):t}function Up(t,e){return Object.entries(t).map(([r,o])=>`${e}${r}: ${Xm(o)}`).join(`
|
|
119
119
|
`)}function Qm(t,e){let r=t.test.map(o=>JSON.stringify(o)).join(", ");return [`${e}healthcheck:`,`${e} test: [${r}]`,`${e} interval: ${t.interval}`,`${e} timeout: ${t.timeout}`,`${e} retries: ${t.retries}`].join(`
|
|
120
120
|
`)}function Bp(t){let e=["# Generated by Workspai infra plan \u2014 do not edit manually.",`# Workspace: ${t.workspaceName}`,`# Generated at: ${t.plan.generatedAt}`,"name: workspai-infra"],r=new Set;if(t.plan.services.length===0)return e.push("services: {}"),e.push(""),e.join(`
|
|
121
121
|
`);e.push("services:");for(let o of t.plan.services){let n=t.contract.services[o.id];if(n){if(e.push(` ${o.id}:`),e.push(` image: ${n.image}`),e.push(` container_name: workspai-${o.id}`),n.command?.length){let a=n.command.map(i=>JSON.stringify(i)).join(", ");e.push(` command: [${a}]`);}if(n.env&&Object.keys(n.env).length>0){e.push(" environment:");let a={...n.env,...t.plan.serviceEnvOverrides?.[o.id]||{}};e.push(Up(a," "));}else t.plan.serviceEnvOverrides?.[o.id]&&(e.push(" environment:"),e.push(Up(t.plan.serviceEnvOverrides[o.id]," ")));if(n.ports.length>0){e.push(" ports:");for(let a of n.ports)e.push(` - "${a.host}:${a.container}"`);}if(n.volumes?.length){e.push(" volumes:");for(let a of n.volumes){e.push(` - ${a}`);let i=a.split(":")[0];i&&!i.startsWith("/")&&r.add(i);}}if(n.healthcheck){let a=t.plan.serviceEnvOverrides?.[o.id];if(o.id==="postgres"&&a){let i=Kp(a).map(c=>JSON.stringify(c)).join(", ");e.push(" healthcheck:"),e.push(` test: [${i}]`),e.push(` interval: ${n.healthcheck.interval}`),e.push(` timeout: ${n.healthcheck.timeout}`),e.push(` retries: ${n.healthcheck.retries}`);}else e.push(Qm(n.healthcheck," "));}e.push(" restart: unless-stopped");}}if(r.size>0){e.push("volumes:");for(let o of [...r].sort())e.push(` ${o}:`),e.push(" driver: local");}return e.push(""),e.join(`
|
|
122
|
-
`)}function eg(t,e,r){return t.kind==="override"?t.value===e:t.kind==="module"?r.moduleMappings[t.value]?.includes(e)??false:r.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function tg(t){let e=new Map,r=[];for(let o of t)for(let n of o.ports){let a=e.get(n.host);a&&a!==o.id?r.push(`Port collision on host ${n.host} between services '${a}' and '${o.id}'`):e.set(n.host,o.id);}return r}async function rg(t){let e=t$1(t,"workspace.json").find(r=>existsSync(r));if(e)try{let r=await M__default.readJson(e);return r.workspace_name||r.name}catch{return}}async function
|
|
122
|
+
`)}function eg(t,e,r){return t.kind==="override"?t.value===e:t.kind==="module"?r.moduleMappings[t.value]?.includes(e)??false:r.envVarMappings[t.value.toUpperCase()]?.includes(e)??false}function tg(t){let e=new Map,r=[];for(let o of t)for(let n of o.ports){let a=e.get(n.host);a&&a!==o.id?r.push(`Port collision on host ${n.host} between services '${a}' and '${o.id}'`):e.set(n.host,o.id);}return r}async function rg(t){let e=t$1(t,"workspace.json").find(r=>existsSync(r));if(e)try{let r=await M__default.readJson(e);return r.workspace_name||r.name}catch{return}}async function rs(t$1){let e=b.resolve(t$1.workspacePath),r=zt(),o=await Lp({workspacePath:e,contract:r}),n=o.serviceIds.map(f=>{let P=r.services[f];return P?{id:f,displayName:P.displayName,category:P.category,image:P.image,ports:P.ports,sources:o.sources.filter(y=>eg(y,f,r))}:null}).filter(f=>f!==null),a=tg(n);n.length===0&&a.push("No infrastructure services detected. Install modules with infra dependencies or add .workspai/infra/overrides.json");for(let f of o.overrides)r.services[f]||a.push(`Override references unknown service '${f}'`);let i=await g$1(e,t.workspaceContract)?t.workspaceContract:void 0,c=Dp(r,o.serviceIds),l=await Gp({workspacePath:e,contract:r}),p={...c,...l};l.RAPIDKIT_DB_POSTGRES_URL&&(p.DATABASE_URL=l.RAPIDKIT_DB_POSTGRES_URL);let m={},u=Jp(p);return u&&o.serviceIds.includes("postgres")&&(m.postgres=u),{schemaVersion:Mp,generatedAt:(t$1.now||(()=>new Date))().toISOString(),workspacePath:e,workspaceName:await rg(e),contractPath:i,strategy:"sidecar",composePath:Rr,envExamplePath:es,services:n,connectionEnv:p,serviceEnvOverrides:Object.keys(m).length>0?m:void 0,sources:{modules:o.modules,envVars:o.envVars,overrides:o.overrides},warnings:a}}async function os(t){let e=b.resolve(t.workspacePath),r=b.join(e,Rr),o=b.join(e,xr),n=b.join(e,es),a=zt();a$4(t.plan,"contracts/infra-plan.v1.json","Workspai infrastructure plan");let i=Bp({plan:t.plan,contract:a,workspaceName:t.plan.workspaceName||b.basename(e)}),c=["# Generated by: npx workspai infra plan","# Copy values into project .env files as needed.",...Object.entries(t.plan.connectionEnv).map(([l,p])=>`${l}=${p}`),""].join(`
|
|
123
123
|
`);return t.dryRun?{composePath:r,planPath:o,envExamplePath:n}:(await M__default.ensureDir(b.dirname(r)),await M__default.ensureDir(b.dirname(o)),await M__default.writeFile(r,i,"utf-8"),await M__default.writeFile(o,`${JSON.stringify(t.plan,null,2)}
|
|
124
|
-
`,"utf-8"),await M__default.writeFile(n,c,"utf-8"),{composePath:r,planPath:o,envExamplePath:n})}function og(t){return b.resolve(t).split(b.sep).join("/")}async function qp(){if((await execa("docker",["compose","version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker",prefixArgs:["compose"]};if((await execa("docker-compose",["version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker-compose",prefixArgs:[]};throw new Error("Docker Compose is not available. Install Docker Desktop or the docker-compose plugin, then verify with: docker compose version")}async function ng(){if((await execa("docker",["version"],{reject:false,timeout:5e3})).exitCode!==0)throw new Error("Docker is not available in PATH. Install Docker and ensure the daemon is running before using rapidkit infra.");await qp();}function zp(t){let e=t.toLowerCase();return e.includes("no space left on device")?"Docker failed because the disk is full. Free space with: docker system prune -f (or docker system prune -a --volumes -f).":e.includes("address already in use")||e.includes("bind")?"Docker failed to bind a host port. Stop the conflicting service or adjust ports in contracts/infra-stack.v1.json via .workspai/infra/overrides.json.":e.includes("cannot connect to the docker daemon")?"Docker daemon is not running. Start Docker Desktop or the docker service, then retry.":null}async function Yp(t){await ng();let e=await qp(),r=og(t.composePath),o=await execa(e.command,[...e.prefixArgs,"-f",r,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}function
|
|
124
|
+
`,"utf-8"),await M__default.writeFile(n,c,"utf-8"),{composePath:r,planPath:o,envExamplePath:n})}function og(t){return b.resolve(t).split(b.sep).join("/")}async function qp(){if((await execa("docker",["compose","version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker",prefixArgs:["compose"]};if((await execa("docker-compose",["version"],{reject:false,timeout:5e3})).exitCode===0)return {command:"docker-compose",prefixArgs:[]};throw new Error("Docker Compose is not available. Install Docker Desktop or the docker-compose plugin, then verify with: docker compose version")}async function ng(){if((await execa("docker",["version"],{reject:false,timeout:5e3})).exitCode!==0)throw new Error("Docker is not available in PATH. Install Docker and ensure the daemon is running before using rapidkit infra.");await qp();}function zp(t){let e=t.toLowerCase();return e.includes("no space left on device")?"Docker failed because the disk is full. Free space with: docker system prune -f (or docker system prune -a --volumes -f).":e.includes("address already in use")||e.includes("bind")?"Docker failed to bind a host port. Stop the conflicting service or adjust ports in contracts/infra-stack.v1.json via .workspai/infra/overrides.json.":e.includes("cannot connect to the docker daemon")?"Docker daemon is not running. Start Docker Desktop or the docker service, then retry.":null}async function Yp(t){await ng();let e=await qp(),r=og(t.composePath),o=await execa(e.command,[...e.prefixArgs,"-f",r,...t.args],{cwd:t.workspacePath,reject:false});return {exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}function Pn(t){let e=t?b.resolve(t):Ha(process.cwd())??b$5({startPath:process.cwd()})?.workspacePath??null;if(!e)throw new Error("Not inside a Workspai workspace. Run from workspace root or pass --workspace.");return a$9(e)}function ag(t){return b.join(t,Rr)}async function ns(t){let e=b.join(t,xr);if(!await M__default.pathExists(e))throw new Error(`Infra plan not found at ${xr}. Run: npx workspai infra plan`);let r=await M__default.readJson(e);return a$4(r,"contracts/infra-plan.v1.json",`Infra plan ${e}`),r}async function as(t){let e=ag(t.workspacePath);if(!await M__default.pathExists(e))throw new Error(`Compose file not found at ${Rr}. Run: npx workspai infra plan`);return Yp({composePath:e,workspacePath:t.workspacePath,args:t.args})}function sg(t,e={}){if(console.log(s.bold(`
|
|
125
125
|
Workspai infra plan
|
|
126
|
-
`)),console.log(s.gray(`Workspace: ${t.workspacePath}`)),t.workspaceName&&console.log(s.gray(`Name: ${t.workspaceName}`)),console.log(s.gray(`Strategy: ${t.strategy} (sidecar compose)`)),console.log(s.gray(`Compose: ${t.composePath}`)),console.log(s.gray(`Plan report: ${xr}`)),console.log(s.gray(`Env example: ${t.envExamplePath}`)),console.log(""),t.services.length===0)console.log(s.yellow("No infrastructure services detected."));else {console.log(s.bold("Services:"));for(let r of t.services){let o=r.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${r.id}`),s.gray(`(${r.displayName})`),o?s.white(`ports ${o}`):"");}}if(t.sources.modules.length>0&&(console.log(""),console.log(s.bold("Detected from modules:")),console.log(s.gray(` ${t.sources.modules.join(", ")}`))),t.sources.envVars.length>0){let r=zt(),o=Vp(t.sources.envVars,r);console.log(s.bold("Detected from env vars (infra-mapped):")),o.length>0?console.log(s.gray(` ${o.join(", ")}`)):console.log(s.gray(" none"));let n=t.sources.envVars.length-o.length;if(n>0&&!e.verbose)console.log(s.gray(` (${n} other project env vars scanned \u2014 use --verbose to list all)`));else if(e.verbose){let a=t.sources.envVars.filter(i=>!o.includes(i));a.length>0&&console.log(s.gray(` Other scanned env vars: ${a.join(", ")}`));}}if(t.sources.overrides.length>0&&(console.log(s.bold("Overrides:")),console.log(s.gray(` ${t.sources.overrides.join(", ")}`))),Object.keys(t.connectionEnv).length>0){console.log(""),console.log(s.bold("Connection env (preview):"));for(let[r,o]of Object.entries(t.connectionEnv))console.log(s.gray(` ${r}=${o}`));}if(t.warnings.length>0){console.log(""),console.log(s.yellow("Warnings:"));for(let r of t.warnings)console.log(s.yellow(` - ${r}`));}console.log("");}function Xp(t){let e=t.command("infra").description("Plan and manage workspace infrastructure (Docker sidecar stack)");e.command("plan").description("Discover infra needs and generate compose plan artifacts").option("--workspace <path>","Workspace root path").option("--json","Print plan as JSON").option("--dry-run","Compute plan without writing artifacts").option("--verbose","Show all scanned project env vars").action(async r=>{try{let o=
|
|
126
|
+
`)),console.log(s.gray(`Workspace: ${t.workspacePath}`)),t.workspaceName&&console.log(s.gray(`Name: ${t.workspaceName}`)),console.log(s.gray(`Strategy: ${t.strategy} (sidecar compose)`)),console.log(s.gray(`Compose: ${t.composePath}`)),console.log(s.gray(`Plan report: ${xr}`)),console.log(s.gray(`Env example: ${t.envExamplePath}`)),console.log(""),t.services.length===0)console.log(s.yellow("No infrastructure services detected."));else {console.log(s.bold("Services:"));for(let r of t.services){let o=r.ports.map(n=>`${n.host}:${n.container}`).join(", ");console.log(s.cyan(` ${r.id}`),s.gray(`(${r.displayName})`),o?s.white(`ports ${o}`):"");}}if(t.sources.modules.length>0&&(console.log(""),console.log(s.bold("Detected from modules:")),console.log(s.gray(` ${t.sources.modules.join(", ")}`))),t.sources.envVars.length>0){let r=zt(),o=Vp(t.sources.envVars,r);console.log(s.bold("Detected from env vars (infra-mapped):")),o.length>0?console.log(s.gray(` ${o.join(", ")}`)):console.log(s.gray(" none"));let n=t.sources.envVars.length-o.length;if(n>0&&!e.verbose)console.log(s.gray(` (${n} other project env vars scanned \u2014 use --verbose to list all)`));else if(e.verbose){let a=t.sources.envVars.filter(i=>!o.includes(i));a.length>0&&console.log(s.gray(` Other scanned env vars: ${a.join(", ")}`));}}if(t.sources.overrides.length>0&&(console.log(s.bold("Overrides:")),console.log(s.gray(` ${t.sources.overrides.join(", ")}`))),Object.keys(t.connectionEnv).length>0){console.log(""),console.log(s.bold("Connection env (preview):"));for(let[r,o]of Object.entries(t.connectionEnv))console.log(s.gray(` ${r}=${o}`));}if(t.warnings.length>0){console.log(""),console.log(s.yellow("Warnings:"));for(let r of t.warnings)console.log(s.yellow(` - ${r}`));}console.log("");}function Xp(t){let e=t.command("infra").description("Plan and manage workspace infrastructure (Docker sidecar stack)");e.command("plan").description("Discover infra needs and generate compose plan artifacts").option("--workspace <path>","Workspace root path").option("--json","Print plan as JSON").option("--dry-run","Compute plan without writing artifacts").option("--verbose","Show all scanned project env vars").action(async r=>{try{let o=Pn(r.workspace),n=await rs({workspacePath:o}),a=await os({workspacePath:o,plan:n,dryRun:r.dryRun});if(r.json){console.log(JSON.stringify({...n,artifacts:r.dryRun?{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath,dryRun:true}:{composePath:a.composePath,planPath:a.planPath,envExamplePath:a.envExamplePath}},null,2));return}sg(n,{verbose:r.verbose}),r.dryRun?console.log(s.yellow(`Dry run \u2014 no files written.
|
|
127
127
|
`)):(console.log(s.green("Artifacts written:")),console.log(s.gray(` ${a.composePath}`)),console.log(s.gray(` ${a.planPath}`)),console.log(s.gray(` ${a.envExamplePath}
|
|
128
128
|
`)));}catch(o){console.error(s.red(`
|
|
129
129
|
\u274C ${o instanceof Error?o.message:String(o)}
|
|
130
|
-
`)),process.exit(1);}}),e.command("up").description("Start planned infrastructure services via Docker Compose").option("--workspace <path>","Workspace root path").option("--detach","Run containers in background",true).option("--build","Build images before starting").option("--no-plan","Skip refreshing plan artifacts before starting").action(async r=>{try{let o=
|
|
130
|
+
`)),process.exit(1);}}),e.command("up").description("Start planned infrastructure services via Docker Compose").option("--workspace <path>","Workspace root path").option("--detach","Run containers in background",true).option("--build","Build images before starting").option("--no-plan","Skip refreshing plan artifacts before starting").action(async r=>{try{let o=Pn(r.workspace);if(r.plan!==false){let c=await rs({workspacePath:o});await os({workspacePath:o,plan:c});}if((await ns(o)).services.length===0)throw new Error("Infra plan has no services. Run: npx workspai infra plan (from a workspace with .env.example, core modules, or .workspai/infra/overrides.json)");let a=["up"];r.detach!==false&&a.push("-d"),r.build&&a.push("--build");let i=await as({workspacePath:o,args:a});if(i.stdout&&process.stdout.write(i.stdout),i.stderr&&process.stderr.write(i.stderr),i.exitCode!==0){let c=zp(i.stderr);c&&console.error(s.yellow(`
|
|
131
131
|
\u26A0\uFE0F ${c}
|
|
132
132
|
`)),process.exit(i.exitCode);}r.detach!==false&&(console.log(s.green(`
|
|
133
133
|
\u2705 Infrastructure stack started.
|
|
134
134
|
`)),console.log(s.gray(`Check status: npx workspai infra status
|
|
135
135
|
`)));}catch(o){console.error(s.red(`
|
|
136
136
|
\u274C ${o instanceof Error?o.message:String(o)}
|
|
137
|
-
`)),process.exit(1);}}),e.command("down").description("Stop planned infrastructure services").option("--workspace <path>","Workspace root path").option("--volumes","Remove named volumes").action(async r=>{try{let o=
|
|
137
|
+
`)),process.exit(1);}}),e.command("down").description("Stop planned infrastructure services").option("--workspace <path>","Workspace root path").option("--volumes","Remove named volumes").action(async r=>{try{let o=Pn(r.workspace);await ns(o);let n=["down"];r.volumes&&n.push("-v");let a=await as({workspacePath:o,args:n});a.stdout&&process.stdout.write(a.stdout),a.stderr&&process.stderr.write(a.stderr),a.exitCode!==0&&process.exit(a.exitCode),console.log(s.green(`
|
|
138
138
|
\u2705 Infrastructure stack stopped.
|
|
139
139
|
`));}catch(o){console.error(s.red(`
|
|
140
140
|
\u274C ${o instanceof Error?o.message:String(o)}
|
|
141
|
-
`)),process.exit(1);}}),e.command("status").description("Show Docker Compose status for planned infrastructure").option("--workspace <path>","Workspace root path").option("--json","Print docker compose ps JSON output").option("--strict","Exit non-zero when any container is not healthy/running").action(async r=>{try{let o=
|
|
141
|
+
`)),process.exit(1);}}),e.command("status").description("Show Docker Compose status for planned infrastructure").option("--workspace <path>","Workspace root path").option("--json","Print docker compose ps JSON output").option("--strict","Exit non-zero when any container is not healthy/running").action(async r=>{try{let o=Pn(r.workspace),n=await ns(o),a=r.json?["ps","--format","json"]:["ps"],i=await as({workspacePath:o,args:a});if(r.json){i.stdout&&process.stdout.write(i.stdout),i.exitCode!==0&&process.exit(i.exitCode);return}console.log(s.bold(`
|
|
142
142
|
Workspai infra status
|
|
143
143
|
`)),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Planned services: ${n.services.map(c=>c.id).join(", ")||"none"}`)),console.log(""),i.stdout.trim()?process.stdout.write(i.stdout):(console.log(s.yellow("No running containers found for the infra stack.")),console.log(s.gray(`Start with: npx workspai infra up
|
|
144
144
|
`))),i.exitCode!==0&&(i.stderr&&process.stderr.write(i.stderr),process.exit(i.exitCode)),r.strict&&/Restarting|Exit|unhealthy/i.test(i.stdout)&&(console.log(""),console.log(s.red("One or more infra containers are not healthy.")),console.log(s.gray(`Inspect logs with: docker logs workspai-postgres (or redis/mailpit)
|
|
145
145
|
`)),process.exit(1));}catch(o){console.error(s.red(`
|
|
146
146
|
\u274C ${o instanceof Error?o.message:String(o)}
|
|
147
|
-
`)),process.exit(1);}});}function ig(t){return t.strict&&t.state==="blocked"?2:void 0}function ot(t){let e=b$5({startPath:process.cwd(),explicitWorkspacePath:t.workspace,strict:true,requireProjectMembership:!t.workspace});if(!e)throw new Error("No canonical Workspai workspace could be resolved.");return b.resolve(e.workspacePath)}async function ss(t){let e=b.resolve(process.cwd(),t);if(!await M__default.pathExists(e))throw new Error(`JSON input does not exist: ${t}`);return M__default.readJson(e)}function cg(t,e){if(e){console.log(JSON.stringify(t,null,2));return}let r=t.capsule.status==="sealed",o=t.capsule.status==="blocked",n=r?s.green("\u2713"):o?s.red("\u25A0"):s.cyan("\u25C6");console.log(`${n} Proof-Carrying Change \xB7 ${t.capsule.status}`),console.log(s.bold(` ${t.changeId}`)),console.log(s.gray(` State: ${t.state}`)),console.log(s.gray(` Assurance: ${t.capsule.assurances.filter(a=>a.status==="passed").length}/${t.capsule.assurances.length} passed`)),t.capsule.remainingUncertainty.length>0&&console.log(s.yellow(` Uncertainty: ${t.capsule.remainingUncertainty.join(" ")}`)),console.log(s.gray(` Capsule: ${t.artifacts.capsule}`));for(let a of t.nextActions)console.log(s.gray(` Next: ${a}`));}async function jt(t,e,r){try{let o=await e();cg(o,t.json);let n=r?.(o);n!==void 0&&(process.exitCode=n);}catch(o){let n=o instanceof Error?o.message:String(o);t.json?console.log(JSON.stringify({schemaVersion:"workspai.change-error.v1",status:"error",message:n},null,2)):console.error(s.red(`Proof-Carrying Change failed: ${n}`)),process.exitCode=1;}}var lg=new Set(["filesystem","command","configuration","dependency","external"]);function pg(t){let e=[...new Set(t.split(",").map(r=>r.trim()).filter(Boolean))];for(let r of e)if(!lg.has(r))throw new Error(`Unsupported effect class: ${r}`);return e}function nt(t){return t.option("--workspace <path>","Explicit canonical workspace path").option("--json","Emit a versioned machine-readable result")}function ed(t){let e=t.command("change").description("Create and verify tamper-evident, architecture-aware change capsules");nt(e.command("begin").description("Pin an active Goal and architecture baseline")).option("--goal <goal-id>","Require this Goal Pack to be the active Goal").action(async a=>{await jt(a,()=>c$8({workspacePath:ot(a),goalId:a.goal}));}),nt(e.command("list").description("List discoverable change capsules and integrity")).action(async a=>{try{let i=await m({workspacePath:ot(a)});if(a.json){console.log(JSON.stringify(i,null,2));return}console.log(s.bold(`Proof-Carrying Changes \xB7 ${i.summary.total}`)),i.changes.length===0&&console.log(s.gray(" No changes recorded."));for(let c of i.changes){let l=c.valid?c.status==="sealed"?s.green("\u2713"):s.cyan("\u25C6"):s.red("\u25A0");console.log(`${l} ${c.changeId} \xB7 ${c.status} \xB7 ${c.assurance.passed}/${c.assurance.total}`);}}catch(i){let c=i instanceof Error?i.message:String(i);a.json?console.log(JSON.stringify({status:"error",message:c},null,2)):console.error(s.red(c)),process.exitCode=1;}}),nt(e.command("predict").description("Attach a noncanonical architecture prediction")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--file <prediction.json>","Typed predicted architecture change JSON").action(async a=>{await jt(a,async()=>d$9({workspacePath:ot(a),changeId:a.change,prediction:q$2(await ss(a.file))}));}),nt(e.command("authorize").description("Grant bounded effect capabilities")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--effects <classes>","Comma-separated filesystem,command,configuration,dependency,external classes").option("--granted-by <identity>","Human or policy identity granting authorization","operator").action(async a=>{await jt(a,()=>f$2({workspacePath:ot(a),changeId:a.change,effectClasses:pg(a.effects),grantedBy:a.grantedBy}));}),nt(e.command("resume").description("Resume a blocked transaction with human intent")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--to <state>","Resume target: authorized, executing, or verifying").requiredOption("--reason <text>","Durable reason for resuming").option("--actor <identity>","Human identity resuming the change","operator").action(async a=>{await jt(a,()=>{if(!["authorized","executing","verifying"].includes(a.to))throw new Error("--to must be authorized, executing, or verifying.");return g$b({workspacePath:ot(a),changeId:a.change,resumeTo:a.to,reason:a.reason,actorId:a.actor})});});let r=e.command("effect").description("Record typed observed effects");nt(r.command("record").description("Append an idempotent effect receipt")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--file <receipt.json>","Typed effect receipt JSON").action(async a=>{await jt(a,async()=>h$6({workspacePath:ot(a),changeId:a.change,receipt:r$3(await ss(a.file))}));});let o$1=e.command("verification").description("Record independent Goal-criterion verification");nt(o$1.command("record").description("Append an exact-generation verification receipt")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--file <receipt.json>","Typed verification receipt JSON").action(async a=>{await jt(a,async()=>i$5({workspacePath:ot(a),changeId:a.change,receipt:s$4(await ss(a.file))}));}),nt(e.command("status").description("Inspect the derived transaction and assurance state")).requiredOption("--change <change-id>","Proof-carrying change id").action(async a=>{await jt(a,()=>l$7({workspacePath:ot(a),changeId:a.change,operation:"status"}));}),nt(e.command("explain").description("Explain proof, uncertainty, and next actions")).requiredOption("--change <change-id>","Proof-carrying change id").action(async a=>{await jt(a,()=>l$7({workspacePath:ot(a),changeId:a.change,operation:"explain"}));}),nt(e.command("verify").description("Re-observe architecture and verify exact effects")).requiredOption("--change <change-id>","Proof-carrying change id").option("--strict","Treat advisory Workspace Verify findings as blockers").option("--no-refresh","Use current canonical intelligence without refreshing it").action(async a=>{await jt(a,()=>k$6({workspacePath:ot(a),changeId:a.change,strict:a.strict,refresh:a.refresh}),i=>ig({strict:a.strict===true,state:i.state}));}),nt(e.command("abort").description("Terminate an open change without deleting evidence")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--reason <text>","Durable reason for aborting the change").option("--actor <identity>","Human identity aborting the change","operator").action(async a=>{await jt(a,()=>n$2({workspacePath:ot(a),changeId:a.change,reason:a.reason,actorId:a.actor}));});let n=e.command("capsule").description("Validate or export a change capsule");nt(n.command("validate").description("Validate capsule and referenced local evidence")).requiredOption("--change <change-id>","Proof-carrying change id").action(async a=>{try{let i=await o({workspacePath:ot(a),changeId:a.change});a.json?console.log(JSON.stringify(i,null,2)):console.log(i.valid?s.green(`\u2713 Capsule ${a.change} is valid.`):s.red(`\u25A0 Capsule ${a.change} is invalid: ${i.errors.join("; ")}`)),i.valid||(process.exitCode=1);}catch(i){let c=i instanceof Error?i.message:String(i);a.json?console.log(JSON.stringify({valid:false,errors:[c]},null,2)):console.error(s.red(c)),process.exitCode=1;}}),nt(n.command("export").description("Export a validated portable capsule manifest")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--output <path>","Workspace-contained export path").action(async a=>{try{let i=await p$1({workspacePath:ot(a),changeId:a.change,outputPath:a.output});a.json?console.log(JSON.stringify(i,null,2)):console.log(s.green(`\u2713 Capsule exported: ${i.outputPath}`));}catch(i){let c=i instanceof Error?i.message:String(i);a.json?console.log(JSON.stringify({status:"error",message:c},null,2)):console.error(s.red(c)),process.exitCode=1;}});}var td=["python","dotnet","node"];function uo(t){return t.trim().toLowerCase().replace(/[^a-z0-9.-]+/g,"-")}function dg(t,e){let r=uo(e);return t.implementation.runtimes.some(o=>uo(o)===r)}function ug(t,e){let r=uo(e);return r===uo(t.framework.id)||r===uo(t.adapter.id)}function bn(t){let e=t.trim().toLowerCase();if(!td.includes(e))throw new Error(`Unsupported agent framework runtime: ${t}. Choose python, dotnet, or node.`);return e}function mo(t){return t.list().flatMap(e=>{let r=t.resolveAdapter(e.manifest.adapter.id).status;return e.manifest.implementation.runtimes.map(o=>({adapterId:e.manifest.adapter.id,frameworkId:e.manifest.framework.id,frameworkName:e.manifest.framework.name,runtime:o,status:r}))})}function Pn(t){return mo(t).map(e=>`${e.frameworkId} + ${e.runtime} (${e.adapterId}, ${e.status})`).join("; ")}function is(t){let e=t.framework?.trim(),r=t.registry.list().filter(l=>dg(l.manifest,t.runtime)).filter(l=>!e||ug(l.manifest,e));if(r.length===0)throw new Error(e?`No agent framework adapter matches framework ${e} and runtime ${t.runtime}. Available combinations: ${Pn(t.registry)||"none"}.`:`No agent framework adapter matches runtime ${t.runtime}. Available combinations: ${Pn(t.registry)||"none"}.`);let o=new Set(G$1().map(l=>l.adapterId)),n=r.filter(l=>o.has(l.manifest.adapter.id)),a=r.filter(l=>t.registry.resolveAdapter(l.manifest.adapter.id).status==="admitted");if(!e&&n.length>1)throw new Error(`Runtime ${t.runtime} matches multiple published frameworks (${n.map(l=>l.manifest.framework.id).join(", ")}). Pass --framework explicitly; Workspai does not guess.`);let i=n[0]??a[0]??r[0];if(!i)throw new Error(`No agent framework adapter matches runtime ${t.runtime}. Available combinations: ${Pn(t.registry)||"none"}.`);if(!e&&n.length===0&&r.length>1)throw new Error(`Runtime ${t.runtime} matches multiple registered frameworks and none are published create kits. Pass --framework explicitly. Available combinations: ${Pn(t.registry)}.`);let c=t.registry.resolveAdapter(i.manifest.adapter.id);return {adapterId:i.manifest.adapter.id,frameworkId:i.manifest.framework.id,frameworkName:i.manifest.framework.name,runtime:t.runtime,admitted:c.status==="admitted",blockers:c.blockers}}var cs="agent-framework-change-plan",wg=[".workspai/project.json","package.json","pyproject.toml","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts"];async function yg(t$1){let e=[],r=new Set,o=(i,c)=>{r.has(i)||(r.add(i),e.push({operation:"change",targetKind:"artifact",targetId:i,rationale:c,confidence:"high"}));},n=(i,c)=>{o(nd(t$1.target.artifactPrefix,i),c);};for(let i of t$1.plan.files)n(i.path,`${i.overwrite} under the admitted agent-framework plan.`);n(".workspai/project.json","Create and attach refresh the governed project lens after nested runtime files exist."),o(t.workspaceContract,"Agent required environment is recorded on the workspace contract during Graph refresh.");for(let i of wg)await M__default.pathExists(b.join(t$1.target.projectRoot,i))&&n(i,"Nested runtime attach re-observes the existing project-root manifest during Graph refresh.");let a=await M__default.readdir(t$1.target.projectRoot).catch(()=>[]);for(let i of a)/\.(?:cs|fs|vb)proj$/i.test(i)&&n(i,"Nested runtime attach re-observes the existing .NET project manifest during Graph refresh.");return e}var kg="workspai.agent-framework-managed-file.v1",rd=1024*1024;function Yt(t){return t.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/$/,"")}function nd(t,e){let r=Yt(t);return r==="."||r===""?Yt(e):`${r}/${Yt(e)}`}function ls(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,48)||"project",r=createHash("sha256").update(t).digest("hex").slice(0,12);return `${e}-${r}`}function ds(t){return createHash("sha256").update(`${JSON.stringify(t.manifest)}
|
|
148
|
-
`).digest("hex")}function ad(t){let e=t.registry.resolveAdapter(t.adapterId);if(e.status!=="admitted"||!e.entry){let o=e.blockers.length>0?` ${e.blockers.join(" ")}`:"";throw new Error(`Agent framework adapter is not admitted: ${t.adapterId}.${o}`)}let r=E$1.find(o=>o.manifest.adapter.id===e.entry?.manifest.adapter.id);if(!r||ds(r)!==e.entry.manifestSha256)throw new Error(`Admitted adapter implementation does not match its registry manifest: ${t.adapterId}`);return r}function vg(t){return `.workspai/agent-frameworks/ownership/${ls(t.adapterId)}/${ls(t.projectName)}/${D$1(t.instanceName)}.json`}async function sd(t,e){let r=b.resolve(t),o=await b$p(r,m$7);if(!o)throw new Error("Workspace Model is missing; run Workspace Intelligence before planning an agent framework change.");let n=await M__default.readJson(o),a=n.projects.filter(p=>p.name===e||Yt(p.path)===Yt(e));if(a.length!==1)throw new Error(a.length===0?`Project is not present in the canonical Workspace Model: ${e}`:`Project target is ambiguous in the canonical Workspace Model: ${e}`);let i=a[0],c=k$5(r,i);if(!(await M__default.stat(c).catch(()=>null))?.isDirectory())throw new Error(`Canonical project root is unavailable: ${i.name}`);return {workspacePath:r,workspaceName:n.workspace.name,projectName:i.name,projectRoot:c,artifactPrefix:c===r?".":a$g({workspacePath:r,projectPath:c,projectName:i.name}).contractRelativePath}}async function ps(t,e){let r=b.resolve(t),o=b.resolve(r,e),n=b.relative(r,o);if(!n||n===".."||n.startsWith(`..${b.sep}`)||b.isAbsolute(n))throw new Error(`Managed path escapes the canonical project root: ${e}`);let a=await M__default.realpath(r),i=o;for(;!await M__default.pathExists(i);){let p=b.dirname(i);if(p===i)throw new Error(`Cannot resolve managed path: ${e}`);i=p;}let c=await M__default.realpath(i),l=b.relative(a,c);if(l===".."||l.startsWith(`..${b.sep}`)||b.isAbsolute(l))throw new Error(`Managed path resolves through a symlink outside the project root: ${e}`);if(await M__default.pathExists(o)){let p=await M__default.lstat(o);if(!p.isFile()||p.isSymbolicLink())throw new Error(`Managed target is not a regular file: ${e}`)}return o}async function Pg(t,e,r){let o=e.render({projectRoot:t.projectRoot,instanceName:r}).files,n=new Map;for(let a of o){let i=await ps(t.projectRoot,a.path),c=await M__default.stat(i).catch(()=>null);if(c){if(c.size>rd)throw new Error(`Managed file exceeds the ${rd} byte safety limit: ${a.path}`);n.set(a.path,await M__default.readFile(i,"utf8"));}}return n}async function bg(t){let e=vg({adapterId:t.adapter.manifest.adapter.id,projectName:t.target.projectName,instanceName:t.instanceName}),r=await b$p(t.target.workspacePath,e);if(!r)return {path:e,ledger:new Map};let o=await M__default.readJson(r);if(a$4(o,C$1,"Agent framework ownership receipt"),o.schemaVersion!==z||o.adapter?.id!==t.adapter.manifest.adapter.id||o.adapter.version!==t.adapter.manifest.adapter.version||o.adapter.manifestSha256!==ds(t.adapter)||o.framework?.id!==t.adapter.manifest.framework.id||!t.adapter.manifest.framework.testedVersions.includes(o.framework.version)||o.target?.workspace!==t.target.workspaceName||o.target?.project!==t.target.projectName||Yt(o.target.artifactPrefix)!==t.target.artifactPrefix||o.target.instanceName!==D$1(t.instanceName)||!Array.isArray(o.files))throw new Error(`Agent framework ownership receipt is incompatible or corrupt: ${e}`);let n=new Map;for(let a of o.files){if(!a||typeof a.path!="string"||!/^[a-f0-9]{64}$/.test(a.sha256))throw new Error(`Agent framework ownership receipt contains an invalid file entry: ${e}`);if(n.has(a.path))throw new Error(`Agent framework ownership receipt contains duplicate paths: ${e}`);n.set(a.path,a.sha256);}return {path:e,ledger:n}}async function id(t){let[e,r]=await Promise.all([Pg(t.target,t.adapter,t.instanceName),bg(t)]);return {input:{projectRoot:t.target.projectRoot,instanceName:t.instanceName,target:{project:t.target.projectName,artifactPrefix:t.target.artifactPrefix},existingFiles:e,ownershipLedger:r.ledger},receiptPath:r.path}}async function cd(t){let e=ad(t),r=await sd(t.workspacePath,t.project),o=await id({target:r,adapter:e,instanceName:t.instanceName}),n=e.plan(t.mode,o.input);a$4(n,B,"Agent framework change plan");let a=c$h(n);if(n.status!=="planned")return {status:n.status,changeId:t.changeId,project:r.projectName,plan:n,planArtifact:null,planDigest:a};await d$9({workspacePath:r.workspacePath,changeId:t.changeId,actorKind:"cli",actorId:"workspai-agent-framework",prediction:{schemaVersion:i$2,changeId:t.changeId,goalId:"",generatedAt:new Date().toISOString(),baselineGeneration:"",nonCanonical:true,proofEligible:false,operations:await yg({target:r,plan:n}),assumptions:["Only hash-bound Workspai-managed files in the admitted ownership roots will change.","The project lens metadata at .workspai/project.json is rewritten after the nested runtime is applied.","Existing project-root manifests are re-observed when the nested runtime makes the project polyglot."],predictedRisk:n.files.length>0?"low":"none"}});let i=await e$d({workspacePath:r.workspacePath,changeId:t.changeId,role:cs,schemaVersion:y,contractPath:B,payload:n,actorId:"workspai-agent-framework"});return {status:"planned",changeId:t.changeId,project:r.projectName,plan:n,planArtifact:i.artifact,planDigest:i.digest}}async function jg(t,e){let o=(await a$R(t,e)).transaction.plans.filter(c=>c.role===cs);if(o.length!==1)throw new Error(`PCC transaction must contain exactly one ${cs} reference.`);let n=o[0],a=await b$p(t,n.artifact);if(!a)throw new Error(`Attached agent framework plan is missing: ${n.artifact}`);let i=await M__default.readJson(a);if(a$4(i,B,"Attached agent framework change plan"),c$h(i)!==n.digest.value)throw new Error("Attached agent framework plan digest does not match the PCC event chain.");return i}function Cg(t){let{transaction:e}=t;if(e.state!=="authorized"&&e.state!=="executing")throw new Error(`Agent framework apply requires an authorized PCC transaction; observed ${e.state}.`);if(!e.authorization?.effectClasses.includes("filesystem"))throw new Error("Agent framework apply requires an explicit filesystem effect grant.");if(!e.scope?.projects.includes(t.projectName))throw new Error(`Project ${t.projectName} is outside the immutable PCC scope.`)}function Eg(t,e){return {role:"agent-framework-managed-file",artifact:t,schemaVersion:kg,digest:{algorithm:"sha256",semantics:"raw-bytes-v1",value:e}}}async function Sg(t,e){await M__default.ensureDir(b.dirname(t));let r=`${t}.${process.pid}.${randomUUID()}.workspai-tmp`;try{await M__default.writeFile(r,e,{encoding:"utf8",flag:"wx"});try{await M__default.rename(r,t);}catch(o){let n=o.code;if(n!=="EEXIST"&&n!=="EPERM")throw o;await M__default.move(r,t,{overwrite:true});}}finally{await M__default.remove(r).catch(()=>{});}}async function us(t){let e=ad(t),r=await sd(t.workspacePath,t.project),o=b.join(r.workspacePath,".workspai","locks","agent-framework",ls(`${r.projectName}:${e.manifest.adapter.id}`));return a$Q(o,async()=>{let[n,a]=await Promise.all([a$R(r.workspacePath,t.changeId),jg(r.workspacePath,t.changeId)]);if(Cg({transaction:n.transaction,projectName:r.projectName}),a.status!=="planned"||a.adapterId!==e.manifest.adapter.id||a.adapterVersion!==e.manifest.adapter.version)throw new Error("Attached plan is not executable by the selected adapter version.");if(a.target.project!==r.projectName||Yt(a.target.artifactPrefix)!==r.artifactPrefix)throw new Error("Attached plan target does not match the canonical Workspace Model project.");let i=await id({target:r,adapter:e,instanceName:a.instanceName}),c=e.plan(a.mode,i.input);if(c$h(c)!==c$h(a))throw new Error("Agent framework plan is stale; project files or ownership evidence changed after authorization.");let l=e.render(i.input);if(l.conflicts.length>0)throw new Error("Adapter render became blocked after authorization.");let p=new Map(a.files.map(y=>[y.path,y]));if(l.files.length!==p.size||l.files.some(y=>{let E=p.get(y.path);return !E||E.sha256!==y.sha256||E.overwrite!==y.overwrite}))throw new Error("Rendered files do not match the hash-bound PCC plan.");let m=new Map,u=[],f=await b$p(r.workspacePath,i.receiptPath),P=f?await M__default.readFile(f):null;try{for(let S of l.files){let d=await ps(r.projectRoot,S.path);m.set(S.path,await M__default.pathExists(d)?await M__default.readFile(d):null),await Sg(d,S.content),u.push({path:S.path,artifact:nd(r.artifactPrefix,S.path),sha256:S.sha256});}let y=e.render({projectRoot:r.projectRoot,instanceName:a.instanceName,target:a.target}).files,E={schemaVersion:z,generatedAt:new Date().toISOString(),changeId:t.changeId,adapter:{id:e.manifest.adapter.id,version:e.manifest.adapter.version,manifestSha256:ds(e)},framework:{id:e.manifest.framework.id,version:a.frameworkVersion},target:{workspace:r.workspaceName,project:r.projectName,artifactPrefix:r.artifactPrefix,instanceName:a.instanceName},files:y.map(S=>({path:S.path,sha256:S.sha256}))};a$4(E,C$1,"Agent framework ownership receipt"),await h$5(r.workspacePath,i.receiptPath,E);let A={role:"agent-framework-ownership-receipt",artifact:i.receiptPath,schemaVersion:z,digest:{algorithm:"sha256",semantics:"canonical-json-v1",value:c$h(E)}};return await h$6({workspacePath:r.workspacePath,changeId:t.changeId,actorKind:"cli",actorId:"workspai-agent-framework",receipt:{id:`agent-framework-${t.changeId}`,effectClass:"filesystem",status:"succeeded",summary:`Applied ${e.manifest.framework.name} instance ${a.instanceName}.`,artifacts:[...u.map(S=>Eg(S.artifact,S.sha256)),A],observedAt:E.generatedAt,idempotencyKey:`agent-framework:${t.changeId}:${c$h(a)}`}}),{status:"applied",changeId:t.changeId,project:r.projectName,adapterId:e.manifest.adapter.id,instanceName:a.instanceName,files:u,ownershipReceipt:i.receiptPath}}catch(y){for(let[E,A]of [...m].reverse()){let S=await ps(r.projectRoot,E);A===null?await M__default.remove(S):await M__default.outputFile(S,A);}if(P===null){let E=await b$p(r.workspacePath,i.receiptPath);E&&await M__default.remove(E);}else await M__default.outputFile(b.join(r.workspacePath,i.receiptPath),P);throw y}},{purpose:`agent-framework:${r.projectName}:${e.manifest.adapter.id}`,timeoutMs:3e4,staleMs:6e4})}function ld(){return F({},{trustReviewedReleaseAdmissions:true})}function pd(t){let e=ld(),r=is({registry:e,runtime:t.runtime,framework:t.framework});if(!r.admitted)throw new Error(`Agent framework adapter ${r.adapterId} is not release-admitted. ${r.blockers.join(" ")}`.trim());return {registry:e,selection:r}}function Ag(t){return `workspai agent framework apply --project ${JSON.stringify(t.project)} --framework ${t.frameworkId} --runtime ${t.runtime} --change ${t.changeId}`}async function go(t){let{registry:e,selection:r}=pd(t),o=D$1(t.instanceName),n=t.goalId,a=!n;if(!n){let c=t.intent?.trim()||`Attach a governed ${r.frameworkName} ${t.runtime} agent named ${o} to ${t.project}`,l=await a$l({startPath:t.workspacePath,workspacePath:t.workspacePath,intent:c,scope:`project:${t.project}`,consumer:"generic"});if(l.result!=="planned"||l.goalPack.state!=="ready-to-plan")throw new Error(`The attachment Goal is not ready (${l.goalPack.state}). Resolve its bounded evidence or pass an existing ready Goal with --goal.`);n=l.goalPack.id;}let i=await c$8({workspacePath:t.workspacePath,goalId:n,actorKind:"cli",actorId:"workspai-agent-framework"});try{let c=await cd({workspacePath:t.workspacePath,project:t.project,changeId:i.changeId,registry:e,adapterId:r.adapterId,instanceName:o,mode:t.mode??"attach"});return c.status!=="planned"&&(await n$2({workspacePath:t.workspacePath,changeId:i.changeId,reason:`Agent framework planning completed as ${c.status}; no mutation is authorized.`,actorId:"workspai-agent-framework"}),a&&await m$3({workspacePath:t.workspacePath,goalId:n,action:"cancel"})),{schemaVersion:"workspai.agent-framework-attachment.v1",operation:"plan",mode:t.mode??"attach",status:c.status,workspacePath:t.workspacePath,project:c.project,runtime:t.runtime,frameworkId:r.frameworkId,adapterId:r.adapterId,frameworkVersion:c.plan.frameworkVersion,instanceName:c.plan.instanceName,goalId:n,changeId:c.changeId,planArtifact:c.planArtifact,files:c.plan.files,requiredEnvironment:c.plan.requiredEnvironment,permissions:c.plan.permissions,blockers:c.plan.blockers,nextActions:c.status==="planned"?[Ag({project:c.project,runtime:t.runtime,frameworkId:r.frameworkId,changeId:c.changeId})]:[]}}catch(c){throw await n$2({workspacePath:t.workspacePath,changeId:i.changeId,reason:`Agent framework planning failed: ${c instanceof Error?c.message:String(c)}`,actorId:"workspai-agent-framework"}).catch(()=>{}),a&&n&&await m$3({workspacePath:t.workspacePath,goalId:n,action:"cancel"}).catch(()=>{}),c}}async function jn(t){if(t.prepared.status!=="planned")throw new Error("Only a planned agent framework attachment can be applied.");let e=t.grantedBy.trim();if(!e)throw new Error("The authorization identity cannot be empty.");let r=ld();await f$2({workspacePath:t.prepared.workspacePath,changeId:t.prepared.changeId,effectClasses:["filesystem"],grantedBy:e,actorKind:"human"});let o;try{o=await us({workspacePath:t.prepared.workspacePath,project:t.prepared.project,changeId:t.prepared.changeId,registry:r,adapterId:t.prepared.adapterId});}catch(n){throw await n$2({workspacePath:t.prepared.workspacePath,changeId:t.prepared.changeId,reason:`Agent framework apply failed: ${n instanceof Error?n.message:String(n)}`,actorId:"workspai-agent-framework"}).catch(()=>{}),n}return {...t.prepared,operation:t.prepared.mode,status:"applied",files:o.files.map(n=>({path:n.path,sha256:n.sha256,overwrite:"applied"})),ownershipReceipt:o.ownershipReceipt,nextActions:[`workspai workspace run init --workspace ${JSON.stringify(t.prepared.workspacePath)} --scope ${JSON.stringify(t.prepared.project)} --json`,`workspai workspace run test --workspace ${JSON.stringify(t.prepared.workspacePath)} --scope ${JSON.stringify(t.prepared.project)} --json`,`workspai workspace run build --workspace ${JSON.stringify(t.prepared.workspacePath)} --scope ${JSON.stringify(t.prepared.project)} --json`,`workspai change verify --workspace ${JSON.stringify(t.prepared.workspacePath)} --change ${t.prepared.changeId} --json`]}}async function dd(t){let{registry:e,selection:r}=pd(t),o=await us({workspacePath:t.workspacePath,project:t.project,changeId:t.changeId,registry:e,adapterId:r.adapterId});return {schemaVersion:"workspai.agent-framework-attachment.v1",operation:"apply",status:"applied",project:o.project,runtime:t.runtime,frameworkId:r.frameworkId,adapterId:r.adapterId,changeId:o.changeId,files:o.files,ownershipReceipt:o.ownershipReceipt,nextActions:[`workspai workspace run init --workspace ${JSON.stringify(t.workspacePath)} --scope ${JSON.stringify(o.project)} --json`,`workspai workspace run test --workspace ${JSON.stringify(t.workspacePath)} --scope ${JSON.stringify(o.project)} --json`,`workspai workspace run build --workspace ${JSON.stringify(t.workspacePath)} --scope ${JSON.stringify(o.project)} --json`,`workspai change verify --workspace ${JSON.stringify(t.workspacePath)} --change ${t.changeId} --json`]}}function ms(t){let e=b$5({startPath:process.cwd(),explicitWorkspacePath:t.workspace,strict:true,requireProjectMembership:!t.workspace});if(!e)throw new Error("No canonical Workspai workspace could be resolved.");return b.resolve(e.workspacePath)}async function ud(t,e,r){let o=await a$k(t);if(o.status==="miss")throw new Error(`Canonical Workspace Model and Graph are required (${o.reason}). Run workspai workspace intelligence run --for-agent generic --strict --json.`);let n=o.model.projects.map(i=>({name:i.name,path:i.path,runtime:i.runtime})).sort((i,c)=>i.name.localeCompare(c.name));if(e){let i=n.filter(c=>c.name===e||c.path===e);if(i.length!==1)throw new Error(i.length===0?`Project is not present in the canonical Workspace Model: ${e}`:`Project target is ambiguous: ${e}`);return i[0].name}if(n.length===1)return n[0].name;if(!r)throw new Error("--project is required when the workspace has multiple projects.");return (await b$1([{type:"rawlist",name:"project",message:"Which project should own this agent?",choices:n.map(i=>({value:i.name,label:i.name,hint:`${i.runtime} \xB7 ${i.path}`}))}])).project}async function md(t,e){if(t)return bn(t);if(!e)throw new Error("--runtime is required. Choose python, dotnet, or node.");let r=[...new Set(mo(F({},{trustReviewedReleaseAdmissions:true})).filter(a=>a.status==="admitted").map(a=>a.runtime))],o=r.length>0?r.map(a=>({value:a,label:a,hint:"release-admitted runtime"})):[{value:"python",label:"Python",hint:"Python 3.10+"},{value:"dotnet",label:".NET",hint:".NET 8+"},{value:"node",label:"Node.js",hint:"Node.js 22+"}];return (await b$1([{type:"rawlist",name:"runtime",message:"Choose the agent runtime:",choices:o}])).runtime}async function gd(t,e,r){if(t?.trim())return t.trim();let o=mo(F({},{trustReviewedReleaseAdmissions:true})).filter(a=>a.runtime===e&&a.status==="admitted");if(o.length<=1)return o[0]?.frameworkId;if(!r)throw new Error(`--framework is required for runtime ${e}. Choose ${o.map(a=>a.frameworkId).join(", ")}.`);return (await b$1([{type:"rawlist",name:"framework",message:"Choose the agent framework:",choices:o.map(a=>({value:a.frameworkId,label:a.frameworkName,hint:a.adapterId}))}])).framework}async function fd(t,e){if(t?.trim())return t.trim();if(!e)throw new Error("--name is required.");return (await b$1([{type:"input",name:"instanceName",message:"Name this agent:",default:"workspace-agent",validate:o=>o.trim().length>0||"Agent name is required"}])).instanceName.trim()}function gs(t){let e=t.status==="planned"?s.cyan:t.status==="no-op"?s.green:s.red;console.log(e(`\u25C6 ${t.frameworkId} \xB7 ${t.status}`)),console.log(s.bold(` ${t.instanceName} \xB7 ${t.runtime} \xB7 ${t.project}`)),console.log(s.gray(` Framework: ${t.frameworkVersion}`)),console.log(s.gray(` Goal: ${t.goalId}`)),console.log(s.gray(` Change: ${t.changeId}`));for(let r of t.files)console.log(s.gray(` ${r.overwrite}: ${r.path}`));t.requiredEnvironment.length>0&&console.log(s.gray(` Secret references: ${t.requiredEnvironment.join(", ")}`)),console.log(s.gray(" Dependency install: not executed"));for(let r of t.blockers)console.log(s.red(` Blocked: ${r}`));for(let r of t.nextActions)console.log(s.gray(` Next: ${r}`));}function hd(t){console.log(s.green("\u2714 Governed agent attached")),console.log(s.bold(` ${t.runtime} \xB7 ${t.project}`)),console.log(s.gray(` Change: ${t.changeId}`)),console.log(s.gray(` Managed files: ${t.files.length}`)),console.log(s.gray(` Ownership: ${t.ownershipReceipt}`)),console.log(s.gray(" Dependencies and model calls were not executed."));for(let e of t.nextActions)console.log(s.gray(` Next: ${e}`));}function fs(t,e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify({schemaVersion:"workspai.agent-framework-operation-error.v1",status:"error",message:r},null,2)):console.error(s.red(`Agent Framework failed: ${r}`)),process.exitCode=1;}function wd(t){let e=t.command("framework").description("Create and attach release-admitted agent runtimes through Workspai governance");e.command("list").description("List tested framework runtimes and their release-admission state").option("--json","Emit machine-readable JSON").action(o=>{let n=F({},{trustReviewedReleaseAdmissions:true}),a=n.list().map(c=>{let l=n.resolveAdapter(c.manifest.adapter.id);return {id:c.manifest.adapter.id,framework:c.manifest.framework.name,runtime:c.manifest.implementation.runtimes[0],frameworkVersion:c.manifest.framework.testedVersions[0],stability:c.manifest.adapter.stability,status:l.status,blockers:l.blockers}}),i={schemaVersion:"workspai.agent-framework-list.v1",adapters:a};if(o.json)console.log(JSON.stringify(i,null,2));else {console.log(s.bold("Agent Framework runtimes"));for(let c of a){let l=c.status==="admitted"?s.green("\u25CF"):s.red("\u25A0");console.log(`${l} ${c.framework} \xB7 ${c.runtime} \xB7 ${c.frameworkVersion} \xB7 ${c.stability} \xB7 ${c.status}`);}}});let r=o=>o.option("--workspace <path>","Explicit canonical workspace path").option("--project <name>","Canonical project name or path").option("--runtime <runtime>","python, dotnet, or node").option("--framework <framework>","Independent framework id, for example microsoft-agent-framework or openai-agents").option("--name <name>","Agent instance name").option("--goal <goal-id>","Reuse an existing ready Goal Pack").option("--intent <text>","Plain-language Goal intent when creating a dedicated Goal").option("--json","Emit machine-readable JSON");r(e.command("plan").description("Create a hash-bound attachment plan without writing project files")).action(async o=>{try{let n=!o.json&&process.stdin.isTTY===true,a=ms(o),i=await ud(a,o.project,n),c=await md(o.runtime,n),l=await gd(o.framework,c,n),p=await fd(o.name,n),m=await go({workspacePath:a,project:i,runtime:c,framework:l,instanceName:p,goalId:o.goal,intent:o.intent});o.json?console.log(JSON.stringify(m,null,2)):gs(m),m.status==="blocked"&&(process.exitCode=2);}catch(n){fs(o,n);}}),r(e.command("attach").description("Plan, approve, and write one isolated governed agent instance").option("-y, --yes","Approve the displayed filesystem plan without another prompt").option("--granted-by <identity>","Identity recorded in the authorization","operator")).action(async o=>{try{let n=!o.json&&process.stdin.isTTY===true,a=ms(o),i=await ud(a,o.project,n),c=await md(o.runtime,n),l=await gd(o.framework,c,n),p=await fd(o.name,n),m=await go({workspacePath:a,project:i,runtime:c,framework:l,instanceName:p,goalId:o.goal,intent:o.intent});if(m.status!=="planned"){o.json?console.log(JSON.stringify(m,null,2)):gs(m),process.exitCode=m.status==="blocked"?2:0;return}let u=o.yes===true;if(!u&&n&&(gs(m),u=(await b$1([{type:"confirm",name:"approved",message:`Write these ${m.files.length} Workspai-managed files?`,default:false}])).approved),!u){o.json?console.log(JSON.stringify(m,null,2)):(console.log(s.yellow("Plan saved; no project files were written.")),console.log(s.gray(` Change: ${m.changeId}`)));return}let f=await jn({prepared:m,grantedBy:o.grantedBy});o.json?console.log(JSON.stringify(f,null,2)):hd(f);}catch(n){fs(o,n);}}),e.command("apply").description("Apply an already authorized hash-bound framework plan").requiredOption("--change <change-id>","Proof-Carrying Change id").requiredOption("--project <name>","Canonical project name or path").requiredOption("--runtime <runtime>","python, dotnet, or node").option("--framework <framework>","Independent framework id").option("--workspace <path>","Explicit canonical workspace path").option("--json","Emit machine-readable JSON").action(async o=>{try{let n=await dd({workspacePath:ms(o),project:o.project,runtime:bn(o.runtime),framework:o.framework,changeId:o.change});o.json?console.log(JSON.stringify(n,null,2)):hd(n);}catch(n){fs(o,n);}});}var En=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}async ensureDotnetInstalled(e){return (await this.run("dotnet",["--version"],e)).exitCode===0?null:{exitCode:1,message:".NET SDK is not installed or not available on PATH. Install .NET 8+ from https://dotnet.microsoft.com/download and retry."}}findFilesBySuffix(e,r,o=3){let n=[],a=[{dir:e,depth:0}],i=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;a.length>0;){let c=a.shift();if(!c||c.depth>o)continue;let l=[];try{l=$.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let p of l){let m=b.join(c.dir,p.name);if(p.isDirectory()){i.has(p.name)||a.push({dir:m,depth:c.depth+1});continue}p.name.toLowerCase().endsWith(r.toLowerCase())&&n.push(m);}}return n.sort()}findProjectFile(e){let r=this.findFilesBySuffix(e,".csproj");return r.find(o=>!o.toLowerCase().includes(".tests.csproj"))||r[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(o=>o.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let r=await this.ensureDotnetInstalled(e);return r||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=await this.run("dotnet",o?["restore",o]:["restore"],e);return n.exitCode===0?n:{exitCode:n.exitCode,message:"dotnet restore failed. Check NuGet connectivity, package references, and .NET SDK workload availability, then retry."}}async runDev(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=o?["watch","--project",o,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",o?["test",o]:["test"],e)}async runBuild(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["build",o,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["run","--project",o]:["run"],e)}async runLint(e){if(!b$3()&&w$4(e,"lint"))return this.run("make",["lint"],e);let r=b.join(e,"Directory.Build.props");if($.existsSync(r)&&$.readFileSync(r,"utf-8").includes("EnforceCodeStyleInBuild")){let o=await this.ensureDotnetInstalled(e);if(o)return o;let n=this.findProjectFile(e);return this.run("dotnet",n?["build",n,"-warnaserror"]:["build","-warnaserror"],e)}return {exitCode:1,message:"No .NET lint tooling detected. Add a Makefile lint target or enable EnforceCodeStyleInBuild in Directory.Build.props."}}async runFormat(e){if(!b$3()&&w$4(e,"format"))return this.run("make",["format"],e);let r=await this.ensureDotnetInstalled(e);return r||($.existsSync(b.join(e,".editorconfig"))?this.run("dotnet",["format","--verify-no-changes"],e):{exitCode:1,message:"No .NET format tooling detected. Add a Makefile format target or an .editorconfig file for dotnet format."})}async doctorHints(e){return ["Install .NET 8+ SDK and ensure dotnet is on PATH.","Run dotnet restore after changing package references.","Use dotnet format --verify-no-changes in CI for deterministic code style."]}};var Sn=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}async ensureGoInstalled(e){return (await this.run("go",["version"],e)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findWorkspaceRoot(e){let r=e;for(;;){if($.existsSync(b.join(r,".workspai-workspace"))||$.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=t$1(o,"policies.yml").find(a=>$.existsSync(a));if(!n)return "isolated";try{let c=$.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withGoCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","go"):b.join(e,".workspai","cache","go"),i=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=b.join(a,"mod"),process.env.GOCACHE=b.join(a,"build"),r().finally(()=>{typeof i>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=i,typeof c>"u"?delete process.env.GOCACHE:process.env.GOCACHE=c;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(e){return this.withGoCacheEnv(e,async()=>{try{return process.env.GOMODCACHE&&$.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&$.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let r=await this.ensureGoInstalled(e);if(r)return r;let o=b.join(e,"Makefile");if(!b$3()&&$.existsSync(o)&&w$4(e,"run"))return this.run("make",["run"],e);let n=v$4(e);return n?this.run("go",["run",n],e):{exitCode:1,message:"No unambiguous Go run target was detected. Add a root main package, keep one cmd/<name>/main.go target, or declare a Makefile run target."}})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let o=(b$3()?[b.join(e,"server.exe"),b.join(e,"server")]:[b.join(e,"server")]).find(i=>$.existsSync(i));if(o)return this.run(o,[],e);let n=await this.ensureGoInstalled(e);if(n)return n;let a=v$4(e);return a?this.run("go",["run",a],e):{exitCode:1,message:"No unambiguous Go start target was detected. Add a root main package, keep one cmd/<name>/main.go target, declare a Makefile run target, or provide the built server binary."}})}async runLint(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||(!b$3()&&w$4(e,"lint")?this.run("make",["lint"],e):$.existsSync(b.join(e,".golangci.yml"))||$.existsSync(b.join(e,".golangci.yaml"))?this.run("golangci-lint",["run","./..."],e):{exitCode:1,message:"No Go lint tooling detected. Add a Makefile lint target or .golangci.yml configuration."})})}async runFormat(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||(!b$3()&&w$4(e,"fmt")?this.run("make",["fmt"],e):!b$3()&&w$4(e,"format")?this.run("make",["format"],e):this.run("go",["fmt","./..."],e))})}async doctorHints(e){return ["Install Go from https://go.dev/dl/ if missing.","Run go mod tidy when dependencies are out of sync.","Use make run for hot-reload if Makefile exists."]}};var An=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return ($.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return $.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let r=process.env.JAVA_HOME?.trim();if(!r)return "java";let o=b.join(r,"bin",process.platform==="win32"?"java.exe":"java");return $.existsSync(o)?o:"java"}parseMajorJavaVersion(e){if(!e)return null;let o=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(o,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let r=b.join(e,"pom.xml");if(!$.existsSync(r))return 21;try{let n=$.readFileSync(r,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,r){try{let o=await execa(e,["-version"],{cwd:r,timeout:5e3,reject:false});if(o.exitCode!==0)return null;let n=`${o.stdout||""}
|
|
147
|
+
`)),process.exit(1);}});}function ig(t){return t.strict&&t.state==="blocked"?2:void 0}function ot(t){let e=b$5({startPath:process.cwd(),explicitWorkspacePath:t.workspace,strict:true,requireProjectMembership:!t.workspace});if(!e)throw new Error("No canonical Workspai workspace could be resolved.");return b.resolve(e.workspacePath)}async function cs(t){let e=b.resolve(process.cwd(),t);if(!await M__default.pathExists(e))throw new Error(`JSON input does not exist: ${t}`);return M__default.readJson(e)}function cg(t,e){if(e){console.log(JSON.stringify(t,null,2));return}let r=t.capsule.status==="sealed",o=t.capsule.status==="blocked",n=r?s.green("\u2713"):o?s.red("\u25A0"):s.cyan("\u25C6");console.log(`${n} Proof-Carrying Change \xB7 ${t.capsule.status}`),console.log(s.bold(` ${t.changeId}`)),console.log(s.gray(` State: ${t.state}`)),console.log(s.gray(` Assurance: ${t.capsule.assurances.filter(a=>a.status==="passed").length}/${t.capsule.assurances.length} passed`)),t.capsule.remainingUncertainty.length>0&&console.log(s.yellow(` Uncertainty: ${t.capsule.remainingUncertainty.join(" ")}`)),console.log(s.gray(` Capsule: ${t.artifacts.capsule}`));for(let a of t.nextActions)console.log(s.gray(` Next: ${a}`));}async function jt(t,e,r){try{let o=await e();cg(o,t.json);let n=r?.(o);n!==void 0&&(process.exitCode=n);}catch(o){let n=o instanceof Error?o.message:String(o);t.json?console.log(JSON.stringify({schemaVersion:"workspai.change-error.v1",status:"error",message:n},null,2)):console.error(s.red(`Proof-Carrying Change failed: ${n}`)),process.exitCode=1;}}var lg=new Set(["filesystem","command","configuration","dependency","external"]);function pg(t){let e=[...new Set(t.split(",").map(r=>r.trim()).filter(Boolean))];for(let r of e)if(!lg.has(r))throw new Error(`Unsupported effect class: ${r}`);return e}function nt(t){return t.option("--workspace <path>","Explicit canonical workspace path").option("--json","Emit a versioned machine-readable result")}function ed(t){let e=t.command("change").description("Create and verify tamper-evident, architecture-aware change capsules");nt(e.command("begin").description("Pin an active Goal and architecture baseline")).option("--goal <goal-id>","Require this Goal Pack to be the active Goal").action(async a=>{await jt(a,()=>c$8({workspacePath:ot(a),goalId:a.goal}));}),nt(e.command("list").description("List discoverable change capsules and integrity")).action(async a=>{try{let i=await m({workspacePath:ot(a)});if(a.json){console.log(JSON.stringify(i,null,2));return}console.log(s.bold(`Proof-Carrying Changes \xB7 ${i.summary.total}`)),i.changes.length===0&&console.log(s.gray(" No changes recorded."));for(let c of i.changes){let l=c.valid?c.status==="sealed"?s.green("\u2713"):s.cyan("\u25C6"):s.red("\u25A0");console.log(`${l} ${c.changeId} \xB7 ${c.status} \xB7 ${c.assurance.passed}/${c.assurance.total}`);}}catch(i){let c=i instanceof Error?i.message:String(i);a.json?console.log(JSON.stringify({status:"error",message:c},null,2)):console.error(s.red(c)),process.exitCode=1;}}),nt(e.command("predict").description("Attach a noncanonical architecture prediction")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--file <prediction.json>","Typed predicted architecture change JSON").action(async a=>{await jt(a,async()=>d$9({workspacePath:ot(a),changeId:a.change,prediction:q$2(await cs(a.file))}));}),nt(e.command("authorize").description("Grant bounded effect capabilities")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--effects <classes>","Comma-separated filesystem,command,configuration,dependency,external classes").option("--granted-by <identity>","Human or policy identity granting authorization","operator").action(async a=>{await jt(a,()=>f$2({workspacePath:ot(a),changeId:a.change,effectClasses:pg(a.effects),grantedBy:a.grantedBy}));}),nt(e.command("resume").description("Resume a blocked transaction with human intent")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--to <state>","Resume target: authorized, executing, or verifying").requiredOption("--reason <text>","Durable reason for resuming").option("--actor <identity>","Human identity resuming the change","operator").action(async a=>{await jt(a,()=>{if(!["authorized","executing","verifying"].includes(a.to))throw new Error("--to must be authorized, executing, or verifying.");return g$b({workspacePath:ot(a),changeId:a.change,resumeTo:a.to,reason:a.reason,actorId:a.actor})});});let r=e.command("effect").description("Record typed observed effects");nt(r.command("record").description("Append an idempotent effect receipt")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--file <receipt.json>","Typed effect receipt JSON").action(async a=>{await jt(a,async()=>h$6({workspacePath:ot(a),changeId:a.change,receipt:r$3(await cs(a.file))}));});let o$1=e.command("verification").description("Record independent Goal-criterion verification");nt(o$1.command("record").description("Append an exact-generation verification receipt")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--file <receipt.json>","Typed verification receipt JSON").action(async a=>{await jt(a,async()=>i$5({workspacePath:ot(a),changeId:a.change,receipt:s$4(await cs(a.file))}));}),nt(e.command("status").description("Inspect the derived transaction and assurance state")).requiredOption("--change <change-id>","Proof-carrying change id").action(async a=>{await jt(a,()=>l$7({workspacePath:ot(a),changeId:a.change,operation:"status"}));}),nt(e.command("explain").description("Explain proof, uncertainty, and next actions")).requiredOption("--change <change-id>","Proof-carrying change id").action(async a=>{await jt(a,()=>l$7({workspacePath:ot(a),changeId:a.change,operation:"explain"}));}),nt(e.command("verify").description("Re-observe architecture and verify exact effects")).requiredOption("--change <change-id>","Proof-carrying change id").option("--strict","Treat advisory Workspace Verify findings as blockers").option("--no-refresh","Use current canonical intelligence without refreshing it").action(async a=>{await jt(a,()=>k$6({workspacePath:ot(a),changeId:a.change,strict:a.strict,refresh:a.refresh}),i=>ig({strict:a.strict===true,state:i.state}));}),nt(e.command("abort").description("Terminate an open change without deleting evidence")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--reason <text>","Durable reason for aborting the change").option("--actor <identity>","Human identity aborting the change","operator").action(async a=>{await jt(a,()=>n$2({workspacePath:ot(a),changeId:a.change,reason:a.reason,actorId:a.actor}));});let n=e.command("capsule").description("Validate or export a change capsule");nt(n.command("validate").description("Validate capsule and referenced local evidence")).requiredOption("--change <change-id>","Proof-carrying change id").action(async a=>{try{let i=await o({workspacePath:ot(a),changeId:a.change});a.json?console.log(JSON.stringify(i,null,2)):console.log(i.valid?s.green(`\u2713 Capsule ${a.change} is valid.`):s.red(`\u25A0 Capsule ${a.change} is invalid: ${i.errors.join("; ")}`)),i.valid||(process.exitCode=1);}catch(i){let c=i instanceof Error?i.message:String(i);a.json?console.log(JSON.stringify({valid:false,errors:[c]},null,2)):console.error(s.red(c)),process.exitCode=1;}}),nt(n.command("export").description("Export a validated portable capsule manifest")).requiredOption("--change <change-id>","Proof-carrying change id").requiredOption("--output <path>","Workspace-contained export path").action(async a=>{try{let i=await p$1({workspacePath:ot(a),changeId:a.change,outputPath:a.output});a.json?console.log(JSON.stringify(i,null,2)):console.log(s.green(`\u2713 Capsule exported: ${i.outputPath}`));}catch(i){let c=i instanceof Error?i.message:String(i);a.json?console.log(JSON.stringify({status:"error",message:c},null,2)):console.error(s.red(c)),process.exitCode=1;}});}var td=["python","dotnet","node"];function uo(t){return t.trim().toLowerCase().replace(/[^a-z0-9.-]+/g,"-")}function dg(t,e){let r=uo(e);return t.implementation.runtimes.some(o=>uo(o)===r)}function ug(t,e){let r=uo(e);return r===uo(t.framework.id)||r===uo(t.adapter.id)}function jn(t){let e=t.trim().toLowerCase();if(!td.includes(e))throw new Error(`Unsupported agent framework runtime: ${t}. Choose python, dotnet, or node.`);return e}function mo(t){return t.list().flatMap(e=>{let r=t.resolveAdapter(e.manifest.adapter.id).status;return e.manifest.implementation.runtimes.map(o=>({adapterId:e.manifest.adapter.id,frameworkId:e.manifest.framework.id,frameworkName:e.manifest.framework.name,runtime:o,status:r}))})}function bn(t){return mo(t).map(e=>`${e.frameworkId} + ${e.runtime} (${e.adapterId}, ${e.status})`).join("; ")}function ls(t){let e=t.framework?.trim(),r=t.registry.list().filter(l=>dg(l.manifest,t.runtime)).filter(l=>!e||ug(l.manifest,e));if(r.length===0)throw new Error(e?`No agent framework adapter matches framework ${e} and runtime ${t.runtime}. Available combinations: ${bn(t.registry)||"none"}.`:`No agent framework adapter matches runtime ${t.runtime}. Available combinations: ${bn(t.registry)||"none"}.`);let o=new Set(G$1().map(l=>l.adapterId)),n=r.filter(l=>o.has(l.manifest.adapter.id)),a=r.filter(l=>t.registry.resolveAdapter(l.manifest.adapter.id).status==="admitted");if(!e&&n.length>1)throw new Error(`Runtime ${t.runtime} matches multiple published frameworks (${n.map(l=>l.manifest.framework.id).join(", ")}). Pass --framework explicitly; Workspai does not guess.`);let i=n[0]??a[0]??r[0];if(!i)throw new Error(`No agent framework adapter matches runtime ${t.runtime}. Available combinations: ${bn(t.registry)||"none"}.`);if(!e&&n.length===0&&r.length>1)throw new Error(`Runtime ${t.runtime} matches multiple registered frameworks and none are published create kits. Pass --framework explicitly. Available combinations: ${bn(t.registry)}.`);let c=t.registry.resolveAdapter(i.manifest.adapter.id);return {adapterId:i.manifest.adapter.id,frameworkId:i.manifest.framework.id,frameworkName:i.manifest.framework.name,runtime:t.runtime,admitted:c.status==="admitted",blockers:c.blockers}}var ps="agent-framework-change-plan",wg=[".workspai/project.json","package.json","pyproject.toml","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts"];async function yg(t$1){let e=[],r=new Set,o=(i,c)=>{r.has(i)||(r.add(i),e.push({operation:"change",targetKind:"artifact",targetId:i,rationale:c,confidence:"high"}));},n=(i,c)=>{o(nd(t$1.target.artifactPrefix,i),c);};for(let i of t$1.plan.files)n(i.path,`${i.overwrite} under the admitted agent-framework plan.`);n(".workspai/project.json","Create and attach refresh the governed project lens after nested runtime files exist."),o(t.workspaceContract,"Agent required environment is recorded on the workspace contract during Graph refresh.");for(let i of wg)await M__default.pathExists(b.join(t$1.target.projectRoot,i))&&n(i,"Nested runtime attach re-observes the existing project-root manifest during Graph refresh.");let a=await M__default.readdir(t$1.target.projectRoot).catch(()=>[]);for(let i of a)/\.(?:cs|fs|vb)proj$/i.test(i)&&n(i,"Nested runtime attach re-observes the existing .NET project manifest during Graph refresh.");return e}var kg="workspai.agent-framework-managed-file.v1",rd=1024*1024;function Yt(t){return t.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/$/,"")}function nd(t,e){let r=Yt(t);return r==="."||r===""?Yt(e):`${r}/${Yt(e)}`}function ds(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,48)||"project",r=createHash("sha256").update(t).digest("hex").slice(0,12);return `${e}-${r}`}function ms(t){return createHash("sha256").update(`${JSON.stringify(t.manifest)}
|
|
148
|
+
`).digest("hex")}function ad(t){let e=t.registry.resolveAdapter(t.adapterId);if(e.status!=="admitted"||!e.entry){let o=e.blockers.length>0?` ${e.blockers.join(" ")}`:"";throw new Error(`Agent framework adapter is not admitted: ${t.adapterId}.${o}`)}let r=E$1.find(o=>o.manifest.adapter.id===e.entry?.manifest.adapter.id);if(!r||ms(r)!==e.entry.manifestSha256)throw new Error(`Admitted adapter implementation does not match its registry manifest: ${t.adapterId}`);return r}function vg(t){return `.workspai/agent-frameworks/ownership/${ds(t.adapterId)}/${ds(t.projectName)}/${D$1(t.instanceName)}.json`}async function sd(t,e){let r=b.resolve(t),o=await b$p(r,m$7);if(!o)throw new Error("Workspace Model is missing; run Workspace Intelligence before planning an agent framework change.");let n=await M__default.readJson(o),a=n.projects.filter(p=>p.name===e||Yt(p.path)===Yt(e));if(a.length!==1)throw new Error(a.length===0?`Project is not present in the canonical Workspace Model: ${e}`:`Project target is ambiguous in the canonical Workspace Model: ${e}`);let i=a[0],c=k$5(r,i);if(!(await M__default.stat(c).catch(()=>null))?.isDirectory())throw new Error(`Canonical project root is unavailable: ${i.name}`);return {workspacePath:r,workspaceName:n.workspace.name,projectName:i.name,projectRoot:c,artifactPrefix:c===r?".":a$g({workspacePath:r,projectPath:c,projectName:i.name}).contractRelativePath}}async function us(t,e){let r=b.resolve(t),o=b.resolve(r,e),n=b.relative(r,o);if(!n||n===".."||n.startsWith(`..${b.sep}`)||b.isAbsolute(n))throw new Error(`Managed path escapes the canonical project root: ${e}`);let a=await M__default.realpath(r),i=o;for(;!await M__default.pathExists(i);){let p=b.dirname(i);if(p===i)throw new Error(`Cannot resolve managed path: ${e}`);i=p;}let c=await M__default.realpath(i),l=b.relative(a,c);if(l===".."||l.startsWith(`..${b.sep}`)||b.isAbsolute(l))throw new Error(`Managed path resolves through a symlink outside the project root: ${e}`);if(await M__default.pathExists(o)){let p=await M__default.lstat(o);if(!p.isFile()||p.isSymbolicLink())throw new Error(`Managed target is not a regular file: ${e}`)}return o}async function Pg(t,e,r){let o=e.render({projectRoot:t.projectRoot,instanceName:r}).files,n=new Map;for(let a of o){let i=await us(t.projectRoot,a.path),c=await M__default.stat(i).catch(()=>null);if(c){if(c.size>rd)throw new Error(`Managed file exceeds the ${rd} byte safety limit: ${a.path}`);n.set(a.path,await M__default.readFile(i,"utf8"));}}return n}async function bg(t){let e=vg({adapterId:t.adapter.manifest.adapter.id,projectName:t.target.projectName,instanceName:t.instanceName}),r=await b$p(t.target.workspacePath,e);if(!r)return {path:e,ledger:new Map};let o=await M__default.readJson(r);if(a$4(o,C$1,"Agent framework ownership receipt"),o.schemaVersion!==z||o.adapter?.id!==t.adapter.manifest.adapter.id||o.adapter.version!==t.adapter.manifest.adapter.version||o.adapter.manifestSha256!==ms(t.adapter)||o.framework?.id!==t.adapter.manifest.framework.id||!t.adapter.manifest.framework.testedVersions.includes(o.framework.version)||o.target?.workspace!==t.target.workspaceName||o.target?.project!==t.target.projectName||Yt(o.target.artifactPrefix)!==t.target.artifactPrefix||o.target.instanceName!==D$1(t.instanceName)||!Array.isArray(o.files))throw new Error(`Agent framework ownership receipt is incompatible or corrupt: ${e}`);let n=new Map;for(let a of o.files){if(!a||typeof a.path!="string"||!/^[a-f0-9]{64}$/.test(a.sha256))throw new Error(`Agent framework ownership receipt contains an invalid file entry: ${e}`);if(n.has(a.path))throw new Error(`Agent framework ownership receipt contains duplicate paths: ${e}`);n.set(a.path,a.sha256);}return {path:e,ledger:n}}async function id(t){let[e,r]=await Promise.all([Pg(t.target,t.adapter,t.instanceName),bg(t)]);return {input:{projectRoot:t.target.projectRoot,instanceName:t.instanceName,target:{project:t.target.projectName,artifactPrefix:t.target.artifactPrefix},existingFiles:e,ownershipLedger:r.ledger},receiptPath:r.path}}async function cd(t){let e=ad(t),r=await sd(t.workspacePath,t.project),o=await id({target:r,adapter:e,instanceName:t.instanceName}),n=e.plan(t.mode,o.input);a$4(n,B,"Agent framework change plan");let a=c$h(n);if(n.status!=="planned")return {status:n.status,changeId:t.changeId,project:r.projectName,plan:n,planArtifact:null,planDigest:a};await d$9({workspacePath:r.workspacePath,changeId:t.changeId,actorKind:"cli",actorId:"workspai-agent-framework",prediction:{schemaVersion:i$2,changeId:t.changeId,goalId:"",generatedAt:new Date().toISOString(),baselineGeneration:"",nonCanonical:true,proofEligible:false,operations:await yg({target:r,plan:n}),assumptions:["Only hash-bound Workspai-managed files in the admitted ownership roots will change.","The project lens metadata at .workspai/project.json is rewritten after the nested runtime is applied.","Existing project-root manifests are re-observed when the nested runtime makes the project polyglot."],predictedRisk:n.files.length>0?"low":"none"}});let i=await e$d({workspacePath:r.workspacePath,changeId:t.changeId,role:ps,schemaVersion:y,contractPath:B,payload:n,actorId:"workspai-agent-framework"});return {status:"planned",changeId:t.changeId,project:r.projectName,plan:n,planArtifact:i.artifact,planDigest:i.digest}}async function jg(t,e){let o=(await a$R(t,e)).transaction.plans.filter(c=>c.role===ps);if(o.length!==1)throw new Error(`PCC transaction must contain exactly one ${ps} reference.`);let n=o[0],a=await b$p(t,n.artifact);if(!a)throw new Error(`Attached agent framework plan is missing: ${n.artifact}`);let i=await M__default.readJson(a);if(a$4(i,B,"Attached agent framework change plan"),c$h(i)!==n.digest.value)throw new Error("Attached agent framework plan digest does not match the PCC event chain.");return i}function Cg(t){let{transaction:e}=t;if(e.state!=="authorized"&&e.state!=="executing")throw new Error(`Agent framework apply requires an authorized PCC transaction; observed ${e.state}.`);if(!e.authorization?.effectClasses.includes("filesystem"))throw new Error("Agent framework apply requires an explicit filesystem effect grant.");if(!e.scope?.projects.includes(t.projectName))throw new Error(`Project ${t.projectName} is outside the immutable PCC scope.`)}function Eg(t,e){return {role:"agent-framework-managed-file",artifact:t,schemaVersion:kg,digest:{algorithm:"sha256",semantics:"raw-bytes-v1",value:e}}}async function Sg(t,e){await M__default.ensureDir(b.dirname(t));let r=`${t}.${process.pid}.${randomUUID()}.workspai-tmp`;try{await M__default.writeFile(r,e,{encoding:"utf8",flag:"wx"});try{await M__default.rename(r,t);}catch(o){let n=o.code;if(n!=="EEXIST"&&n!=="EPERM")throw o;await M__default.move(r,t,{overwrite:true});}}finally{await M__default.remove(r).catch(()=>{});}}async function gs(t){let e=ad(t),r=await sd(t.workspacePath,t.project),o=b.join(r.workspacePath,".workspai","locks","agent-framework",ds(`${r.projectName}:${e.manifest.adapter.id}`));return a$Q(o,async()=>{let[n,a]=await Promise.all([a$R(r.workspacePath,t.changeId),jg(r.workspacePath,t.changeId)]);if(Cg({transaction:n.transaction,projectName:r.projectName}),a.status!=="planned"||a.adapterId!==e.manifest.adapter.id||a.adapterVersion!==e.manifest.adapter.version)throw new Error("Attached plan is not executable by the selected adapter version.");if(a.target.project!==r.projectName||Yt(a.target.artifactPrefix)!==r.artifactPrefix)throw new Error("Attached plan target does not match the canonical Workspace Model project.");let i=await id({target:r,adapter:e,instanceName:a.instanceName}),c=e.plan(a.mode,i.input);if(c$h(c)!==c$h(a))throw new Error("Agent framework plan is stale; project files or ownership evidence changed after authorization.");let l=e.render(i.input);if(l.conflicts.length>0)throw new Error("Adapter render became blocked after authorization.");let p=new Map(a.files.map(y=>[y.path,y]));if(l.files.length!==p.size||l.files.some(y=>{let E=p.get(y.path);return !E||E.sha256!==y.sha256||E.overwrite!==y.overwrite}))throw new Error("Rendered files do not match the hash-bound PCC plan.");let m=new Map,u=[],f=await b$p(r.workspacePath,i.receiptPath),P=f?await M__default.readFile(f):null;try{for(let S of l.files){let d=await us(r.projectRoot,S.path);m.set(S.path,await M__default.pathExists(d)?await M__default.readFile(d):null),await Sg(d,S.content),u.push({path:S.path,artifact:nd(r.artifactPrefix,S.path),sha256:S.sha256});}let y=e.render({projectRoot:r.projectRoot,instanceName:a.instanceName,target:a.target}).files,E={schemaVersion:z,generatedAt:new Date().toISOString(),changeId:t.changeId,adapter:{id:e.manifest.adapter.id,version:e.manifest.adapter.version,manifestSha256:ms(e)},framework:{id:e.manifest.framework.id,version:a.frameworkVersion},target:{workspace:r.workspaceName,project:r.projectName,artifactPrefix:r.artifactPrefix,instanceName:a.instanceName},files:y.map(S=>({path:S.path,sha256:S.sha256}))};a$4(E,C$1,"Agent framework ownership receipt"),await h$5(r.workspacePath,i.receiptPath,E);let A={role:"agent-framework-ownership-receipt",artifact:i.receiptPath,schemaVersion:z,digest:{algorithm:"sha256",semantics:"canonical-json-v1",value:c$h(E)}};return await h$6({workspacePath:r.workspacePath,changeId:t.changeId,actorKind:"cli",actorId:"workspai-agent-framework",receipt:{id:`agent-framework-${t.changeId}`,effectClass:"filesystem",status:"succeeded",summary:`Applied ${e.manifest.framework.name} instance ${a.instanceName}.`,artifacts:[...u.map(S=>Eg(S.artifact,S.sha256)),A],observedAt:E.generatedAt,idempotencyKey:`agent-framework:${t.changeId}:${c$h(a)}`}}),{status:"applied",changeId:t.changeId,project:r.projectName,adapterId:e.manifest.adapter.id,instanceName:a.instanceName,files:u,ownershipReceipt:i.receiptPath}}catch(y){for(let[E,A]of [...m].reverse()){let S=await us(r.projectRoot,E);A===null?await M__default.remove(S):await M__default.outputFile(S,A);}if(P===null){let E=await b$p(r.workspacePath,i.receiptPath);E&&await M__default.remove(E);}else await M__default.outputFile(b.join(r.workspacePath,i.receiptPath),P);throw y}},{purpose:`agent-framework:${r.projectName}:${e.manifest.adapter.id}`,timeoutMs:3e4,staleMs:6e4})}function ld(){return F({},{trustReviewedReleaseAdmissions:true})}function pd(t){let e=ld(),r=ls({registry:e,runtime:t.runtime,framework:t.framework});if(!r.admitted)throw new Error(`Agent framework adapter ${r.adapterId} is not release-admitted. ${r.blockers.join(" ")}`.trim());return {registry:e,selection:r}}function Ag(t){return `workspai agent framework apply --project ${JSON.stringify(t.project)} --framework ${t.frameworkId} --runtime ${t.runtime} --change ${t.changeId}`}async function go(t){let e=D$1(t.instanceName),{registry:r,selection:o}=pd(t),n=t.goalId,a=!n;if(!n){let c=t.intent?.trim()||`Attach a governed ${o.frameworkName} ${t.runtime} agent named ${e} to ${t.project}`,l=await a$l({startPath:t.workspacePath,workspacePath:t.workspacePath,intent:c,scope:`project:${t.project}`,consumer:"generic"});if(l.result!=="planned"||l.goalPack.state!=="ready-to-plan")throw new Error(`The attachment Goal is not ready (${l.goalPack.state}). Resolve its bounded evidence or pass an existing ready Goal with --goal.`);n=l.goalPack.id;}let i=await c$8({workspacePath:t.workspacePath,goalId:n,actorKind:"cli",actorId:"workspai-agent-framework"});try{let c=await cd({workspacePath:t.workspacePath,project:t.project,changeId:i.changeId,registry:r,adapterId:o.adapterId,instanceName:e,mode:t.mode??"attach"});return c.status!=="planned"&&(await n$2({workspacePath:t.workspacePath,changeId:i.changeId,reason:`Agent framework planning completed as ${c.status}; no mutation is authorized.`,actorId:"workspai-agent-framework"}),a&&await m$3({workspacePath:t.workspacePath,goalId:n,action:"cancel"})),{schemaVersion:"workspai.agent-framework-attachment.v1",operation:"plan",mode:t.mode??"attach",status:c.status,workspacePath:t.workspacePath,project:c.project,runtime:t.runtime,frameworkId:o.frameworkId,adapterId:o.adapterId,frameworkVersion:c.plan.frameworkVersion,instanceName:c.plan.instanceName,goalId:n,changeId:c.changeId,planArtifact:c.planArtifact,files:c.plan.files,requiredEnvironment:c.plan.requiredEnvironment,permissions:c.plan.permissions,blockers:c.plan.blockers,nextActions:c.status==="planned"?[Ag({project:c.project,runtime:t.runtime,frameworkId:o.frameworkId,changeId:c.changeId})]:[]}}catch(c){throw await n$2({workspacePath:t.workspacePath,changeId:i.changeId,reason:`Agent framework planning failed: ${c instanceof Error?c.message:String(c)}`,actorId:"workspai-agent-framework"}).catch(()=>{}),a&&n&&await m$3({workspacePath:t.workspacePath,goalId:n,action:"cancel"}).catch(()=>{}),c}}async function Cn(t){if(t.prepared.status!=="planned")throw new Error("Only a planned agent framework attachment can be applied.");let e=t.grantedBy.trim();if(!e)throw new Error("The authorization identity cannot be empty.");let r=ld();await f$2({workspacePath:t.prepared.workspacePath,changeId:t.prepared.changeId,effectClasses:["filesystem"],grantedBy:e,actorKind:"human"});let o;try{o=await gs({workspacePath:t.prepared.workspacePath,project:t.prepared.project,changeId:t.prepared.changeId,registry:r,adapterId:t.prepared.adapterId});}catch(n){throw await n$2({workspacePath:t.prepared.workspacePath,changeId:t.prepared.changeId,reason:`Agent framework apply failed: ${n instanceof Error?n.message:String(n)}`,actorId:"workspai-agent-framework"}).catch(()=>{}),n}return {...t.prepared,operation:t.prepared.mode,status:"applied",files:o.files.map(n=>({path:n.path,sha256:n.sha256,overwrite:"applied"})),ownershipReceipt:o.ownershipReceipt,nextActions:[`workspai workspace run init --workspace ${JSON.stringify(t.prepared.workspacePath)} --scope ${JSON.stringify(t.prepared.project)} --json`,`workspai workspace run test --workspace ${JSON.stringify(t.prepared.workspacePath)} --scope ${JSON.stringify(t.prepared.project)} --json`,`workspai workspace run build --workspace ${JSON.stringify(t.prepared.workspacePath)} --scope ${JSON.stringify(t.prepared.project)} --json`,`workspai change verify --workspace ${JSON.stringify(t.prepared.workspacePath)} --change ${t.prepared.changeId} --json`]}}async function dd(t){let{registry:e,selection:r}=pd(t),o=await gs({workspacePath:t.workspacePath,project:t.project,changeId:t.changeId,registry:e,adapterId:r.adapterId});return {schemaVersion:"workspai.agent-framework-attachment.v1",operation:"apply",status:"applied",project:o.project,runtime:t.runtime,frameworkId:r.frameworkId,adapterId:r.adapterId,changeId:o.changeId,files:o.files,ownershipReceipt:o.ownershipReceipt,nextActions:[`workspai workspace run init --workspace ${JSON.stringify(t.workspacePath)} --scope ${JSON.stringify(o.project)} --json`,`workspai workspace run test --workspace ${JSON.stringify(t.workspacePath)} --scope ${JSON.stringify(o.project)} --json`,`workspai workspace run build --workspace ${JSON.stringify(t.workspacePath)} --scope ${JSON.stringify(o.project)} --json`,`workspai change verify --workspace ${JSON.stringify(t.workspacePath)} --change ${t.changeId} --json`]}}function fs(t){let e=b$5({startPath:process.cwd(),explicitWorkspacePath:t.workspace,strict:true,requireProjectMembership:!t.workspace});if(!e)throw new Error("No canonical Workspai workspace could be resolved.");return b.resolve(e.workspacePath)}async function ud(t,e,r){let o=await a$k(t);if(o.status==="miss")throw new Error(`Canonical Workspace Model and Graph are required (${o.reason}). Run workspai workspace intelligence run --for-agent generic --strict --json.`);let n=o.model.projects.map(i=>({name:i.name,path:i.path,runtime:i.runtime})).sort((i,c)=>i.name.localeCompare(c.name));if(e){let i=n.filter(c=>c.name===e||c.path===e);if(i.length!==1)throw new Error(i.length===0?`Project is not present in the canonical Workspace Model: ${e}`:`Project target is ambiguous: ${e}`);return i[0].name}if(n.length===1)return n[0].name;if(!r)throw new Error("--project is required when the workspace has multiple projects.");return (await b$1([{type:"rawlist",name:"project",message:"Which project should own this agent?",choices:n.map(i=>({value:i.name,label:i.name,hint:`${i.runtime} \xB7 ${i.path}`}))}])).project}async function md(t,e){if(t)return jn(t);if(!e)throw new Error("--runtime is required. Choose python, dotnet, or node.");let r=[...new Set(mo(F({},{trustReviewedReleaseAdmissions:true})).filter(a=>a.status==="admitted").map(a=>a.runtime))],o=r.length>0?r.map(a=>({value:a,label:a,hint:"release-admitted runtime"})):[{value:"python",label:"Python",hint:"Python 3.10+"},{value:"dotnet",label:".NET",hint:".NET 8+"},{value:"node",label:"Node.js",hint:"Node.js 22+"}];return (await b$1([{type:"rawlist",name:"runtime",message:"Choose the agent runtime:",choices:o}])).runtime}async function gd(t,e,r){if(t?.trim())return t.trim();let o=mo(F({},{trustReviewedReleaseAdmissions:true})).filter(a=>a.runtime===e&&a.status==="admitted");if(o.length<=1)return o[0]?.frameworkId;if(!r)throw new Error(`--framework is required for runtime ${e}. Choose ${o.map(a=>a.frameworkId).join(", ")}.`);return (await b$1([{type:"rawlist",name:"framework",message:"Choose the agent framework:",choices:o.map(a=>({value:a.frameworkId,label:a.frameworkName,hint:a.adapterId}))}])).framework}async function fd(t,e){if(t?.trim())return t.trim();if(!e)throw new Error("--name is required.");return (await b$1([{type:"input",name:"instanceName",message:"Name this agent:",default:"workspace-agent",validate:o=>o.trim().length>0||"Agent name is required"}])).instanceName.trim()}function hs(t){let e=t.status==="planned"?s.cyan:t.status==="no-op"?s.green:s.red;console.log(e(`\u25C6 ${t.frameworkId} \xB7 ${t.status}`)),console.log(s.bold(` ${t.instanceName} \xB7 ${t.runtime} \xB7 ${t.project}`)),console.log(s.gray(` Framework: ${t.frameworkVersion}`)),console.log(s.gray(` Goal: ${t.goalId}`)),console.log(s.gray(` Change: ${t.changeId}`));for(let r of t.files)console.log(s.gray(` ${r.overwrite}: ${r.path}`));t.requiredEnvironment.length>0&&console.log(s.gray(` Secret references: ${t.requiredEnvironment.join(", ")}`)),console.log(s.gray(" Dependency install: not executed"));for(let r of t.blockers)console.log(s.red(` Blocked: ${r}`));for(let r of t.nextActions)console.log(s.gray(` Next: ${r}`));}function hd(t){console.log(s.green("\u2714 Governed agent attached")),console.log(s.bold(` ${t.runtime} \xB7 ${t.project}`)),console.log(s.gray(` Change: ${t.changeId}`)),console.log(s.gray(` Managed files: ${t.files.length}`)),console.log(s.gray(` Ownership: ${t.ownershipReceipt}`)),console.log(s.gray(" Dependencies and model calls were not executed."));for(let e of t.nextActions)console.log(s.gray(` Next: ${e}`));}function ws(t,e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify({schemaVersion:"workspai.agent-framework-operation-error.v1",status:"error",message:r},null,2)):console.error(s.red(`Agent Framework failed: ${r}`)),process.exitCode=1;}function wd(t){let e=t.command("framework").description("Create and attach release-admitted agent runtimes through Workspai governance");e.command("list").description("List tested framework runtimes and their release-admission state").option("--json","Emit machine-readable JSON").action(o=>{let n=F({},{trustReviewedReleaseAdmissions:true}),a=n.list().map(c=>{let l=n.resolveAdapter(c.manifest.adapter.id);return {id:c.manifest.adapter.id,framework:c.manifest.framework.name,runtime:c.manifest.implementation.runtimes[0],frameworkVersion:c.manifest.framework.testedVersions[0],stability:c.manifest.adapter.stability,status:l.status,blockers:l.blockers}}),i={schemaVersion:"workspai.agent-framework-list.v1",adapters:a};if(o.json)console.log(JSON.stringify(i,null,2));else {console.log(s.bold("Agent Framework runtimes"));for(let c of a){let l=c.status==="admitted"?s.green("\u25CF"):s.red("\u25A0");console.log(`${l} ${c.framework} \xB7 ${c.runtime} \xB7 ${c.frameworkVersion} \xB7 ${c.stability} \xB7 ${c.status}`);}}});let r=o=>o.option("--workspace <path>","Explicit canonical workspace path").option("--project <name>","Canonical project name or path").option("--runtime <runtime>","python, dotnet, or node").option("--framework <framework>","Independent framework id, for example microsoft-agent-framework, openai-agents, or google-adk").option("--name <name>","Agent instance name").option("--goal <goal-id>","Reuse an existing ready Goal Pack").option("--intent <text>","Plain-language Goal intent when creating a dedicated Goal").option("--json","Emit machine-readable JSON");r(e.command("plan").description("Create a hash-bound attachment plan without writing project files")).action(async o=>{try{let n=!o.json&&process.stdin.isTTY===true,a=fs(o),i=await ud(a,o.project,n),c=await md(o.runtime,n),l=await gd(o.framework,c,n),p=await fd(o.name,n),m=await go({workspacePath:a,project:i,runtime:c,framework:l,instanceName:p,goalId:o.goal,intent:o.intent});o.json?console.log(JSON.stringify(m,null,2)):hs(m),m.status==="blocked"&&(process.exitCode=2);}catch(n){ws(o,n);}}),r(e.command("attach").description("Plan, approve, and write one isolated governed agent instance").option("-y, --yes","Approve the displayed filesystem plan without another prompt").option("--granted-by <identity>","Identity recorded in the authorization","operator")).action(async o=>{try{let n=!o.json&&process.stdin.isTTY===true,a=fs(o),i=await ud(a,o.project,n),c=await md(o.runtime,n),l=await gd(o.framework,c,n),p=await fd(o.name,n),m=await go({workspacePath:a,project:i,runtime:c,framework:l,instanceName:p,goalId:o.goal,intent:o.intent});if(m.status!=="planned"){o.json?console.log(JSON.stringify(m,null,2)):hs(m),process.exitCode=m.status==="blocked"?2:0;return}let u=o.yes===true;if(!u&&n&&(hs(m),u=(await b$1([{type:"confirm",name:"approved",message:`Write these ${m.files.length} Workspai-managed files?`,default:false}])).approved),!u){o.json?console.log(JSON.stringify(m,null,2)):(console.log(s.yellow("Plan saved; no project files were written.")),console.log(s.gray(` Change: ${m.changeId}`)));return}let f=await Cn({prepared:m,grantedBy:o.grantedBy});o.json?console.log(JSON.stringify(f,null,2)):hd(f);}catch(n){ws(o,n);}}),e.command("apply").description("Apply an already authorized hash-bound framework plan").requiredOption("--change <change-id>","Proof-Carrying Change id").requiredOption("--project <name>","Canonical project name or path").requiredOption("--runtime <runtime>","python, dotnet, or node").option("--framework <framework>","Independent framework id").option("--workspace <path>","Explicit canonical workspace path").option("--json","Emit machine-readable JSON").action(async o=>{try{let n=await dd({workspacePath:fs(o),project:o.project,runtime:jn(o.runtime),framework:o.framework,changeId:o.change});o.json?console.log(JSON.stringify(n,null,2)):hd(n);}catch(n){ws(o,n);}});}var Sn=class{constructor(e){this.runCommand=e;}runCommand;runtime="dotnet";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}async ensureDotnetInstalled(e){return (await this.run("dotnet",["--version"],e)).exitCode===0?null:{exitCode:1,message:".NET SDK is not installed or not available on PATH. Install .NET 8+ from https://dotnet.microsoft.com/download and retry."}}findFilesBySuffix(e,r,o=3){let n=[],a=[{dir:e,depth:0}],i=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;a.length>0;){let c=a.shift();if(!c||c.depth>o)continue;let l=[];try{l=$.readdirSync(c.dir,{withFileTypes:true});}catch{continue}for(let p of l){let m=b.join(c.dir,p.name);if(p.isDirectory()){i.has(p.name)||a.push({dir:m,depth:c.depth+1});continue}p.name.toLowerCase().endsWith(r.toLowerCase())&&n.push(m);}}return n.sort()}findProjectFile(e){let r=this.findFilesBySuffix(e,".csproj");return r.find(o=>!o.toLowerCase().includes(".tests.csproj"))||r[0]||null}findTestProjectFile(e){return this.findFilesBySuffix(e,".csproj").find(o=>o.toLowerCase().includes(".tests.csproj"))||null}async checkPrereqs(){return this.run("dotnet",["--version"],process.cwd())}async warmSetupCache(e){let r=await this.ensureDotnetInstalled(e);return r||this.run("dotnet",["nuget","locals","all","--list"],e)}async initProject(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=await this.run("dotnet",o?["restore",o]:["restore"],e);return n.exitCode===0?n:{exitCode:n.exitCode,message:"dotnet restore failed. Check NuGet connectivity, package references, and .NET SDK workload availability, then retry."}}async runDev(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e),n=o?["watch","--project",o,"run"]:["watch","run"];return this.run("dotnet",n,e)}async runTest(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findTestProjectFile(e)||this.findProjectFile(e);return this.run("dotnet",o?["test",o]:["test"],e)}async runBuild(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["build",o,"-c","Release"]:["build","-c","Release"],e)}async runStart(e){let r=await this.ensureDotnetInstalled(e);if(r)return r;let o=this.findProjectFile(e);return this.run("dotnet",o?["run","--project",o]:["run"],e)}async runLint(e){if(!b$3()&&w$4(e,"lint"))return this.run("make",["lint"],e);let r=b.join(e,"Directory.Build.props");if($.existsSync(r)&&$.readFileSync(r,"utf-8").includes("EnforceCodeStyleInBuild")){let o=await this.ensureDotnetInstalled(e);if(o)return o;let n=this.findProjectFile(e);return this.run("dotnet",n?["build",n,"-warnaserror"]:["build","-warnaserror"],e)}return {exitCode:1,message:"No .NET lint tooling detected. Add a Makefile lint target or enable EnforceCodeStyleInBuild in Directory.Build.props."}}async runFormat(e){if(!b$3()&&w$4(e,"format"))return this.run("make",["format"],e);let r=await this.ensureDotnetInstalled(e);return r||($.existsSync(b.join(e,".editorconfig"))?this.run("dotnet",["format","--verify-no-changes"],e):{exitCode:1,message:"No .NET format tooling detected. Add a Makefile format target or an .editorconfig file for dotnet format."})}async doctorHints(e){return ["Install .NET 8+ SDK and ensure dotnet is on PATH.","Run dotnet restore after changing package references.","Use dotnet format --verify-no-changes in CI for deterministic code style."]}};var An=class{constructor(e){this.runCommand=e;}runCommand;runtime="go";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}async ensureGoInstalled(e){return (await this.run("go",["version"],e)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findWorkspaceRoot(e){let r=e;for(;;){if($.existsSync(b.join(r,".workspai-workspace"))||$.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=t$1(o,"policies.yml").find(a=>$.existsSync(a));if(!n)return "isolated";try{let c=$.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withGoCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","go"):b.join(e,".workspai","cache","go"),i=process.env.GOMODCACHE,c=process.env.GOCACHE;return process.env.GOMODCACHE=b.join(a,"mod"),process.env.GOCACHE=b.join(a,"build"),r().finally(()=>{typeof i>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=i,typeof c>"u"?delete process.env.GOCACHE:process.env.GOCACHE=c;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(e){return this.withGoCacheEnv(e,async()=>{try{return process.env.GOMODCACHE&&$.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&$.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["mod","tidy"],e)})}async runDev(e){return this.withGoCacheEnv(e,()=>(async()=>{let r=await this.ensureGoInstalled(e);if(r)return r;let o=b.join(e,"Makefile");if(!b$3()&&$.existsSync(o)&&w$4(e,"run"))return this.run("make",["run"],e);let n=v$4(e);return n?this.run("go",["run",n],e):{exitCode:1,message:"No unambiguous Go run target was detected. Add a root main package, keep one cmd/<name>/main.go target, or declare a Makefile run target."}})())}async runTest(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["test","./..."],e)})}async runBuild(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||this.run("go",["build","-buildvcs=false","./..."],e)})}async runStart(e){return this.withGoCacheEnv(e,async()=>{let o=(b$3()?[b.join(e,"server.exe"),b.join(e,"server")]:[b.join(e,"server")]).find(i=>$.existsSync(i));if(o)return this.run(o,[],e);let n=await this.ensureGoInstalled(e);if(n)return n;let a=v$4(e);return a?this.run("go",["run",a],e):{exitCode:1,message:"No unambiguous Go start target was detected. Add a root main package, keep one cmd/<name>/main.go target, declare a Makefile run target, or provide the built server binary."}})}async runLint(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||(!b$3()&&w$4(e,"lint")?this.run("make",["lint"],e):$.existsSync(b.join(e,".golangci.yml"))||$.existsSync(b.join(e,".golangci.yaml"))?this.run("golangci-lint",["run","./..."],e):{exitCode:1,message:"No Go lint tooling detected. Add a Makefile lint target or .golangci.yml configuration."})})}async runFormat(e){return this.withGoCacheEnv(e,async()=>{let r=await this.ensureGoInstalled(e);return r||(!b$3()&&w$4(e,"fmt")?this.run("make",["fmt"],e):!b$3()&&w$4(e,"format")?this.run("make",["format"],e):this.run("go",["fmt","./..."],e))})}async doctorHints(e){return ["Install Go from https://go.dev/dl/ if missing.","Run go mod tidy when dependencies are out of sync.","Use make run for hot-reload if Makefile exists."]}};var Rn=class{constructor(e){this.runCommand=e;}runCommand;runtime="java";isExecutable(e){if(process.platform==="win32")return true;try{return ($.statSync(e).mode&73)!==0}catch{return false}}ensureWrapperExecutable(e){if(process.platform==="win32"||this.isExecutable(e))return true;try{return $.chmodSync(e,493),this.isExecutable(e)}catch{return false}}resolveJavaCommand(e){let r=process.env.JAVA_HOME?.trim();if(!r)return "java";let o=b.join(r,"bin",process.platform==="win32"?"java.exe":"java");return $.existsSync(o)?o:"java"}parseMajorJavaVersion(e){if(!e)return null;let o=e.trim().replace(/\"/g,"").split(".")[0],n=Number.parseInt(o,10);return Number.isFinite(n)?n:null}readRequiredJavaMajor(e){let r=b.join(e,"pom.xml");if(!$.existsSync(r))return 21;try{let n=$.readFileSync(r,"utf-8").match(/<java\.version>\s*([^<\s]+)\s*<\/java\.version>/i);return this.parseMajorJavaVersion(n?.[1])??21}catch{return 21}}async detectInstalledJavaMajor(e,r){try{let o=await execa(e,["-version"],{cwd:r,timeout:5e3,reject:false});if(o.exitCode!==0)return null;let n=`${o.stdout||""}
|
|
149
149
|
${o.stderr||""}`,a=n.match(/version\s+"([^"]+)"/i);if(a?.[1])return this.parseMajorJavaVersion(a[1]);let i=n.match(/(?:openjdk|java)\s+(\d+(?:[._]\d+)?)/i);return i?.[1]?this.parseMajorJavaVersion(i[1]):null}catch{return null}}parseMavenVersion(e){if(!e)return null;let r=e.match(/Apache Maven\s+(\d+)\.(\d+)\.(\d+)/i);return r?[Number.parseInt(r[1],10),Number.parseInt(r[2],10),Number.parseInt(r[3],10)]:null}isMavenVersionAtLeast(e,r){for(let o=0;o<3;o+=1){if(e[o]>r[o])return true;if(e[o]<r[o])return false}return true}async checkSystemMavenVersion(e){try{let r=await execa("mvn",["-version"],{cwd:e,timeout:5e3,reject:false});if(r.exitCode!==0)return {exitCode:r.exitCode||1,message:"Maven is required and must be available on PATH (3.9+)."};let o=this.parseMavenVersion(`${r.stdout||""}
|
|
150
|
-
${r.stderr||""}`);return o?this.isMavenVersionAtLeast(o,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${o.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let r=$.existsSync(b.join(e,"pom.xml")),o=$.existsSync(b.join(e,"mvnw"))||$.existsSync(b.join(e,"mvnw.cmd")),n=$.existsSync(b.join(e,"build.gradle"))||$.existsSync(b.join(e,"build.gradle.kts"))||$.existsSync(b.join(e,"settings.gradle"))||$.existsSync(b.join(e,"settings.gradle.kts")),a=$.existsSync(b.join(e,"gradlew"))||$.existsSync(b.join(e,"gradlew.bat"));return {hasMavenProject:r||o,hasMavenWrapper:o,hasGradleProject:n||a,hasGradleWrapper:a}}findWorkspaceRoot(e){let r=e;for(;;){if($.existsSync(b.join(r,".workspai-workspace"))||$.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=t$1(o,"policies.yml").find(a=>$.existsSync(a));if(!n)return "isolated";try{let c=$.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let r=b.join(e,"mvnw.cmd");if(process.platform==="win32"&&$.existsSync(r))return {command:r,baseArgs:[]};let o=b.join(e,"mvnw");return $.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let r=b.join(e,"gradlew.bat");if(process.platform==="win32"&&$.existsSync(r))return {command:r,baseArgs:[]};let o=b.join(e,"gradlew");return $.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let r=[],o=new Set,n=[e];for(;n.length>0;){let a=n.shift();if(!a||o.has(a))continue;o.add(a);let i=[];try{i=$.readdirSync(a,{withFileTypes:true});}catch{continue}for(let c of i){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let l=b.join(a,c.name),p=this.inspectJavaProject(l);(p.hasMavenProject||p.hasGradleProject)&&r.push(l),n.push(l);}}return r}withJavaCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","m2"):b.join(e,".workspai","cache","java","m2"),i=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","gradle"):b.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,l=process.env.GRADLE_USER_HOME,p=`-Dmaven.repo.local=${a}`;return process.env.MAVEN_OPTS=c?`${c} ${p}`:p,process.env.GRADLE_USER_HOME=i,r().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof l>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=l;})}async runBuildTool(e,r,o=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:a}=this.buildToolCommand(e),i=await this.runCommand(n,[...a,...r],e);if(i===0||!o)return {exitCode:i};let c=$.existsSync(b.join(e,"pom.xml")),l=$.existsSync(b.join(e,"build.gradle"))||$.existsSync(b.join(e,"build.gradle.kts"));return {exitCode:i,message:c||l?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let r=[b.join(e,"target"),b.join(e,"build","libs")];for(let o of r){if(!$.existsSync(o))continue;let a=$.readdirSync(o).filter(i=>i.toLowerCase().endsWith(".jar")).find(i=>!i.toLowerCase().endsWith("-sources.jar")&&!i.toLowerCase().endsWith("-javadoc.jar")&&!i.toLowerCase().endsWith("-plain.jar"));if(a)return b.join(o,a)}return null}commandArgsFor(e,r){if(e==="gradle"){let o=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return r==="init"?[...o,"dependencies"]:r==="dev"?[...o,"bootRun"]:r==="test"?[...o,"test"]:[...o,"bootJar"]}return r==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:r==="dev"?["spring-boot:run"]:r==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),r=this.resolveJavaCommand(e),o=await this.runCommand(r,["-version"],e);if(o!==0)return {exitCode:o,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),l=await this.detectInstalledJavaMajor(r,e);if(l!==null&&l<c)return {exitCode:1,message:`Detected Java ${l}, but project requires Java ${c}+.`};let p=b.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&$.existsSync(p))try{let u=$.readFileSync(p,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),f=this.parseMajorJavaVersion(u?.[1]);if(f!==null&&f<c)return {exitCode:1,message:`Detected JAVA_HOME version ${f}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),l=c==="gradle"?["--version"]:["-version"],p=await this.runBuildTool(e,l);return p.exitCode!==0?p:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):p}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let l=c.reduce((u,f)=>Math.max(u,this.readRequiredJavaMajor(f)),0);if(l>0){let u=await this.detectInstalledJavaMajor(r,e);if(u!==null&&u<l){let f=c.filter(P=>this.readRequiredJavaMajor(P)>u).map(P=>b.relative(e,P)).join(", ");return {exitCode:1,message:`Detected Java ${u}, but workspace project(s) [${f}] require Java ${l}+.`}}}let p=false,m=false;for(let u of c){let f=this.inspectJavaProject(u);f.hasMavenProject&&!f.hasMavenWrapper&&(p=true),f.hasGradleProject&&!f.hasGradleWrapper&&(m=true);}if(p){let u=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(u!==0)return {exitCode:u,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let f=await this.checkSystemMavenVersion(e);if(f.exitCode!==0)return f}if(m){let u=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(u!==0)return {exitCode:u,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(a===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return i===0?{exitCode:0}:{exitCode:a||i||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let r=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return r&&$.mkdirSync(r,{recursive:true}),process.env.GRADLE_USER_HOME&&$.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let r=this.resolveJarPath(e);if(r)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",r],e)};let o=await this.runBuild(e);if(o.exitCode!==0)return o;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(w$4(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let r=b.join(e,"pom.xml");if($.existsSync(r)){let o=$.readFileSync(r,"utf-8");if(o.includes("spotless-maven-plugin"))return this.runBuildTool(e,["spotless:check"]);if(o.includes("checkstyle"))return this.runBuildTool(e,["checkstyle:check"])}return {exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){if(w$4(e,"format"))return {exitCode:await this.runCommand("make",["format"],e)};let r=b.join(e,"pom.xml");return $.existsSync(r)&&$.readFileSync(r,"utf-8").includes("spotless-maven-plugin")?this.runBuildTool(e,["spotless:apply"]):["build.gradle","build.gradle.kts"].map(n=>b.join(e,n)).filter(n=>$.existsSync(n)).some(n=>$.readFileSync(n,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure Spotless in Maven/Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run npx workspai init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var Rn=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}findWorkspaceRoot(e){let r=e;for(;;){if($.existsSync(b.join(r,".workspai-workspace"))||$.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=t$1(o,"policies.yml").find(a=>$.existsSync(a));if(!n)return "isolated";try{let c=$.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,r,o){let n=this.resolveDependencyMode(e),a=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=n==="isolated"?b.join(e,".workspai","cache","node"):b.join(a||e,".workspai","cache","node"),c=process.env.npm_config_cache,l=process.env.npm_config_store_dir,p=process.env.BUN_INSTALL_CACHE_DIR,m=process.env.RAPIDKIT_DEP_SHARING_MODE,u=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,a&&(process.env.RAPIDKIT_WORKSPACE_PATH=a),r==="bun"?process.env.BUN_INSTALL_CACHE_DIR=b.join(i,"bun-cache"):r==="pnpm"?(process.env.npm_config_store_dir=b.join(i,"pnpm-store"),process.env.npm_config_cache=b.join(i,"pnpm-cache")):r==="yarn"?process.env.npm_config_cache=b.join(i,"yarn-cache"):process.env.npm_config_cache=b.join(i,"npm-cache"),o().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof l>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=l,typeof p>"u"?delete process.env.BUN_INSTALL_CACHE_DIR:process.env.BUN_INSTALL_CACHE_DIR=p,typeof m>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=m,typeof u>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=u;})}detectPackageManager(e){if($.existsSync(b.join(e,"bun.lock"))||$.existsSync(b.join(e,"bun.lockb")))return "bun";if($.existsSync(b.join(e,"package-lock.json")))return "npm";if($.existsSync(b.join(e,"pnpm-lock.yaml")))return "pnpm";if($.existsSync(b.join(e,"yarn.lock")))return "yarn";if(!this.commandAvailable("npm")){if(this.commandAvailable("pnpm"))return "pnpm";if(this.commandAvailable("yarn"))return "yarn"}return "npm"}hasPinnedPackageManager(e){return $.existsSync(b.join(e,"package-lock.json"))||$.existsSync(b.join(e,"bun.lock"))||$.existsSync(b.join(e,"bun.lockb"))||$.existsSync(b.join(e,"pnpm-lock.yaml"))||$.existsSync(b.join(e,"yarn.lock"))}availablePackageManagers(e){let r=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[r]:[r,...["npm","pnpm","yarn","bun"].filter(n=>n!==r&&this.commandAvailable(n))]}commandAvailable(e){let r=e$f(e);return spawnSync(r.command,[...r.prefixArgs,"--version"],{stdio:"ignore",shell:c$i(),env:g$a()}).status===0}scriptArgs(e,r){return e==="npm"?["run-script",r,"--foreground-scripts"]:["run",r]}async runScriptWithFallback(e,r){let o={exitCode:1};for(let n of this.availablePackageManagers(e))if(o=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,r),e)),o.exitCode===0)return o;return {...o,message:o.message??`Node lifecycle script failed. Re-run \`${z$1(e,r)}\` in ${e} to inspect the native tool output.`}}async runLifecycle(e,r){let o=j$2(e),n=m$2(e,o),a=u$2(e,r,{framework:n.key});return a?this.runScriptWithFallback(e,a.scriptName):{exitCode:1,message:`No npm script available for \`${r}\`. Add a "${r}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let r=this.detectPackageManager(e);return this.withDependencyEnv(e,r,async()=>{try{return process.env.npm_config_cache&&$.mkdirSync(process.env.npm_config_cache,{recursive:true}),r==="pnpm"&&process.env.npm_config_store_dir&&$.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let r=this.detectPackageManager(e),o=this.resolveDependencyMode(e),n=o==="shared-runtime-caches"||o==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,r,()=>this.run(r,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var In=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,r){return {exitCode:await this.withPythonCacheEnv(r,()=>this.runCore(e,r))}}findWorkspaceRoot(e){let r=e;for(;;){if($.existsSync(b.join(r,".workspai-workspace"))||$.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=t$1(o,"policies.yml").find(a=>$.existsSync(a));if(!n)return "isolated";try{let c=$.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","python"):b.join(e,".workspai","cache","python"),i=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=b.join(a,"pip"),process.env.POETRY_CACHE_DIR=b.join(a,"poetry"),r().finally(()=>{typeof i>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=i,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),r=await this.run(["doctor","check"],e);return r.exitCode===0?r:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx workspai doctor workspace" for a full workspace scan.','Use "npx workspai init" after adding or changing modules.',"Use `npx workspai <command>` from the project root to avoid environment drift."]}};var _n=class{constructor(e){this.runCommand=e;}runCommand;runtime="php";async run(e,r,o){let n=await this.runCommand(e,r,o);return n===0?{exitCode:n}:{exitCode:n,message:`PHP lifecycle command failed (${e} ${r.join(" ")}). Ensure ${e} is available on PATH, then review composer.json and the command diagnostics above.`}}hasComposer(e){return $.existsSync(b.join(e,"composer.json"))}hasArtisan(e){return $.existsSync(b.join(e,"artisan"))}hasComposerScript(e,r){try{let o=JSON.parse($.readFileSync(b.join(e,"composer.json"),"utf8"));return !!o.scripts&&Object.prototype.hasOwnProperty.call(o.scripts,r)}catch{return false}}missingManifest(){return {exitCode:1,message:"composer.json was not found. Run the command from a PHP project root."}}unsupported(e){return {exitCode:1,message:`No deterministic PHP ${e} command was detected. Add a "${e}" Composer script or the expected Laravel tooling.`}}async checkPrereqs(){let e=await this.run("php",["--version"],process.cwd());return e.exitCode!==0?e:this.run("composer",["--version"],process.cwd())}async initProject(e){return this.hasComposer(e)?this.run("composer",["install","--no-interaction"],e):this.missingManifest()}async runDev(e){return this.hasComposerScript(e,"dev")?this.run("composer",["run-script","dev"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("dev")}async runTest(e){return this.hasArtisan(e)?this.run("php",["artisan","test"],e):this.hasComposerScript(e,"test")?this.run("composer",["run-script","test"],e):this.unsupported("test")}async runBuild(e){return this.hasComposerScript(e,"build")?this.run("composer",["run-script","build"],e):this.unsupported("build")}async runStart(e){return this.hasComposerScript(e,"start")?this.run("composer",["run-script","start"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("start")}async runLint(e){for(let r of ["lint","analyse","analyze"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return this.unsupported("lint")}async runFormat(e){for(let r of ["format","fmt"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return $.existsSync(b.join(e,"vendor","bin","pint"))||$.existsSync(b.join(e,"pint.json"))?this.run("php",["vendor/bin/pint"],e):this.unsupported("format")}async doctorHints(e){return ["Install a supported PHP release and Composer, then keep both on PATH.","Commit composer.lock for deterministic application installs.","Expose test, lint, format, and build commands as Composer scripts when the framework does not provide them."]}};var On=class{constructor(e){this.runCommand=e;}runCommand;runtime="rust";async run(e,r){let o=await this.runCommand("cargo",e,r);return o===0?{exitCode:o}:{exitCode:o,message:`Cargo command failed (cargo ${e.join(" ")}). Ensure the stable Rust toolchain and cargo are available on PATH, then review Cargo.toml and the command diagnostics above.`}}hasManifest(e){return $.existsSync(b.join(e,"Cargo.toml"))}missingManifest(){return {exitCode:1,message:"Cargo.toml was not found. Run the command from a Rust project root."}}async checkPrereqs(){return this.run(["--version"],process.cwd())}async initProject(e){return this.hasManifest(e)?this.run(["fetch"],e):this.missingManifest()}async runDev(e){return this.hasManifest(e)?this.run(["run"],e):this.missingManifest()}async runTest(e){return this.hasManifest(e)?this.run(["test","--all-targets"],e):this.missingManifest()}async runBuild(e){return this.hasManifest(e)?this.run(["build","--release"],e):this.missingManifest()}async runStart(e){return this.hasManifest(e)?this.run(["run","--release"],e):this.missingManifest()}async runLint(e){return this.hasManifest(e)?this.run(["clippy","--all-targets","--all-features","--","-D","warnings"],e):this.missingManifest()}async runFormat(e){return this.hasManifest(e)?this.run(["fmt","--all"],e):this.missingManifest()}async doctorHints(e){return ["Install the Rust toolchain with rustup and ensure cargo is on PATH.","Use Cargo.lock for deterministic application builds.","Install rustfmt and clippy components for format and lint lifecycle commands."]}};function Og(){let t={...process.env},e=t.PATH||"";if(e){let r=e.split(b.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter);t.PATH=r;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||i$4(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ze(t,e){return t==="go"?new Sn((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="node"?new Rn((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="java"?new An((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="dotnet"?new En((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="rust"?new On((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="php"?new _n((r,o,n)=>e.runCommandInCwd(r,o,n)):new In((r,o)=>e.runCoreRapidkit(r,{cwd:o,env:Og()}))}var vd=b.join($a.homedir(),".workspai","cache"),Pd=1440*60*1e3;function ws(){let t=f$3("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?b.join(vd,`vitest-${e}`):vd}var $n=class t{static instance;memoryCache=new Map;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getCacheKey(e){return createHash("md5").update(e).digest("hex")}getCachePath(e){return b.join(ws(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let r=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${r}.tmp`}async get(e$1,r="1.0"){let o=this.memoryCache.get(e$1);if(o&&o.version===r&&Date.now()-o.timestamp<Pd)return e.debug(`Cache hit (memory): ${e$1}`),o.data;try{let n=this.getCachePath(e$1),a=await promises.readFile(n,"utf-8"),i=JSON.parse(a);if(i.version===r&&Date.now()-i.timestamp<Pd)return e.debug(`Cache hit (disk): ${e$1}`),this.memoryCache.set(e$1,i),i.data;await promises.unlink(n).catch(()=>{});}catch{e.debug(`Cache miss: ${e$1}`);}return null}async set(e$1,r,o="1.0"){let n={data:r,timestamp:Date.now(),version:o};this.memoryCache.set(e$1,n);try{await promises.mkdir(ws(),{recursive:true});let a=this.getCachePath(e$1),i=this.getTempCachePath(a);await promises.writeFile(i,JSON.stringify(n),"utf-8"),await promises.rename(i,a),e.debug(`Cache set: ${e$1}`);}catch(a){e.debug(`Cache write failed: ${e$1}`,a);}}async invalidate(e$1){this.memoryCache.delete(e$1);try{let r=this.getCachePath(e$1);await promises.unlink(r),e.debug(`Cache invalidated: ${e$1}`);}catch{}}async clear(){this.memoryCache.clear();try{let e$1=ws(),r=await promises.readdir(e$1);await Promise.all(r.map(o=>promises.unlink(b.join(e$1,o)))),e.debug("Cache cleared");}catch{}}};function bd(t){let e=C(t);return e?`Workspai project found at ${e}, but no Python virtual environment or activation script is available.`:"No Workspai project metadata, Python virtual environment, or activation script was found in this directory or its parents."}async function jd(t){let e=b.resolve(t),r=v$2(e,"project.json");if(!await M__default.pathExists(r))return false;let o=await ks(r);if(!o)return false;let n=typeof o.kit_name=="string"&&o.kit_name||typeof o.kit=="string"&&o.kit||void 0,a=a$3(n);if(!a||a.owner!=="core")return false;let i=Ce(o.name)||b.basename(e),c=await Wg(e),l=v$2(e,"context.json"),p=await ks(l)??{},m=await Dg({kit:a,projectRoot:e,existingContextEngine:p.engine,pythonProjectEngine:c}),u=Mg(o),f=Ce(o.generated_at)||Ce(o.created_at)||new Date().toISOString(),P={...o,schema_version:Ce(o.schema_version)??o.schema_version??"1.0",name:Ce(o.name)||i,slug:Ce(o.slug)||i,kind:Ce(o.kind)||a.category,project_type:Ce(o.project_type)||a.category,category:Ce(o.category)||a.category,runtime:Ce(o.runtime)||a.runtime,framework:Ce(o.framework)||a.framework,kit_name:a.id,kit:Ce(o.kit)||a.id,engine:a.runtime==="node"?Ce(o.engine)==="npm"?o.engine:"npm":c||(ro(o.engine)?o.engine:m),module_support:typeof o.module_support=="boolean"?o.module_support:a.moduleSupport,workspai_version:Ce(o.workspai_version)||h(),generated_by:Ce(o.generated_by)||"workspai",generated_at:f,generator:o.generator??{id:a.id,source:"rapidkit-core-bridge",official:false}};u&&P.rapidkit_core_version===void 0&&(P.rapidkit_core_version=u);let y={...p,engine:m,project:Ce(p.project)||i,kind:Ce(p.kind)||a.category,category:Ce(p.category)||a.category,runtime:Ce(p.runtime)||a.runtime,framework:Ce(p.framework)||a.framework,source:Ce(p.source)||"core-bridge"};return await M__default.ensureDir(b.dirname(r)),await M__default.writeJson(r,P,{spaces:2}),await M__default.writeJson(l,y,{spaces:2}),true}function Ce(t){return typeof t=="string"&&t.trim()?t:void 0}function Mg(t){if(typeof t.rapidkit_core_version=="string"&&t.rapidkit_core_version.trim())return t.rapidkit_core_version;let e=Ce(t.generated_by),r=Ce(t.created_by),o=Ce(t.rapidkit_version);if(o&&!(e==="workspai"||r==="workspai-cli-fallback")&&!t.schema_version)return o}async function Wg(t){let e=b.join(t,"pyproject.toml");if(await M__default.pathExists(e)){let r=await M__default.readFile(e,"utf8");if(/\[tool\.poetry\]/.test(r))return "poetry";if(/\[tool\.uv\]/.test(r))return "uv"}if(await M__default.pathExists(b.join(t,"uv.lock")))return "uv";if(await M__default.pathExists(b.join(t,"requirements.txt")))return "pip"}async function Dg(t){if(t.kit.runtime==="python")return t.pythonProjectEngine||ys(t.existingContextEngine)||"pip";let e=ys(t.existingContextEngine,{allowPip:false});if(e)return e;let r=await Lg(t.projectRoot);return r||ys(t.existingContextEngine)||"pip"}function ys(t,e={}){if(ro(t)&&!(e.allowPip===false&&(t==="pip"||t==="python")))return t}async function Lg(t){let e=b.resolve(t);for(;;){for(let o of [c$j,d$a]){let n=b.join(e,o);if(!$.existsSync(n))continue;let c=(await ks(n))?.metadata?.npm?.installMethod;if(c==="poetry"||c==="venv"||c==="pipx")return c}let r=b.dirname(e);if(r===e)break;e=r;}}async function ks(t){if(!await M__default.pathExists(t))return null;try{let e=await M__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Te(t,e,r,o,n="process",a){return {id:t,label:e,order:r,layoutHint:n,...o?{parentId:o}:{},...a?{group:a}:{}}}function Fg(t){return t.slice(1).map((e,r)=>{let o=t[r];return {id:`${o.id}->${e.id}`,from:o.id,to:e.id,kind:e.layoutHint==="gate"?"gate":e.layoutHint==="sink"?"handoff":"sequence",order:r+1}})}var Gg=[["workspace.intelligence.preflight.sync","Sync","source","DISCOVER"],["workspace.intelligence.stage.model","Model + Graph","process","UNDERSTAND"],["workspace.intelligence.preflight.baseline","Baseline","process","UNDERSTAND"],["workspace.intelligence.stage.diff","Diff","process","UNDERSTAND"],["workspace.intelligence.stage.impact","Impact","process","UNDERSTAND"],["workspace.intelligence.stage.doctor-evidence","Doctor","gate","ASSURE"],["workspace.intelligence.stage.contract-evidence","Contracts","gate","ASSURE"],["workspace.intelligence.stage.analyze-evidence","Analyze","gate","ASSURE"],["workspace.intelligence.stage.readiness-evidence","Readiness","gate","ASSURE"],["workspace.intelligence.stage.verify","Verify","gate","ASSURE"],["workspace.intelligence.stage.context","Context","process","PUBLISH"],["workspace.intelligence.stage.agent-sync","Agent Sync","process","PUBLISH"],["workspace.intelligence.stage.explain","Explain","sink","PUBLISH"]];function wo(t,e,r){return {id:t,version:3,nodes:[e,...r],edges:Fg(r)}}function Cd(t){let e=t.filter(a=>!a.startsWith("-")&&/^[a-z][a-z0-9-]*$/i.test(a)).slice(0,3),r=e.slice(0,3).join(".")||"cli",o=`command.${r}`,n=Te(o,e.join(" ")||"Workspai command",0,void 0,"source");if(e[0]==="workspace"&&e[1]==="intelligence"){let a=Gg.map(([i,c,l,p],m)=>Te(i,c,m+1,o,l,p));return wo(`cli.${r}`,n,a)}return e[0]==="adopt"?wo(`cli.${r}`,n,[Te("adopt.resolve","Resolve",1,o,"source","DISCOVER"),Te("adopt.detect","Detect",2,o,"process","DISCOVER"),Te("adopt.link","Link",3,o,"process","CONNECT"),Te("adopt.publish","Seal Intelligence",4,o,"gate","PUBLISH"),Te("adopt.ground","Agent Entry",5,o,"sink","PUBLISH")]):e[0]==="workspace"&&e[1]==="run"?wo(`cli.${r}`,n,[Te("workspace.run.resolve","Resolve Fleet",1,o,"source","DISCOVER"),Te("workspace.run.gates","Gates",2,o,"gate","ASSURE"),Te("workspace.run.execute","Execute",3,o,"process","EXECUTE"),Te("workspace.run.publish","Publish",4,o,"sink","PUBLISH")]):e[0]==="doctor"?wo(`cli.${r}`,n,[Te("doctor.observe","Observe",1,o,"source","OBSERVE"),Te("doctor.diagnose","Diagnose",2,o,"process","DIAGNOSE"),Te("doctor.plan","Plan",3,o,"process","DECIDE"),Te("doctor.verify","Verify",4,o,"gate","VERIFY")]):e[0]==="workspace"&&e[1]==="repair"?wo(`cli.${r}`,n,[Te("repair.observe","Observe",1,o,"source","OBSERVE"),Te("repair.plan","Plan",2,o,"process","DECIDE"),Te("repair.authorize","Authorize",3,o,"gate","AUTHORIZE"),Te("repair.execute","Execute",4,o,"process","EXECUTE"),Te("repair.verify","Verify",5,o,"gate","VERIFY")]):{id:`cli.${r}`,version:3,nodes:[n],edges:[]}}var yo=["list","sync","registry","foundation","intelligence","model","snapshot","diff","impact","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp","policy","contract","share","export","archive","hydrate","import","connect","run","init"],Tn=["intelligence","model","snapshot","diff","impact","contract","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp"];function Ed(t){return Tn.includes(t)}var Sd="workspai-project-entry-capability-v1";var vs="workspai-cli-runtime-command-inventory-v1",Mn=[...w$3,"autopilot","pipeline","import","adopt","goal","change","agent","snapshot","live","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands","create","project"],Ps=["bootstrap","setup","cache","mirror"],Wn="create",Vg=[...Ps,Wn],Jg={bootstrap:"Bootstrap project or workspace dependencies through runtime-aware setup rules.",setup:"Prepare a selected runtime toolchain through the supported adapter boundary.",cache:"Inspect or clear Workspai cache state through the managed cache boundary.",mirror:"Coordinate supported mirror lifecycle operations for the current project.",create:"Create a supported workspace or project through the canonical planner boundary."},Dn=[["ai","generate-embeddings"],["ai","info"],["ai","recommend"],["ai","update-embeddings"],["agent","bootstrap"],["agent","framework"],["agent","framework","list"],["agent","framework","plan"],["agent","framework","attach"],["agent","framework","apply"],["config","ai"],["config","remove-api-key"],["config","set-api-key"],["config","show"],["change","begin"],["change","list"],["change","predict"],["change","authorize"],["change","resume"],["change","effect"],["change","effect","record"],["change","verification"],["change","verification","record"],["change","status"],["change","explain"],["change","verify"],["change","abort"],["change","capsule"],["change","capsule","validate"],["change","capsule","export"],["infra","down"],["infra","plan"],["infra","status"],["infra","up"],["product","manifest"],["product","manifest","create"],["product","plan"],["project","commands"],["project","agent-entry"],["project","coverage"],["project","workspace"],["project","archives"],["project","archive"],["project","restore"],["project","delete"],["snapshot","create"],["snapshot","inspect"],["snapshot","list"],["snapshot","restore"]];function Kg(t,e,r,o){let n=new Set(t),a=new Set(e),i=t.filter(f=>!a.has(f)).sort(),c=e.filter(f=>!n.has(f)).sort(),l=new Set(r),p=new Set(o),m=r.filter(f=>!p.has(f)).sort(),u=o.filter(f=>!l.has(f)).sort();return {ok:i.length===0&&c.length===0&&m.length===0&&u.length===0,registeredButUndeclared:i,declaredButUnregistered:c,registeredScopedButUndeclared:m,declaredScopedButUnregistered:u}}function Ad(t,e=[]){return t.commands.flatMap(r=>{let o=r.name(),n=[...e,o];return [{path:n,command:o,parent:e.length>0?e.join(" "):null,registrationKind:"commander",aliases:r.aliases?.()??[],description:r.description?.()??"",hidden:r._hidden===true,arguments:(r.registeredArguments??[]).map(i=>({name:i.name(),required:i.required,variadic:i.variadic})),options:(r.options??[]).map(i=>({flags:i.flags,attributeName:i.attributeName?.()??null}))},...Ad(r,n)]})}function Rd(t){let e=Ad(t),r=e.filter(c=>c.path.length===1).map(c=>c.command),o=new Set(r),n=Vg.filter(c=>!o.has(c)).map(c=>({path:[c],command:c,parent:null,registrationKind:"manual-handler",aliases:[],description:Jg[c],hidden:false,arguments:[],options:[]})),a=[...e,...n].sort((c,l)=>c.path.join(" ").localeCompare(l.path.join(" "))),i=[...new Set(a.filter(c=>c.path.length===1).map(c=>c.command))].sort();return {schemaVersion:vs,commands:a,topLevelCommands:i,integrity:Kg(i,Mn,e.filter(c=>c.path.length>1).map(c=>c.path.join(" ")),Dn.map(c=>c.join(" ")))}}function xd(t){return `CLI command surface integrity violation (${[t.registeredButUndeclared.length>0?`registered but undeclared: ${t.registeredButUndeclared.join(", ")}`:null,t.declaredButUnregistered.length>0?`declared but unreachable: ${t.declaredButUnregistered.join(", ")}`:null,t.registeredScopedButUndeclared.length>0?`registered scoped but undeclared: ${t.registeredScopedButUndeclared.join(", ")}`:null,t.declaredScopedButUnregistered.length>0?`declared scoped but unreachable: ${t.declaredScopedButUnregistered.join(", ")}`:null].filter(r=>r!==null).join("; ")})`}var Ug={"--workspace":"Use an explicit workspace root instead of the nearest workspace.","--json":"Emit machine-readable JSON.","--strict":"Return a non-zero exit when governed evidence blocks the result.","--for-agent":"Build output for an agent surface (for example codex, copilot, or cursor).","--include-paths":"Include absolute filesystem paths.","--include-evidence":"Read and include referenced evidence metadata.","--scan-depth":"Set the bounded observable-project discovery depth.","--cache":"Reuse the model cache when the structural inputs are unchanged.","--refresh-graph":"Bypass the compatible persisted graph and rebuild from live sources.","--incremental":"Reuse unchanged projects and rebuild affected graph relations.","--write":"Persist the command artifact under .workspai/reports.","--scope":"Limit the operation to a bounded scope such as project:<name>.","--kind":"Limit graph entity search to one canonical entity kind.","--dry-run":"Preview the operation without applying writes.","--preset":"Select the generated agent customization preset.","--refresh-context":"Rebuild agent context before synchronization.","--refresh":"Refresh the underlying registry or context before reading it.","--agent-sync":"Synchronize agent grounding after writing the context artifact.","--no-agent-sync":"Do not synchronize agent grounding after writing context.","--target":"Select one or more agent customization targets.","--experimental-hooks":"Generate advisory VS Code agent hook design files.","--hydrate-prompts":"Add workspace-specific verification steps to supported prompts.","--project-grounding":"Select the project entrypoint policy: managed, local, or off.","--ci":"Produce a CI-oriented command plan.","--from":"Read the specified baseline, report, or graph artifact.","--from-impact":"Read the specified impact report for verification.","--output":"Write the requested export or report to this path.","--limit":"Bound graph query results (1\u2013100).","--once":"Build the initial observed state and exit.","--graph-stream":"Emit graph snapshot/delta events as NDJSON.","--force":"Replace an existing generated target where supported.","--no-doctor":"Exclude Doctor evidence from a share bundle.","--no-blueprint":"Exclude the reproducibility blueprint from a share bundle.","--include-env":"Include private environment files in an export archive.","--archive-compression":"Select the archive compression format.","--max-download-size":"Bound a remote archive download.","--max-expanded-size":"Bound the expanded archive size.","--download-timeout-ms":"Bound remote archive download time.","--allow-private-network":"Allow private-network archive sources explicitly.","--affected":"Run only projects affected by the selected Git change.","--blast-radius":"Include transitive downstream dependents.","--since":"Select the Git baseline used for affected-project discovery.","--parallel":"Run selected projects concurrently.","--plan":"Resolve lifecycle commands without executing project code.","--runtime":"Limit lifecycle planning or execution to one detected runtime family.","--max-workers":"Bound concurrent project workers.","--continue-on-error":"Continue remaining projects after a project failure.","--reuse-passed":"Reuse successful project-stage results where safe.","--no-gates":"Skip Doctor and Readiness pre-run gates.","--allow-breaking":"Allow a verified goal to use breaking dependency changes.","--allow-force":"Allow a verified goal to use force-based repair commands.","--card":"Select the dashboard card whose governed remediation actions should be repaired.","--action-id":"Select one exact governed remediation action.","--project":"Limit the repair transaction to one registered project name.","--proposal":"Read a bounded model repair proposal from a JSON file inside the workspace.","--transaction":"Select one durable repair transaction by id.","--approved-by":"Record the local actor approving the immutable repair plan.","--decision":"Submit one of the exact options exposed by a decision-required transaction.","--max-risk":"Set the maximum approved repair risk: safe, guarded, or invasive.","--no-auto-rollback":"Require a decision instead of automatically restoring a failed transaction.","--no-build":"Do not require build validation for the selected verified goal.","--no-tests":"Do not require test validation for the selected verified goal.","--no-run":"Read current goal evidence without executing verification commands.","--reuse-intelligence":"Reuse a just-completed canonical intelligence run while executing goal-specific checks."},ko={list:{usage:"workspai workspace list [--json]",summary:"List registered Workspai workspaces.",flags:["--json"],examples:["workspai workspace list","workspai workspace list --json"]},intelligence:{usage:"workspai workspace intelligence run [--for-agent <agent>] [--strict] [--json]",summary:"Run the canonical Workspace Intelligence chain in contract order.",flags:["--workspace","--json","--strict","--for-agent"],subactions:["run"],artifact:p.intelligenceRun,examples:["workspai workspace intelligence run --strict","workspai workspace intelligence run --for-agent codex --json"]},model:{usage:"workspai workspace model [--cache|--incremental] [--write] [--strict] [--json]",summary:"Build the canonical workspace model from registered and observed sources.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--cache","--incremental","--write","--strict"],artifact:p.model,examples:["workspai workspace model --write --json","workspai workspace model --incremental --write --json"]},"agent-sync":{usage:"workspai workspace agent-sync [--for-agent <agent>] [--target <targets>] [--project-grounding <mode>] [--write]",summary:"Synchronize bounded workspace grounding for supported agent surfaces.",flags:["--workspace","--json","--scope","--for-agent","--write","--dry-run","--strict","--preset","--refresh-context","--refresh","--target","--experimental-hooks","--hydrate-prompts","--project-grounding"],artifact:p.agentCustomizationPack,examples:["workspai workspace agent-sync --target all --write --strict","workspai workspace agent-sync --for-agent copilot --dry-run --json"]},"remediation-plan":{usage:"workspai workspace remediation-plan [--ci] [--write] [--json]",summary:"Build a governed repair plan from current workspace evidence.",flags:["--workspace","--json","--include-paths","--ci","--write"],artifact:t.artifactRemediationPlan,examples:["workspai workspace remediation-plan --write --json","workspai workspace remediation-plan --ci --json"]},repair:{usage:"workspai workspace repair <capabilities|plan|propose|approve|decide|execute|resume|status|list|rollback|cancel> [--transaction <id>] [--json]",summary:"Run a durable, approval-bound repair transaction through checkpoint, validation, canonical verification, and rollback.",flags:["--workspace","--json","--card","--action-id","--project","--proposal","--transaction","--approved-by","--decision","--max-risk","--allow-breaking","--allow-force","--no-auto-rollback"],subactions:["capabilities","plan","propose","approve","decide","execute","resume","status","list","rollback","cancel"],artifact:p.repairTransaction,examples:["workspai workspace repair capabilities --json","workspai workspace repair plan --card doctor --project api --json","workspai workspace repair propose --proposal .workspai/repair/inbox/proposal.json --json","workspai workspace repair approve --transaction repair_123 --approved-by local-user --json","workspai workspace repair decide --transaction repair_123 --decision approve-invasive --json","workspai workspace repair execute --transaction repair_123 --json","workspai workspace repair rollback --transaction repair_123 --json"]},context:{usage:"workspai workspace context [--for-agent <agent>] [--scope <scope>] [--write] [--json]",summary:"Build a bounded, evidence-backed context pack for people and agents.",flags:["--workspace","--json","--for-agent","--scope","--include-evidence","--scan-depth","--write","--agent-sync","--no-agent-sync","--preset","--target","--strict","--project-grounding"],artifact:p.agentContext,examples:["workspai workspace context --for-agent codex --write --json","workspai workspace context --scope project:api --json"]},snapshot:{usage:"workspai workspace snapshot [--json]",summary:"Persist the current model as the comparison baseline.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth"],artifact:p.snapshot,examples:["workspai workspace snapshot --json"]},diff:{usage:"workspai workspace diff --from <snapshot-or-model|git[:ref]> [--strict] [--json]",summary:"Compare the current model with a trusted model baseline.",flags:["--workspace","--json","--from","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:p.diff,examples:["workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","workspai workspace diff --from git --json"]},impact:{usage:"workspai workspace impact --from <diff> [--scope <scope>] [--strict] [--json]",summary:"Calculate the evidence-backed blast radius of the current model change.",flags:["--workspace","--json","--from","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:p.impact,examples:["workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json","workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --strict --json"]},verify:{usage:"workspai workspace verify [--from-impact <impact-report>] [--scope <scope>] [--strict] [--json]",summary:"Verify the selected change against contracts, gates, and current evidence.",flags:["--workspace","--json","--from-impact","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:p.verify,examples:["workspai workspace verify --strict --json","workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json"]},goal:{usage:"workspai workspace goal <plan|status|verify> <kind|goal-id> [--scope <scope>] [--runtime <runtime>] [--target <percent>] [--json]",summary:"Plan, resume, and evidence-verify a durable engineering goal for people and agents.",flags:["--workspace","--json","--scope","--runtime","--target","--allow-breaking","--allow-force","--no-build","--no-tests","--no-run","--reuse-intelligence"],flagDescriptions:{"--runtime":"Select the runtime measured by a test-coverage goal.","--target":"Set the required test coverage percentage (0\u2013100)."},subactions:["plan","status","verify"],artifact:p.verifiedGoalStatus,examples:["workspai workspace goal plan release-readiness --json","workspai workspace goal plan dependency-security --scope project:api --json","workspai workspace goal plan test-coverage --scope project:web --runtime node --target 75 --json","workspai workspace goal verify <goal-id> --json"]},graph:{usage:"workspai workspace graph [mode] [query|from] [to] [--json]",summary:"Query and export the canonical Knowledge Graph; explain, dot, and mermaid target the project dependency topology.",flags:["--workspace","--json","--output","--from","--limit","--kind","--refresh-graph","--include-paths","--include-evidence","--scan-depth","--scope","--write"],subactions:["emit","explain","entities","search","evidence","path","overlay","benchmark","benchmark-suite","dot","mermaid","jsonld","graphml","gexf"],examples:['workspai workspace graph search "authentication endpoint" --kind endpoint --limit 12 --json','workspai workspace graph evidence "GET /users" --json',"workspai workspace graph benchmark-suite agent-core.v1 --write --json","workspai workspace graph mermaid"]},watch:{usage:"workspai workspace watch [--once] [--graph-stream] [--json]",summary:"Observe model changes and optionally stream graph deltas.",flags:["--workspace","--json","--once","--graph-stream","--scan-depth"],examples:["workspai workspace watch --once --json","workspai workspace watch --graph-stream"]},sync:{usage:"workspai workspace sync [--project-grounding <mode>] [--json]",summary:"Synchronize canonical workspace registration and project metadata.",flags:["--workspace","--json","--project-grounding"],examples:["workspai workspace sync --json"]},registry:{usage:"workspai workspace registry [--refresh] [--json]",summary:"Inspect the canonical workspace registry summary.",flags:["--workspace","--json","--refresh"],examples:["workspai workspace registry --refresh --json"]},foundation:{usage:"workspai workspace foundation [--force] [--json]",summary:"Create or repair the standard workspace foundation files.",flags:["--workspace","--json","--force"],examples:["workspai workspace foundation --json"]},policy:{usage:"workspai workspace policy [show|status|get|set] [key] [value] [--json]",summary:"Inspect or update workspace governance policy.",flags:["--workspace","--json"],subactions:["show","status","get","set"],examples:["workspai workspace policy get --json"]},contract:{usage:"workspai workspace contract [init|inspect|sync|verify|graph] [--strict] [--json]",summary:"Create, inspect, synchronize, verify, or project the workspace contract.",flags:["--workspace","--json","--output","--force","--strict"],subactions:["init","inspect","sync","verify","graph"],artifact:t.workspaceContract,examples:["workspai workspace contract sync --strict --json","workspai workspace contract verify --strict --json","workspai workspace contract graph --json"]},share:{usage:"workspai workspace share [--output <file>] [--json]",summary:"Create a bounded, shareable workspace evidence bundle.",flags:["--workspace","--json","--output","--include-paths","--no-doctor","--no-blueprint"],examples:["workspai workspace share --output workspace-share.json --json"]},export:{usage:"workspai workspace export [--output <archive>] [--archive-compression <format>]",summary:"Export a portable workspace archive.",flags:["--workspace","--json","--output","--include-env","--archive-compression"],examples:["workspai workspace export --output workspace.tar.gz"]},archive:{usage:"workspai workspace archive <inspect|verify|doctor> <source> [safety options] [--json]",summary:"Inspect, verify, or diagnose a portable workspace archive without materializing it.",flags:["--json","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],subactions:["inspect","verify","doctor"],examples:["workspai workspace archive inspect ./workspace.tar.gz --json","workspai workspace archive verify ./workspace.tar.gz --strict --json","workspai workspace archive doctor ./workspace.tar.gz --json"]},hydrate:{usage:"workspai workspace hydrate <source> [--output <directory>] [--dry-run] [--json]",summary:"Hydrate a portable workspace into a controlled destination.",flags:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace hydrate workspace.tar.gz --output ./restored --dry-run --json"]},import:{usage:"workspai workspace import <source> [--output <directory>] [--dry-run] [--json]",summary:"Verify, materialize, register, relink, and reconcile a portable workspace archive safely.",flags:["--json","--output","--dry-run","--strict","--project-grounding","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace import workspace.tar.gz --output ./imported --json"]},connect:{usage:"workspai workspace connect [directory] [--project-grounding <mode>] [--dry-run] [--json]",summary:"Register and reconcile an existing Workspai workspace in place without moving its source.",flags:["--json","--dry-run","--project-grounding"],examples:["workspai workspace connect /path/to/existing-workspace --json"]},run:{usage:"workspai workspace run <stage> [selection and concurrency options] [--json]",summary:"Run a lifecycle stage across selected workspace projects.",flags:["--workspace","--json","--scope","--plan","--runtime","--affected","--blast-radius","--since","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],subactions:["init","test","build","start","<custom-from-context>"],artifact:t.workspaceRunLast,examples:["workspai workspace run test --scope project:api --plan --runtime ruby --json","workspai workspace run test --affected --blast-radius --strict","workspai workspace run build --parallel --max-workers 4 --json"]},explain:{usage:"workspai workspace explain [target] [--scope <scope>] [--write] [--json]",summary:"Explain current blockers or a selected workspace target from evidence.",flags:["--workspace","--json","--scope","--write"],artifact:p.explain,examples:["workspai workspace explain --write --json"]},why:{usage:"workspai workspace why [target] [--scope <scope>] [--write] [--json]",summary:"Alias the evidence-backed workspace explanation flow.",flags:["--workspace","--json","--scope","--write"],artifact:d$5,examples:["workspai workspace why readiness --json"]},trace:{usage:"workspai workspace trace --from <diff-artifact> [--write] [--json]",summary:"Trace a model change through blast radius and decision gates.",flags:["--workspace","--json","--from","--write"],artifact:e$3,examples:["workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --write --json"]},feedback:{usage:"echo '<event-json>' | workspai workspace feedback record --json",summary:"Record a structured outcome event for the workspace intelligence history.",flags:["--workspace","--json"],subactions:["record"],examples:[`echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | workspai workspace feedback record --json`]},eval:{usage:"workspai workspace eval [init|record|status|report|compare] [arguments] [--json]",summary:"Measure agent/model calls, tool use, tokens, latency, and verified outcome.",flags:["--workspace","--json","--from","--output"],subactions:["init","record","status","report","compare"],artifact:p.evaluationLastRun,examples:["workspai workspace eval init repair-readiness workspace-intelligence --json","workspai workspace eval report --output ./evaluation.json --json"]},mcp:{usage:"workspai workspace mcp serve",summary:"Serve bounded, read-mostly workspace evidence over stdio MCP.",flags:["--workspace","--json"],subactions:["serve"],examples:["workspai workspace mcp serve"]},init:{usage:"workspai workspace init [selection and concurrency options] [--json]",summary:"Initialize all selected projects through the workspace fleet runner.",flags:["--workspace","--json","--scope","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],artifact:t.workspaceRunLast,examples:["workspai workspace init --parallel --strict"]}};function bs(t){if(t)return ko[t]}function Id(t){return t[0]==="workspace"&&!!bs(t[1])&&t.slice(2).some(e=>e==="--help"||e==="-h")}function _d(t,e){let r=bs(e)?.flagDescriptions?.[t]??Ug[t];if(!r)throw new Error(`Workspace action flag has no description: ${t}`);return r}function Od(t){let e=bs(t);if(!e)throw new Error(`Unknown workspace action: ${t}`);let r=[`Workspai workspace ${t}`,"",e.summary,"","Usage:",` ${e.usage}`];if(e.subactions&&e.subactions.length>0&&r.push("","Modes:",` ${e.subactions.join(" | ")}`),e.flags.length>0){r.push("","Options:");for(let o of e.flags){let n=_d(o,t);r.push(` ${o.padEnd(24)} ${n}`.trimEnd());}}return e.artifact&&r.push("","Evidence:",` ${e.artifact}`),r.push("","Examples:",...e.examples.map(o=>` ${o}`),""),r.join(`
|
|
151
|
-
`)}var Nd="rapidkit-runtime-command-surface-v1";var js=s$1.doctorRemediationPlan.schemaVersion;var $d="workspai-workspace-intelligence-architecture-v1";var Td={autopilotRelease:s$1.autopilotReleaseLastRun.schemaVersion,workspaceList:"rapidkit-workspace-list-v1",workspaceSync:"rapidkit-workspace-sync-v1",compatibilityMatrix:s$1.compatibilityMatrix.schemaVersion,mcpDesign:s$1.workspaiMcpDesign.schemaVersion,agentHooks:s$1.agentHooks.schemaVersion,projectArchive:"rapidkit-project-archive-v1",workspaceSnapshot:"rapidkit-workspace-snapshot-v1",workspaceSnapshotV2:"rapidkit-workspace-snapshot-v2",infraPlan:s$1.infraPlan.schemaVersion,privateProductManifest:"rapidkit.private-product-manifest.v1",productFactoryPlan:"rapidkit.product-factory-plan.v1",workspaceModelCache:s$1.workspaceModelCache.schemaVersion,workspaceWatchEvent:"workspace-watch-event.v1",doctorProjectScan:"doctor-project-scan-v2",doctorWorkspaceCache:s$1.doctorWorkspaceCache.schemaVersion};var Md="project-workspace-resolution.v1";function Wd(t){a$4(t,"contracts/project-workspace-resolution.v1.json","Project workspace resolution");}var Cs="workspai.ingestion-plan.v1",Ln="workspai.ingestion-result.v1",Fn="workspai.adopt-effects.v1";var Dd="contracts/ingestion-result.v1.json";function Qt(t){return {schemaVersion:Cs,...t}}var Bg="workspai-published-contract-catalog-v1",Hg="workspace-graph-stream.v1";function vo(){return {workspaceContract:1,runtimeCommandSurface:Nd,cliRuntimeCommandInventory:vs,cliOperationResult:a$N,publishedContractCatalog:Bg,workspaceArchiveCapabilities:a$M,workspaceArchiveManifest:b$m,workspaceArchiveOperationResult:c$3,ingestionPlan:Cs,ingestionResult:Ln,adoptEffects:Fn,projectEntryCapability:Sd,projectWorkspaceLink:s$1.projectWorkspaceLink.schemaVersion,projectWorkspaceResolution:Md,projectContextAgent:s$1.projectContextAgent.schemaVersion,projectKnowledgeGraphReference:s$1.projectKnowledgeGraphReference.schemaVersion,projectAgentEntry:a$L,agentBootstrapReceipt:c$g,doctorProjectEvidence:b$l,doctorWorkspaceEvidence:a$K,doctorGraphDiagnosis:b$k,doctorDiagnosis:a$J,doctorCapabilities:a$I,doctorValidation:c$f,doctorReceipt:s$1.doctorReceipt.schemaVersion,doctorSummary:c$e,projectTestCoverage:s$1.projectTestCoverage.schemaVersion,verifiedGoal:"workspai.verified-goal.v1",verifiedGoalStatus:q.verifiedGoalStatus,goalPack:a$H,goalAgentHandoff:b$j,goalPlanResult:c$d,goalIndex:e$c,goalLifecycleResult:g$8,decisionEvent:f$5,decisionTransaction:e$b,decisionCheckpoint:g$7,changeOperationResult:l$3,architectureChangeLease:h$3,predictedArchitectureChange:i$2,architectureSurpriseReport:j$7,proofCarryingChangeCapsule:k$4,proofCarryingChangeList:m$4,proofCarryingChangeCapsuleValidation:n$3,proofCarryingChangeCapsuleExport:o$2,workspaceIntelligenceArchitecture:$d,workspaceIntelligenceChain:a$G,workspaceIntelligenceArtifacts:q,cliLogEvent:a$F,workspaceActivityEvent:a$E,workspaceActivityMonitorSnapshot:a$D,workspaceActivityMonitorFleet:b$i,workspaceActivityBoard:h$2,freshnessMetadata:c$c,factFreshness:e$a,blockerResolution:a$C,workspaceModel:l$2,workspaceImpact:f$4,workspaceVerify:c$b,workspaceContext:a$B,workspaceDependencyGraph:e$9,workspaceKnowledgeGraph:a$A,workspaceGraphStream:Hg,workspaceKnowledgeGraphChangeOverlay:a$z,workspaceKnowledgeSearch:a$y,workspaceGraphTokenEfficiency:a$x,workspaceIntelligenceBenchmark:a$w,modelUsageEvent:a$v,workspaceIntelligenceEvaluation:b$h,workspaceIntelligenceEvaluationComparison:c$a,workspaceIntelligenceHistory:a$u,agentCustomizationPackCapabilities:c$9,agentFrameworkCapabilities:v$3,agentFrameworkAdapterManifest:w$2,agentFrameworkConformanceReport:x$1,agentFrameworkConformanceReportLegacy:"workspai.agent-framework-conformance-report.v1",agentFrameworkChangePlan:y,agentFrameworkOwnershipReceipt:z,agentFrameworkAdmissionCandidate:A,agentFrameworkAdmissionCandidateLegacy:"workspai.agent-framework-admission-candidate.v1",agentCustomizationPackReport:q.agentCustomizationPack,agentReportsIndex:q.agentIndex,workspaceOperationalSkill:a$t,workspaceSkillsIndex:b$g,workspaceExplain:a$s,agentActionOutcome:a$r,doctorRemediationPlan:js,doctorDependencyRepairTransaction:"workspai.doctor-dependency-repair-transaction.v1",artifactRemediationPlan:a$q,studioCardRepairCapabilities:j$6,workspaceRepairProposal:e$8,workspaceRepairCapabilities:g$6,workspaceRepairTransaction:a$p,doctorFixResult:a$o,backendImportStackParitySnapshot:"backend-import-stack-parity-v1",bootstrapCompliance:s$1.bootstrapCompliance.schemaVersion,commandCapabilities:"rapidkit-command-capabilities-v1",createPlannerCapabilities:"rapidkit-create-planner-capabilities-v1",doctorRemediationPlanLegacy:js,extensionCliCompatibility:"rapidkit-extension-cli-compatibility.v1",infraStack:"rapidkit.infra-stack.v1",mirrorOps:s$1.mirrorOps.schemaVersion,moduleLayout:"rapidkit.module-layout.v1",moduleSupport:"rapidkit-module-support-v1",pipelineLastRun:s$1.pipelineLastRun.schemaVersion,transparencyEvidence:s$1.transparencyEvidence.schemaVersion,version:"rapidkit-version-v1",studioBlockerHandoff:"rapidkit-studio-blocker-handoff-v1",workspaceRegistry:s$1.workspaceRegistry.schemaVersion,workspaceRunLast:s$1.workspaceRunLast.schemaVersion,workspaceShareBundle:s$1.workspaceShareBundle.schemaVersion,...Td}}function Gn(){let t=vo(),e={workspaceContract:"contracts/workspace-contract.v1.json",runtimeCommandSurface:"contracts/runtime-command-surface.v1.json",cliRuntimeCommandInventory:"contracts/cli-runtime-command-inventory.v1.snapshot.json",cliOperationResult:"contracts/cli-operation-result.v1.json",publishedContractCatalog:"contracts/published-contract-catalog.v1.json",workspaceArchiveCapabilities:"contracts/workspace-archive-capabilities.v1.json",workspaceArchiveManifest:"contracts/workspace-archive-manifest.v1.json",workspaceArchiveOperationResult:"contracts/workspace-archive-operation-result.v1.json",ingestionPlan:"contracts/ingestion-plan.v1.json",ingestionResult:"contracts/ingestion-result.v1.json",adoptEffects:"contracts/adopt-effects.v1.json",projectEntryCapability:"contracts/project-entry-capability.v1.json",projectWorkspaceLink:"contracts/project-workspace-link.v1.json",projectWorkspaceResolution:"contracts/project-workspace-resolution.v1.json",projectContextAgent:"contracts/workspace-intelligence/project-context-agent.v1.json",projectKnowledgeGraphReference:"contracts/workspace-intelligence/project-knowledge-graph-reference.v1.json",projectAgentEntry:"contracts/workspace-intelligence/project-agent-entry.v1.json",agentBootstrapReceipt:"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json",doctorProjectEvidence:"contracts/doctor-project-evidence.v1.json",doctorWorkspaceEvidence:"contracts/doctor-workspace-evidence.v1.json",doctorGraphDiagnosis:"contracts/workspace-intelligence/doctor-graph-diagnosis.v1.json",doctorDiagnosis:"contracts/workspace-intelligence/doctor-diagnosis.v1.json",doctorCapabilities:"contracts/workspace-intelligence/doctor-capabilities.v1.json",doctorValidation:"contracts/workspace-intelligence/doctor-validation.v1.json",doctorReceipt:"contracts/workspace-intelligence/doctor-receipt.v1.json",doctorSummary:"contracts/workspace-intelligence/doctor-summary.v1.json",projectTestCoverage:"contracts/project-test-coverage.v1.json",verifiedGoal:"contracts/workspace-intelligence/verified-goal.v1.json",verifiedGoalStatus:"contracts/workspace-intelligence/verified-goal-status.v1.json",goalPack:"contracts/workspace-intelligence/goal-pack.v1.json",goalAgentHandoff:"contracts/workspace-intelligence/goal-agent-handoff.v1.json",goalPlanResult:"contracts/workspace-intelligence/goal-plan-result.v1.json",goalIndex:"contracts/workspace-intelligence/goal-index.v1.json",goalLifecycleResult:"contracts/workspace-intelligence/goal-lifecycle-result.v1.json",decisionEvent:"contracts/workspace-intelligence/decision-event.v1.json",decisionTransaction:"contracts/workspace-intelligence/decision-transaction.v1.json",decisionCheckpoint:"contracts/workspace-intelligence/decision-checkpoint.v1.json",changeOperationResult:"contracts/workspace-intelligence/change-operation-result.v1.json",architectureChangeLease:"contracts/workspace-intelligence/architecture-change-lease.v1.json",predictedArchitectureChange:"contracts/workspace-intelligence/predicted-architecture-change.v1.json",architectureSurpriseReport:"contracts/workspace-intelligence/architecture-surprise-report.v1.json",proofCarryingChangeCapsule:"contracts/workspace-intelligence/proof-carrying-change-capsule.v1.json",proofCarryingChangeList:"contracts/workspace-intelligence/proof-carrying-change-list.v1.json",proofCarryingChangeCapsuleValidation:"contracts/workspace-intelligence/proof-carrying-change-capsule-validation.v1.json",proofCarryingChangeCapsuleExport:"contracts/workspace-intelligence/proof-carrying-change-capsule-export.v1.json",workspaceIntelligenceArchitecture:"contracts/workspace-intelligence-architecture.v1.json",workspaceIntelligenceChain:"contracts/workspace-intelligence-chain.v1.json",workspaceIntelligenceArtifacts:null,cliLogEvent:"contracts/cli-log-event.v1.json",workspaceActivityEvent:"contracts/workspace-activity-event.v1.json",workspaceActivityMonitorSnapshot:"contracts/workspace-activity-monitor-snapshot.v1.json",workspaceActivityMonitorFleet:"contracts/workspace-activity-monitor-fleet.v1.json",workspaceActivityBoard:"contracts/workspace-activity-board.v1.json",freshnessMetadata:null,factFreshness:"contracts/workspace-intelligence/fact-freshness.v1.json",blockerResolution:"contracts/workspace-intelligence/blocker-resolution.v1.json",workspaceModel:"contracts/workspace-intelligence/workspace-model.v1.json",workspaceImpact:"contracts/workspace-intelligence/workspace-impact.v1.json",workspaceVerify:"contracts/workspace-intelligence/workspace-verify.v1.json",workspaceContext:"contracts/workspace-intelligence/workspace-context.v1.json",workspaceDependencyGraph:"contracts/workspace-intelligence/workspace-dependency-graph.v1.json",workspaceKnowledgeGraph:"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json",workspaceGraphStream:"contracts/workspace-intelligence/workspace-graph-stream.v1.json",workspaceKnowledgeGraphChangeOverlay:"contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json",workspaceKnowledgeSearch:"contracts/workspace-intelligence/workspace-knowledge-search.v1.json",workspaceGraphTokenEfficiency:"contracts/workspace-intelligence/workspace-graph-token-efficiency.v1.json",workspaceIntelligenceBenchmark:"contracts/workspace-intelligence/workspace-intelligence-benchmark.v1.json",modelUsageEvent:"contracts/workspace-intelligence/model-usage-event.v1.json",workspaceIntelligenceEvaluation:"contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",workspaceIntelligenceEvaluationComparison:"contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",workspaceIntelligenceHistory:"contracts/workspace-intelligence/workspace-intelligence-history.v1.json",agentCustomizationPackCapabilities:"contracts/agent-customization-pack.v1.json",agentFrameworkCapabilities:"contracts/agent-framework-capabilities.v1.json",agentFrameworkAdapterManifest:"contracts/workspace-intelligence/agent-framework-adapter-manifest.v1.json",agentFrameworkConformanceReport:"contracts/workspace-intelligence/agent-framework-conformance-report.v2.json",agentFrameworkConformanceReportLegacy:"contracts/workspace-intelligence/agent-framework-conformance-report.v1.json",agentFrameworkChangePlan:"contracts/workspace-intelligence/agent-framework-change-plan.v1.json",agentFrameworkOwnershipReceipt:"contracts/workspace-intelligence/agent-framework-ownership-receipt.v1.json",agentFrameworkAdmissionCandidate:"contracts/workspace-intelligence/agent-framework-admission-candidate.v2.json",agentFrameworkAdmissionCandidateLegacy:"contracts/workspace-intelligence/agent-framework-admission-candidate.v1.json",agentCustomizationPackReport:"contracts/workspace-intelligence/agent-customization-pack-report.v1.json",agentReportsIndex:"contracts/workspace-intelligence/agent-reports-index.v1.json",workspaceOperationalSkill:"contracts/workspace-intelligence/workspace-operational-skill.v1.json",workspaceSkillsIndex:"contracts/workspace-intelligence/workspace-skills-index.v1.json",workspaceExplain:"contracts/workspace-intelligence/workspace-explain.v1.json",agentActionOutcome:"contracts/workspace-intelligence/agent-action-outcome.v1.json",doctorRemediationPlan:"contracts/doctor-remediation-plan.v2.json",doctorDependencyRepairTransaction:"contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json",artifactRemediationPlan:"contracts/artifact-remediation-plan.v1.json",studioCardRepairCapabilities:"contracts/studio-card-repair-capabilities.v1.json",workspaceRepairProposal:"contracts/workspace-intelligence/workspace-repair-proposal.v1.json",workspaceRepairCapabilities:"contracts/workspace-repair-capabilities.v1.json",workspaceRepairTransaction:"contracts/workspace-intelligence/workspace-repair-transaction.v1.json",doctorFixResult:"contracts/workspace-intelligence/doctor-fix-result.v1.json",backendImportStackParitySnapshot:"contracts/backend-import-stack-parity.snapshot.json",bootstrapCompliance:"contracts/bootstrap-compliance.v1.json",commandCapabilities:"contracts/command-capabilities.v1.json",createPlannerCapabilities:"contracts/create-planner-capabilities.v1.json",doctorRemediationPlanLegacy:"contracts/doctor-remediation-plan.v1.json",extensionCliCompatibility:"contracts/extension-cli-compatibility.v1.json",infraStack:"contracts/infra-stack.v1.json",mirrorOps:"contracts/mirror-ops.v1.json",moduleLayout:"contracts/module-layout.v1.json",moduleSupport:"contracts/module-support.v1.json",pipelineLastRun:"contracts/pipeline-last-run.v1.json",transparencyEvidence:"contracts/transparency-evidence.v1.json",version:"contracts/version.v1.json",studioBlockerHandoff:"contracts/workspace-intelligence/studio-blocker-handoff.v1.json",workspaceRegistry:"contracts/workspace-registry.v1.json",workspaceRunLast:"contracts/workspace-run-last.v1.json",workspaceShareBundle:"contracts/workspace-share-bundle.v1.json",autopilotRelease:"contracts/autopilot-release.v1.json",workspaceList:"contracts/workspace-list.v1.json",workspaceSync:"contracts/workspace-sync.v1.json",compatibilityMatrix:"contracts/compatibility-matrix.v1.json",mcpDesign:"contracts/workspace-intelligence/mcp-design.v1.json",agentHooks:"contracts/workspace-intelligence/agent-hooks.v1.json",projectArchive:"contracts/project-archive.v1.json",workspaceSnapshot:"contracts/workspace-snapshot.v1.json",workspaceSnapshotV2:"contracts/workspace-snapshot.v2.json",infraPlan:"contracts/infra-plan.v1.json",privateProductManifest:"contracts/private-product-manifest.v1.json",productFactoryPlan:"contracts/product-factory-plan.v1.json",workspaceModelCache:"contracts/workspace-model-cache.v1.json",workspaceWatchEvent:"contracts/workspace-watch-event.v1.json",doctorProjectScan:"contracts/doctor-project-scan.v2.json",doctorWorkspaceCache:"contracts/doctor-workspace-cache.v2.json"};return Object.fromEntries(Object.entries(t).map(([r$1,o])=>{let n=e[r$1];return [r$1,{schemaVersion:o,contractPath:n,publication:n?r$1==="runtimeCommandSurface"||r$1==="cliRuntimeCommandInventory"||r$1.endsWith("Capabilities")||r$1.endsWith("Snapshot")||r$1==="extensionCliCompatibility"||r$1==="moduleLayout"||r$1==="moduleSupport"?"capability-contract":"json-schema":"embedded-type",...r$1==="workspaceIntelligenceArtifacts"?{artifacts:Object.fromEntries(Object.keys(p).map(a=>[a,{path:p[a],schemaVersion:q[a],contractPath:r[a]}]))}:{}}]}))}var Es="rapidkit-command-capabilities-v1",Ld="rapidkit-version-v1";var qg=["catalog","pulse","nova","orbit","atlas","vertex","summit","beacon","ledger","flux","nexus","apex","harbor","forge","spark","portal","studio","canvas","quantum","vault","zenith","compass","vector","catalyst","saas","commerce","radar","stellar","prism","cedar","momentum","signal","cipher","lumen","trail","ridge"],zg={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},Yg={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"},Xg={tauri:"desktop",electron:"desktop","vscode-extension":"extension",laravel:"api"};function Qg(t){return t[Math.floor(Math.random()*t.length)]}function Ss(t){let e=Qg(qg),r=l$5(t);if(r){let c=Yg[r.id]??"app";return `${e}-${c}`}let o=r$2(t);if(o)return `${e}-${Xg[o.id]??"app"}`;if(R(t))return `${e}-gateway`;let a=a$3(t),i=a?zg[a.id]??"service":"app";return `${e}-${i}`}async function rf(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function of(t){if(!await M.pathExists(t))return [];let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(o)for(let n of await promises.readdir(o,{withFileTypes:true})){let a=b.join(o,n.name);n.isFile()?e.push(a):n.isDirectory()&&r.push(a);}}return e}async function Gd(t,e){await M.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
150
|
+
${r.stderr||""}`);return o?this.isMavenVersionAtLeast(o,[3,9,0])?{exitCode:0}:{exitCode:1,message:`Maven ${o.join(".")} detected; Maven 3.9+ is required.`}:{exitCode:1,message:"Unable to parse Maven version. Ensure Maven 3.9+ is installed and retry."}}catch{return {exitCode:1,message:"Maven version check failed. Install Maven 3.9+ and ensure mvn is on PATH."}}}shouldUseGradleNoDaemon(){return process.env.CI==="true"||process.env.RAPIDKIT_GRADLE_NO_DAEMON==="1"}inspectJavaProject(e){let r=$.existsSync(b.join(e,"pom.xml")),o=$.existsSync(b.join(e,"mvnw"))||$.existsSync(b.join(e,"mvnw.cmd")),n=$.existsSync(b.join(e,"build.gradle"))||$.existsSync(b.join(e,"build.gradle.kts"))||$.existsSync(b.join(e,"settings.gradle"))||$.existsSync(b.join(e,"settings.gradle.kts")),a=$.existsSync(b.join(e,"gradlew"))||$.existsSync(b.join(e,"gradlew.bat"));return {hasMavenProject:r||o,hasMavenWrapper:o,hasGradleProject:n||a,hasGradleWrapper:a}}findWorkspaceRoot(e){let r=e;for(;;){if($.existsSync(b.join(r,".workspai-workspace"))||$.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=t$1(o,"policies.yml").find(a=>$.existsSync(a));if(!n)return "isolated";try{let c=$.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}buildToolCommand(e){return this.isGradleProject(e)?this.gradleCommand(e):this.mavenCommand(e)}mavenCommand(e){let r=b.join(e,"mvnw.cmd");if(process.platform==="win32"&&$.existsSync(r))return {command:r,baseArgs:[]};let o=b.join(e,"mvnw");return $.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"mvn",baseArgs:[]}}gradleCommand(e){let r=b.join(e,"gradlew.bat");if(process.platform==="win32"&&$.existsSync(r))return {command:r,baseArgs:[]};let o=b.join(e,"gradlew");return $.existsSync(o)?this.ensureWrapperExecutable(o)?{command:o,baseArgs:[]}:{command:"sh",baseArgs:[o]}:{command:"gradle",baseArgs:[]}}isGradleProject(e){return this.inspectJavaProject(e).hasGradleProject}isMavenProject(e){return this.inspectJavaProject(e).hasMavenProject}discoverWorkspaceJavaProjects(e){let r=[],o=new Set,n=[e];for(;n.length>0;){let a=n.shift();if(!a||o.has(a))continue;o.add(a);let i=[];try{i=$.readdirSync(a,{withFileTypes:true});}catch{continue}for(let c of i){if(!c.isDirectory()||c.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(c.name))continue;let l=b.join(a,c.name),p=this.inspectJavaProject(l);(p.hasMavenProject||p.hasGradleProject)&&r.push(l),n.push(l);}}return r}withJavaCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","m2"):b.join(e,".workspai","cache","java","m2"),i=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","java","gradle"):b.join(e,".workspai","cache","java","gradle"),c=process.env.MAVEN_OPTS,l=process.env.GRADLE_USER_HOME,p=`-Dmaven.repo.local=${a}`;return process.env.MAVEN_OPTS=c?`${c} ${p}`:p,process.env.GRADLE_USER_HOME=i,r().finally(()=>{typeof c>"u"?delete process.env.MAVEN_OPTS:process.env.MAVEN_OPTS=c,typeof l>"u"?delete process.env.GRADLE_USER_HOME:process.env.GRADLE_USER_HOME=l;})}async runBuildTool(e,r,o=true){return this.withJavaCacheEnv(e,async()=>{try{let{command:n,baseArgs:a}=this.buildToolCommand(e),i=await this.runCommand(n,[...a,...r],e);if(i===0||!o)return {exitCode:i};let c=$.existsSync(b.join(e,"pom.xml")),l=$.existsSync(b.join(e,"build.gradle"))||$.existsSync(b.join(e,"build.gradle.kts"));return {exitCode:i,message:c||l?"Java build failed. Verify pom.xml/build.gradle syntax and dependencies, then retry.":"Java build tool is not installed or not available on PATH. Install Maven/Gradle and JDK 21+, or commit mvnw/gradlew wrapper scripts."}}catch(n){return {exitCode:1,message:`Java command execution failed: ${n instanceof Error?n.message:String(n)}. Verify pom.xml/build.gradle integrity and wrapper permissions.`}}})}resolveJarPath(e){let r=[b.join(e,"target"),b.join(e,"build","libs")];for(let o of r){if(!$.existsSync(o))continue;let a=$.readdirSync(o).filter(i=>i.toLowerCase().endsWith(".jar")).find(i=>!i.toLowerCase().endsWith("-sources.jar")&&!i.toLowerCase().endsWith("-javadoc.jar")&&!i.toLowerCase().endsWith("-plain.jar"));if(a)return b.join(o,a)}return null}commandArgsFor(e,r){if(e==="gradle"){let o=this.shouldUseGradleNoDaemon()?["--no-daemon"]:[];return r==="init"?[...o,"dependencies"]:r==="dev"?[...o,"bootRun"]:r==="test"?[...o,"test"]:[...o,"bootJar"]}return r==="init"?["-B","-q","-DskipTests","dependency:go-offline"]:r==="dev"?["spring-boot:run"]:r==="test"?["test"]:["-DskipTests","package"]}detectBuildTool(e){return this.isGradleProject(e)?"gradle":"maven"}async checkPrereqs(){let e=process.cwd(),r=this.resolveJavaCommand(e),o=await this.runCommand(r,["-version"],e);if(o!==0)return {exitCode:o,message:"JDK 21+ is required. Ensure java is on PATH or JAVA_HOME/bin/java is available."};if(this.isMavenProject(e)){let c=this.readRequiredJavaMajor(e),l=await this.detectInstalledJavaMajor(r,e);if(l!==null&&l<c)return {exitCode:1,message:`Detected Java ${l}, but project requires Java ${c}+.`};let p=b.join(process.env.JAVA_HOME||"","release");if(process.env.JAVA_HOME&&$.existsSync(p))try{let u=$.readFileSync(p,"utf-8").match(/^JAVA_VERSION="([^"]+)"/m),f=this.parseMajorJavaVersion(u?.[1]);if(f!==null&&f<c)return {exitCode:1,message:`Detected JAVA_HOME version ${f}, but project requires Java ${c}+.`}}catch{}}if(this.isMavenProject(e)||this.isGradleProject(e)){let c=this.detectBuildTool(e),l=c==="gradle"?["--version"]:["-version"],p=await this.runBuildTool(e,l);return p.exitCode!==0?p:c==="maven"&&!this.inspectJavaProject(e).hasMavenWrapper?this.checkSystemMavenVersion(e):p}let n=this.findWorkspaceRoot(e);if(n&&n===e){let c=this.discoverWorkspaceJavaProjects(n);if(c.length>0){let l=c.reduce((u,f)=>Math.max(u,this.readRequiredJavaMajor(f)),0);if(l>0){let u=await this.detectInstalledJavaMajor(r,e);if(u!==null&&u<l){let f=c.filter(P=>this.readRequiredJavaMajor(P)>u).map(P=>b.relative(e,P)).join(", ");return {exitCode:1,message:`Detected Java ${u}, but workspace project(s) [${f}] require Java ${l}+.`}}}let p=false,m=false;for(let u of c){let f=this.inspectJavaProject(u);f.hasMavenProject&&!f.hasMavenWrapper&&(p=true),f.hasGradleProject&&!f.hasGradleWrapper&&(m=true);}if(p){let u=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(u!==0)return {exitCode:u,message:"Maven is required for one or more workspace Java projects without Maven Wrapper. Install Maven 3.9+, or add mvnw/mvnw.cmd to those projects."};let f=await this.checkSystemMavenVersion(e);if(f.exitCode!==0)return f}if(m){let u=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));if(u!==0)return {exitCode:u,message:"Gradle is required for one or more workspace Java projects without Gradle Wrapper. Install Gradle 8+, or add gradlew/gradlew.bat to those projects."}}return {exitCode:0}}}let a=await this.withJavaCacheEnv(e,async()=>this.runCommand("mvn",["-version"],e));if(a===0){let c=await this.checkSystemMavenVersion(e);return c.exitCode!==0?c:{exitCode:0}}let i=await this.withJavaCacheEnv(e,async()=>this.runCommand("gradle",["--version"],e));return i===0?{exitCode:0}:{exitCode:a||i||1,message:"Neither Maven nor Gradle is available on PATH. Install one of them, or use mvnw/gradlew wrappers in project roots."}}async warmSetupCache(e){return this.withJavaCacheEnv(e,async()=>{try{let r=process.env.MAVEN_OPTS?.match(/-Dmaven\.repo\.local=([^\s]+)/)?.[1];return r&&$.mkdirSync(r,{recursive:true}),process.env.GRADLE_USER_HOME&&$.mkdirSync(process.env.GRADLE_USER_HOME,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Java cache directories"}}})}async initProject(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"init"))}async runDev(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"dev"))}async runTest(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"test"))}async runBuild(e){return this.runBuildTool(e,this.commandArgsFor(this.detectBuildTool(e),"build"))}async runStart(e){let r=this.resolveJarPath(e);if(r)return {exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",r],e)};let o=await this.runBuild(e);if(o.exitCode!==0)return o;let n=this.resolveJarPath(e);return n?{exitCode:await this.runCommand(this.resolveJavaCommand(e),["-jar",n],e)}:{exitCode:1,message:"Spring Boot build completed, but no runnable JAR was found under target/ or build/libs/. Verify build output naming and packaging plugins."}}async runLint(e){if(w$4(e,"lint"))return {exitCode:await this.runCommand("make",["lint"],e)};let r=b.join(e,"pom.xml");if($.existsSync(r)){let o=$.readFileSync(r,"utf-8");if(o.includes("spotless-maven-plugin"))return this.runBuildTool(e,["spotless:check"]);if(o.includes("checkstyle"))return this.runBuildTool(e,["checkstyle:check"])}return {exitCode:1,message:"No Java lint tooling detected. Add a Makefile lint target or configure checkstyle in Maven/Gradle."}}async runFormat(e){if(w$4(e,"format"))return {exitCode:await this.runCommand("make",["format"],e)};let r=b.join(e,"pom.xml");return $.existsSync(r)&&$.readFileSync(r,"utf-8").includes("spotless-maven-plugin")?this.runBuildTool(e,["spotless:apply"]):["build.gradle","build.gradle.kts"].map(n=>b.join(e,n)).filter(n=>$.existsSync(n)).some(n=>$.readFileSync(n,"utf-8").includes("spotless"))?this.runBuildTool(e,["spotlessApply"]):{exitCode:1,message:"No Java format tooling detected. Add a Makefile format target or configure Spotless in Maven/Gradle."}}async doctorHints(e){return ["Install JDK 21+ and Maven/Gradle (or commit mvnw/gradlew wrappers) for reliable local builds.","Run npx workspai init after dependency changes to warm Java caches for your build tool.","Use SPRING_PROFILES_ACTIVE to switch environments without changing source config."]}};var xn=class{constructor(e){this.runCommand=e;}runCommand;runtime="node";async run(e,r,o){return {exitCode:await this.runCommand(e,r,o)}}findWorkspaceRoot(e){let r=e;for(;;){if($.existsSync(b.join(r,".workspai-workspace"))||$.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=t$1(o,"policies.yml").find(a=>$.existsSync(a));if(!n)return "isolated";try{let c=$.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withDependencyEnv(e,r,o){let n=this.resolveDependencyMode(e),a=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),i=n==="isolated"?b.join(e,".workspai","cache","node"):b.join(a||e,".workspai","cache","node"),c=process.env.npm_config_cache,l=process.env.npm_config_store_dir,p=process.env.BUN_INSTALL_CACHE_DIR,m=process.env.RAPIDKIT_DEP_SHARING_MODE,u=process.env.RAPIDKIT_WORKSPACE_PATH;return process.env.RAPIDKIT_DEP_SHARING_MODE=n,a&&(process.env.RAPIDKIT_WORKSPACE_PATH=a),r==="bun"?process.env.BUN_INSTALL_CACHE_DIR=b.join(i,"bun-cache"):r==="pnpm"?(process.env.npm_config_store_dir=b.join(i,"pnpm-store"),process.env.npm_config_cache=b.join(i,"pnpm-cache")):r==="yarn"?process.env.npm_config_cache=b.join(i,"yarn-cache"):process.env.npm_config_cache=b.join(i,"npm-cache"),o().finally(()=>{typeof c>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=c,typeof l>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=l,typeof p>"u"?delete process.env.BUN_INSTALL_CACHE_DIR:process.env.BUN_INSTALL_CACHE_DIR=p,typeof m>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=m,typeof u>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=u;})}detectPackageManager(e){if($.existsSync(b.join(e,"bun.lock"))||$.existsSync(b.join(e,"bun.lockb")))return "bun";if($.existsSync(b.join(e,"package-lock.json")))return "npm";if($.existsSync(b.join(e,"pnpm-lock.yaml")))return "pnpm";if($.existsSync(b.join(e,"yarn.lock")))return "yarn";if(!this.commandAvailable("npm")){if(this.commandAvailable("pnpm"))return "pnpm";if(this.commandAvailable("yarn"))return "yarn"}return "npm"}hasPinnedPackageManager(e){return $.existsSync(b.join(e,"package-lock.json"))||$.existsSync(b.join(e,"bun.lock"))||$.existsSync(b.join(e,"bun.lockb"))||$.existsSync(b.join(e,"pnpm-lock.yaml"))||$.existsSync(b.join(e,"yarn.lock"))}availablePackageManagers(e){let r=this.detectPackageManager(e);return this.hasPinnedPackageManager(e)?[r]:[r,...["npm","pnpm","yarn","bun"].filter(n=>n!==r&&this.commandAvailable(n))]}commandAvailable(e){let r=e$f(e);return spawnSync(r.command,[...r.prefixArgs,"--version"],{stdio:"ignore",shell:c$i(),env:g$a()}).status===0}scriptArgs(e,r){return e==="npm"?["run-script",r,"--foreground-scripts"]:["run",r]}async runScriptWithFallback(e,r){let o={exitCode:1};for(let n of this.availablePackageManagers(e))if(o=await this.withDependencyEnv(e,n,()=>this.run(n,this.scriptArgs(n,r),e)),o.exitCode===0)return o;return {...o,message:o.message??`Node lifecycle script failed. Re-run \`${z$1(e,r)}\` in ${e} to inspect the native tool output.`}}async runLifecycle(e,r){let o=j$2(e),n=m$2(e,o),a=u$2(e,r,{framework:n.key});return a?this.runScriptWithFallback(e,a.scriptName):{exitCode:1,message:`No npm script available for \`${r}\`. Add a "${r}" script to package.json.`}}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(e){let r=this.detectPackageManager(e);return this.withDependencyEnv(e,r,async()=>{try{return process.env.npm_config_cache&&$.mkdirSync(process.env.npm_config_cache,{recursive:true}),r==="pnpm"&&process.env.npm_config_store_dir&&$.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(e){let r=this.detectPackageManager(e),o=this.resolveDependencyMode(e),n=o==="shared-runtime-caches"||o==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(e,r,()=>this.run(r,n,e))}async runDev(e){return this.runLifecycle(e,"dev")}async runTest(e){return this.runLifecycle(e,"test")}async runBuild(e){return this.runLifecycle(e,"build")}async runStart(e){return this.runLifecycle(e,"start")}async runLint(e){return this.runLifecycle(e,"lint")}async runFormat(e){return this.runLifecycle(e,"format")}async doctorHints(e){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var _n=class{constructor(e){this.runCore=e;}runCore;runtime="python";async run(e,r){return {exitCode:await this.withPythonCacheEnv(r,()=>this.runCore(e,r))}}findWorkspaceRoot(e){let r=e;for(;;){if($.existsSync(b.join(r,".workspai-workspace"))||$.existsSync(b.join(r,".rapidkit-workspace")))return r;let o=b.dirname(r);if(o===r)break;r=o;}return null}resolveDependencyMode(e){let r=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(r==="shared-runtime-caches"||r==="shared-node-deps"||r==="isolated")return r;let o=this.findWorkspaceRoot(e);if(!o)return "isolated";let n=t$1(o,"policies.yml").find(a=>$.existsSync(a));if(!n)return "isolated";try{let c=$.readFileSync(n,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(c==="shared-runtime-caches"||c==="shared-node-deps"||c==="isolated")return c}catch{}return "isolated"}withPythonCacheEnv(e,r){let o=this.resolveDependencyMode(e),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(e),a=o==="shared-runtime-caches"?b.join(n||e,".workspai","cache","python"):b.join(e,".workspai","cache","python"),i=process.env.PIP_CACHE_DIR,c=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=b.join(a,"pip"),process.env.POETRY_CACHE_DIR=b.join(a,"poetry"),r().finally(()=>{typeof i>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=i,typeof c>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=c;})}async checkPrereqs(){let e=process.cwd(),r=await this.run(["doctor","check"],e);return r.exitCode===0?r:this.run(["doctor"],e)}async initProject(e){return this.run(["init"],e)}async runDev(e){return this.run(["dev"],e)}async runTest(e){return this.run(["test"],e)}async runBuild(e){return this.run(["build"],e)}async runStart(e){return this.run(["start"],e)}async doctorHints(e){return ['Run "npx workspai doctor workspace" for a full workspace scan.','Use "npx workspai init" after adding or changing modules.',"Use `npx workspai <command>` from the project root to avoid environment drift."]}};var On=class{constructor(e){this.runCommand=e;}runCommand;runtime="php";async run(e,r,o){let n=await this.runCommand(e,r,o);return n===0?{exitCode:n}:{exitCode:n,message:`PHP lifecycle command failed (${e} ${r.join(" ")}). Ensure ${e} is available on PATH, then review composer.json and the command diagnostics above.`}}hasComposer(e){return $.existsSync(b.join(e,"composer.json"))}hasArtisan(e){return $.existsSync(b.join(e,"artisan"))}hasComposerScript(e,r){try{let o=JSON.parse($.readFileSync(b.join(e,"composer.json"),"utf8"));return !!o.scripts&&Object.prototype.hasOwnProperty.call(o.scripts,r)}catch{return false}}missingManifest(){return {exitCode:1,message:"composer.json was not found. Run the command from a PHP project root."}}unsupported(e){return {exitCode:1,message:`No deterministic PHP ${e} command was detected. Add a "${e}" Composer script or the expected Laravel tooling.`}}async checkPrereqs(){let e=await this.run("php",["--version"],process.cwd());return e.exitCode!==0?e:this.run("composer",["--version"],process.cwd())}async initProject(e){return this.hasComposer(e)?this.run("composer",["install","--no-interaction"],e):this.missingManifest()}async runDev(e){return this.hasComposerScript(e,"dev")?this.run("composer",["run-script","dev"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("dev")}async runTest(e){return this.hasArtisan(e)?this.run("php",["artisan","test"],e):this.hasComposerScript(e,"test")?this.run("composer",["run-script","test"],e):this.unsupported("test")}async runBuild(e){return this.hasComposerScript(e,"build")?this.run("composer",["run-script","build"],e):this.unsupported("build")}async runStart(e){return this.hasComposerScript(e,"start")?this.run("composer",["run-script","start"],e):this.hasArtisan(e)?this.run("php",["artisan","serve"],e):this.unsupported("start")}async runLint(e){for(let r of ["lint","analyse","analyze"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return this.unsupported("lint")}async runFormat(e){for(let r of ["format","fmt"])if(this.hasComposerScript(e,r))return this.run("composer",["run-script",r],e);return $.existsSync(b.join(e,"vendor","bin","pint"))||$.existsSync(b.join(e,"pint.json"))?this.run("php",["vendor/bin/pint"],e):this.unsupported("format")}async doctorHints(e){return ["Install a supported PHP release and Composer, then keep both on PATH.","Commit composer.lock for deterministic application installs.","Expose test, lint, format, and build commands as Composer scripts when the framework does not provide them."]}};var Nn=class{constructor(e){this.runCommand=e;}runCommand;runtime="rust";async run(e,r){let o=await this.runCommand("cargo",e,r);return o===0?{exitCode:o}:{exitCode:o,message:`Cargo command failed (cargo ${e.join(" ")}). Ensure the stable Rust toolchain and cargo are available on PATH, then review Cargo.toml and the command diagnostics above.`}}hasManifest(e){return $.existsSync(b.join(e,"Cargo.toml"))}missingManifest(){return {exitCode:1,message:"Cargo.toml was not found. Run the command from a Rust project root."}}async checkPrereqs(){return this.run(["--version"],process.cwd())}async initProject(e){return this.hasManifest(e)?this.run(["fetch"],e):this.missingManifest()}async runDev(e){return this.hasManifest(e)?this.run(["run"],e):this.missingManifest()}async runTest(e){return this.hasManifest(e)?this.run(["test","--all-targets"],e):this.missingManifest()}async runBuild(e){return this.hasManifest(e)?this.run(["build","--release"],e):this.missingManifest()}async runStart(e){return this.hasManifest(e)?this.run(["run","--release"],e):this.missingManifest()}async runLint(e){return this.hasManifest(e)?this.run(["clippy","--all-targets","--all-features","--","-D","warnings"],e):this.missingManifest()}async runFormat(e){return this.hasManifest(e)?this.run(["fmt","--all"],e):this.missingManifest()}async doctorHints(e){return ["Install the Rust toolchain with rustup and ensure cargo is on PATH.","Use Cargo.lock for deterministic application builds.","Install rustfmt and clippy components for format and lint lifecycle commands."]}};function Og(){let t={...process.env},e=t.PATH||"";if(e){let r=e.split(b.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter);t.PATH=r;}return t.PYENV_VERSION="system",t.POETRY_PYTHON=t.POETRY_PYTHON||i$4(),typeof t.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t}function Ze(t,e){return t==="go"?new An((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="node"?new xn((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="java"?new Rn((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="dotnet"?new Sn((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="rust"?new Nn((r,o,n)=>e.runCommandInCwd(r,o,n)):t==="php"?new On((r,o,n)=>e.runCommandInCwd(r,o,n)):new _n((r,o)=>e.runCoreRapidkit(r,{cwd:o,env:Og()}))}var vd=b.join(Ma.homedir(),".workspai","cache"),Pd=1440*60*1e3;function ks(){let t=f$3("CACHE_DIR");if(t)return t;let e=process.env.VITEST_WORKER_ID?.trim();return e?b.join(vd,`vitest-${e}`):vd}var Tn=class t{static instance;memoryCache=new Map;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getCacheKey(e){return createHash("md5").update(e).digest("hex")}getCachePath(e){return b.join(ks(),`${this.getCacheKey(e)}.json`)}getTempCachePath(e){let r=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return `${e}.${r}.tmp`}async get(e$1,r="1.0"){let o=this.memoryCache.get(e$1);if(o&&o.version===r&&Date.now()-o.timestamp<Pd)return e.debug(`Cache hit (memory): ${e$1}`),o.data;try{let n=this.getCachePath(e$1),a=await promises.readFile(n,"utf-8"),i=JSON.parse(a);if(i.version===r&&Date.now()-i.timestamp<Pd)return e.debug(`Cache hit (disk): ${e$1}`),this.memoryCache.set(e$1,i),i.data;await promises.unlink(n).catch(()=>{});}catch{e.debug(`Cache miss: ${e$1}`);}return null}async set(e$1,r,o="1.0"){let n={data:r,timestamp:Date.now(),version:o};this.memoryCache.set(e$1,n);try{await promises.mkdir(ks(),{recursive:true});let a=this.getCachePath(e$1),i=this.getTempCachePath(a);await promises.writeFile(i,JSON.stringify(n),"utf-8"),await promises.rename(i,a),e.debug(`Cache set: ${e$1}`);}catch(a){e.debug(`Cache write failed: ${e$1}`,a);}}async invalidate(e$1){this.memoryCache.delete(e$1);try{let r=this.getCachePath(e$1);await promises.unlink(r),e.debug(`Cache invalidated: ${e$1}`);}catch{}}async clear(){this.memoryCache.clear();try{let e$1=ks(),r=await promises.readdir(e$1);await Promise.all(r.map(o=>promises.unlink(b.join(e$1,o)))),e.debug("Cache cleared");}catch{}}};function bd(t){let e=C(t);return e?`Workspai project found at ${e}, but no Python virtual environment or activation script is available.`:"No Workspai project metadata, Python virtual environment, or activation script was found in this directory or its parents."}async function jd(t){let e=b.resolve(t),r=v$2(e,"project.json");if(!await M__default.pathExists(r))return false;let o=await Ps(r);if(!o)return false;let n=typeof o.kit_name=="string"&&o.kit_name||typeof o.kit=="string"&&o.kit||void 0,a=a$3(n);if(!a||a.owner!=="core")return false;let i=Ce(o.name)||b.basename(e),c=await Wg(e),l=v$2(e,"context.json"),p=await Ps(l)??{},m=await Dg({kit:a,projectRoot:e,existingContextEngine:p.engine,pythonProjectEngine:c}),u=Mg(o),f=Ce(o.generated_at)||Ce(o.created_at)||new Date().toISOString(),P={...o,schema_version:Ce(o.schema_version)??o.schema_version??"1.0",name:Ce(o.name)||i,slug:Ce(o.slug)||i,kind:Ce(o.kind)||a.category,project_type:Ce(o.project_type)||a.category,category:Ce(o.category)||a.category,runtime:Ce(o.runtime)||a.runtime,framework:Ce(o.framework)||a.framework,kit_name:a.id,kit:Ce(o.kit)||a.id,engine:a.runtime==="node"?Ce(o.engine)==="npm"?o.engine:"npm":c||(ro(o.engine)?o.engine:m),module_support:typeof o.module_support=="boolean"?o.module_support:a.moduleSupport,workspai_version:Ce(o.workspai_version)||h(),generated_by:Ce(o.generated_by)||"workspai",generated_at:f,generator:o.generator??{id:a.id,source:"rapidkit-core-bridge",official:false}};u&&P.rapidkit_core_version===void 0&&(P.rapidkit_core_version=u);let y={...p,engine:m,project:Ce(p.project)||i,kind:Ce(p.kind)||a.category,category:Ce(p.category)||a.category,runtime:Ce(p.runtime)||a.runtime,framework:Ce(p.framework)||a.framework,source:Ce(p.source)||"core-bridge"};return await M__default.ensureDir(b.dirname(r)),await M__default.writeJson(r,P,{spaces:2}),await M__default.writeJson(l,y,{spaces:2}),true}function Ce(t){return typeof t=="string"&&t.trim()?t:void 0}function Mg(t){if(typeof t.rapidkit_core_version=="string"&&t.rapidkit_core_version.trim())return t.rapidkit_core_version;let e=Ce(t.generated_by),r=Ce(t.created_by),o=Ce(t.rapidkit_version);if(o&&!(e==="workspai"||r==="workspai-cli-fallback")&&!t.schema_version)return o}async function Wg(t){let e=b.join(t,"pyproject.toml");if(await M__default.pathExists(e)){let r=await M__default.readFile(e,"utf8");if(/\[tool\.poetry\]/.test(r))return "poetry";if(/\[tool\.uv\]/.test(r))return "uv"}if(await M__default.pathExists(b.join(t,"uv.lock")))return "uv";if(await M__default.pathExists(b.join(t,"requirements.txt")))return "pip"}async function Dg(t){if(t.kit.runtime==="python")return t.pythonProjectEngine||vs(t.existingContextEngine)||"pip";let e=vs(t.existingContextEngine,{allowPip:false});if(e)return e;let r=await Lg(t.projectRoot);return r||vs(t.existingContextEngine)||"pip"}function vs(t,e={}){if(ro(t)&&!(e.allowPip===false&&(t==="pip"||t==="python")))return t}async function Lg(t){let e=b.resolve(t);for(;;){for(let o of [c$j,d$a]){let n=b.join(e,o);if(!$.existsSync(n))continue;let c=(await Ps(n))?.metadata?.npm?.installMethod;if(c==="poetry"||c==="venv"||c==="pipx")return c}let r=b.dirname(e);if(r===e)break;e=r;}}async function Ps(t){if(!await M__default.pathExists(t))return null;try{let e=await M__default.readJson(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Te(t,e,r,o,n="process",a){return {id:t,label:e,order:r,layoutHint:n,...o?{parentId:o}:{},...a?{group:a}:{}}}function Fg(t){return t.slice(1).map((e,r)=>{let o=t[r];return {id:`${o.id}->${e.id}`,from:o.id,to:e.id,kind:e.layoutHint==="gate"?"gate":e.layoutHint==="sink"?"handoff":"sequence",order:r+1}})}var Gg=[["workspace.intelligence.preflight.sync","Sync","source","DISCOVER"],["workspace.intelligence.stage.model","Model + Graph","process","UNDERSTAND"],["workspace.intelligence.preflight.baseline","Baseline","process","UNDERSTAND"],["workspace.intelligence.stage.diff","Diff","process","UNDERSTAND"],["workspace.intelligence.stage.impact","Impact","process","UNDERSTAND"],["workspace.intelligence.stage.doctor-evidence","Doctor","gate","ASSURE"],["workspace.intelligence.stage.contract-evidence","Contracts","gate","ASSURE"],["workspace.intelligence.stage.analyze-evidence","Analyze","gate","ASSURE"],["workspace.intelligence.stage.readiness-evidence","Readiness","gate","ASSURE"],["workspace.intelligence.stage.verify","Verify","gate","ASSURE"],["workspace.intelligence.stage.context","Context","process","PUBLISH"],["workspace.intelligence.stage.agent-sync","Agent Sync","process","PUBLISH"],["workspace.intelligence.stage.explain","Explain","sink","PUBLISH"]];function wo(t,e,r){return {id:t,version:3,nodes:[e,...r],edges:Fg(r)}}function Cd(t){let e=t.filter(a=>!a.startsWith("-")&&/^[a-z][a-z0-9-]*$/i.test(a)).slice(0,3),r=e.slice(0,3).join(".")||"cli",o=`command.${r}`,n=Te(o,e.join(" ")||"Workspai command",0,void 0,"source");if(e[0]==="workspace"&&e[1]==="intelligence"){let a=Gg.map(([i,c,l,p],m)=>Te(i,c,m+1,o,l,p));return wo(`cli.${r}`,n,a)}return e[0]==="adopt"?wo(`cli.${r}`,n,[Te("adopt.resolve","Resolve",1,o,"source","DISCOVER"),Te("adopt.detect","Detect",2,o,"process","DISCOVER"),Te("adopt.link","Link",3,o,"process","CONNECT"),Te("adopt.publish","Seal Intelligence",4,o,"gate","PUBLISH"),Te("adopt.ground","Agent Entry",5,o,"sink","PUBLISH")]):e[0]==="workspace"&&e[1]==="run"?wo(`cli.${r}`,n,[Te("workspace.run.resolve","Resolve Fleet",1,o,"source","DISCOVER"),Te("workspace.run.gates","Gates",2,o,"gate","ASSURE"),Te("workspace.run.execute","Execute",3,o,"process","EXECUTE"),Te("workspace.run.publish","Publish",4,o,"sink","PUBLISH")]):e[0]==="doctor"?wo(`cli.${r}`,n,[Te("doctor.observe","Observe",1,o,"source","OBSERVE"),Te("doctor.diagnose","Diagnose",2,o,"process","DIAGNOSE"),Te("doctor.plan","Plan",3,o,"process","DECIDE"),Te("doctor.verify","Verify",4,o,"gate","VERIFY")]):e[0]==="workspace"&&e[1]==="repair"?wo(`cli.${r}`,n,[Te("repair.observe","Observe",1,o,"source","OBSERVE"),Te("repair.plan","Plan",2,o,"process","DECIDE"),Te("repair.authorize","Authorize",3,o,"gate","AUTHORIZE"),Te("repair.execute","Execute",4,o,"process","EXECUTE"),Te("repair.verify","Verify",5,o,"gate","VERIFY")]):{id:`cli.${r}`,version:3,nodes:[n],edges:[]}}var yo=["list","sync","registry","foundation","intelligence","model","snapshot","diff","impact","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp","policy","contract","share","export","archive","hydrate","import","connect","run","init"],Mn=["intelligence","model","snapshot","diff","impact","contract","verify","goal","graph","watch","context","agent-sync","remediation-plan","repair","explain","why","trace","feedback","eval","mcp"];function Ed(t){return Mn.includes(t)}var Sd="workspai-project-entry-capability-v1";var bs="workspai-cli-runtime-command-inventory-v1",Wn=[...w$3,"autopilot","pipeline","import","adopt","goal","change","agent","snapshot","live","bootstrap","setup","cache","mirror","ai","config","product","infra","shell","commands","create","project"],js=["bootstrap","setup","cache","mirror"],Dn="create",Vg=[...js,Dn],Jg={bootstrap:"Bootstrap project or workspace dependencies through runtime-aware setup rules.",setup:"Prepare a selected runtime toolchain through the supported adapter boundary.",cache:"Inspect or clear Workspai cache state through the managed cache boundary.",mirror:"Coordinate supported mirror lifecycle operations for the current project.",create:"Create a supported workspace or project through the canonical planner boundary."},Ln=[["ai","generate-embeddings"],["ai","info"],["ai","recommend"],["ai","update-embeddings"],["agent","bootstrap"],["agent","framework"],["agent","framework","list"],["agent","framework","plan"],["agent","framework","attach"],["agent","framework","apply"],["config","ai"],["config","remove-api-key"],["config","set-api-key"],["config","show"],["change","begin"],["change","list"],["change","predict"],["change","authorize"],["change","resume"],["change","effect"],["change","effect","record"],["change","verification"],["change","verification","record"],["change","status"],["change","explain"],["change","verify"],["change","abort"],["change","capsule"],["change","capsule","validate"],["change","capsule","export"],["infra","down"],["infra","plan"],["infra","status"],["infra","up"],["product","manifest"],["product","manifest","create"],["product","plan"],["project","commands"],["project","agent-entry"],["project","coverage"],["project","workspace"],["project","archives"],["project","archive"],["project","restore"],["project","delete"],["snapshot","create"],["snapshot","inspect"],["snapshot","list"],["snapshot","restore"]];function Kg(t,e,r,o){let n=new Set(t),a=new Set(e),i=t.filter(f=>!a.has(f)).sort(),c=e.filter(f=>!n.has(f)).sort(),l=new Set(r),p=new Set(o),m=r.filter(f=>!p.has(f)).sort(),u=o.filter(f=>!l.has(f)).sort();return {ok:i.length===0&&c.length===0&&m.length===0&&u.length===0,registeredButUndeclared:i,declaredButUnregistered:c,registeredScopedButUndeclared:m,declaredScopedButUnregistered:u}}function Ad(t,e=[]){return t.commands.flatMap(r=>{let o=r.name(),n=[...e,o];return [{path:n,command:o,parent:e.length>0?e.join(" "):null,registrationKind:"commander",aliases:r.aliases?.()??[],description:r.description?.()??"",hidden:r._hidden===true,arguments:(r.registeredArguments??[]).map(i=>({name:i.name(),required:i.required,variadic:i.variadic})),options:(r.options??[]).map(i=>({flags:i.flags,attributeName:i.attributeName?.()??null}))},...Ad(r,n)]})}function Rd(t){let e=Ad(t),r=e.filter(c=>c.path.length===1).map(c=>c.command),o=new Set(r),n=Vg.filter(c=>!o.has(c)).map(c=>({path:[c],command:c,parent:null,registrationKind:"manual-handler",aliases:[],description:Jg[c],hidden:false,arguments:[],options:[]})),a=[...e,...n].sort((c,l)=>c.path.join(" ").localeCompare(l.path.join(" "))),i=[...new Set(a.filter(c=>c.path.length===1).map(c=>c.command))].sort();return {schemaVersion:bs,commands:a,topLevelCommands:i,integrity:Kg(i,Wn,e.filter(c=>c.path.length>1).map(c=>c.path.join(" ")),Ln.map(c=>c.join(" ")))}}function xd(t){return `CLI command surface integrity violation (${[t.registeredButUndeclared.length>0?`registered but undeclared: ${t.registeredButUndeclared.join(", ")}`:null,t.declaredButUnregistered.length>0?`declared but unreachable: ${t.declaredButUnregistered.join(", ")}`:null,t.registeredScopedButUndeclared.length>0?`registered scoped but undeclared: ${t.registeredScopedButUndeclared.join(", ")}`:null,t.declaredScopedButUnregistered.length>0?`declared scoped but unreachable: ${t.declaredScopedButUnregistered.join(", ")}`:null].filter(r=>r!==null).join("; ")})`}var Ug={"--workspace":"Use an explicit workspace root instead of the nearest workspace.","--json":"Emit machine-readable JSON.","--strict":"Return a non-zero exit when governed evidence blocks the result.","--for-agent":"Build output for an agent surface (for example codex, copilot, or cursor).","--include-paths":"Include absolute filesystem paths.","--include-evidence":"Read and include referenced evidence metadata.","--scan-depth":"Set the bounded observable-project discovery depth.","--cache":"Reuse the model cache when the structural inputs are unchanged.","--refresh-graph":"Bypass the compatible persisted graph and rebuild from live sources.","--incremental":"Reuse unchanged projects and rebuild affected graph relations.","--write":"Persist the command artifact under .workspai/reports.","--scope":"Limit the operation to a bounded scope such as project:<name>.","--kind":"Limit graph entity search to one canonical entity kind.","--dry-run":"Preview the operation without applying writes.","--preset":"Select the generated agent customization preset.","--refresh-context":"Rebuild agent context before synchronization.","--refresh":"Refresh the underlying registry or context before reading it.","--agent-sync":"Synchronize agent grounding after writing the context artifact.","--no-agent-sync":"Do not synchronize agent grounding after writing context.","--target":"Select one or more agent customization targets.","--experimental-hooks":"Generate advisory VS Code agent hook design files.","--hydrate-prompts":"Add workspace-specific verification steps to supported prompts.","--project-grounding":"Select the project entrypoint policy: managed, local, or off.","--ci":"Produce a CI-oriented command plan.","--from":"Read the specified baseline, report, or graph artifact.","--from-impact":"Read the specified impact report for verification.","--output":"Write the requested export or report to this path.","--limit":"Bound graph query results (1\u2013100).","--once":"Build the initial observed state and exit.","--graph-stream":"Emit graph snapshot/delta events as NDJSON.","--force":"Replace an existing generated target where supported.","--no-doctor":"Exclude Doctor evidence from a share bundle.","--no-blueprint":"Exclude the reproducibility blueprint from a share bundle.","--include-env":"Include private environment files in an export archive.","--archive-compression":"Select the archive compression format.","--max-download-size":"Bound a remote archive download.","--max-expanded-size":"Bound the expanded archive size.","--download-timeout-ms":"Bound remote archive download time.","--allow-private-network":"Allow private-network archive sources explicitly.","--affected":"Run only projects affected by the selected Git change.","--blast-radius":"Include transitive downstream dependents.","--since":"Select the Git baseline used for affected-project discovery.","--parallel":"Run selected projects concurrently.","--plan":"Resolve lifecycle commands without executing project code.","--runtime":"Limit lifecycle planning or execution to one detected runtime family.","--max-workers":"Bound concurrent project workers.","--continue-on-error":"Continue remaining projects after a project failure.","--reuse-passed":"Reuse successful project-stage results where safe.","--no-gates":"Skip Doctor and Readiness pre-run gates.","--allow-breaking":"Allow a verified goal to use breaking dependency changes.","--allow-force":"Allow a verified goal to use force-based repair commands.","--card":"Select the dashboard card whose governed remediation actions should be repaired.","--action-id":"Select one exact governed remediation action.","--project":"Limit the repair transaction to one registered project name.","--proposal":"Read a bounded model repair proposal from a JSON file inside the workspace.","--transaction":"Select one durable repair transaction by id.","--approved-by":"Record the local actor approving the immutable repair plan.","--decision":"Submit one of the exact options exposed by a decision-required transaction.","--max-risk":"Set the maximum approved repair risk: safe, guarded, or invasive.","--no-auto-rollback":"Require a decision instead of automatically restoring a failed transaction.","--no-build":"Do not require build validation for the selected verified goal.","--no-tests":"Do not require test validation for the selected verified goal.","--no-run":"Read current goal evidence without executing verification commands.","--reuse-intelligence":"Reuse a just-completed canonical intelligence run while executing goal-specific checks."},ko={list:{usage:"workspai workspace list [--json]",summary:"List registered Workspai workspaces.",flags:["--json"],examples:["workspai workspace list","workspai workspace list --json"]},intelligence:{usage:"workspai workspace intelligence run [--for-agent <agent>] [--strict] [--json]",summary:"Run the canonical Workspace Intelligence chain in contract order.",flags:["--workspace","--json","--strict","--for-agent"],subactions:["run"],artifact:p.intelligenceRun,examples:["workspai workspace intelligence run --strict","workspai workspace intelligence run --for-agent codex --json"]},model:{usage:"workspai workspace model [--cache|--incremental] [--write] [--strict] [--json]",summary:"Build the canonical workspace model from registered and observed sources.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth","--cache","--incremental","--write","--strict"],artifact:p.model,examples:["workspai workspace model --write --json","workspai workspace model --incremental --write --json"]},"agent-sync":{usage:"workspai workspace agent-sync [--for-agent <agent>] [--target <targets>] [--project-grounding <mode>] [--write]",summary:"Synchronize bounded workspace grounding for supported agent surfaces.",flags:["--workspace","--json","--scope","--for-agent","--write","--dry-run","--strict","--preset","--refresh-context","--refresh","--target","--experimental-hooks","--hydrate-prompts","--project-grounding"],artifact:p.agentCustomizationPack,examples:["workspai workspace agent-sync --target all --write --strict","workspai workspace agent-sync --for-agent copilot --dry-run --json"]},"remediation-plan":{usage:"workspai workspace remediation-plan [--ci] [--write] [--json]",summary:"Build a governed repair plan from current workspace evidence.",flags:["--workspace","--json","--include-paths","--ci","--write"],artifact:t.artifactRemediationPlan,examples:["workspai workspace remediation-plan --write --json","workspai workspace remediation-plan --ci --json"]},repair:{usage:"workspai workspace repair <capabilities|plan|propose|approve|decide|execute|resume|status|list|rollback|cancel> [--transaction <id>] [--json]",summary:"Run a durable, approval-bound repair transaction through checkpoint, validation, canonical verification, and rollback.",flags:["--workspace","--json","--card","--action-id","--project","--proposal","--transaction","--approved-by","--decision","--max-risk","--allow-breaking","--allow-force","--no-auto-rollback"],subactions:["capabilities","plan","propose","approve","decide","execute","resume","status","list","rollback","cancel"],artifact:p.repairTransaction,examples:["workspai workspace repair capabilities --json","workspai workspace repair plan --card doctor --project api --json","workspai workspace repair propose --proposal .workspai/repair/inbox/proposal.json --json","workspai workspace repair approve --transaction repair_123 --approved-by local-user --json","workspai workspace repair decide --transaction repair_123 --decision approve-invasive --json","workspai workspace repair execute --transaction repair_123 --json","workspai workspace repair rollback --transaction repair_123 --json"]},context:{usage:"workspai workspace context [--for-agent <agent>] [--scope <scope>] [--write] [--json]",summary:"Build a bounded, evidence-backed context pack for people and agents.",flags:["--workspace","--json","--for-agent","--scope","--include-evidence","--scan-depth","--write","--agent-sync","--no-agent-sync","--preset","--target","--strict","--project-grounding"],artifact:p.agentContext,examples:["workspai workspace context --for-agent codex --write --json","workspai workspace context --scope project:api --json"]},snapshot:{usage:"workspai workspace snapshot [--json]",summary:"Persist the current model as the comparison baseline.",flags:["--workspace","--json","--include-paths","--include-evidence","--scan-depth"],artifact:p.snapshot,examples:["workspai workspace snapshot --json"]},diff:{usage:"workspai workspace diff --from <snapshot-or-model|git[:ref]> [--strict] [--json]",summary:"Compare the current model with a trusted model baseline.",flags:["--workspace","--json","--from","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:p.diff,examples:["workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json","workspai workspace diff --from git --json"]},impact:{usage:"workspai workspace impact --from <diff> [--scope <scope>] [--strict] [--json]",summary:"Calculate the evidence-backed blast radius of the current model change.",flags:["--workspace","--json","--from","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:p.impact,examples:["workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json","workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --strict --json"]},verify:{usage:"workspai workspace verify [--from-impact <impact-report>] [--scope <scope>] [--strict] [--json]",summary:"Verify the selected change against contracts, gates, and current evidence.",flags:["--workspace","--json","--from-impact","--scope","--include-paths","--include-evidence","--scan-depth","--strict"],artifact:p.verify,examples:["workspai workspace verify --strict --json","workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json"]},goal:{usage:"workspai workspace goal <plan|status|verify> <kind|goal-id> [--scope <scope>] [--runtime <runtime>] [--target <percent>] [--json]",summary:"Plan, resume, and evidence-verify a durable engineering goal for people and agents.",flags:["--workspace","--json","--scope","--runtime","--target","--allow-breaking","--allow-force","--no-build","--no-tests","--no-run","--reuse-intelligence"],flagDescriptions:{"--runtime":"Select the runtime measured by a test-coverage goal.","--target":"Set the required test coverage percentage (0\u2013100)."},subactions:["plan","status","verify"],artifact:p.verifiedGoalStatus,examples:["workspai workspace goal plan release-readiness --json","workspai workspace goal plan dependency-security --scope project:api --json","workspai workspace goal plan test-coverage --scope project:web --runtime node --target 75 --json","workspai workspace goal verify <goal-id> --json"]},graph:{usage:"workspai workspace graph [mode] [query|from] [to] [--json]",summary:"Query and export the canonical Knowledge Graph; explain, dot, and mermaid target the project dependency topology.",flags:["--workspace","--json","--output","--from","--limit","--kind","--refresh-graph","--include-paths","--include-evidence","--scan-depth","--scope","--write"],subactions:["emit","explain","entities","search","evidence","path","overlay","benchmark","benchmark-suite","dot","mermaid","jsonld","graphml","gexf"],examples:['workspai workspace graph search "authentication endpoint" --kind endpoint --limit 12 --json','workspai workspace graph evidence "GET /users" --json',"workspai workspace graph benchmark-suite agent-core.v1 --write --json","workspai workspace graph mermaid"]},watch:{usage:"workspai workspace watch [--once] [--graph-stream] [--json]",summary:"Observe model changes and optionally stream graph deltas.",flags:["--workspace","--json","--once","--graph-stream","--scan-depth"],examples:["workspai workspace watch --once --json","workspai workspace watch --graph-stream"]},sync:{usage:"workspai workspace sync [--project-grounding <mode>] [--json]",summary:"Synchronize canonical workspace registration and project metadata.",flags:["--workspace","--json","--project-grounding"],examples:["workspai workspace sync --json"]},registry:{usage:"workspai workspace registry [--refresh] [--json]",summary:"Inspect the canonical workspace registry summary.",flags:["--workspace","--json","--refresh"],examples:["workspai workspace registry --refresh --json"]},foundation:{usage:"workspai workspace foundation [--force] [--json]",summary:"Create or repair the standard workspace foundation files.",flags:["--workspace","--json","--force"],examples:["workspai workspace foundation --json"]},policy:{usage:"workspai workspace policy [show|status|get|set] [key] [value] [--json]",summary:"Inspect or update workspace governance policy.",flags:["--workspace","--json"],subactions:["show","status","get","set"],examples:["workspai workspace policy get --json"]},contract:{usage:"workspai workspace contract [init|inspect|sync|verify|graph] [--strict] [--json]",summary:"Create, inspect, synchronize, verify, or project the workspace contract.",flags:["--workspace","--json","--output","--force","--strict"],subactions:["init","inspect","sync","verify","graph"],artifact:t.workspaceContract,examples:["workspai workspace contract sync --strict --json","workspai workspace contract verify --strict --json","workspai workspace contract graph --json"]},share:{usage:"workspai workspace share [--output <file>] [--json]",summary:"Create a bounded, shareable workspace evidence bundle.",flags:["--workspace","--json","--output","--include-paths","--no-doctor","--no-blueprint"],examples:["workspai workspace share --output workspace-share.json --json"]},export:{usage:"workspai workspace export [--output <archive>] [--archive-compression <format>]",summary:"Export a portable workspace archive.",flags:["--workspace","--json","--output","--include-env","--archive-compression"],examples:["workspai workspace export --output workspace.tar.gz"]},archive:{usage:"workspai workspace archive <inspect|verify|doctor> <source> [safety options] [--json]",summary:"Inspect, verify, or diagnose a portable workspace archive without materializing it.",flags:["--json","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],subactions:["inspect","verify","doctor"],examples:["workspai workspace archive inspect ./workspace.tar.gz --json","workspai workspace archive verify ./workspace.tar.gz --strict --json","workspai workspace archive doctor ./workspace.tar.gz --json"]},hydrate:{usage:"workspai workspace hydrate <source> [--output <directory>] [--dry-run] [--json]",summary:"Hydrate a portable workspace into a controlled destination.",flags:["--json","--output","--force","--dry-run","--strict","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace hydrate workspace.tar.gz --output ./restored --dry-run --json"]},import:{usage:"workspai workspace import <source> [--output <directory>] [--dry-run] [--json]",summary:"Verify, materialize, register, relink, and reconcile a portable workspace archive safely.",flags:["--json","--output","--dry-run","--strict","--project-grounding","--max-download-size","--max-expanded-size","--download-timeout-ms","--allow-private-network"],examples:["workspai workspace import workspace.tar.gz --output ./imported --json"]},connect:{usage:"workspai workspace connect [directory] [--project-grounding <mode>] [--dry-run] [--json]",summary:"Register and reconcile an existing Workspai workspace in place without moving its source.",flags:["--json","--dry-run","--project-grounding"],examples:["workspai workspace connect /path/to/existing-workspace --json"]},run:{usage:"workspai workspace run <stage> [selection and concurrency options] [--json]",summary:"Run a lifecycle stage across selected workspace projects.",flags:["--workspace","--json","--scope","--plan","--runtime","--affected","--blast-radius","--since","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],subactions:["init","test","build","start","<custom-from-context>"],artifact:t.workspaceRunLast,examples:["workspai workspace run test --scope project:api --plan --runtime ruby --json","workspai workspace run test --affected --blast-radius --strict","workspai workspace run build --parallel --max-workers 4 --json"]},explain:{usage:"workspai workspace explain [target] [--scope <scope>] [--write] [--json]",summary:"Explain current blockers or a selected workspace target from evidence.",flags:["--workspace","--json","--scope","--write"],artifact:p.explain,examples:["workspai workspace explain --write --json"]},why:{usage:"workspai workspace why [target] [--scope <scope>] [--write] [--json]",summary:"Alias the evidence-backed workspace explanation flow.",flags:["--workspace","--json","--scope","--write"],artifact:d$5,examples:["workspai workspace why readiness --json"]},trace:{usage:"workspai workspace trace --from <diff-artifact> [--write] [--json]",summary:"Trace a model change through blast radius and decision gates.",flags:["--workspace","--json","--from","--write"],artifact:e$3,examples:["workspai workspace trace --from .workspai/reports/workspace-model-diff-last-run.json --write --json"]},feedback:{usage:"echo '<event-json>' | workspai workspace feedback record --json",summary:"Record a structured outcome event for the workspace intelligence history.",flags:["--workspace","--json"],subactions:["record"],examples:[`echo '{"actionId":"fix","summary":"ok","outcome":"ok"}' | workspai workspace feedback record --json`]},eval:{usage:"workspai workspace eval [init|record|status|report|compare] [arguments] [--json]",summary:"Measure agent/model calls, tool use, tokens, latency, and verified outcome.",flags:["--workspace","--json","--from","--output"],subactions:["init","record","status","report","compare"],artifact:p.evaluationLastRun,examples:["workspai workspace eval init repair-readiness workspace-intelligence --json","workspai workspace eval report --output ./evaluation.json --json"]},mcp:{usage:"workspai workspace mcp serve",summary:"Serve bounded, read-mostly workspace evidence over stdio MCP.",flags:["--workspace","--json"],subactions:["serve"],examples:["workspai workspace mcp serve"]},init:{usage:"workspai workspace init [selection and concurrency options] [--json]",summary:"Initialize all selected projects through the workspace fleet runner.",flags:["--workspace","--json","--scope","--parallel","--max-workers","--continue-on-error","--reuse-passed","--strict","--no-gates"],artifact:t.workspaceRunLast,examples:["workspai workspace init --parallel --strict"]}};function Cs(t){if(t)return ko[t]}function Id(t){return t[0]==="workspace"&&!!Cs(t[1])&&t.slice(2).some(e=>e==="--help"||e==="-h")}function _d(t,e){let r=Cs(e)?.flagDescriptions?.[t]??Ug[t];if(!r)throw new Error(`Workspace action flag has no description: ${t}`);return r}function Od(t){let e=Cs(t);if(!e)throw new Error(`Unknown workspace action: ${t}`);let r=[`Workspai workspace ${t}`,"",e.summary,"","Usage:",` ${e.usage}`];if(e.subactions&&e.subactions.length>0&&r.push("","Modes:",` ${e.subactions.join(" | ")}`),e.flags.length>0){r.push("","Options:");for(let o of e.flags){let n=_d(o,t);r.push(` ${o.padEnd(24)} ${n}`.trimEnd());}}return e.artifact&&r.push("","Evidence:",` ${e.artifact}`),r.push("","Examples:",...e.examples.map(o=>` ${o}`),""),r.join(`
|
|
151
|
+
`)}var Nd="rapidkit-runtime-command-surface-v1";var Es=s$1.doctorRemediationPlan.schemaVersion;var $d="workspai-workspace-intelligence-architecture-v1";var Td={autopilotRelease:s$1.autopilotReleaseLastRun.schemaVersion,workspaceList:"rapidkit-workspace-list-v1",workspaceSync:"rapidkit-workspace-sync-v1",compatibilityMatrix:s$1.compatibilityMatrix.schemaVersion,mcpDesign:s$1.workspaiMcpDesign.schemaVersion,agentHooks:s$1.agentHooks.schemaVersion,projectArchive:"rapidkit-project-archive-v1",workspaceSnapshot:"rapidkit-workspace-snapshot-v1",workspaceSnapshotV2:"rapidkit-workspace-snapshot-v2",infraPlan:s$1.infraPlan.schemaVersion,privateProductManifest:"rapidkit.private-product-manifest.v1",productFactoryPlan:"rapidkit.product-factory-plan.v1",workspaceModelCache:s$1.workspaceModelCache.schemaVersion,workspaceWatchEvent:"workspace-watch-event.v1",doctorProjectScan:"doctor-project-scan-v2",doctorWorkspaceCache:s$1.doctorWorkspaceCache.schemaVersion};var Md="project-workspace-resolution.v1";function Wd(t){a$4(t,"contracts/project-workspace-resolution.v1.json","Project workspace resolution");}var Ss="workspai.ingestion-plan.v1",Fn="workspai.ingestion-result.v1",Gn="workspai.adopt-effects.v1";var Dd="contracts/ingestion-result.v1.json";function Qt(t){return {schemaVersion:Ss,...t}}var Bg="workspai-published-contract-catalog-v1",Hg="workspace-graph-stream.v1";function vo(){return {workspaceContract:1,runtimeCommandSurface:Nd,cliRuntimeCommandInventory:bs,cliOperationResult:a$N,publishedContractCatalog:Bg,workspaceArchiveCapabilities:a$M,workspaceArchiveManifest:b$m,workspaceArchiveOperationResult:c$3,ingestionPlan:Ss,ingestionResult:Fn,adoptEffects:Gn,projectEntryCapability:Sd,projectWorkspaceLink:s$1.projectWorkspaceLink.schemaVersion,projectWorkspaceResolution:Md,projectContextAgent:s$1.projectContextAgent.schemaVersion,projectKnowledgeGraphReference:s$1.projectKnowledgeGraphReference.schemaVersion,projectAgentEntry:a$L,agentBootstrapReceipt:c$g,doctorProjectEvidence:b$l,doctorWorkspaceEvidence:a$K,doctorGraphDiagnosis:b$k,doctorDiagnosis:a$J,doctorCapabilities:a$I,doctorValidation:c$f,doctorReceipt:s$1.doctorReceipt.schemaVersion,doctorSummary:c$e,projectTestCoverage:s$1.projectTestCoverage.schemaVersion,verifiedGoal:"workspai.verified-goal.v1",verifiedGoalStatus:q.verifiedGoalStatus,goalPack:a$H,goalAgentHandoff:b$j,goalPlanResult:c$d,goalIndex:e$c,goalLifecycleResult:g$8,decisionEvent:f$5,decisionTransaction:e$b,decisionCheckpoint:g$7,changeOperationResult:l$3,architectureChangeLease:h$3,predictedArchitectureChange:i$2,architectureSurpriseReport:j$7,proofCarryingChangeCapsule:k$4,proofCarryingChangeList:m$4,proofCarryingChangeCapsuleValidation:n$3,proofCarryingChangeCapsuleExport:o$2,workspaceIntelligenceArchitecture:$d,workspaceIntelligenceChain:a$G,workspaceIntelligenceArtifacts:q,cliLogEvent:a$F,workspaceActivityEvent:a$E,workspaceActivityMonitorSnapshot:a$D,workspaceActivityMonitorFleet:b$i,workspaceActivityBoard:h$2,freshnessMetadata:c$c,factFreshness:e$a,blockerResolution:a$C,workspaceModel:l$2,workspaceImpact:f$4,workspaceVerify:c$b,workspaceContext:a$B,workspaceDependencyGraph:e$9,workspaceKnowledgeGraph:a$A,workspaceGraphStream:Hg,workspaceKnowledgeGraphChangeOverlay:a$z,workspaceKnowledgeSearch:a$y,workspaceGraphTokenEfficiency:a$x,workspaceIntelligenceBenchmark:a$w,modelUsageEvent:a$v,workspaceIntelligenceEvaluation:b$h,workspaceIntelligenceEvaluationComparison:c$a,workspaceIntelligenceHistory:a$u,agentCustomizationPackCapabilities:c$9,agentFrameworkCapabilities:v$3,agentFrameworkAdapterManifest:w$2,agentFrameworkConformanceReport:x$1,agentFrameworkConformanceReportLegacy:"workspai.agent-framework-conformance-report.v1",agentFrameworkChangePlan:y,agentFrameworkOwnershipReceipt:z,agentFrameworkAdmissionCandidate:A,agentFrameworkAdmissionCandidateLegacy:"workspai.agent-framework-admission-candidate.v1",agentCustomizationPackReport:q.agentCustomizationPack,agentReportsIndex:q.agentIndex,workspaceOperationalSkill:a$t,workspaceSkillsIndex:b$g,workspaceExplain:a$s,agentActionOutcome:a$r,doctorRemediationPlan:Es,doctorDependencyRepairTransaction:"workspai.doctor-dependency-repair-transaction.v1",artifactRemediationPlan:a$q,studioCardRepairCapabilities:j$6,workspaceRepairProposal:e$8,workspaceRepairCapabilities:g$6,workspaceRepairTransaction:a$p,doctorFixResult:a$o,backendImportStackParitySnapshot:"backend-import-stack-parity-v1",bootstrapCompliance:s$1.bootstrapCompliance.schemaVersion,commandCapabilities:"rapidkit-command-capabilities-v1",createPlannerCapabilities:"rapidkit-create-planner-capabilities-v1",doctorRemediationPlanLegacy:Es,extensionCliCompatibility:"rapidkit-extension-cli-compatibility.v1",infraStack:"rapidkit.infra-stack.v1",mirrorOps:s$1.mirrorOps.schemaVersion,moduleLayout:"rapidkit.module-layout.v1",moduleSupport:"rapidkit-module-support-v1",pipelineLastRun:s$1.pipelineLastRun.schemaVersion,transparencyEvidence:s$1.transparencyEvidence.schemaVersion,version:"rapidkit-version-v1",studioBlockerHandoff:"rapidkit-studio-blocker-handoff-v1",workspaceRegistry:s$1.workspaceRegistry.schemaVersion,workspaceRunLast:s$1.workspaceRunLast.schemaVersion,workspaceShareBundle:s$1.workspaceShareBundle.schemaVersion,...Td}}function Vn(){let t=vo(),e={workspaceContract:"contracts/workspace-contract.v1.json",runtimeCommandSurface:"contracts/runtime-command-surface.v1.json",cliRuntimeCommandInventory:"contracts/cli-runtime-command-inventory.v1.snapshot.json",cliOperationResult:"contracts/cli-operation-result.v1.json",publishedContractCatalog:"contracts/published-contract-catalog.v1.json",workspaceArchiveCapabilities:"contracts/workspace-archive-capabilities.v1.json",workspaceArchiveManifest:"contracts/workspace-archive-manifest.v1.json",workspaceArchiveOperationResult:"contracts/workspace-archive-operation-result.v1.json",ingestionPlan:"contracts/ingestion-plan.v1.json",ingestionResult:"contracts/ingestion-result.v1.json",adoptEffects:"contracts/adopt-effects.v1.json",projectEntryCapability:"contracts/project-entry-capability.v1.json",projectWorkspaceLink:"contracts/project-workspace-link.v1.json",projectWorkspaceResolution:"contracts/project-workspace-resolution.v1.json",projectContextAgent:"contracts/workspace-intelligence/project-context-agent.v1.json",projectKnowledgeGraphReference:"contracts/workspace-intelligence/project-knowledge-graph-reference.v1.json",projectAgentEntry:"contracts/workspace-intelligence/project-agent-entry.v1.json",agentBootstrapReceipt:"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json",doctorProjectEvidence:"contracts/doctor-project-evidence.v1.json",doctorWorkspaceEvidence:"contracts/doctor-workspace-evidence.v1.json",doctorGraphDiagnosis:"contracts/workspace-intelligence/doctor-graph-diagnosis.v1.json",doctorDiagnosis:"contracts/workspace-intelligence/doctor-diagnosis.v1.json",doctorCapabilities:"contracts/workspace-intelligence/doctor-capabilities.v1.json",doctorValidation:"contracts/workspace-intelligence/doctor-validation.v1.json",doctorReceipt:"contracts/workspace-intelligence/doctor-receipt.v1.json",doctorSummary:"contracts/workspace-intelligence/doctor-summary.v1.json",projectTestCoverage:"contracts/project-test-coverage.v1.json",verifiedGoal:"contracts/workspace-intelligence/verified-goal.v1.json",verifiedGoalStatus:"contracts/workspace-intelligence/verified-goal-status.v1.json",goalPack:"contracts/workspace-intelligence/goal-pack.v1.json",goalAgentHandoff:"contracts/workspace-intelligence/goal-agent-handoff.v1.json",goalPlanResult:"contracts/workspace-intelligence/goal-plan-result.v1.json",goalIndex:"contracts/workspace-intelligence/goal-index.v1.json",goalLifecycleResult:"contracts/workspace-intelligence/goal-lifecycle-result.v1.json",decisionEvent:"contracts/workspace-intelligence/decision-event.v1.json",decisionTransaction:"contracts/workspace-intelligence/decision-transaction.v1.json",decisionCheckpoint:"contracts/workspace-intelligence/decision-checkpoint.v1.json",changeOperationResult:"contracts/workspace-intelligence/change-operation-result.v1.json",architectureChangeLease:"contracts/workspace-intelligence/architecture-change-lease.v1.json",predictedArchitectureChange:"contracts/workspace-intelligence/predicted-architecture-change.v1.json",architectureSurpriseReport:"contracts/workspace-intelligence/architecture-surprise-report.v1.json",proofCarryingChangeCapsule:"contracts/workspace-intelligence/proof-carrying-change-capsule.v1.json",proofCarryingChangeList:"contracts/workspace-intelligence/proof-carrying-change-list.v1.json",proofCarryingChangeCapsuleValidation:"contracts/workspace-intelligence/proof-carrying-change-capsule-validation.v1.json",proofCarryingChangeCapsuleExport:"contracts/workspace-intelligence/proof-carrying-change-capsule-export.v1.json",workspaceIntelligenceArchitecture:"contracts/workspace-intelligence-architecture.v1.json",workspaceIntelligenceChain:"contracts/workspace-intelligence-chain.v1.json",workspaceIntelligenceArtifacts:null,cliLogEvent:"contracts/cli-log-event.v1.json",workspaceActivityEvent:"contracts/workspace-activity-event.v1.json",workspaceActivityMonitorSnapshot:"contracts/workspace-activity-monitor-snapshot.v1.json",workspaceActivityMonitorFleet:"contracts/workspace-activity-monitor-fleet.v1.json",workspaceActivityBoard:"contracts/workspace-activity-board.v1.json",freshnessMetadata:null,factFreshness:"contracts/workspace-intelligence/fact-freshness.v1.json",blockerResolution:"contracts/workspace-intelligence/blocker-resolution.v1.json",workspaceModel:"contracts/workspace-intelligence/workspace-model.v1.json",workspaceImpact:"contracts/workspace-intelligence/workspace-impact.v1.json",workspaceVerify:"contracts/workspace-intelligence/workspace-verify.v1.json",workspaceContext:"contracts/workspace-intelligence/workspace-context.v1.json",workspaceDependencyGraph:"contracts/workspace-intelligence/workspace-dependency-graph.v1.json",workspaceKnowledgeGraph:"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json",workspaceGraphStream:"contracts/workspace-intelligence/workspace-graph-stream.v1.json",workspaceKnowledgeGraphChangeOverlay:"contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json",workspaceKnowledgeSearch:"contracts/workspace-intelligence/workspace-knowledge-search.v1.json",workspaceGraphTokenEfficiency:"contracts/workspace-intelligence/workspace-graph-token-efficiency.v1.json",workspaceIntelligenceBenchmark:"contracts/workspace-intelligence/workspace-intelligence-benchmark.v1.json",modelUsageEvent:"contracts/workspace-intelligence/model-usage-event.v1.json",workspaceIntelligenceEvaluation:"contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",workspaceIntelligenceEvaluationComparison:"contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",workspaceIntelligenceHistory:"contracts/workspace-intelligence/workspace-intelligence-history.v1.json",agentCustomizationPackCapabilities:"contracts/agent-customization-pack.v1.json",agentFrameworkCapabilities:"contracts/agent-framework-capabilities.v1.json",agentFrameworkAdapterManifest:"contracts/workspace-intelligence/agent-framework-adapter-manifest.v1.json",agentFrameworkConformanceReport:"contracts/workspace-intelligence/agent-framework-conformance-report.v2.json",agentFrameworkConformanceReportLegacy:"contracts/workspace-intelligence/agent-framework-conformance-report.v1.json",agentFrameworkChangePlan:"contracts/workspace-intelligence/agent-framework-change-plan.v1.json",agentFrameworkOwnershipReceipt:"contracts/workspace-intelligence/agent-framework-ownership-receipt.v1.json",agentFrameworkAdmissionCandidate:"contracts/workspace-intelligence/agent-framework-admission-candidate.v2.json",agentFrameworkAdmissionCandidateLegacy:"contracts/workspace-intelligence/agent-framework-admission-candidate.v1.json",agentCustomizationPackReport:"contracts/workspace-intelligence/agent-customization-pack-report.v1.json",agentReportsIndex:"contracts/workspace-intelligence/agent-reports-index.v1.json",workspaceOperationalSkill:"contracts/workspace-intelligence/workspace-operational-skill.v1.json",workspaceSkillsIndex:"contracts/workspace-intelligence/workspace-skills-index.v1.json",workspaceExplain:"contracts/workspace-intelligence/workspace-explain.v1.json",agentActionOutcome:"contracts/workspace-intelligence/agent-action-outcome.v1.json",doctorRemediationPlan:"contracts/doctor-remediation-plan.v2.json",doctorDependencyRepairTransaction:"contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json",artifactRemediationPlan:"contracts/artifact-remediation-plan.v1.json",studioCardRepairCapabilities:"contracts/studio-card-repair-capabilities.v1.json",workspaceRepairProposal:"contracts/workspace-intelligence/workspace-repair-proposal.v1.json",workspaceRepairCapabilities:"contracts/workspace-repair-capabilities.v1.json",workspaceRepairTransaction:"contracts/workspace-intelligence/workspace-repair-transaction.v1.json",doctorFixResult:"contracts/workspace-intelligence/doctor-fix-result.v1.json",backendImportStackParitySnapshot:"contracts/backend-import-stack-parity.snapshot.json",bootstrapCompliance:"contracts/bootstrap-compliance.v1.json",commandCapabilities:"contracts/command-capabilities.v1.json",createPlannerCapabilities:"contracts/create-planner-capabilities.v1.json",doctorRemediationPlanLegacy:"contracts/doctor-remediation-plan.v1.json",extensionCliCompatibility:"contracts/extension-cli-compatibility.v1.json",infraStack:"contracts/infra-stack.v1.json",mirrorOps:"contracts/mirror-ops.v1.json",moduleLayout:"contracts/module-layout.v1.json",moduleSupport:"contracts/module-support.v1.json",pipelineLastRun:"contracts/pipeline-last-run.v1.json",transparencyEvidence:"contracts/transparency-evidence.v1.json",version:"contracts/version.v1.json",studioBlockerHandoff:"contracts/workspace-intelligence/studio-blocker-handoff.v1.json",workspaceRegistry:"contracts/workspace-registry.v1.json",workspaceRunLast:"contracts/workspace-run-last.v1.json",workspaceShareBundle:"contracts/workspace-share-bundle.v1.json",autopilotRelease:"contracts/autopilot-release.v1.json",workspaceList:"contracts/workspace-list.v1.json",workspaceSync:"contracts/workspace-sync.v1.json",compatibilityMatrix:"contracts/compatibility-matrix.v1.json",mcpDesign:"contracts/workspace-intelligence/mcp-design.v1.json",agentHooks:"contracts/workspace-intelligence/agent-hooks.v1.json",projectArchive:"contracts/project-archive.v1.json",workspaceSnapshot:"contracts/workspace-snapshot.v1.json",workspaceSnapshotV2:"contracts/workspace-snapshot.v2.json",infraPlan:"contracts/infra-plan.v1.json",privateProductManifest:"contracts/private-product-manifest.v1.json",productFactoryPlan:"contracts/product-factory-plan.v1.json",workspaceModelCache:"contracts/workspace-model-cache.v1.json",workspaceWatchEvent:"contracts/workspace-watch-event.v1.json",doctorProjectScan:"contracts/doctor-project-scan.v2.json",doctorWorkspaceCache:"contracts/doctor-workspace-cache.v2.json"};return Object.fromEntries(Object.entries(t).map(([r$1,o])=>{let n=e[r$1];return [r$1,{schemaVersion:o,contractPath:n,publication:n?r$1==="runtimeCommandSurface"||r$1==="cliRuntimeCommandInventory"||r$1.endsWith("Capabilities")||r$1.endsWith("Snapshot")||r$1==="extensionCliCompatibility"||r$1==="moduleLayout"||r$1==="moduleSupport"?"capability-contract":"json-schema":"embedded-type",...r$1==="workspaceIntelligenceArtifacts"?{artifacts:Object.fromEntries(Object.keys(p).map(a=>[a,{path:p[a],schemaVersion:q[a],contractPath:r[a]}]))}:{}}]}))}var As="rapidkit-command-capabilities-v1",Ld="rapidkit-version-v1";var qg=["catalog","pulse","nova","orbit","atlas","vertex","summit","beacon","ledger","flux","nexus","apex","harbor","forge","spark","portal","studio","canvas","quantum","vault","zenith","compass","vector","catalyst","saas","commerce","radar","stellar","prism","cedar","momentum","signal","cipher","lumen","trail","ridge"],zg={"fastapi.standard":"api","fastapi.ddd":"api","nestjs.standard":"api","springboot.standard":"service","gofiber.standard":"api","gogin.standard":"api","dotnet.webapi.clean":"api"},Yg={nextjs:"web",remix:"app","vite-react":"web","vite-vue":"web","vite-svelte":"web","vite-solid":"web","vite-vanilla":"app",nuxt:"app",angular:"app",astro:"site",sveltekit:"app"},Xg={tauri:"desktop",electron:"desktop","vscode-extension":"extension",laravel:"api"};function Qg(t){return t[Math.floor(Math.random()*t.length)]}function Rs(t){let e=Qg(qg),r=l$5(t);if(r){let c=Yg[r.id]??"app";return `${e}-${c}`}let o=r$2(t);if(o)return `${e}-${Xg[o.id]??"app"}`;if(Q(t))return `${e}-gateway`;let a=a$3(t),i=a?zg[a.id]??"service":"app";return `${e}-${i}`}async function rf(t){let e=await promises.readFile(t);return createHash("sha256").update(e).digest("hex")}async function of(t){if(!await M.pathExists(t))return [];let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(o)for(let n of await promises.readdir(o,{withFileTypes:true})){let a=b.join(o,n.name);n.isFile()?e.push(a):n.isDirectory()&&r.push(a);}}return e}async function Gd(t,e){await M.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
152
152
|
`,"utf-8");}function ft(t,e){return b.isAbsolute(e)?e:b.join(t,e)}function nf(t,e){if(!e.trim()||b.isAbsolute(e)||/^[a-zA-Z]:[\\/]/.test(e))throw new Error(`Mirror artifact target must be a non-empty relative path: ${e}`);let r=b.resolve(t),o=b.resolve(r,e),n=b.relative(r,o);if(!n||n.startsWith("..")||b.isAbsolute(n))throw new Error(`Mirror artifact target escapes the managed artifact directory: ${e}`);return o}async function Vd(t,e){let r=b.relative(t,e),o=t;for(let a of r.split(b.sep).slice(0,-1)){o=b.join(o,a);let i=await promises.lstat(o).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)break;if(i.isSymbolicLink())throw new Error(`Mirror artifact target traverses a symbolic link: ${o}`);if(!i.isDirectory())throw new Error(`Mirror artifact target parent is not a directory: ${o}`)}let n=await promises.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(n?.isSymbolicLink()||n&&!n.isFile())throw new Error(`Mirror artifact target must be absent or a regular file: ${e}`)}async function af(t,e){let r=b.resolve(t),o=b.relative(r,b.resolve(e));if(!o||o.startsWith("..")||b.isAbsolute(o))throw new Error("Managed mirror directory escapes the workspace.");let n=r;for(let a of o.split(b.sep)){n=b.join(n,a);let i=await promises.lstat(n);if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Managed mirror path must contain only real directories: ${n}`)}}function sf(t,e){if(t.target)return t.target;if(t.source)return b.basename(t.source);if(t.url)try{let r=new URL(t.url).pathname,o=b.basename(r);if(o&&o!=="/")return o}catch{}return `${e}.artifact`}async function cf(t){let e=t$1(t,"trusted-sources.lock").find(o=>existsSync(o)),r=new Set(["localhost","127.0.0.1"]);if(!e)return r;try{let n=(await promises.readFile(e,"utf-8")).split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));for(let a of n)r.add(a.toLowerCase());}catch{}return r}async function lf(t,e,r){await M.ensureDir(b.dirname(e)),await new Promise((o,n)=>{let i=(t.startsWith("https://")?qd:Hd).get(t,c=>{if(!c.statusCode||c.statusCode<200||c.statusCode>=300){n(new Error(`HTTP ${c.statusCode||"unknown"}`)),c.resume();return}let l=createWriteStream(e);c.pipe(l),l.on("finish",()=>{l.close(),o();}),l.on("error",p=>{n(p);});});i.setTimeout(r,()=>{i.destroy(new Error(`Request timeout after ${r}ms`));}),i.on("error",c=>{n(c);});});}async function pf(t,e,r,o,n){let a=new URL(t),i=JSON.stringify(e),c=a.protocol==="https:"?qd:Hd;await new Promise((l,p)=>{let m=c.request({method:"POST",hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:`${a.pathname}${a.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...o?{Authorization:`Bearer ${o}`}:{},...n||{}}},u=>{if(!u.statusCode||u.statusCode<200||u.statusCode>=300){p(new Error(`HTTP ${u.statusCode||"unknown"}`)),u.resume();return}u.resume(),l();});m.setTimeout(r,()=>{m.destroy(new Error(`Request timeout after ${r}ms`));}),m.on("error",u=>{p(u);}),m.write(i),m.end();});}function Jd(t){return new Promise(e=>setTimeout(e,t))}async function df(t,e,r,o){let n=ft(t,e||".workspai/reports/evidence-export-dead-letter.ndjson");return await M.ensureDir(b.dirname(n)),await promises.appendFile(n,`${JSON.stringify({timestamp:new Date().toISOString(),reason:o,payload:r})}
|
|
153
|
-
`,"utf-8"),n}function uf(t,e){if(!e?.enabled)return {headers:{}};let r=process.env[e.hmacKeyEnv];if(!r)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let o=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(o,r).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":o}}}async function mf(t,e,r){let o=(r.algorithm||"sha256").toLowerCase(),n=ft(t,r.publicKeyPath);if(!await M.pathExists(n))return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(o);c.update(i),c.end();let l=Buffer.from(r.signature,"base64"),p=c.verify(a,l),m=createHash("sha256").update(a).digest("hex");return {verified:p,algorithm:o,publicKeyPath:n,publicKeyFingerprint:m,signature:r.signature,message:p?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Attestation verification error: ${a.message}`}}}async function gf(t,e,r,o){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};let a=r.signaturePath?ft(t,r.signaturePath):null;if(!a||!await M.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=r.certificatePath?ft(t,r.certificatePath):null;c&&i.push("--certificate",c);let l=r.bundlePath?ft(t,r.bundlePath):null;l&&i.push("--bundle",l);let p=r.keyPath?ft(t,r.keyPath):null;p&&i.push("--key",p),r.identity&&i.push("--certificate-identity",r.identity),r.issuer&&i.push("--certificate-oidc-issuer",r.issuer),r.rekorUrl&&i.push("--rekor-url",r.rekorUrl),o.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let m=await execa("cosign",i,{reject:false});return m.exitCode===0?{verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${m.stderr||m.stdout||"unknown error"}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}catch(m){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${m.message}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}}async function ff(t,e){let r=e.algorithm||"sha256",o=ft(t,e.policyPath),n=ft(t,e.signaturePath),a=ft(t,e.publicKeyPath);if(!await M.pathExists(o))return {verified:false,message:`Governance policy bundle not found: ${o}`,policies:null};if(!await M.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await M.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(o,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),l=await promises.readFile(a,"utf-8"),p=createVerify(r);return p.update(i),p.end(),p.verify(l,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function As(t$2,e){let r=[],o={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=t$1(t$2,"mirror-config.json").find(C=>existsSync(C))??q$1(t$2,"mirror-config.json"),a=q$1(t$2,"mirror.lock"),i=q$1(t$2,"mirror","artifacts"),c=q$1(t$2,"reports"),l=await cf(t$2);if(!await M.pathExists(n))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:r,details:o};let p={};try{p=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return r.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:r,details:o}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||p.mode==="offline-only"))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:r,details:o};await M.ensureDir(i);try{await af(t$2,i);}catch(C){return r.push({id:"mirror.root.safety",status:"failed",message:C instanceof Error?C.message:String(C)}),{checks:r,details:o}}let u=Math.max(0,p.prefetch?.retries??2),f=Math.max(0,p.prefetch?.backoffMs??250),P=Math.max(1e3,p.prefetch?.timeoutMs??15e3),y=p.security?.requireAttestation===true,E=p.security?.requireSigstore===true,A=p.security?.requireTransparencyLog===true,S=p.security?.requireSignedGovernance===true,d=p.security?.evidenceExport,g=(process.env.RAPIDKIT_ENV||p.security?.governance?.environment||"dev").toLowerCase(),w=p.security?.governance?.policies||{};if(p.security?.governanceBundle){let C=await ff(t$2,p.security.governanceBundle);if(r.push({id:"governance.bundle.verify",status:C.verified?"passed":"failed",message:C.message}),C.verified&&C.policies)w=C.policies,o.governanceBundleVerified=true;else if(S)return {checks:r,details:o}}let k=w[g],h=A||k?.requireTransparencyLog===true,v=[],I=Array.isArray(p.artifacts)?p.artifacts:[],x=[];for(let C=0;C<I.length;C+=1){let _=I[C],N=_.id||`artifact-${C+1}`,V=_.source?ft(t$2,_.source):null,D=sf(_,N),q;try{q=nf(i,D),await Vd(i,q);}catch(te){r.push({id:`mirror.target.${N}`,status:"failed",message:te instanceof Error?te.message:String(te)});continue}let J=false,ae=q,pe=false,se=async()=>{pe&&await promises.rm(ae,{force:true}).catch(()=>{});},qe={sourceType:"path",source:V||_.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(V&&await M.pathExists(V))await M.ensureDir(b.dirname(q)),ae=`${q}.${process.pid}.${randomUUID()}.tmp`,pe=true,await promises.copyFile(V,ae),o.syncedArtifacts+=1,J=true,qe={sourceType:"path",source:V,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},r.push({id:`mirror.sync.${N}`,status:"passed",message:`Mirrored artifact ${N} from source path.`});else if(_.url){let te="";try{te=new URL(_.url).hostname.toLowerCase();}catch{r.push({id:`mirror.prefetch.${N}`,status:"failed",message:`Invalid URL for ${N}: ${_.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||l.has(te))){r.push({id:`mirror.prefetch.trust.${N}`,status:"failed",message:`Untrusted mirror host for ${N}: ${te}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await M.pathExists(q)?(J=true,qe={sourceType:"url",source:_.url,host:te,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},r.push({id:`mirror.prefetch.${N}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${N}.`})):r.push({id:`mirror.prefetch.${N}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${N} without an existing mirrored copy.`}),!J))continue;if(!J){await M.ensureDir(b.dirname(q)),ae=`${q}.${process.pid}.${randomUUID()}.tmp`,pe=true;let Y=null,O=0;for(let B=1;B<=u+1;B+=1){O=B;try{await promises.rm(ae,{force:true}).catch(()=>{}),await lf(_.url,ae,P),o.syncedArtifacts+=1,J=true,qe={sourceType:"url",source:_.url,host:te,fetchedAt:new Date().toISOString(),attempts:O,trusted:true},r.push({id:`mirror.prefetch.${N}`,status:"passed",message:O>1?`Prefetched artifact ${N} from ${te} after ${O} attempts.`:`Prefetched artifact ${N} from ${te}.`});break}catch(H){if(Y=H,B<=u){await Jd(f*B);continue}}}if(!J){await se(),r.push({id:`mirror.prefetch.${N}`,status:"failed",message:`Failed to prefetch ${N} after ${u+1} attempt(s): ${Y?.message||"unknown error"}`});continue}}if(!J){r.push({id:`mirror.prefetch.${N}`,status:"failed",message:`Failed to prefetch ${N}.`});continue}}if(!J){_.required||e.offlineMode?r.push({id:`mirror.sync.${N}`,status:"failed",message:`Mirror source missing for ${N}${V?`: ${V}`:""}`}):r.push({id:`mirror.sync.${N}`,status:"skipped",message:`Mirror source not found for optional artifact ${N}.`});continue}let Ye=await rf(ae);if(_.sha256&&_.sha256.toLowerCase()!==Ye.toLowerCase()){r.push({id:`mirror.verify.${N}`,status:"failed",message:`Checksum mismatch for ${N}.`}),await se();continue}o.verifiedArtifacts+=1,r.push({id:`mirror.verify.${N}`,status:"passed",message:`Checksum verified for ${N}.`});let Ee=_.attestation?await mf(t$2,ae,_.attestation):null;if(_.attestation){if(r.push({id:`mirror.attest.${N}`,status:Ee?.verified?"passed":"failed",message:Ee?.message||"Attestation verification failed."}),!Ee?.verified){await se();continue}}else if(y){r.push({id:`mirror.attest.${N}`,status:"failed",message:`Attestation is required but missing for ${N}.`}),await se();continue}else r.push({id:`mirror.attest.${N}`,status:"skipped",message:`No attestation provided for ${N}.`});let L=_.attestation?.sigstore,G=L?await gf(t$2,ae,L,{requireTransparencyLog:h}):null;if(L){if(r.push({id:`mirror.sigstore.${N}`,status:G?.verified?"passed":"failed",message:G?.message||"Sigstore verification failed."}),v.push({artifactId:N,verified:!!G?.verified,tlogVerified:!!G?.tlogVerified,identity:G?.identity||null,issuer:G?.issuer||null,rekorUrl:G?.rekorUrl||null,timestamp:new Date().toISOString(),environment:g}),!G?.verified){await se();continue}}else if(E){r.push({id:`mirror.sigstore.${N}`,status:"failed",message:`Sigstore attestation is required but missing for ${N}.`}),await se();continue}else r.push({id:`mirror.sigstore.${N}`,status:"skipped",message:`No Sigstore attestation provided for ${N}.`});if(L&&G?.verified&&k){let te=k.allowedIdentities||[];if(te.length>0){let Y=!!G.identity&&te.includes(G.identity);if(r.push({id:`mirror.sigstore.policy.identity.${N}`,status:Y?"passed":"failed",message:Y?`Sigstore identity policy passed for ${N} in ${g}.`:`Sigstore identity policy failed for ${N} in ${g}.`}),!Y){await se();continue}}let z=k.allowedIssuers||[];if(z.length>0){let Y=!!G.issuer&&z.includes(G.issuer);if(r.push({id:`mirror.sigstore.policy.issuer.${N}`,status:Y?"passed":"failed",message:Y?`Sigstore issuer policy passed for ${N} in ${g}.`:`Sigstore issuer policy failed for ${N} in ${g}.`}),!Y){await se();continue}}let ee=k.allowedRekorUrls||[];if(ee.length>0){let Y=!!G.rekorUrl&&ee.includes(G.rekorUrl);if(r.push({id:`mirror.sigstore.policy.rekor.${N}`,status:Y?"passed":"failed",message:Y?`Sigstore Rekor policy passed for ${N} in ${g}.`:`Sigstore Rekor policy failed for ${N} in ${g}.`}),!Y){await se();continue}}}else k&&r.push({id:`mirror.sigstore.policy.${N}`,status:"skipped",message:`Sigstore governance policy configured for ${g} but no verified Sigstore attestation for ${N}.`});pe&&(await Vd(i,q),await promises.rename(ae,q),pe=false);let oe=await promises.stat(q);x.push({id:N,path:b.relative(t$2,q),sha256:Ye,size:oe.size,provenance:qe,attestation:{detached:{provided:!!_.attestation,verified:Ee?.verified||false,algorithm:Ee?.algorithm||null,publicKeyPath:Ee?.publicKeyPath||null,publicKeyFingerprint:Ee?.publicKeyFingerprint||null,signature:Ee?.signature||null,verifiedAt:Ee?.verified?new Date().toISOString():null},sigstore:{provided:!!L,verified:G?.verified||false,tlogVerified:G?.tlogVerified||false,identity:G?.identity||null,issuer:G?.issuer||null,rekorUrl:G?.rekorUrl||null,bundlePath:G?.bundlePath||null,certificatePath:G?.certificatePath||null,signaturePath:G?.signaturePath||null,verifiedAt:G?.verified?new Date().toISOString():null}}});}let j=p.retention?.keepLast;if(typeof j=="number"&&j>0){let C=new Set(x.map(N=>b.resolve(t$2,N.path))),_=(await of(i)).filter(N=>!C.has(b.resolve(N)));if(_.length>j){let N=await Promise.all(_.map(async D=>({filePath:D,stat:await promises.stat(D)})));N.sort((D,q)=>q.stat.mtimeMs-D.stat.mtimeMs);let V=N.slice(j);for(let D of V)await promises.unlink(D.filePath),o.rotatedFiles+=1;}}r.push({id:"mirror.rotate",status:"passed",message:o.rotatedFiles>0?`Mirror retention rotation removed ${o.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let R={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:p.mode||null,environment:g,artifacts:x};if(await promises.writeFile(a,`${JSON.stringify(R,null,2)}
|
|
153
|
+
`,"utf-8"),n}function uf(t,e){if(!e?.enabled)return {headers:{}};let r=process.env[e.hmacKeyEnv];if(!r)return {headers:{},error:`Evidence signing key env is missing: ${e.hmacKeyEnv}`};let o=(e.algorithm||"sha256").toLowerCase(),n=e.headerName||"x-rapidkit-evidence-signature",a=createHmac(o,r).update(JSON.stringify(t)).digest("hex");return {headers:{[n]:a,"x-rapidkit-evidence-signature-alg":o}}}async function mf(t,e,r){let o=(r.algorithm||"sha256").toLowerCase(),n=ft(t,r.publicKeyPath);if(!await M.pathExists(n))return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Public key not found: ${n}`};try{let a=await promises.readFile(n,"utf-8"),i=await promises.readFile(e),c=createVerify(o);c.update(i),c.end();let l=Buffer.from(r.signature,"base64"),p=c.verify(a,l),m=createHash("sha256").update(a).digest("hex");return {verified:p,algorithm:o,publicKeyPath:n,publicKeyFingerprint:m,signature:r.signature,message:p?"Attestation verified.":"Attestation signature verification failed."}}catch(a){return {verified:false,algorithm:o,publicKeyPath:n,publicKeyFingerprint:"",signature:r.signature,message:`Attestation verification error: ${a.message}`}}}async function gf(t,e,r,o){let n=process.env.RAPIDKIT_SIGSTORE_MOCK;if(n==="success")return {verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};if(n==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:r.signaturePath||null};let a=r.signaturePath?ft(t,r.signaturePath):null;if(!a||!await M.pathExists(a))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:r.bundlePath||null,certificatePath:r.certificatePath||null,signaturePath:a};let i=["verify-blob",e,"--signature",a],c=r.certificatePath?ft(t,r.certificatePath):null;c&&i.push("--certificate",c);let l=r.bundlePath?ft(t,r.bundlePath):null;l&&i.push("--bundle",l);let p=r.keyPath?ft(t,r.keyPath):null;p&&i.push("--key",p),r.identity&&i.push("--certificate-identity",r.identity),r.issuer&&i.push("--certificate-oidc-issuer",r.issuer),r.rekorUrl&&i.push("--rekor-url",r.rekorUrl),o.requireTransparencyLog||i.push("--insecure-ignore-tlog");try{let m=await execa("cosign",i,{reject:false});return m.exitCode===0?{verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed.",identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${m.stderr||m.stdout||"unknown error"}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}catch(m){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${m.message}`,identity:r.identity||null,issuer:r.issuer||null,rekorUrl:r.rekorUrl||null,bundlePath:l,certificatePath:c,signaturePath:a}}}async function ff(t,e){let r=e.algorithm||"sha256",o=ft(t,e.policyPath),n=ft(t,e.signaturePath),a=ft(t,e.publicKeyPath);if(!await M.pathExists(o))return {verified:false,message:`Governance policy bundle not found: ${o}`,policies:null};if(!await M.pathExists(n))return {verified:false,message:`Governance policy signature not found: ${n}`,policies:null};if(!await M.pathExists(a))return {verified:false,message:`Governance policy public key not found: ${a}`,policies:null};try{let i=await promises.readFile(o,"utf-8"),c=(await promises.readFile(n,"utf-8")).trim(),l=await promises.readFile(a,"utf-8"),p=createVerify(r);return p.update(i),p.end(),p.verify(l,Buffer.from(c,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(i).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(i){return {verified:false,message:`Governance policy bundle verification error: ${i.message}`,policies:null}}}async function xs(t$2,e){let r=[],o={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},n=t$1(t$2,"mirror-config.json").find(C=>existsSync(C))??q$1(t$2,"mirror-config.json"),a=q$1(t$2,"mirror.lock"),i=q$1(t$2,"mirror","artifacts"),c=q$1(t$2,"reports"),l=await cf(t$2);if(!await M.pathExists(n))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .workspai/mirror-config.json not found."}),{checks:r,details:o};let p={};try{p=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return r.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:r,details:o}}if(!(e.forceRun===true||e.ciMode||e.offlineMode||p.mode==="offline-only"))return r.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:r,details:o};await M.ensureDir(i);try{await af(t$2,i);}catch(C){return r.push({id:"mirror.root.safety",status:"failed",message:C instanceof Error?C.message:String(C)}),{checks:r,details:o}}let u=Math.max(0,p.prefetch?.retries??2),f=Math.max(0,p.prefetch?.backoffMs??250),P=Math.max(1e3,p.prefetch?.timeoutMs??15e3),y=p.security?.requireAttestation===true,E=p.security?.requireSigstore===true,A=p.security?.requireTransparencyLog===true,S=p.security?.requireSignedGovernance===true,d=p.security?.evidenceExport,g=(process.env.RAPIDKIT_ENV||p.security?.governance?.environment||"dev").toLowerCase(),w=p.security?.governance?.policies||{};if(p.security?.governanceBundle){let C=await ff(t$2,p.security.governanceBundle);if(r.push({id:"governance.bundle.verify",status:C.verified?"passed":"failed",message:C.message}),C.verified&&C.policies)w=C.policies,o.governanceBundleVerified=true;else if(S)return {checks:r,details:o}}let k=w[g],h=A||k?.requireTransparencyLog===true,v=[],I=Array.isArray(p.artifacts)?p.artifacts:[],x=[];for(let C=0;C<I.length;C+=1){let _=I[C],N=_.id||`artifact-${C+1}`,V=_.source?ft(t$2,_.source):null,D=sf(_,N),q;try{q=nf(i,D),await Vd(i,q);}catch(te){r.push({id:`mirror.target.${N}`,status:"failed",message:te instanceof Error?te.message:String(te)});continue}let J=false,ae=q,pe=false,se=async()=>{pe&&await promises.rm(ae,{force:true}).catch(()=>{});},qe={sourceType:"path",source:V||_.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(V&&await M.pathExists(V))await M.ensureDir(b.dirname(q)),ae=`${q}.${process.pid}.${randomUUID()}.tmp`,pe=true,await promises.copyFile(V,ae),o.syncedArtifacts+=1,J=true,qe={sourceType:"path",source:V,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},r.push({id:`mirror.sync.${N}`,status:"passed",message:`Mirrored artifact ${N} from source path.`});else if(_.url){let te="";try{te=new URL(_.url).hostname.toLowerCase();}catch{r.push({id:`mirror.prefetch.${N}`,status:"failed",message:`Invalid URL for ${N}: ${_.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||l.has(te))){r.push({id:`mirror.prefetch.trust.${N}`,status:"failed",message:`Untrusted mirror host for ${N}: ${te}. Add host to .workspai/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(e.offlineMode&&(await M.pathExists(q)?(J=true,qe={sourceType:"url",source:_.url,host:te,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},r.push({id:`mirror.prefetch.${N}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${N}.`})):r.push({id:`mirror.prefetch.${N}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${N} without an existing mirrored copy.`}),!J))continue;if(!J){await M.ensureDir(b.dirname(q)),ae=`${q}.${process.pid}.${randomUUID()}.tmp`,pe=true;let Y=null,O=0;for(let B=1;B<=u+1;B+=1){O=B;try{await promises.rm(ae,{force:true}).catch(()=>{}),await lf(_.url,ae,P),o.syncedArtifacts+=1,J=true,qe={sourceType:"url",source:_.url,host:te,fetchedAt:new Date().toISOString(),attempts:O,trusted:true},r.push({id:`mirror.prefetch.${N}`,status:"passed",message:O>1?`Prefetched artifact ${N} from ${te} after ${O} attempts.`:`Prefetched artifact ${N} from ${te}.`});break}catch(H){if(Y=H,B<=u){await Jd(f*B);continue}}}if(!J){await se(),r.push({id:`mirror.prefetch.${N}`,status:"failed",message:`Failed to prefetch ${N} after ${u+1} attempt(s): ${Y?.message||"unknown error"}`});continue}}if(!J){r.push({id:`mirror.prefetch.${N}`,status:"failed",message:`Failed to prefetch ${N}.`});continue}}if(!J){_.required||e.offlineMode?r.push({id:`mirror.sync.${N}`,status:"failed",message:`Mirror source missing for ${N}${V?`: ${V}`:""}`}):r.push({id:`mirror.sync.${N}`,status:"skipped",message:`Mirror source not found for optional artifact ${N}.`});continue}let Ye=await rf(ae);if(_.sha256&&_.sha256.toLowerCase()!==Ye.toLowerCase()){r.push({id:`mirror.verify.${N}`,status:"failed",message:`Checksum mismatch for ${N}.`}),await se();continue}o.verifiedArtifacts+=1,r.push({id:`mirror.verify.${N}`,status:"passed",message:`Checksum verified for ${N}.`});let Ee=_.attestation?await mf(t$2,ae,_.attestation):null;if(_.attestation){if(r.push({id:`mirror.attest.${N}`,status:Ee?.verified?"passed":"failed",message:Ee?.message||"Attestation verification failed."}),!Ee?.verified){await se();continue}}else if(y){r.push({id:`mirror.attest.${N}`,status:"failed",message:`Attestation is required but missing for ${N}.`}),await se();continue}else r.push({id:`mirror.attest.${N}`,status:"skipped",message:`No attestation provided for ${N}.`});let L=_.attestation?.sigstore,G=L?await gf(t$2,ae,L,{requireTransparencyLog:h}):null;if(L){if(r.push({id:`mirror.sigstore.${N}`,status:G?.verified?"passed":"failed",message:G?.message||"Sigstore verification failed."}),v.push({artifactId:N,verified:!!G?.verified,tlogVerified:!!G?.tlogVerified,identity:G?.identity||null,issuer:G?.issuer||null,rekorUrl:G?.rekorUrl||null,timestamp:new Date().toISOString(),environment:g}),!G?.verified){await se();continue}}else if(E){r.push({id:`mirror.sigstore.${N}`,status:"failed",message:`Sigstore attestation is required but missing for ${N}.`}),await se();continue}else r.push({id:`mirror.sigstore.${N}`,status:"skipped",message:`No Sigstore attestation provided for ${N}.`});if(L&&G?.verified&&k){let te=k.allowedIdentities||[];if(te.length>0){let Y=!!G.identity&&te.includes(G.identity);if(r.push({id:`mirror.sigstore.policy.identity.${N}`,status:Y?"passed":"failed",message:Y?`Sigstore identity policy passed for ${N} in ${g}.`:`Sigstore identity policy failed for ${N} in ${g}.`}),!Y){await se();continue}}let z=k.allowedIssuers||[];if(z.length>0){let Y=!!G.issuer&&z.includes(G.issuer);if(r.push({id:`mirror.sigstore.policy.issuer.${N}`,status:Y?"passed":"failed",message:Y?`Sigstore issuer policy passed for ${N} in ${g}.`:`Sigstore issuer policy failed for ${N} in ${g}.`}),!Y){await se();continue}}let ee=k.allowedRekorUrls||[];if(ee.length>0){let Y=!!G.rekorUrl&&ee.includes(G.rekorUrl);if(r.push({id:`mirror.sigstore.policy.rekor.${N}`,status:Y?"passed":"failed",message:Y?`Sigstore Rekor policy passed for ${N} in ${g}.`:`Sigstore Rekor policy failed for ${N} in ${g}.`}),!Y){await se();continue}}}else k&&r.push({id:`mirror.sigstore.policy.${N}`,status:"skipped",message:`Sigstore governance policy configured for ${g} but no verified Sigstore attestation for ${N}.`});pe&&(await Vd(i,q),await promises.rename(ae,q),pe=false);let oe=await promises.stat(q);x.push({id:N,path:b.relative(t$2,q),sha256:Ye,size:oe.size,provenance:qe,attestation:{detached:{provided:!!_.attestation,verified:Ee?.verified||false,algorithm:Ee?.algorithm||null,publicKeyPath:Ee?.publicKeyPath||null,publicKeyFingerprint:Ee?.publicKeyFingerprint||null,signature:Ee?.signature||null,verifiedAt:Ee?.verified?new Date().toISOString():null},sigstore:{provided:!!L,verified:G?.verified||false,tlogVerified:G?.tlogVerified||false,identity:G?.identity||null,issuer:G?.issuer||null,rekorUrl:G?.rekorUrl||null,bundlePath:G?.bundlePath||null,certificatePath:G?.certificatePath||null,signaturePath:G?.signaturePath||null,verifiedAt:G?.verified?new Date().toISOString():null}}});}let j=p.retention?.keepLast;if(typeof j=="number"&&j>0){let C=new Set(x.map(N=>b.resolve(t$2,N.path))),_=(await of(i)).filter(N=>!C.has(b.resolve(N)));if(_.length>j){let N=await Promise.all(_.map(async D=>({filePath:D,stat:await promises.stat(D)})));N.sort((D,q)=>q.stat.mtimeMs-D.stat.mtimeMs);let V=N.slice(j);for(let D of V)await promises.unlink(D.filePath),o.rotatedFiles+=1;}}r.push({id:"mirror.rotate",status:"passed",message:o.rotatedFiles>0?`Mirror retention rotation removed ${o.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let R={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:p.mode||null,environment:g,artifacts:x};if(await promises.writeFile(a,`${JSON.stringify(R,null,2)}
|
|
154
154
|
`,"utf-8"),o.lockWritten=true,r.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${b.relative(t$2,a)}.`}),o.transparencyEvidenceRecords=v.length,v.length>0){let C={schemaVersion:s$1.transparencyEvidence.schemaVersion,generatedAt:new Date().toISOString(),environment:g,records:v},_=new Date().toISOString().replace(/[:.]/g,"-"),N=b.join(c,`transparency-evidence-${_}.json`),V=b.join(c,"transparency-evidence.latest.json");if(b$q(`.workspai/reports/${b.basename(N)}`,C),b$q(t.transparencyEvidence,C),await M.ensureDir(c),await Gd(N,C),await Gd(V,C),o.transparencyEvidenceWritten=true,r.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${b.relative(t$2,V)}.`}),d?.enabled){let D=Math.max(1e3,d.timeoutMs??1e4);if(d.target==="file")if(!d.filePath)r.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let q=ft(t$2,d.filePath);await M.ensureDir(b.dirname(q)),await promises.appendFile(q,`${JSON.stringify(C)}
|
|
155
|
-
`,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=q,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${q}.`});}catch(q){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${q.message}`});}else if(d.target==="http")if(!d.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let q=Math.max(0,d.retries??0),J=Math.max(0,d.backoffMs??500),ae=uf(C,d.signing);ae.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:ae.error});try{let pe=d.authTokenEnv?process.env[d.authTokenEnv]:void 0,se=false,qe=null;for(let Ye=1;Ye<=q+1;Ye+=1)try{if(ae.error)throw new Error(ae.error);await pf(d.endpoint,C,D,pe,ae.headers),o.evidenceExported=true,o.evidenceExportTarget=d.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:Ye>1?`Transparency evidence exported to HTTP endpoint ${d.endpoint} after ${Ye} attempts.`:`Transparency evidence exported to HTTP endpoint ${d.endpoint}.`}),se=true;break}catch(Ee){qe=Ee,Ye<=q&&await Jd(J*Ye);}if(!se)throw qe||new Error("unknown evidence export error")}catch(pe){let se=`Evidence HTTP export failed: ${pe.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:se});try{let qe=await df(t$2,d.deadLetterPath,C,se);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${qe}.`});}catch(qe){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${qe.message}`});}}}if(d.failOnError&&r.some(J=>J.status==="failed"&&(J.id==="sigstore.evidence.export.file"||J.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function Vn(t){let e=f$6(t.detection.runtime),r=x$2({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function hf(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function Jn(t){if(t.existingProjectJson?.module_support===true){let e=hf(t.existingProjectJson),r=e?a$3(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}var zd=[a$e,b$b];function wf(t,e){let r=b.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!b.isAbsolute(r)}async function pt(t){let e=await M__default.realpath(t);for(let r of zd){let o=b.join(t,r),n=await M__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await M__default.realpath(o);if(!wf(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function Yd(t){let e=b.basename(t);return zd.includes(e)?(await M__default.lstat(t)).isSymbolicLink():false}function Xd(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function kf(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return Xd(a)||"imported-project"}function Gt(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function vf(t){return Gt(t)?"git-url":"local-folder"}async function Pf(t,e){let r=Xd(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=b.join(t,n);if(!await M__default.pathExists(a))return a;o+=1;}}function bf(t,e){let r=b.resolve(t),o=b.resolve(e),n=b.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!b.isAbsolute(n)}function jf(t,e){if(bf(t,e))throw new Error("Import source must be outside the current workspace root.")}function Cf(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function Ef(t){let e=b.basename(t);return !(await Yd(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||Cf(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Sf(t){await pt(t);for(let e of u$1(t,"project.json"))if(await M__default.pathExists(e))try{return await M__default.readJson(e)}catch{return null}return null}async function Af(t){await pt(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),o=a$g({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=v$2(t.projectPath,"project.json"),i=v$2(t.projectPath,"import.json"),c=v$2(t.projectPath,"import-readiness.json"),l=Jn({existingProjectJson:t.existingProjectJson}),p=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],m=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},u={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:b.basename(t.projectPath),kind:t.projectKind,category:a$h(t.projectKind),project_type:a$h(t.projectKind),runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:l,modules:p,contracts:m,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},f={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:b.basename(t.projectPath)},project:{name:u.name,slug:u.slug,relative_path:n,kind:t.projectKind,category:a$h(t.projectKind),module_support:l},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$h(t.projectKind),confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:l,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},P=Vn({projectName:String(u.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:l,projectPath:t.projectPath,generatedAt:new Date(e)});return await M__default.ensureDir(b.dirname(a)),await M__default.writeJson(a,u,{spaces:2}),await M__default.writeJson(i,f,{spaces:2}),await M__default.writeJson(c,P,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:l}}async function Rf(t,e){let r={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,relationship:"imported",importedAt:new Date().toISOString()};await b$e(t,[r]);}async function xf(t){await M__default.pathExists(t)&&(await pt(t),await M__default.remove(t));}async function If(t,e){await xf(e),await c$4(t,[e]);}async function Qd(t){let e=b.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??vf(r),n=t.name??(o==="git-url"?kf(r):b.basename(r)),a=await Pf(e,n),i=false;try{if(o==="local-folder"){let g=b.resolve(r),w=await M__default.stat(g).catch(()=>null);if(!w||!w.isDirectory())throw new Error("Import source is not a directory.");if(await pt(g),k$1(g))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");jf(e,g),i=true,await M__default.copy(g,a,{overwrite:false,errorOnExist:true,filter:Ef});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$f()});await pt(a);let c=await Sf(a),l=m$2(a,c),p=await b$c(a,c,{runtime:l.runtime,framework:l.key}),[m,u]=await Promise.all([Z(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):Y(e)]),f=X({profile:m,runtime:l.runtime,subjectLabel:b.basename(a),mode:u}),P=W({profile:m,runtimes:await _(e,{additionalRuntimes:[l.runtime]}),mode:u}),y=f.ok?P:f;if(!y.ok&&u==="strict")throw new Error(y.message);let E=await Af({workspacePath:e,projectPath:a,sourceType:o,detection:l,existingProjectJson:c,projectKind:p,profileCompatibility:y}),A=a$g({workspacePath:e,projectPath:a,projectName:b.basename(a)}),S={ingestionPlan:Qt({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:b.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:b.basename(a),path:a,relativePath:A.contractRelativePath,stack:l.importStack,runtime:l.runtime,framework:l.key,frameworkDisplayName:l.displayName,supportTier:l.supportTier,moduleSupport:E.moduleSupport,confidence:l.confidence,source:o,projectJsonPath:E.projectJsonPath,importJsonPath:E.importJsonPath,importReadinessPath:E.importReadinessPath,profileCompatibility:y};await Rf(e,S);let{syncWorkspaceContract:d}=await import('./workspace-contract-3QUZDBMM.js');return await d({workspacePath:e,strict:true}),await k$3({workspacePath:e,projectPath:S.path,projectName:S.name,relationship:"imported",mode:t.projectGrounding??"managed"}),S}catch(c){if(i)try{await If(e,a);let{syncWorkspaceContract:l}=await import('./workspace-contract-3QUZDBMM.js');await l({workspacePath:e,strict:true});}catch(l){let p=c instanceof Error?c.message:String(c),m=l instanceof Error?l.message:String(l);throw new Error(`Import failed: ${p}. Rollback also failed: ${m}`)}throw c}}function _f(t){return {schemaVersion:Fn,sourceMode:"linked",sourceCodeModified:false,projectMetadataFiles:[".workspai/project.json",".workspai/adopt.json",".workspai/adopt-readiness.json",f$1,...t==="off"?[]:[h$1,g$3,b$a,i$1]],repositoryControlFiles:[{path:".gitignore",action:"reconcile",condition:"machine-local workspace binding and project-grounding portability rules"},...t==="managed"?[{path:"AGENTS.md",action:"reconcile",condition:"managed grounding is enabled and the path is a regular file; authored deletions and symbolic links are preserved"},{path:".agents/skills/workspai-*/SKILL.md",action:"reconcile",condition:"managed provider-neutral Skill discovery is enabled; authored collisions and unsafe symbolic links are preserved"},...g$4.map(e=>({path:e,action:"reconcile",condition:"managed provider adapter is enabled; authored content, deletions, symbolic links, and unsafe parent paths are preserved"}))]:[]],workspaceOperations:["register-project","sync-contract","rebuild-model","rebuild-graph","sync-agent-grounding"]}}function Of(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Nf(t,e){return b.resolve(t)===b.resolve(e)}async function $f(t){await pt(t);for(let e of u$1(t,"project.json")){if(!await M__default.pathExists(e))continue;let r;try{r=JSON.parse((await M__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}async function Zd(t,e){let r=b.relative(t,e);if(r.startsWith("..")||b.isAbsolute(r))return true;let o=r.split(b.sep).slice(0,-1),n=t;for(let a of o){n=b.join(n,a);let i=await M__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)return false;if(i.isSymbolicLink()||!i.isDirectory())return true}return false}async function Tf(t){let e=b.join(t,".amazonq"),r=await M__default.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!r)return [e,b.join(e,"rules")];if(r.isSymbolicLink()||!r.isDirectory())return [];let o=b.join(e,"rules");return await M__default.lstat(o).catch(a=>{if(a.code==="ENOENT")return null;throw a})?[]:[o]}async function eu(t,e){let r=[b.join(e,"AGENTS.md"),...g$4.map(n=>b.join(e,n))],o=[];for(let n of r){if(!(await M__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c}))?.isSymbolicLink())continue;let i=await a$d(e,n);i&&o.push(i);}return [v$2(e,"project.json"),v$2(e,"adopt.json"),v$2(e,"adopt-readiness.json"),b.join(e,f$1),b.join(e,g$3),b.join(e,h$1),b.join(e,b$a),...r,...o,b.join(e,".gitignore"),q$1(t,"imported-projects.json")].filter((n,a,i)=>i.indexOf(n)===a)}async function Rs(t,e){let r=b.resolve(t),o=b.resolve(e);await pt(o);let n=await eu(r,o);return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>{if(a.startsWith(`${o}${b.sep}`)&&await Zd(o,a))return {path:a,contents:null,preserve:"unsafe-parent"};let i=await M__default.lstat(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});return i?.isSymbolicLink()?{path:a,contents:null,preserve:"symbolic-link"}:{path:a,contents:i?.isFile()?await M__default.readFile(a):null}})),createdAdapterDirectories:await Tf(o)}}async function tu(t,e,r){let o=(await eu(e,r)).map(a=>b.resolve(a)),n=new Set([".amazonq",".amazonq/rules"].map(a=>b.resolve(r,a)));if(t.workspacePath!==b.resolve(e)||t.projectPath!==b.resolve(r)||t.files.length!==o.length||t.files.some((a,i)=>b.resolve(a.path)!==o[i])||t.createdAdapterDirectories.some(a=>!n.has(b.resolve(a)))||new Set(t.createdAdapterDirectories.map(a=>b.resolve(a))).size!==t.createdAdapterDirectories.length)throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function Mf(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,category:a$h(t.projectKind),project_type:a$h(t.projectKind),runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,framework:t.detection.key,kit:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function Wf(t,e,r){await pt(e),await tu(r,t,e);let o=[];for(let n of r.files)try{if(n.preserve==="symbolic-link")continue;n.contents===null?await M__default.remove(n.path):(await M__default.ensureDir(b.dirname(n.path)),await M__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}for(let n of [...r.createdAdapterDirectories].reverse())try{if(await Zd(e,n))continue;await M__default.rmdir(n);}catch(a){let i=a.code;i!=="ENOENT"&&i!=="ENOTEMPTY"&&o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function xs(t$1){let e=b.resolve(t$1.workspacePath),r=b.resolve(t$1.source),o=await M__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await pt(r),Nf(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(k$1(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t$1.rollbackSnapshot??await Rs(e,r);await tu(n,e,r);let a=await $f(r),i=j$5(a),c=m$2(r,i?null:a),l=l$1(r),p=[c.runtime,...l.filter(R=>R!==c.runtime)].filter((R,C,_)=>R!=="unknown"&&_.indexOf(R)===C);p.length===0&&p.push("unknown");let m=await b$c(r,i?{}:a,{runtime:c.runtime,framework:c.key}),u=Of(t$1.name||(typeof a?.name=="string"?a.name:"")||b.basename(r))||"adopted-project",f=a$g({workspacePath:e,projectPath:r,projectName:u}),P=(t$1.now??new Date).toISOString(),y=v$2(r,"project.json"),E=v$2(r,"adopt.json"),A=v$2(r,"adopt-readiness.json"),S=Jn({existingProjectJson:a}),[d,g]=await Promise.all([Z(e),t$1.profilePolicyMode?Promise.resolve(t$1.profilePolicyMode):Y(e)]),w=X({profile:d,runtime:c.runtime,subjectLabel:u,mode:g}),k=W({profile:d,runtimes:await _(e,{additionalRuntimes:p,excludeProjectPath:r}),mode:g}),h=w.ok?k:w;if(!h.ok&&g==="strict")throw new Error(h.message);let v=Mf({projectName:u,contractRelativePath:f.contractRelativePath,isExternal:f.isExternal,discoveredRelativePath:f.relativePath,detection:c,runtimeCandidates:p,existingProjectJson:a,refreshManagedDetection:i,projectKind:m,moduleSupport:S,adoptedAt:P}),I=await b$d(e),x={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:P,managed_by:"workspai",mode:"linked",workspace:{name:I,contract:t.workspaceContract},project:{name:u,relative_path:f.contractRelativePath,...f.isExternal?{}:{discovered_relative_path:f.relativePath},is_external:f.isExternal,kind:m,category:a$h(m),module_support:S},detection:{framework:c.key,framework_display_name:c.displayName,runtime:c.runtime,runtime_candidates:p,kind:m,category:a$h(m),confidence:c.confidence,support_tier:c.supportTier,import_stack:c.importStack,source:c.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:S,workspace_contract:"linked-project",profile_compatibility:{ok:h.ok,profile:h.profile,runtimes:h.runtimes,message:h.message,recommended_profile:h.recommendedProfile,recommended_command:h.recommendedCommand}}},j=Vn({projectName:u,relativePath:f.contractRelativePath,projectKind:m,source:"adopted-local",detection:c,moduleSupport:S,projectPath:r,generatedAt:new Date(P)});if(t$1.dryRun!==true)try{await pt(r),await M__default.ensureDir(b.dirname(y)),await M__default.writeJson(y,v,{spaces:2}),await M__default.writeJson(E,x,{spaces:2}),await M__default.writeJson(A,j,{spaces:2});let R={name:u,path:r,relativePath:f.contractRelativePath,relationship:"adopted",stack:c.importStack,runtime:c.runtime,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:S,confidence:c.confidence,source:"adopted-local",importedAt:P};await b$e(e,[R]);let{syncWorkspaceContract:C}=await import('./workspace-contract-3QUZDBMM.js');await C({workspacePath:e,strict:true}),await k$3({workspacePath:e,projectPath:r,projectName:u,relationship:"adopted",mode:t$1.projectGrounding??"managed",now:new Date(P)});}catch(R){try{await Wf(e,r,n);let{syncWorkspaceContract:C}=await import('./workspace-contract-3QUZDBMM.js');await C({workspacePath:e,strict:true});}catch(C){throw new AggregateError([R,C],`Adopt failed and rollback was incomplete: ${R instanceof Error?R.message:String(R)}`)}throw R}return {ingestionPlan:Qt({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t$1.projectGrounding??"managed"}),name:u,path:r,relativePath:f.relativePath,contractRelativePath:f.contractRelativePath,isExternal:f.isExternal,relationship:"adopted",stack:c.importStack,runtime:c.runtime,runtimeCandidates:p,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:S,confidence:c.confidence,projectJsonPath:y,adoptJsonPath:E,adoptReadinessPath:A,profileCompatibility:h,effects:_f(t$1.projectGrounding??"managed"),wroteFiles:t$1.dryRun!==true}}async function Df(t){for(let e of [a$e,b$b]){let r=b.join(t,e),o=await M__default.lstat(r).catch(()=>null);if(o){if(o.isSymbolicLink())return `${e}/ (symbolic link)`;if(!o.isDirectory())return `${e} (not a directory)`;if(!k$1(t))return `${e}/ (partial workspace metadata without root marker)`}}return null}async function Bn(t,e={}){let r=b.resolve(t),o=await M__default.lstat(r).catch(()=>null);if(!o)return {status:"not-clean",conflicts:["path does not exist"]};if(o.isSymbolicLink())return {status:"not-clean",conflicts:["path is a symbolic link"]};if(!o.isDirectory())return {status:"not-clean",conflicts:["path is not a directory"]};if(k$1(r))return {status:"valid-workspace"};let n=await Df(r);if(n)return {status:"not-clean",conflicts:[n]};let a=await M__default.readdir(r,{withFileTypes:true});if(a.length===0)return {status:"eligible",reason:"empty"};let i=e.containedProjectPath?b.resolve(e.containedProjectPath):null;if(i!==null&&b.dirname(i)===r&&a.length===1){let[l]=a;if(l.name===b.basename(i)&&l.isDirectory()&&!l.isSymbolicLink())return {status:"eligible",reason:"single-project-container"}}return {status:"not-clean",conflicts:a.map(l=>l.isDirectory()?`${l.name}/`:l.isSymbolicLink()?`${l.name} (symbolic link)`:l.name)}}function _s(t){let e=b.resolve(t),r=b.parse(e).root;return e!==r}function Os(t,e){let r=e.conflicts.slice(0,5).join(", "),o=e.conflicts.length>5?` (+${e.conflicts.length-5} more)`:"";return `Workspace path is not a valid Workspai workspace and is not clean enough to bootstrap: ${t}. Conflicts: ${r}${o}`}async function ru(t){let e=b.resolve(t.sourcePath),r=b.dirname(e),o=await Bn(r,{containedProjectPath:e});return {parentEligible:_s(r)&&(o.status==="eligible"||o.status==="valid-workspace"),parentAssessment:o}}async function ou(t,e={}){let r=b.resolve(t),o=await Bn(r);return o.status==="valid-workspace"?{ok:true,result:{workspacePath:r,resolution:"explicit",usedDefaultWorkspace:false,willCreateDefaultWorkspace:false,willBootstrapWorkspace:false,bootstrapTargetPath:null}}:o.status==="eligible"?{ok:true,result:{workspacePath:r,resolution:"explicit-bootstrap",usedDefaultWorkspace:false,willCreateDefaultWorkspace:false,willBootstrapWorkspace:e.dryRun!==true,bootstrapTargetPath:r}}:{ok:false,code:"workspace.adopt.target-not-clean",message:Os(r,o)}}async function nu(t){let e=b.resolve(t.sourcePath),r=b.dirname(e),o=await Bn(r,{containedProjectPath:e}),n=t.outsideWorkspaceMode??"managed";return n==="managed"?{ok:true,result:{workspacePath:p$2(),resolution:"default-auto",usedDefaultWorkspace:true,willCreateDefaultWorkspace:t.dryRun!==true,willBootstrapWorkspace:false,bootstrapTargetPath:null}}:n==="parent"?_s(r)?o.status==="valid-workspace"?{ok:true,result:{workspacePath:r,resolution:"nearest",usedDefaultWorkspace:false,willCreateDefaultWorkspace:false,willBootstrapWorkspace:false,bootstrapTargetPath:null}}:o.status==="eligible"?{ok:true,result:{workspacePath:r,resolution:"parent-bootstrap",usedDefaultWorkspace:false,willCreateDefaultWorkspace:false,willBootstrapWorkspace:t.dryRun!==true,bootstrapTargetPath:r}}:{ok:false,code:"workspace.adopt.parent-not-clean",message:Os(r,o)}:{ok:false,code:"workspace.adopt.parent-not-eligible",message:`Parent folder cannot be turned into a workspace: ${r}`}:{ok:false,code:"workspace.adopt.mode-invalid",message:`Unsupported adopt workspace mode: ${String(n)}`}}function au(){return [{name:"Link it to the managed default workspace",value:"managed"},{name:"Turn the parent folder into a workspace (recommended)",value:"parent"}]}function su(){return 1}async function Lf(t){let e=await M__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=b.join(t,r),n=await M__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function Ff(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await M__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=b.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$i(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$7&&(await M__default.remove(i),e.push(b.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function cu(t,e){if(await b$f(t,await b$d(t)),!(await g$5(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$n(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function Ns(t){let e=b.resolve(t.workspacePath);await Lf(e);let r=Qt({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!k$1(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return Hn(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$5(e);try{let n=await cu(e,t.projectGrounding??"managed");return Hn(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$6(e,o).catch(()=>{}),n}}async function $s(t){if(t.dryRun){let o=await p$3({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=b.resolve(o.outputPath),a=iu(t,n);return Hn(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?b.resolve(t.outputPath):void 0;if(e&&await M__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$3({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=b.resolve(o.outputPath);let n=iu(t,r);if(!k$1(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await Ff(r);o.manifest?.portableContract&&await M__default.outputJson(b.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await cu(r,t.projectGrounding??"managed");return Hn(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,l,p)=>p.indexOf(c)===l),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$5(r).catch(()=>{}),await M__default.remove(r).catch(()=>{})),o}}function iu(t,e){return Qt({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function Hn(t,e){let r={schemaVersion:Ln,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$4(r,Dd,"Workspace ingestion result"),r}function lu(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function pu(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function du(t){let e=t.trim(),r=e.startsWith("~/")?b.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!Gt(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:Gt(r)?r:b.resolve(r)};if(Gt(r))return {kind:"git-project",source:r};let n=b.resolve(r);return k$1(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var Kf=Dn,Uf=Mn;function Ms(t){if(!t||typeof t!="object")return null;let e=t.code;return e==="PYTHON_NOT_FOUND"||e==="BRIDGE_VENV_BOOTSTRAP_FAILED"||e==="BRIDGE_VENV_CREATE_FAILED"||e==="BRIDGE_PIP_BOOTSTRAP_FAILED"?e:null}function Bf(t=process.argv){let e=b.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function $r(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function Hf(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Re(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function qf(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Js(t){try{return qf(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function ni(t,e){let r=Re(t,"--port")?.trim(),o=t[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Re(t,"--output")||".",i=b.resolve(e,a,o),c=u$1(i,"project.json").find(p=>$.existsSync(p))??v$2(i,"project.json");if(!await M__default.pathExists(c))return;let l=await M__default.readJson(c);await M__default.writeJson(c,{...l,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Ws(t){let e=xe(process.cwd()),r=t.trim().toLowerCase();if(!e||!r||L(r))return true;try{let[o,n]=await Promise.all([Z(e),Y(e)]),a=a$3(r),i=l$5(r),c=r$2(r),l=R(r),p=i?"node":c?.runtime??a?.runtime??l?.runtime??"python",m=X({profile:o,runtime:p,subjectLabel:r,mode:n}),u=W({profile:o,runtimes:await _(e,{additionalRuntimes:[p]}),mode:n}),f=m.ok?u:m;if(f.ok)return true;let P=$$1(f);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${f.message}`)),P&&console.log(s.gray(`\u{1F4A1} ${P}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${f.message}`)),P&&console.log(s.gray(`\u{1F4A1} ${P}`));}catch{}return true}function ai(){return j$8()}function Ks(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(b.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$4()),t.RAPIDKIT_SKIP_LOCK_SYNC||(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t.POETRY_KEYRING_ENABLED||(t.POETRY_KEYRING_ENABLED="false"),t.PYTHON_KEYRING_BACKEND||(t.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),t.POETRY_NO_INTERACTION||(t.POETRY_NO_INTERACTION="1"),t}function zf(t){return m$6(b.join(t,".venv"))}async function Yf(t,e){return await Ie(t,["--version"],e)===0}async function Xf(t,e){return new Promise(r=>{let o=spawn(t,["--version"],{cwd:e,stdio:"ignore",env:Ks()});o.once("error",()=>r(false)),o.once("close",n=>r(n===0));})}async function rr(t){let e=b.join(t,"go.mod");if(await M__default.pathExists(e))return "go";let r=b.join(t,"pom.xml"),o=b.join(t,"build.gradle"),n=b.join(t,"build.gradle.kts");if(await M__default.pathExists(r)||await M__default.pathExists(o)||await M__default.pathExists(n))return "java";if((await M__default.pathExists(t)?await $.promises.readdir(t,{withFileTypes:true}):[]).some(P=>P.isFile()&&P.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=b.join(t,"src");if(await M__default.pathExists(i)&&(await $.promises.readdir(i,{withFileTypes:true})).some(y=>y.isFile()&&y.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=b.join(t,"Cargo.toml");if(await M__default.pathExists(c))return "rust";let l=b.join(t,"composer.json");if(await M__default.pathExists(l))return "php";let p=b.join(t,"package.json");if(await M__default.pathExists(p))return "node";let m=b.join(t,"pyproject.toml"),u=b.join(t,"requirements.txt"),f=b.join(t,"poetry.lock");return await M__default.pathExists(m)||await M__default.pathExists(u)||await M__default.pathExists(f)?"python":null}async function Qf(t,e={}){let r=e.runCommand??Ie,o=b.join(t,".venv"),n=await M__default.pathExists(o);for(let a of e.pythonCandidates??ai()){if(await r(a,a==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;n||await M__default.remove(o);}return 1}async function Zf(t,e={}){let r=e.runCommand??Ie,o=b.join(t,".venv"),n=m$6(o);if(await M__default.pathExists(n)){if(await r(n,["-m","pip","--version"],t)===0)return 0;await M__default.remove(o);}let a=await Qf(t,e);if(a!==0)return a;n=m$6(o);let i=await r(n,["-m","pip","--version"],t);return i!==0&&await M__default.remove(o),i}async function xu(t,e={}){let r=e.runCommand??Ie;for(let o of e.pythonCandidates??ai())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function eh(t,e={}){let r=e.runCommand??Ie,o=m$6(b.join(t,".venv"));if(!await M__default.pathExists(o)){let p=await xu(t,e);if(p!==0)return p}let n=process.platform==="win32"?b.join(t,".venv","Scripts","poetry.exe"):b.join(t,".venv","bin","poetry"),a=e.runCommand?await r("poetry",["--version"],t)===0:await Xf("poetry",t),i=await M__default.pathExists(n)?n:a?"poetry":null;if(!i)return 0;let c=await r(i,["config","virtualenvs.in-project","true","--local"],t);if(c!==0)return c;let l=await r(i,["env","use",o],t);return l!==0?l:0}async function th(t,e={}){let r=e.runCommand??Ie,o=m$6(b.join(t,".venv"));if(!await M__default.pathExists(o)){let i=await xu(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=b.join(t,"requirements.txt");if(await M__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=b.join(t,"pyproject.toml");return await M__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function Ds(t,e){return await eh(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await M__default.pathExists(b.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await th(t))}async function Ls(t){let e=await tr("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await Yf(o,t))continue;if(await Ie(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function rh(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Re([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Re([...e],"--java-version"),a=Re([...e],"--spring-boot-version"),i=Re([...e],"--springdoc-version"),c=Re([...e],"--group-id"),l=Re([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(l&&!/^[A-Za-z0-9_.-]+$/.test(l.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Re([...e],"--target-framework"),a=Re([...e],"--root-namespace");if(n&&!/^net\d+\.\d+$/.test(n.trim()))return "Invalid --target-framework. Expected .NET target framework, e.g. net8.0";if(a&&!/^[A-Za-z0-9_.]+$/.test(a.trim()))return "Invalid --root-namespace. Use dot-separated .NET namespace identifiers only."}return null}async function qn(t,e={}){if(t.includes("--dry-run")||t.includes("--no-workspace")||Ys(process.cwd()))return;let r=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:n}=await import('./create-YPAZJYCE.js');await n(process.cwd(),{skipGit:r,yes:t.includes("--yes")||t.includes("-y"),userConfig:await c()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:o}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},...e.requireWorkspace?[]:[{name:"Create it without workspace management",value:"none"}]],default:1}]);if(o==="current"){let{registerWorkspaceAtPath:n}=await import('./create-YPAZJYCE.js');await n(process.cwd(),{skipGit:r,yes:false,userConfig:await c()});}else o==="none"&&t.push("--no-workspace");}async function oh(t,e){if(e.json||e.explicitWorkspace||xe(t)||!process.stdin.isTTY||!(await ru({sourcePath:t})).parentEligible)return;let o=au(),{workspaceMode:n}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:o,default:su()}]);return n}async function nh(t,e){let{registerWorkspaceAtPath:r}=await import('./create-YPAZJYCE.js');await r(t,{skipGit:true,yes:true,testMode:process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",userConfig:await c(),lifecycleTransaction:e});}async function ah(t){await M__default.ensureDir(t);let e=b.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await $.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
|
|
156
|
-
`),async()=>{await o.close().catch(()=>{}),await M__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await M__default.readJson(e).catch(()=>null),a=Number(n?.pid),i=false;if(Number.isInteger(a)&&a>0)try{process.kill(a,0),i=true;}catch(c){i=c.code==="EPERM";}if(!i){await M__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function
|
|
157
|
-
`),1}let o=t[3];if(!o)return process.stderr.write(`Usage: workspai create project ${r.id} <name> [--agent-name <name>] [--output <dir>] [--dry-run]
|
|
155
|
+
`,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=q,r.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${q}.`});}catch(q){r.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${q.message}`});}else if(d.target==="http")if(!d.endpoint)r.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let q=Math.max(0,d.retries??0),J=Math.max(0,d.backoffMs??500),ae=uf(C,d.signing);ae.error&&r.push({id:"sigstore.evidence.export.http",status:"failed",message:ae.error});try{let pe=d.authTokenEnv?process.env[d.authTokenEnv]:void 0,se=false,qe=null;for(let Ye=1;Ye<=q+1;Ye+=1)try{if(ae.error)throw new Error(ae.error);await pf(d.endpoint,C,D,pe,ae.headers),o.evidenceExported=true,o.evidenceExportTarget=d.endpoint,r.push({id:"sigstore.evidence.export.http",status:"passed",message:Ye>1?`Transparency evidence exported to HTTP endpoint ${d.endpoint} after ${Ye} attempts.`:`Transparency evidence exported to HTTP endpoint ${d.endpoint}.`}),se=true;break}catch(Ee){qe=Ee,Ye<=q&&await Jd(J*Ye);}if(!se)throw qe||new Error("unknown evidence export error")}catch(pe){let se=`Evidence HTTP export failed: ${pe.message}`;r.push({id:"sigstore.evidence.export.http",status:"failed",message:se});try{let qe=await df(t$2,d.deadLetterPath,C,se);r.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${qe}.`});}catch(qe){r.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${qe.message}`});}}}if(d.failOnError&&r.some(J=>J.status==="failed"&&(J.id==="sigstore.evidence.export.file"||J.id==="sigstore.evidence.export.http")))return {checks:r,details:o}}else r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else r.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),r.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:r,details:o}}function Jn(t){let e=f$6(t.detection.runtime),r=x$2({runtime:t.detection.runtime,moduleSupport:t.moduleSupport,projectPath:t.projectPath,framework:t.detection.key}),o=[];o.push({id:"framework-detection",status:t.detection.key==="unknown"?"warn":"pass",message:t.detection.key==="unknown"?"Workspai could not confidently identify the project framework.":`Detected ${t.detection.displayName} with ${t.detection.confidence} confidence.`,recommendation:t.detection.key==="unknown"?"Add .workspai/project.json metadata or import a project with recognizable runtime manifests.":void 0}),o.push({id:"runtime-support",status:e.tier==="observed"?"warn":"pass",message:`${e.displayName} is supported at ${e.tier} tier.`,recommendation:e.tier==="observed"?"Observed runtimes are contract-aware but may need manual commands until a first-class kit exists.":void 0}),o.push({id:"module-mutation-policy",status:t.moduleSupport?"pass":"warn",message:t.moduleSupport?"RapidKit Core module mutation is enabled for this project.":"RapidKit Core module mutation is disabled for this imported project.",recommendation:t.moduleSupport?void 0:"Use project lifecycle and workspace governance commands; enable module_support only after validating a compatible module generator."}),o.push({id:"lifecycle-commands",status:r.lifecycleCommands.length>1?"pass":"warn",message:r.lifecycleCommands.length>1?`Lifecycle commands available: ${r.lifecycleCommands.join(", ")}.`:"Only help-level lifecycle support is available for this runtime today.",recommendation:r.lifecycleCommands.length>1?void 0:"Add runtime scripts or a Workspai runtime adapter before relying on dev/test/build/start."});let n=o.some(i=>i.status==="fail"),a=o.some(i=>i.status==="warn");return {schemaVersion:1,kind:"rapidkit.import_readiness",generatedAt:(t.generatedAt??new Date).toISOString(),status:n?"blocked":a?"review":"ready",project:{name:t.projectName,relativePath:t.relativePath,...t.projectKind?{kind:t.projectKind}:{},source:t.source},detection:{runtime:t.detection.runtime,framework:t.detection.key,frameworkDisplayName:t.detection.displayName,confidence:t.detection.confidence,supportTier:t.detection.supportTier,importStack:t.detection.importStack},commandSupport:{lifecycleCommands:r.lifecycleCommands,unsupportedLifecycleCommands:r.unsupportedLifecycleCommands,moduleCommands:r.moduleCommands},checks:o}}function hf(t){if(typeof t?.kit_name=="string")return t.kit_name;if(typeof t?.kit=="string")return t.kit}function Kn(t){if(t.existingProjectJson?.module_support===true){let e=hf(t.existingProjectJson),r=e?a$3(e):void 0;return r?.owner==="core"&&r.moduleSupport===true}return false}var zd=[a$e,b$b];function wf(t,e){let r=b.relative(t,e);return r===""||r.length>0&&!r.startsWith("..")&&!b.isAbsolute(r)}async function pt(t){let e=await M__default.realpath(t);for(let r of zd){let o=b.join(t,r),n=await M__default.lstat(o).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!n)continue;if(n.isSymbolicLink())throw new Error(`Project metadata directory must not be a symlink: ${o}`);let a=await M__default.realpath(o);if(!wf(e,a))throw new Error(`Project metadata directory resolves outside the project: ${o}`)}}async function Yd(t){let e=b.basename(t);return zd.includes(e)?(await M__default.lstat(t)).isSymbolicLink():false}function Xd(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function kf(t){let e=t.trim();if(!e)return "imported-project";let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),o=r[r.length-1]||e,n=o.split(":"),a=(n[n.length-1]||o).replace(/\.git$/i,"");return Xd(a)||"imported-project"}function Gt(t){let e=t.trim();return e.includes("://")||e.startsWith("git@")}function vf(t){return Gt(t)?"git-url":"local-folder"}async function Pf(t,e){let r=Xd(e)||"imported-project",o=0;for(;;){let n=o===0?r:o===1?`${r}-imported`:`${r}-imported-${o}`,a=b.join(t,n);if(!await M__default.pathExists(a))return a;o+=1;}}function bf(t,e){let r=b.resolve(t),o=b.resolve(e),n=b.relative(r,o);return n===""||n.length>0&&!n.startsWith("..")&&!b.isAbsolute(n)}function jf(t,e){if(bf(t,e))throw new Error("Import source must be outside the current workspace root.")}function Cf(t){return t.startsWith(".env")?![".env.example",".env.sample",".env.template",".env.defaults",".env.dist"].includes(t):false}async function Ef(t){let e=b.basename(t);return !(await Yd(t)||[".git","node_modules",".venv","venv","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".turbo",".cache","dist","build","target","bin","obj","vendor"].includes(e)||Cf(e)||e.endsWith(".pem")||e.endsWith(".key"))}async function Sf(t){await pt(t);for(let e of u$1(t,"project.json"))if(await M__default.pathExists(e))try{return await M__default.readJson(e)}catch{return null}return null}async function Af(t){await pt(t.projectPath);let e=new Date().toISOString(),r=typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),o=a$g({workspacePath:t.workspacePath,projectPath:t.projectPath,projectName:r}),n=o.contractRelativePath,a=v$2(t.projectPath,"project.json"),i=v$2(t.projectPath,"import.json"),c=v$2(t.projectPath,"import-readiness.json"),l=Kn({existingProjectJson:t.existingProjectJson}),p=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],m=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]},u={...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:b.basename(t.projectPath),slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:b.basename(t.projectPath),kind:t.projectKind,category:a$h(t.projectKind),project_type:a$h(t.projectKind),runtime:t.detection.runtime,framework:t.detection.key,kit:typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`imported.${t.detection.key}`,kit_name:typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`imported.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:l,modules:p,contracts:m,import:{managed_by:"workspai",source_type:t.sourceType,imported_at:e,relative_path:n,discovered_relative_path:o.relativePath,is_external:o.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}},f={schema_version:"1.0",kind:"workspai.imported_project",imported_at:e,managed_by:"workspai",source:{type:t.sourceType,name:b.basename(t.projectPath)},project:{name:u.name,slug:u.slug,relative_path:n,kind:t.projectKind,category:a$h(t.projectKind),module_support:l},detection:{framework:t.detection.key,framework_display_name:t.detection.displayName,runtime:t.detection.runtime,kind:t.projectKind,category:a$h(t.projectKind),confidence:t.detection.confidence,support_tier:t.detection.supportTier,import_stack:t.detection.importStack,source:t.detection.source},policy:{copied_secrets:false,copied_dependency_caches:false,module_mutation_enabled:l,profile_compatibility:{ok:t.profileCompatibility.ok,profile:t.profileCompatibility.profile,runtimes:t.profileCompatibility.runtimes,message:t.profileCompatibility.message,recommended_profile:t.profileCompatibility.recommendedProfile,recommended_command:t.profileCompatibility.recommendedCommand}}},P=Jn({projectName:String(u.name),relativePath:n,projectKind:t.projectKind,source:t.sourceType,detection:t.detection,moduleSupport:l,projectPath:t.projectPath,generatedAt:new Date(e)});return await M__default.ensureDir(b.dirname(a)),await M__default.writeJson(a,u,{spaces:2}),await M__default.writeJson(i,f,{spaces:2}),await M__default.writeJson(c,P,{spaces:2}),{projectJsonPath:a,importJsonPath:i,importReadinessPath:c,moduleSupport:l}}async function Rf(t,e){let r={name:e.name,path:e.path,relativePath:e.relativePath,stack:e.stack,runtime:e.runtime,framework:e.framework,frameworkDisplayName:e.frameworkDisplayName,supportTier:e.supportTier,moduleSupport:e.moduleSupport,confidence:e.confidence,source:e.source,relationship:"imported",importedAt:new Date().toISOString()};await b$e(t,[r]);}async function xf(t){await M__default.pathExists(t)&&(await pt(t),await M__default.remove(t));}async function If(t,e){await xf(e),await c$4(t,[e]);}async function Qd(t){let e=b.resolve(t.workspacePath),r=t.source.trim(),o=t.sourceType??vf(r),n=t.name??(o==="git-url"?kf(r):b.basename(r)),a=await Pf(e,n),i=false;try{if(o==="local-folder"){let g=b.resolve(r),w=await M__default.stat(g).catch(()=>null);if(!w||!w.isDirectory())throw new Error("Import source is not a directory.");if(await pt(g),k$1(g))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");jf(e,g),i=true,await M__default.copy(g,a,{overwrite:false,errorOnExist:true,filter:Ef});}else i=true,await execa("git",["clone","--depth","1","--",r,a],{timeout:12e4,env:a$f()});await pt(a);let c=await Sf(a),l=m$2(a,c),p=await b$c(a,c,{runtime:l.runtime,framework:l.key}),[m,u]=await Promise.all([Y(e),t.profilePolicyMode?Promise.resolve(t.profilePolicyMode):X(e)]),f=W({profile:m,runtime:l.runtime,subjectLabel:b.basename(a),mode:u}),P=V({profile:m,runtimes:await Z(e,{additionalRuntimes:[l.runtime]}),mode:u}),y=f.ok?P:f;if(!y.ok&&u==="strict")throw new Error(y.message);let E=await Af({workspacePath:e,projectPath:a,sourceType:o,detection:l,existingProjectJson:c,projectKind:p,profileCompatibility:y}),A=a$g({workspacePath:e,projectPath:a,projectName:b.basename(a)}),S={ingestionPlan:Qt({action:"import-project",resourceKind:"project",sourceKind:o,mode:o==="git-url"?"clone":"copy",ownership:o==="git-url"?"materialized":"workspace-owned",registration:"project",source:o==="git-url"?r:b.resolve(r),targetWorkspace:e,destination:a,projectGrounding:t.projectGrounding??"managed"}),name:b.basename(a),path:a,relativePath:A.contractRelativePath,stack:l.importStack,runtime:l.runtime,framework:l.key,frameworkDisplayName:l.displayName,supportTier:l.supportTier,moduleSupport:E.moduleSupport,confidence:l.confidence,source:o,projectJsonPath:E.projectJsonPath,importJsonPath:E.importJsonPath,importReadinessPath:E.importReadinessPath,profileCompatibility:y};await Rf(e,S);let{syncWorkspaceContract:d}=await import('./workspace-contract-N2BJCAJ7.js');return await d({workspacePath:e,strict:true}),await k$3({workspacePath:e,projectPath:S.path,projectName:S.name,relationship:"imported",mode:t.projectGrounding??"managed"}),S}catch(c){if(i)try{await If(e,a);let{syncWorkspaceContract:l}=await import('./workspace-contract-N2BJCAJ7.js');await l({workspacePath:e,strict:true});}catch(l){let p=c instanceof Error?c.message:String(c),m=l instanceof Error?l.message:String(l);throw new Error(`Import failed: ${p}. Rollback also failed: ${m}`)}throw c}}function _f(t){return {schemaVersion:Gn,sourceMode:"linked",sourceCodeModified:false,projectMetadataFiles:[".workspai/project.json",".workspai/adopt.json",".workspai/adopt-readiness.json",f$1,...t==="off"?[]:[h$1,g$3,b$a,i$1]],repositoryControlFiles:[{path:".gitignore",action:"reconcile",condition:"machine-local workspace binding and project-grounding portability rules"},...t==="managed"?[{path:"AGENTS.md",action:"reconcile",condition:"managed grounding is enabled and the path is a regular file; authored deletions and symbolic links are preserved"},{path:".agents/skills/workspai-*/SKILL.md",action:"reconcile",condition:"managed provider-neutral Skill discovery is enabled; authored collisions and unsafe symbolic links are preserved"},...g$4.map(e=>({path:e,action:"reconcile",condition:"managed provider adapter is enabled; authored content, deletions, symbolic links, and unsafe parent paths are preserved"}))]:[]],workspaceOperations:["register-project","sync-contract","rebuild-model","rebuild-graph","sync-agent-grounding"]}}function Of(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}function Nf(t,e){return b.resolve(t)===b.resolve(e)}async function $f(t){await pt(t);for(let e of u$1(t,"project.json")){if(!await M__default.pathExists(e))continue;let r;try{r=JSON.parse((await M__default.readFile(e)).toString("utf8"));}catch(o){throw new Error(`Authoritative project metadata is malformed: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Authoritative project metadata is malformed: ${e}: expected a JSON object`);return r}return null}async function Zd(t,e){let r=b.relative(t,e);if(r.startsWith("..")||b.isAbsolute(r))return true;let o=r.split(b.sep).slice(0,-1),n=t;for(let a of o){n=b.join(n,a);let i=await M__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!i)return false;if(i.isSymbolicLink()||!i.isDirectory())return true}return false}async function Tf(t){let e=b.join(t,".amazonq"),r=await M__default.lstat(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!r)return [e,b.join(e,"rules")];if(r.isSymbolicLink()||!r.isDirectory())return [];let o=b.join(e,"rules");return await M__default.lstat(o).catch(a=>{if(a.code==="ENOENT")return null;throw a})?[]:[o]}async function eu(t,e){let r=[b.join(e,"AGENTS.md"),...g$4.map(n=>b.join(e,n))],o=[];for(let n of r){if(!(await M__default.lstat(n).catch(c=>{if(c.code==="ENOENT")return null;throw c}))?.isSymbolicLink())continue;let i=await a$d(e,n);i&&o.push(i);}return [v$2(e,"project.json"),v$2(e,"adopt.json"),v$2(e,"adopt-readiness.json"),b.join(e,f$1),b.join(e,g$3),b.join(e,h$1),b.join(e,b$a),...r,...o,b.join(e,".gitignore"),q$1(t,"imported-projects.json")].filter((n,a,i)=>i.indexOf(n)===a)}async function Is(t,e){let r=b.resolve(t),o=b.resolve(e);await pt(o);let n=await eu(r,o);return {workspacePath:r,projectPath:o,files:await Promise.all(n.map(async a=>{if(a.startsWith(`${o}${b.sep}`)&&await Zd(o,a))return {path:a,contents:null,preserve:"unsafe-parent"};let i=await M__default.lstat(a).catch(c=>{if(c.code==="ENOENT")return null;throw c});return i?.isSymbolicLink()?{path:a,contents:null,preserve:"symbolic-link"}:{path:a,contents:i?.isFile()?await M__default.readFile(a):null}})),createdAdapterDirectories:await Tf(o)}}async function tu(t,e,r){let o=(await eu(e,r)).map(a=>b.resolve(a)),n=new Set([".amazonq",".amazonq/rules"].map(a=>b.resolve(r,a)));if(t.workspacePath!==b.resolve(e)||t.projectPath!==b.resolve(r)||t.files.length!==o.length||t.files.some((a,i)=>b.resolve(a.path)!==o[i])||t.createdAdapterDirectories.some(a=>!n.has(b.resolve(a)))||new Set(t.createdAdapterDirectories.map(a=>b.resolve(a))).size!==t.createdAdapterDirectories.length)throw new Error("Adopt rollback snapshot does not match the workspace and project paths.")}function Mf(t){let e=Array.isArray(t.existingProjectJson?.modules)?t.existingProjectJson.modules:[],r=t.existingProjectJson?.contracts&&typeof t.existingProjectJson.contracts=="object"&&!Array.isArray(t.existingProjectJson.contracts)?t.existingProjectJson.contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]};return {...t.existingProjectJson||{},schema_version:typeof t.existingProjectJson?.schema_version=="string"?t.existingProjectJson.schema_version:"1.0",name:typeof t.existingProjectJson?.name=="string"?t.existingProjectJson.name:t.projectName,slug:typeof t.existingProjectJson?.slug=="string"?t.existingProjectJson.slug:t.projectName,kind:t.projectKind,category:a$h(t.projectKind),project_type:a$h(t.projectKind),runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,framework:t.detection.key,kit:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit=="string"?t.existingProjectJson.kit:`adopted.${t.detection.key}`,kit_name:!t.refreshManagedDetection&&typeof t.existingProjectJson?.kit_name=="string"?t.existingProjectJson.kit_name:`adopted.${t.detection.key}`,engine:typeof t.existingProjectJson?.engine=="string"?t.existingProjectJson.engine:"npm",module_support:t.moduleSupport,modules:e,contracts:r,adoption:{managed_by:"workspai",mode:"linked",adopted_at:t.adoptedAt,relative_path:t.contractRelativePath,...t.isExternal?{}:{discovered_relative_path:t.discoveredRelativePath},is_external:t.isExternal,detection:{framework:t.detection.key,runtime:t.detection.runtime,runtime_candidates:t.runtimeCandidates,confidence:t.detection.confidence,support_tier:t.detection.supportTier,source:t.detection.source}}}}async function Wf(t,e,r){await pt(e),await tu(r,t,e);let o=[];for(let n of r.files)try{if(n.preserve==="symbolic-link")continue;n.contents===null?await M__default.remove(n.path):(await M__default.ensureDir(b.dirname(n.path)),await M__default.writeFile(n.path,n.contents));}catch(a){o.push(a);}for(let n of [...r.createdAdapterDirectories].reverse())try{if(await Zd(e,n))continue;await M__default.rmdir(n);}catch(a){let i=a.code;i!=="ENOENT"&&i!=="ENOTEMPTY"&&o.push(a);}if(o.length>0)throw new AggregateError(o,"Failed to restore adopt rollback snapshot.")}async function _s(t$1){let e=b.resolve(t$1.workspacePath),r=b.resolve(t$1.source),o=await M__default.stat(r).catch(()=>null);if(!o||!o.isDirectory())throw new Error("Adopt source is not a directory.");if(await pt(r),Nf(e,r))throw new Error("Adopt source cannot be the workspace root itself.");if(k$1(r))throw new Error("This path is a Workspai workspace. Use `workspai workspace connect <path>` instead.");let n=t$1.rollbackSnapshot??await Is(e,r);await tu(n,e,r);let a=await $f(r),i=j$5(a),c=m$2(r,i?null:a),l=l$1(r),p=[c.runtime,...l.filter(R=>R!==c.runtime)].filter((R,C,_)=>R!=="unknown"&&_.indexOf(R)===C);p.length===0&&p.push("unknown");let m=await b$c(r,i?{}:a,{runtime:c.runtime,framework:c.key}),u=Of(t$1.name||(typeof a?.name=="string"?a.name:"")||b.basename(r))||"adopted-project",f=a$g({workspacePath:e,projectPath:r,projectName:u}),P=(t$1.now??new Date).toISOString(),y=v$2(r,"project.json"),E=v$2(r,"adopt.json"),A=v$2(r,"adopt-readiness.json"),S=Kn({existingProjectJson:a}),[d,g]=await Promise.all([Y(e),t$1.profilePolicyMode?Promise.resolve(t$1.profilePolicyMode):X(e)]),w=W({profile:d,runtime:c.runtime,subjectLabel:u,mode:g}),k=V({profile:d,runtimes:await Z(e,{additionalRuntimes:p,excludeProjectPath:r}),mode:g}),h=w.ok?k:w;if(!h.ok&&g==="strict")throw new Error(h.message);let v=Mf({projectName:u,contractRelativePath:f.contractRelativePath,isExternal:f.isExternal,discoveredRelativePath:f.relativePath,detection:c,runtimeCandidates:p,existingProjectJson:a,refreshManagedDetection:i,projectKind:m,moduleSupport:S,adoptedAt:P}),I=await b$d(e),x={schema_version:"1.0",kind:"workspai.adopted_project",adopted_at:P,managed_by:"workspai",mode:"linked",workspace:{name:I,contract:t.workspaceContract},project:{name:u,relative_path:f.contractRelativePath,...f.isExternal?{}:{discovered_relative_path:f.relativePath},is_external:f.isExternal,kind:m,category:a$h(m),module_support:S},detection:{framework:c.key,framework_display_name:c.displayName,runtime:c.runtime,runtime_candidates:p,kind:m,category:a$h(m),confidence:c.confidence,support_tier:c.supportTier,import_stack:c.importStack,source:c.source},policy:{moved_source:false,copied_source:false,module_mutation_enabled:S,workspace_contract:"linked-project",profile_compatibility:{ok:h.ok,profile:h.profile,runtimes:h.runtimes,message:h.message,recommended_profile:h.recommendedProfile,recommended_command:h.recommendedCommand}}},j=Jn({projectName:u,relativePath:f.contractRelativePath,projectKind:m,source:"adopted-local",detection:c,moduleSupport:S,projectPath:r,generatedAt:new Date(P)});if(t$1.dryRun!==true)try{await pt(r),await M__default.ensureDir(b.dirname(y)),await M__default.writeJson(y,v,{spaces:2}),await M__default.writeJson(E,x,{spaces:2}),await M__default.writeJson(A,j,{spaces:2});let R={name:u,path:r,relativePath:f.contractRelativePath,relationship:"adopted",stack:c.importStack,runtime:c.runtime,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:S,confidence:c.confidence,source:"adopted-local",importedAt:P};await b$e(e,[R]);let{syncWorkspaceContract:C}=await import('./workspace-contract-N2BJCAJ7.js');await C({workspacePath:e,strict:true}),await k$3({workspacePath:e,projectPath:r,projectName:u,relationship:"adopted",mode:t$1.projectGrounding??"managed",now:new Date(P)});}catch(R){try{await Wf(e,r,n);let{syncWorkspaceContract:C}=await import('./workspace-contract-N2BJCAJ7.js');await C({workspacePath:e,strict:true});}catch(C){throw new AggregateError([R,C],`Adopt failed and rollback was incomplete: ${R instanceof Error?R.message:String(R)}`)}throw R}return {ingestionPlan:Qt({action:"adopt-project",resourceKind:"project",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"project",source:r,targetWorkspace:e,destination:r,projectGrounding:t$1.projectGrounding??"managed"}),name:u,path:r,relativePath:f.relativePath,contractRelativePath:f.contractRelativePath,isExternal:f.isExternal,relationship:"adopted",stack:c.importStack,runtime:c.runtime,runtimeCandidates:p,framework:c.key,frameworkDisplayName:c.displayName,supportTier:c.supportTier,moduleSupport:S,confidence:c.confidence,projectJsonPath:y,adoptJsonPath:E,adoptReadinessPath:A,profileCompatibility:h,effects:_f(t$1.projectGrounding??"managed"),wroteFiles:t$1.dryRun!==true}}async function Df(t){for(let e of [a$e,b$b]){let r=b.join(t,e),o=await M__default.lstat(r).catch(()=>null);if(o){if(o.isSymbolicLink())return `${e}/ (symbolic link)`;if(!o.isDirectory())return `${e} (not a directory)`;if(!k$1(t))return `${e}/ (partial workspace metadata without root marker)`}}return null}async function Hn(t,e={}){let r=b.resolve(t),o=await M__default.lstat(r).catch(()=>null);if(!o)return {status:"not-clean",conflicts:["path does not exist"]};if(o.isSymbolicLink())return {status:"not-clean",conflicts:["path is a symbolic link"]};if(!o.isDirectory())return {status:"not-clean",conflicts:["path is not a directory"]};if(k$1(r))return {status:"valid-workspace"};let n=await Df(r);if(n)return {status:"not-clean",conflicts:[n]};let a=await M__default.readdir(r,{withFileTypes:true});if(a.length===0)return {status:"eligible",reason:"empty"};let i=e.containedProjectPath?b.resolve(e.containedProjectPath):null;if(i!==null&&b.dirname(i)===r&&a.length===1){let[l]=a;if(l.name===b.basename(i)&&l.isDirectory()&&!l.isSymbolicLink())return {status:"eligible",reason:"single-project-container"}}return {status:"not-clean",conflicts:a.map(l=>l.isDirectory()?`${l.name}/`:l.isSymbolicLink()?`${l.name} (symbolic link)`:l.name)}}function Ns(t){let e=b.resolve(t),r=b.parse(e).root;return e!==r}function $s(t,e){let r=e.conflicts.slice(0,5).join(", "),o=e.conflicts.length>5?` (+${e.conflicts.length-5} more)`:"";return `Workspace path is not a valid Workspai workspace and is not clean enough to bootstrap: ${t}. Conflicts: ${r}${o}`}async function ru(t){let e=b.resolve(t.sourcePath),r=b.dirname(e),o=await Hn(r,{containedProjectPath:e});return {parentEligible:Ns(r)&&(o.status==="eligible"||o.status==="valid-workspace"),parentAssessment:o}}async function ou(t,e={}){let r=b.resolve(t),o=await Hn(r);return o.status==="valid-workspace"?{ok:true,result:{workspacePath:r,resolution:"explicit",usedDefaultWorkspace:false,willCreateDefaultWorkspace:false,willBootstrapWorkspace:false,bootstrapTargetPath:null}}:o.status==="eligible"?{ok:true,result:{workspacePath:r,resolution:"explicit-bootstrap",usedDefaultWorkspace:false,willCreateDefaultWorkspace:false,willBootstrapWorkspace:e.dryRun!==true,bootstrapTargetPath:r}}:{ok:false,code:"workspace.adopt.target-not-clean",message:$s(r,o)}}async function nu(t){let e=b.resolve(t.sourcePath),r=b.dirname(e),o=await Hn(r,{containedProjectPath:e}),n=t.outsideWorkspaceMode??"managed";return n==="managed"?{ok:true,result:{workspacePath:p$2(),resolution:"default-auto",usedDefaultWorkspace:true,willCreateDefaultWorkspace:t.dryRun!==true,willBootstrapWorkspace:false,bootstrapTargetPath:null}}:n==="parent"?Ns(r)?o.status==="valid-workspace"?{ok:true,result:{workspacePath:r,resolution:"nearest",usedDefaultWorkspace:false,willCreateDefaultWorkspace:false,willBootstrapWorkspace:false,bootstrapTargetPath:null}}:o.status==="eligible"?{ok:true,result:{workspacePath:r,resolution:"parent-bootstrap",usedDefaultWorkspace:false,willCreateDefaultWorkspace:false,willBootstrapWorkspace:t.dryRun!==true,bootstrapTargetPath:r}}:{ok:false,code:"workspace.adopt.parent-not-clean",message:$s(r,o)}:{ok:false,code:"workspace.adopt.parent-not-eligible",message:`Parent folder cannot be turned into a workspace: ${r}`}:{ok:false,code:"workspace.adopt.mode-invalid",message:`Unsupported adopt workspace mode: ${String(n)}`}}function au(){return [{name:"Link it to the managed default workspace",value:"managed"},{name:"Turn the parent folder into a workspace (recommended)",value:"parent"}]}function su(){return 1}async function Lf(t){let e=await M__default.lstat(t).catch(()=>null);if(!e||!e.isDirectory()||e.isSymbolicLink())throw new Error(`Workspace path must be a real directory, not a symbolic link: ${t}`);for(let r of [".workspai",".rapidkit"]){let o=b.join(t,r),n=await M__default.lstat(o).catch(()=>null);if(n?.isSymbolicLink())throw new Error(`Workspace metadata directory must not be a symlink: ${o}`);if(n&&!n.isDirectory())throw new Error(`Workspace metadata path must be a directory: ${o}`)}}async function Ff(t){let e=[],r=[t];for(;r.length>0;){let o=r.shift();if(!o)continue;let n=await M__default.readdir(o,{withFileTypes:true}).catch(()=>[]);for(let a of n){if(a.isSymbolicLink())continue;let i=b.join(o,a.name);if(a.isDirectory()){if([".git","node_modules",".venv","dist","build","target"].includes(a.name)||a$i(a.name))continue;r.push(i);continue}a.isFile()&&a.name===e$7&&(await M__default.remove(i),e.push(b.relative(t,i).replace(/\\/g,"/")));}}return e.sort()}async function cu(t,e){if(await b$f(t,await b$d(t)),!(await g$5(t,true)).workspaceFound)throw new Error(`Workspace registry reconciliation failed: ${t}`);let o=await a$n(t,{silent:true,projectGrounding:e});return {writtenFiles:o.writtenFiles,warnings:o.warnings}}async function Ts(t){let e=b.resolve(t.workspacePath);await Lf(e);let r=Qt({action:"connect-workspace",resourceKind:"workspace",sourceKind:"local-folder",mode:"link",ownership:"external",registration:"workspace",source:e,destination:e,projectGrounding:t.projectGrounding??"managed"});if(!k$1(e))throw new Error(`Workspace path is not a valid Workspai workspace: ${e}`);if(t.dryRun)return qn(r,{status:"preview",workspacePath:e,registered:false,verified:true});let o=await c$5(e);try{let n=await cu(e,t.projectGrounding??"managed");return qn(r,{workspacePath:e,writtenFiles:n.writtenFiles,warnings:n.warnings,registered:true,verified:true})}catch(n){throw await d$6(e,o).catch(()=>{}),n}}async function Ms(t){if(t.dryRun){let o=await p$3({archivePathOrUrl:t.archivePathOrUrl,outputPath:t.outputPath,dryRun:true,strict:t.strict,safety:t.safety}),n=b.resolve(o.outputPath),a=iu(t,n);return qn(a,{status:"preview",workspacePath:n,registered:false,verified:true,warnings:(o.manifest?.externalProjects??[]).map(i=>`External project "${i.name}" must be relinked after import.`)})}let e=t.outputPath?b.resolve(t.outputPath):void 0;if(e&&await M__default.pathExists(e))throw new Error(`Workspace import destination already exists: ${e}. Choose a new --output path.`);let r;try{let o=await p$3({archivePathOrUrl:t.archivePathOrUrl,outputPath:e,strict:t.strict,safety:t.safety});r=b.resolve(o.outputPath);let n=iu(t,r);if(!k$1(r))throw new Error("Imported archive did not materialize a valid Workspai workspace.");let a=await Ff(r);o.manifest?.portableContract&&await M__default.outputJson(b.join(r,".workspai","workspace.contract.json"),o.manifest.portableContract,{spaces:2});let i=await cu(r,t.projectGrounding??"managed");return qn(n,{workspacePath:r,writtenFiles:[...o.files.map(c=>c.path),...i.writtenFiles].filter((c,l,p)=>p.indexOf(c)===l),warnings:[...i.warnings,...(o.manifest?.externalProjects??[]).map(c=>`External project "${c.name}" must be relinked after import.`),...a.length>0?[`Rebuilt ${a.length} machine-local project workspace link(s).`]:[]],registered:true,verified:true})}catch(o){throw r&&(await e$5(r).catch(()=>{}),await M__default.remove(r).catch(()=>{})),o}}function iu(t,e){return Qt({action:"import-workspace",resourceKind:"workspace",sourceKind:"archive",mode:"hydrate",ownership:"workspace-owned",registration:"workspace",source:t.archivePathOrUrl,destination:e,projectGrounding:t.projectGrounding??"managed"})}function qn(t,e){let r={schemaVersion:Fn,status:"passed",plan:t,writtenFiles:[],warnings:[],...e};return a$4(r,Dd,"Workspace ingestion result"),r}function lu(t){let e={name:"Add existing software (local project, Git repository, or workspace)",value:"existing"};return t?[{name:"Create a project",value:"project"},e,{name:"Create another workspace (outside the current workspace)\u2026",value:"workspace"}]:[{name:"Create a workspace",value:"workspace"},{name:"Create a project",value:"project"},e]}function pu(){return {type:"input",name:"source",message:"Local path, Git URL, or Workspai archive:",validate:t=>t.trim().length>0||"A source is required"}}function du(t){let e=t.trim(),r=e.startsWith("~/")?b.join(homedir(),e.slice(2)):e;if(/\.(?:workspai|rapidkit)-archive\.zip(?:[?#].*)?$/i.test(r)||!Gt(r)&&/\.zip$/i.test(r))return {kind:"workspace-archive",source:Gt(r)?r:b.resolve(r)};if(Gt(r))return {kind:"git-project",source:r};let n=b.resolve(r);return k$1(n)?{kind:"local-workspace",source:n}:{kind:"local-project",source:n}}var Kf=Ln,Uf=Wn;function Ds(t){if(!t||typeof t!="object")return null;let e=t.code;return e==="PYTHON_NOT_FOUND"||e==="BRIDGE_VENV_BOOTSTRAP_FAILED"||e==="BRIDGE_VENV_CREATE_FAILED"||e==="BRIDGE_PIP_BOOTSTRAP_FAILED"?e:null}function Bf(t=process.argv){let e=b.basename(t[1]??"").toLowerCase().replace(/\.(cmd|ps1|exe|js)$/i,"");return e==="rapidkit"||e==="rapidkit-npm"?"rapidkit":"workspai"}function $r(){return process.env.WORKSPAI_DEBUG_ARGS==="1"||process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"}function Hf(t){let e=t.trim().toLowerCase();return e?e.startsWith("fastapi")?"fastapi":e.startsWith("nestjs")?"nestjs":null:null}function Re(t,e){let r=t.indexOf(e);if(r>=0&&r+1<t.length)return t[r+1];let o=t.find(n=>n.startsWith(`${e}=`));if(o)return o.slice(e.length+1)}function qf(t){if(t===void 0||t.trim()==="")return;let e=t.trim();if(!/^\d+$/.test(e))throw new Error("--max-workers must be an integer between 1 and 16.");let r=Number(e);if(!Number.isSafeInteger(r)||r<1||r>16)throw new Error("--max-workers must be an integer between 1 and 16.");return r}function Us(t){try{return qf(t.raw)}catch(e){let r=e instanceof Error?e.message:String(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"cli.option.max-workers.invalid",message:r,context:{value:t.raw??null,minimum:1,maximum:16}}),null,2)):console.error(s.red(`\u274C ${r}`)),process.exit(1);}}async function si(t,e){let r=Re(t,"--port")?.trim(),o=t[3];if(!r||!o||!/^\d+$/.test(r))return;let n=Number.parseInt(r,10);if(n<1||n>65535)return;let a=Re(t,"--output")||".",i=b.resolve(e,a,o),c=u$1(i,"project.json").find(p=>$.existsSync(p))??v$2(i,"project.json");if(!await M__default.pathExists(c))return;let l=await M__default.readJson(c);await M__default.writeJson(c,{...l,ports:[{name:"http",port:n,protocol:"http"}]},{spaces:2});}async function Ls(t){let e=xe(process.cwd()),r=t.trim().toLowerCase();if(!e||!r||K(r))return true;try{let[o,n]=await Promise.all([Y(e),X(e)]),a=a$3(r),i=l$5(r),c=r$2(r),l=Q(r),p=i?"node":c?.runtime??a?.runtime??l?.runtime??"python",m=W({profile:o,runtime:p,subjectLabel:r,mode:n}),u=V({profile:o,runtimes:await Z(e,{additionalRuntimes:[p]}),mode:n}),f=m.ok?u:m;if(f.ok)return true;let P=_(f);if(n==="strict")return console.log(s.red(`\u274C Profile violation (strict mode): ${f.message}`)),P&&console.log(s.gray(`\u{1F4A1} ${P}`)),false;console.log(s.yellow(`\u26A0\uFE0F Profile warning: ${f.message}`)),P&&console.log(s.gray(`\u{1F4A1} ${P}`));}catch{}return true}function ii(){return j$8()}function Bs(){let t={...process.env},e=t.PATH||"";return e&&(t.PATH=e.split(b.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(b.delimiter)),t.PYENV_VERSION="system",t.POETRY_PYTHON||(t.POETRY_PYTHON=i$4()),t.RAPIDKIT_SKIP_LOCK_SYNC||(t.RAPIDKIT_SKIP_LOCK_SYNC="1"),t.POETRY_KEYRING_ENABLED||(t.POETRY_KEYRING_ENABLED="false"),t.PYTHON_KEYRING_BACKEND||(t.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),t.POETRY_NO_INTERACTION||(t.POETRY_NO_INTERACTION="1"),t}function zf(t){return m$6(b.join(t,".venv"))}async function Yf(t,e){return await Ie(t,["--version"],e)===0}async function Xf(t,e){return new Promise(r=>{let o=spawn(t,["--version"],{cwd:e,stdio:"ignore",env:Bs()});o.once("error",()=>r(false)),o.once("close",n=>r(n===0));})}async function rr(t){let e=b.join(t,"go.mod");if(await M__default.pathExists(e))return "go";let r=b.join(t,"pom.xml"),o=b.join(t,"build.gradle"),n=b.join(t,"build.gradle.kts");if(await M__default.pathExists(r)||await M__default.pathExists(o)||await M__default.pathExists(n))return "java";if((await M__default.pathExists(t)?await $.promises.readdir(t,{withFileTypes:true}):[]).some(P=>P.isFile()&&P.name.toLowerCase().endsWith(".sln")))return "dotnet";let i=b.join(t,"src");if(await M__default.pathExists(i)&&(await $.promises.readdir(i,{withFileTypes:true})).some(y=>y.isFile()&&y.name.toLowerCase().endsWith(".csproj")))return "dotnet";let c=b.join(t,"Cargo.toml");if(await M__default.pathExists(c))return "rust";let l=b.join(t,"composer.json");if(await M__default.pathExists(l))return "php";let p=b.join(t,"package.json");if(await M__default.pathExists(p))return "node";let m=b.join(t,"pyproject.toml"),u=b.join(t,"requirements.txt"),f=b.join(t,"poetry.lock");return await M__default.pathExists(m)||await M__default.pathExists(u)||await M__default.pathExists(f)?"python":null}async function Qf(t,e={}){let r=e.runCommand??Ie,o=b.join(t,".venv"),n=await M__default.pathExists(o);for(let a of e.pythonCandidates??ii()){if(await r(a,a==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;n||await M__default.remove(o);}return 1}async function Zf(t,e={}){let r=e.runCommand??Ie,o=b.join(t,".venv"),n=m$6(o);if(await M__default.pathExists(n)){if(await r(n,["-m","pip","--version"],t)===0)return 0;await M__default.remove(o);}let a=await Qf(t,e);if(a!==0)return a;n=m$6(o);let i=await r(n,["-m","pip","--version"],t);return i!==0&&await M__default.remove(o),i}async function xu(t,e={}){let r=e.runCommand??Ie;for(let o of e.pythonCandidates??ii())if(await r(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],t)===0)return 0;return 1}async function eh(t,e={}){let r=e.runCommand??Ie,o=m$6(b.join(t,".venv"));if(!await M__default.pathExists(o)){let p=await xu(t,e);if(p!==0)return p}let n=process.platform==="win32"?b.join(t,".venv","Scripts","poetry.exe"):b.join(t,".venv","bin","poetry"),a=e.runCommand?await r("poetry",["--version"],t)===0:await Xf("poetry",t),i=await M__default.pathExists(n)?n:a?"poetry":null;if(!i)return 0;let c=await r(i,["config","virtualenvs.in-project","true","--local"],t);if(c!==0)return c;let l=await r(i,["env","use",o],t);return l!==0?l:0}async function th(t,e={}){let r=e.runCommand??Ie,o=m$6(b.join(t,".venv"));if(!await M__default.pathExists(o)){let i=await xu(t,e);if(i!==0)return i}await r(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],t);let n=b.join(t,"requirements.txt");if(await M__default.pathExists(n)&&await r(o,["-m","pip","install","-r","requirements.txt"],t)===0)return 0;let a=b.join(t,"pyproject.toml");return await M__default.pathExists(a)&&(await r(o,["-m","pip","install","-e","."],t)===0||await r(o,["-m","pip","install","."],t)===0)?0:1}async function Fs(t,e){return await eh(t)!==0&&console.log(s.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await e.initProject(t)).exitCode===0&&await M__default.pathExists(b.join(t,".venv"))?0:(console.log(s.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await th(t))}async function Gs(t){let e=await tr("init",t);if(e===0)return 0;let r=["npm","pnpm","yarn"];for(let o of r){if(!await Yf(o,t))continue;if(await Ie(o,["install"],t)===0)return console.log(s.green(`\u2705 Node init fallback succeeded with ${o} install`)),0}return e}function rh(t,e){let r=n=>/^\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?$/.test(n),o=Re([...e],"--port");if(o&&!/^\d+$/.test(o.trim()))return "Invalid --port. Expected numeric TCP port, e.g. 8080";if(t==="springboot.standard"){let n=Re([...e],"--java-version"),a=Re([...e],"--spring-boot-version"),i=Re([...e],"--springdoc-version"),c=Re([...e],"--group-id"),l=Re([...e],"--package-name");if(n&&!/^\d+$/.test(n.trim()))return "Invalid --java-version. Expected major version number, e.g. 21";if(a&&!r(a.trim()))return "Invalid --spring-boot-version. Expected semantic version, e.g. 3.5.0";if(i&&!r(i.trim()))return "Invalid --springdoc-version. Expected semantic version, e.g. 2.8.9";if(c&&!/^[A-Za-z0-9_.-]+$/.test(c.trim()))return "Invalid --group-id. Use dot-separated Java package identifiers only.";if(l&&!/^[A-Za-z0-9_.-]+$/.test(l.trim()))return "Invalid --package-name. Use dot-separated Java package identifiers only."}if(t==="dotnet.webapi.clean"){let n=Re([...e],"--target-framework"),a=Re([...e],"--root-namespace");if(n&&!/^net\d+\.\d+$/.test(n.trim()))return "Invalid --target-framework. Expected .NET target framework, e.g. net8.0";if(a&&!/^[A-Za-z0-9_.]+$/.test(a.trim()))return "Invalid --root-namespace. Use dot-separated .NET namespace identifiers only."}return null}async function zn(t,e={}){if(t.includes("--dry-run")||t.includes("--no-workspace")||Qs(process.cwd()))return;let r=t.includes("--skip-git")||t.includes("--no-git");if(t.includes("--create-workspace")){let{registerWorkspaceAtPath:n}=await import('./create-M3TWRHV6.js');await n(process.cwd(),{skipGit:r,yes:t.includes("--yes")||t.includes("-y"),userConfig:await c()});return}if(t.includes("--yes")||t.includes("-y")||!process.stdin.isTTY)return;let{workspaceMode:o}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:[{name:"Link it to the managed default workspace (recommended)",value:"managed"},{name:"Turn the current folder into a workspace",value:"current"},...e.requireWorkspace?[]:[{name:"Create it without workspace management",value:"none"}]],default:1}]);if(o==="current"){let{registerWorkspaceAtPath:n}=await import('./create-M3TWRHV6.js');await n(process.cwd(),{skipGit:r,yes:false,userConfig:await c()});}else o==="none"&&t.push("--no-workspace");}async function oh(t,e){if(e.json||e.explicitWorkspace||xe(t)||!process.stdin.isTTY||!(await ru({sourcePath:t})).parentEligible)return;let o=au(),{workspaceMode:n}=await b$1([{type:"rawlist",name:"workspaceMode",message:"This project is outside a Workspai workspace. How should it be managed?",choices:o,default:su()}]);return n}async function nh(t,e){let{registerWorkspaceAtPath:r}=await import('./create-M3TWRHV6.js');await r(t,{skipGit:true,yes:true,testMode:process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",userConfig:await c(),lifecycleTransaction:e});}async function ah(t){await M__default.ensureDir(t);let e=b.join(t,"lifecycle.lock"),r=Date.now();for(;;)try{let o=await $.promises.open(e,"wx");return await o.writeFile(`${JSON.stringify({pid:process.pid})}
|
|
156
|
+
`),async()=>{await o.close().catch(()=>{}),await M__default.remove(e).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let n=await M__default.readJson(e).catch(()=>null),a=Number(n?.pid),i=false;if(Number.isInteger(a)&&a>0)try{process.kill(a,0),i=true;}catch(c){i=c.code==="EPERM";}if(!i){await M__default.remove(e).catch(()=>{});continue}if(Date.now()-r>3e4)throw new Error(`Timed out waiting for lifecycle transaction lock: ${e}`);await new Promise(c=>setTimeout(c,25));}}async function ea(t,e={}){let r=b.join(w$1(),"transactions"),o=await ah(r),n;try{await b$9(r),n=await a$a({journalDirectory:r});}catch(i){throw await o(),i}let a=new Set([b.join(w$1(),"workspaces.json"),b.join(x(),"workspaces.json"),a$b(t,g$2),e$6(t,g$2),a$b(t,a$c),e$6(t,a$c),...t$1(t,"imported-projects.json")]);if(e.projectPath){a.add(v$2(e.projectPath,"project.json")),a.add(v$2(e.projectPath,"context.json")),a.add(v$2(e.projectPath,"file-hashes.json")),a.add(v$2(e.projectPath,"adopt.json")),a.add(v$2(e.projectPath,"adopt-readiness.json")),a.add(b.join(e.projectPath,f$1)),a.add(b.join(e.projectPath,g$3)),a.add(b.join(e.projectPath,h$1)),a.add(b.join(e.projectPath,b$a)),a.add(b.join(e.projectPath,i$1));for(let i of g$4)a.add(b.join(e.projectPath,i));for(let i of await j$4({workspacePath:t,projectPath:e.projectPath}))a.add(i);a.add(b.join(e.projectPath,"AGENTS.md")),a.add(b.join(e.projectPath,".gitignore"));}try{let i=new Set,c=e.projectPath;for(let p of a){let u=c&&(p===b.join(c,"AGENTS.md")||g$4.some(P=>p===b.join(c,P)))?await M__default.lstat(p).catch(P=>{if(P.code==="ENOENT")return null;throw P}):null,f=p;if(u?.isSymbolicLink()&&c){let P=await a$d(c,p);if(!P)continue;f=P;}i.has(f)||(await n.captureFile(f),i.add(f));}if(c)for(let p of [a$e,b$b,".agents",".amazonq",".claude",".cursor",".github",".grok",".vscode",".windsurf"])await n.captureOwnedTree(b.join(c,p));e.ownedDestination&&await n.captureOwnedTree(e.ownedDestination),e.ownedWorkspace&&await n.captureOwnedTree(e.ownedWorkspace);let l=false;return {captureFile:p=>n.captureFile(p),captureOwnedTree:p=>n.captureOwnedTree(p),registerCompensation:p=>n.registerCompensation(p),commit:async()=>{l||(await n.commit(),l=true,await o());},rollback:async()=>{if(!l){l=true;try{await n.rollback();}finally{await o();}}}}}catch(i){throw await n.rollback().catch(()=>{}),await o(),i}}async function Tr(t,e){try{await t.rollback();}catch(r){throw new AggregateError([e,r],`Project lifecycle failed and rollback was incomplete: ${e instanceof Error?e.message:String(e)}`)}throw e}async function or(t,e$1,r,o={}){if(t.includes("--dry-run"))return;if(!await M__default.pathExists(e$1)){e.warn(`Created project path was not found for workspace linking: ${e$1}`);return}if(await p$4(e$1),await jd(e$1),t.includes("--no-workspace"))return;let n=xe(e$1)||xe(process.cwd()),a=false,i;if(n)i=await ea(n,{projectPath:e$1});else {n=p$2(),i=await ea(n,{projectPath:e$1,ownedWorkspace:n});try{n=(await ci()).workspacePath;}catch(l){await Tr(i,l);}a=true;}let c="managed";try{let l=b.relative(n,e$1);(l.startsWith("..")||b.isAbsolute(l))&&(c=(await _s({source:e$1,workspacePath:n,name:r})).relationship);let{registerProjectInWorkspaceStrict:m,registerWorkspaceStrict:u}=await import('./workspace-AXU6ODER.js'),{syncWorkspaceContract:f}=await import('./workspace-contract-N2BJCAJ7.js'),{resolveWorkspaceRegistrationName:P}=await import('./workspace-marker-7U3NYRPJ.js');await u(n,await P(n)),await m(n,r,e$1),await f({workspacePath:n,strict:true});let{syncProjectIntelligenceLens:y}=await import('./project-intelligence-lens-OQTZ4K7L.js'),E=c==="adopted"?"adopted":"managed",A=async()=>y({workspacePath:n,projectPath:e$1,projectName:r,relationship:E,mode:"managed"}),S=typeof o.beforeCommit=="function";await A(),await Mr(n,{strict:true,silent:S}),await o.beforeCommit?.({workspacePath:n,registerCompensation:i.registerCompensation}),S&&(await Mr(n,{strict:true}),await A()),await i.commit();}catch(l){await Tr(i,l);}return a&&(console.log(s.gray(`\u2139\uFE0F Project created outside a Workspai workspace \u2014 linked to managed workspace "${j$3}" (${c}).`)),console.log(s.gray(` Registry: ${b.join(w$1(),"workspaces.json")}`)),console.log(s.gray(` Workspace: ${n}`))),n}async function mu(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=J(t[2]);if(!e)return 1;if(!I(e)){let m=F({},{trustReviewedReleaseAdmissions:true}).resolveAdapter(e.adapterId);return process.stderr.write(`Agent framework kit ${e.id} is not release-admitted. ${m.blockers.join(" ")}
|
|
157
|
+
`),1}let r=e,o=t[3];if(!o)return process.stderr.write(`Usage: workspai create project ${r.id} <name> [--agent-name <name>] [--output <dir>] [--dry-run]
|
|
158
158
|
`),1;if(t.includes("--no-workspace"))return process.stderr.write(`Agent framework projects require Workspai workspace governance.
|
|
159
159
|
`),1;try{j(o);}catch(m){return process.stderr.write(`${m instanceof Error?m.message:String(m)}
|
|
160
160
|
`),1}let n=Re(t,"--output")||process.cwd(),a=b.resolve(n,o),i=Re(t,"--agent-name")?.trim()||"primary",c=Re(t,"--granted-by")?.trim()||"operator";if(t.includes("--dry-run"))return console.log(s.bold(`
|
|
161
161
|
AI Agent \xB7 ${r.label}`)),console.log(s.gray(` Target: ${a}`)),console.log(s.gray(` Agent: ${i}`)),console.log(s.gray(" Plan: register project, create Goal/PCC, then apply admitted scaffold")),console.log(s.gray(" Dry run: no files or workspace evidence will be changed.")),0;if(await M__default.pathExists(a))return process.stderr.write(`\u274C Directory "${a}" already exists
|
|
162
|
-
`),1;let l=false,p=null;try{if(await M__default.ensureDir(b.dirname(a)),await
|
|
163
|
-
`),1}}async function gu(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=
|
|
162
|
+
`),1;let l=false,p=null;try{if(await M__default.ensureDir(b.dirname(a)),await L({projectPath:a,projectName:o,kit:r}),l=true,await or(t,a,o,{beforeCommit:async({workspacePath:u,registerCompensation:f})=>{let P=await go({workspacePath:u,project:o,runtime:r.runtime,framework:r.frameworkId,instanceName:i,mode:"scaffold",intent:`Create ${o} as a governed ${r.label} project`});if(f(async()=>{let{abortProofCarryingChange:E}=await import('./proof-carrying-change-GV37YLDQ.js');await E({workspacePath:u,changeId:P.changeId,reason:"Agent framework project creation transaction rolled back.",actorId:"workspai-agent-framework"}).catch(()=>{});}),P.status!=="planned")throw new Error(`Agent framework scaffold is ${P.status}: ${P.blockers.join(" ")}`);let y=await Cn({prepared:P,grantedBy:c});p=y,f(()=>M__default.remove(b.join(u,y.ownershipReceipt)));}}),!t.includes("--skip-git")&&!t.includes("--no-git")){let{initializeStandaloneGitRepository:u}=await import('./create-M3TWRHV6.js');await u(a,a$8("Preparing git repository",{component:"create.agent-framework",phase:"git-init",metadata:{projectName:o,kit:r.id}}),"chore: initialize Workspai agent project");}console.log(s.green(`\u2714 Governed ${r.label} project created at ${a}`)),console.log(s.gray(" Dependencies were not installed and no model was called."));let m=p;if(m){console.log(s.gray(` Change: ${m.changeId}`)),console.log(s.gray(` Ownership: ${m.ownershipReceipt}`));for(let u of m.nextActions)console.log(s.gray(` Next: ${u}`));}return 0}catch(m){return l&&await M__default.remove(a).catch(()=>{}),process.stderr.write(`Workspai ${r.id} generator failed: ${m instanceof Error?m.message:String(m)}
|
|
163
|
+
`),1}}async function gu(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=Q(t[2]);if(!e)return 1;let r=t[3],o=t.includes("--json");if(!r)return process.stderr.write(`Usage: workspai create project ${e.id} <name> [--output <dir>] [--dry-run] [--skip-git] [--json]
|
|
164
164
|
`),1;try{j(r);}catch(c){return process.stderr.write(`${c instanceof Error?c.message:String(c)}
|
|
165
165
|
`),1}let n=Re(t,"--output")||process.cwd(),a=b.resolve(n,r);if(t.includes("--dry-run"))return o?console.log(JSON.stringify(b$6("create project",{kit:e.id,name:r,projectPath:a,dryRun:true}),null,2)):(console.log(s.bold(`
|
|
166
166
|
AI Gateway \xB7 ${e.label}`)),console.log(s.gray(` Runtime: ${e.runtime}`)),console.log(s.gray(` Target: ${a}`)),console.log(s.gray(" Plan: write the OpenRouter Client SDK starter and register it")),console.log(s.gray(" Dry run: no files or workspace evidence will be changed."))),0;if(await M__default.pathExists(a))return process.stderr.write(`\u274C Directory "${a}" already exists
|
|
167
|
-
`),1;let i=false;try{if(await M__default.ensureDir(b.dirname(a)),await
|
|
168
|
-
`),1}}async function
|
|
167
|
+
`),1;let i=false;try{if(await M__default.ensureDir(b.dirname(a)),await S({projectPath:a,projectName:r,kit:e}),i=true,!t.includes("--skip-git")&&!t.includes("--no-git")){let{initializeStandaloneGitRepository:c}=await import('./create-M3TWRHV6.js');await c(a,a$8("Preparing git repository",{component:"create.model-gateway",phase:"git-init",metadata:{projectName:r,kit:e.id}}),"chore: initialize Workspai AI Gateway project");}return await or(t,a,r),o?console.log(JSON.stringify(b$6("create project",{kit:e.id,name:r,projectPath:a,dryRun:false}),null,2)):(console.log(s.green(`\u2714 ${e.label} project created at ${a}`)),console.log(s.gray(" Dependencies were not installed and no model was called."))),0}catch(c){return i&&await M__default.remove(a).catch(()=>{}),process.stderr.write(`Workspai ${e.id} generator failed: ${c instanceof Error?c.message:String(c)}
|
|
168
|
+
`),1}}async function Hs(t){if(t[0]!=="create"||t[1]!=="project")return 1;let e=t[2],r=a$3(e),o=t[3];if(!r||r.owner!=="npm")return 1;if(!o)return process.stderr.write(`Usage: ${r.createUsage??"workspai create project <kit> <name> [--output <dir>]"}
|
|
169
169
|
`),1;try{j(o);}catch(u){let f=u instanceof Error?u.message:String(u);return process.stderr.write(`${f}
|
|
170
170
|
`),1}let n=rh(r.id,t);if(n)return process.stderr.write(`${n}
|
|
171
171
|
`),1;let a=Re(t,"--output")||process.cwd(),i=b.resolve(a,o),c=t.includes("--skip-git")||t.includes("--no-git"),l=t.includes("--skip-install"),p=t.includes("--dry-run"),m=false;try{let{default:u}=await import('fs-extra');return await u.pathExists(i)?(process.stderr.write(`\u274C Directory "${i}" already exists
|
|
172
172
|
`),1):p?(console.log(s.bold(`
|
|
173
|
-
${r.label}`)),console.log(s.gray(` Runtime: ${r.runtime}`)),console.log(s.gray(` Target: ${i}`)),console.log(s.gray(" Dry run: no files or workspace state will be changed.")),0):(await u.ensureDir(b.dirname(i)),await u.ensureDir(i),m=true,await e$4(r,{projectName:o,projectPath:i,args:t,skipGit:c,skipInstall:l}),await
|
|
173
|
+
${r.label}`)),console.log(s.gray(` Runtime: ${r.runtime}`)),console.log(s.gray(` Target: ${i}`)),console.log(s.gray(" Dry run: no files or workspace state will be changed.")),0):(await u.ensureDir(b.dirname(i)),await u.ensureDir(i),m=true,await e$4(r,{projectName:o,projectPath:i,args:t,skipGit:c,skipInstall:l}),await si(t,process.cwd()),await or(t,i,o),0)}catch(u){if(m){let{default:f}=await import('fs-extra');await f.remove(i).catch(()=>{});}return process.stderr.write(`Workspai ${r.id} generator failed: ${u?.message??u}
|
|
174
174
|
`),1}}async function fu(t){let e=l$5(t[2]);if(!e)return 1;let r;try{let o=await p$5({args:t});return o.dryRun||(r=o.projectPath,await or(t,o.projectPath,o.projectName)),0}catch(o){return r&&await M__default.remove(r).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${o?.message??o}
|
|
175
175
|
`),t[3]||process.stderr.write(`Usage: ${o$3(e.id)}
|
|
176
176
|
`),1}}async function hu(t){let e=r$2(t[2]);if(!e)return 1;let r;try{let o=await u$3(t);return o.dryRun||(r=o.projectPath,await or(t,o.projectPath,o.projectName)),0}catch(o){return r&&await M__default.remove(r).catch(()=>{}),process.stderr.write(`Workspai ${e.kitId} generator failed: ${o?.message??o}
|
|
177
177
|
`),t[3]||process.stderr.write(`Usage: ${t$3(e.kitId)}
|
|
178
|
-
`),1}}async function
|
|
178
|
+
`),1}}async function Yn(t,e$1){if(t.includes("--json"))return process.stderr.write("Workspai CLI offline fallback does not support --json for `create` commands.\nInstall Python 3.10+ and retry the same command.\n"),1;if(t[0]!=="create")return 1;if(t[1]!=="project")return process.stderr.write(`Workspai CLI could not run the Python core engine for \`create\`.
|
|
179
179
|
Reason: ${e$1}.
|
|
180
180
|
Install Python 3.10+ to use the interactive wizard and full kit catalog.
|
|
181
181
|
`),1;let n=t[2],a=t[3];if(!n||!a)return process.stderr.write(`Usage: npx workspai create project <kit> <name> [--output <dir>]
|
|
@@ -186,14 +186,16 @@ Requested kit: ${n}
|
|
|
186
186
|
Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
|
|
187
187
|
Install Python 3.10+ to access all kits.
|
|
188
188
|
`),1;let c=Re(t,"--output")||process.cwd(),l=b.resolve(c,a),p=false,m=t.includes("--skip-git")||t.includes("--no-git"),u=t.includes("--skip-install");try{if(await M__default.ensureDir(b.dirname(l)),await M__default.pathExists(l))return process.stderr.write(`\u274C Directory "${l}" already exists
|
|
189
|
-
`),1;let f="pip",P=xe(process.cwd());if(P)try{let{readWorkspaceMarker:E}=await import('./workspace-marker-7U3NYRPJ.js'),A=await E(P);A?.metadata?.npm?.installMethod&&(f=A.metadata.npm.installMethod,e.debug(`Detected workspace engine: ${f}`));}catch(E){e.debug("Failed to read workspace marker",E);}else e.debug("No workspace found, using default engine: pip");await M__default.ensureDir(l),p=true;let{generateDemoKit:y}=await import('./demo-kit-QNGY4KQ5.js');return await y(l,{project_name:a,template:i,kit_name:n,skipGit:m,skipInstall:u,engine:f}),await
|
|
189
|
+
`),1;let f="pip",P=xe(process.cwd());if(P)try{let{readWorkspaceMarker:E}=await import('./workspace-marker-7U3NYRPJ.js'),A=await E(P);A?.metadata?.npm?.installMethod&&(f=A.metadata.npm.installMethod,e.debug(`Detected workspace engine: ${f}`));}catch(E){e.debug("Failed to read workspace marker",E);}else e.debug("No workspace found, using default engine: pip");await M__default.ensureDir(l),p=true;let{generateDemoKit:y}=await import('./demo-kit-QNGY4KQ5.js');return await y(l,{project_name:a,template:i,kit_name:n,skipGit:m,skipInstall:u,engine:f}),await si(t,process.cwd()),await or(t,l,a),0}catch(f){return p&&await M__default.remove(l).catch(()=>{}),process.stderr.write(`Workspai CLI offline fallback failed: ${f?.message??f}
|
|
190
190
|
`),1}}function sh(t){let e=t.requested||"requested stack";if(process.stderr.write(`${s.yellow("Workspai native create is not available for this request yet.")}
|
|
191
191
|
`),process.stderr.write(s.gray(`Requested: ${e}
|
|
192
192
|
`)),process.stderr.write(s.gray(`Lane: ${t.lane} (${t.status})
|
|
193
193
|
`)),process.stderr.write(s.gray(`Reason: ${t.reason}
|
|
194
194
|
`)),t.officialCommands?.length){process.stderr.write(s.gray(`Official generator candidates:
|
|
195
195
|
`));for(let r of t.officialCommands)process.stderr.write(s.gray(` - ${r}
|
|
196
|
-
`));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx workspai adopt <project-path>` to add Workspace Intelligence.\n"));}function wu(){
|
|
196
|
+
`));}process.stderr.write(s.gray("Use an external generator if needed, then run `npx workspai adopt <project-path>` to add Workspace Intelligence.\n"));}function wu(){let t=G$1(),e=t.slice(0,2).map(o=>` npx workspai create project ${o.id} ${o.runtime==="python"?"support-agent":o.runtime==="dotnet"?"operations-agent":"research-agent"} --skip-git`).join(`
|
|
197
|
+
`),r=t.map(o=>{let n=I(o)?"":` (${o.stability} \xB7 awaiting release admission)`;return ` ${o.id.padEnd(23)} ${o.label}${n}`}).join(`
|
|
198
|
+
`);console.log(`Usage: npx workspai create project <kit> <name> [options]
|
|
197
199
|
|
|
198
200
|
Scaffold a project and register it with Workspace Intelligence.
|
|
199
201
|
|
|
@@ -205,7 +207,7 @@ Examples:
|
|
|
205
207
|
npx workspai create project rust.axum api --skip-install
|
|
206
208
|
npx workspai create project desktop.tauri desktop-app
|
|
207
209
|
npx workspai create project extension.vscode editor-tools --skip-install
|
|
208
|
-
|
|
210
|
+
${e}
|
|
209
211
|
npx workspai create project gateway.openrouter.typescript model-gateway
|
|
210
212
|
npx workspai create project gateway.openrouter.python model-gateway
|
|
211
213
|
|
|
@@ -222,8 +224,7 @@ Common kits:
|
|
|
222
224
|
desktop.tauri Desktop Tauri app
|
|
223
225
|
desktop.electron Desktop Electron Forge app
|
|
224
226
|
extension.vscode VS Code extension
|
|
225
|
-
|
|
226
|
-
agent.microsoft.dotnet Microsoft Agent Framework \xB7 .NET
|
|
227
|
+
${r}
|
|
227
228
|
gateway.openrouter.typescript AI Gateway \xB7 OpenRouter \xB7 TypeScript
|
|
228
229
|
gateway.openrouter.python AI Gateway \xB7 OpenRouter \xB7 Python
|
|
229
230
|
php.laravel Backend Laravel application
|
|
@@ -286,25 +287,25 @@ Shortcuts:
|
|
|
286
287
|
|
|
287
288
|
Run:
|
|
288
289
|
npx workspai create workspace --help
|
|
289
|
-
npx workspai create project --help`);}function lh(t){let e=t[2]??"<kit>",r=t[3]??"<name>",o=Re(t,"--output")||process.cwd();console.log("Workspai create project dry run (Dry-run mode)"),console.log(` kit: ${e}`),console.log(` name: ${r}`),console.log(` output: ${b.resolve(o)}`),console.log(" execution: RapidKit Core bridge"),console.log(" writes: none"),console.log(""),console.log("Run without --dry-run to scaffold the project.");}async function
|
|
290
|
+
npx workspai create project --help`);}function lh(t){let e=t[2]??"<kit>",r=t[3]??"<name>",o=Re(t,"--output")||process.cwd();console.log("Workspai create project dry run (Dry-run mode)"),console.log(` kit: ${e}`),console.log(` name: ${r}`),console.log(` output: ${b.resolve(o)}`),console.log(" execution: RapidKit Core bridge"),console.log(" writes: none"),console.log(""),console.log("Run without --dry-run to scaffold the project.");}async function qs(t){if(t[0]==="create"&&(t.includes("--help")||t.includes("-h")||t.includes("help")))return t[1]==="project"?wu():t[1]==="workspace"?ih():ch(),0;let e$1=t[0]==="create"&&t[1]==="frontend",r=n$4(t);if(r&&(t=r),e$1&&!m$5(t[2]))return process.stderr.write(`Unknown frontend generator: ${t[2]?.replace(/^frontend\./,"")}
|
|
290
291
|
`),process.stderr.write(`Usage: ${o$3()}
|
|
291
|
-
`),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return
|
|
292
|
+
`),1;if(process.env.RAPIDKIT_FORCE_OFFLINE_CREATE_FALLBACK==="1"&&t[0]==="create")return Yn(t,"PYTHON_NOT_FOUND");let o=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace","--here"]);if(t[0]==="create"&&(!t[1]||t[1].startsWith("-"))){let n=t.includes("--yes")||t.includes("-y"),a$1=t.slice(1),i;if(!process.stdin.isTTY||n)i="workspace",process.stdin.isTTY&&console.log(s.gray("\u2139\uFE0F No subcommand provided for `create`; defaulting to `create workspace`."));else {process.stdin.isTTY&&a("create");let l=xe(process.cwd()),p=l?b.basename(l):null;i=(await b$1([{type:"rawlist",name:"createTarget",message:p?`What would you like to add to ${p}?`:"What would you like to set up?",choices:lu(p)}])).createTarget;}if(i==="existing"){let l=xe(process.cwd()),{source:p}=await b$1([pu()]),m=du(p);if(m.kind==="workspace-archive"){let f=await Ms({archivePathOrUrl:m.source,projectGrounding:"managed"});console.log(s.green(`\u2714 Workspace imported and registered: ${f.workspacePath}`));for(let P of f.warnings)console.log(s.yellow(` \u26A0 ${P}`));return 0}if(m.kind==="git-project")return await ei(m.source,{workspace:l??void 0});if(m.kind==="local-workspace"){let f=await Ts({workspacePath:m.source,projectGrounding:"managed"});console.log(s.green(`\u2714 Workspace connected: ${f.workspacePath}`));for(let P of f.warnings)console.log(s.yellow(` \u26A0 ${P}`));return 0}let{existingProjectMode:u}=await b$1([{type:"rawlist",name:"existingProjectMode",message:"How should Workspai add this project?",choices:[{name:"Keep it where it is (recommended)",value:"link"},{name:"Copy it into the workspace",value:"copy"}]}]);return u==="link"?await Wu(m.source,{workspace:l??void 0,projectGrounding:"managed"}):await ei(m.source,{workspace:l??void 0,projectGrounding:"managed"})}let c=["create",i,...a$1];return await qs(c)}if(t[0]==="create"&&t[1]==="workspace")try{let n$1=t.includes("--yes")||t.includes("-y"),a$2=t.includes("--skip-git")||t.includes("--no-git"),i$1=t.includes("--skip-python-engine")||t.includes("--no-python-engine"),c$1=t.includes("--dry-run"),l=t.includes("--json"),p=t[2]&&!t[2].startsWith("-")?t[2]:void 0,m=Re(t,"--install-method"),u=m==="poetry"||m==="venv"||m==="pipx"?m:void 0,f=Re(t,"--profile"),P=f==="minimal"||f==="java-only"||f==="go-only"||f==="dotnet-only"||f==="python-only"||f==="node-only"||f==="polyglot"||f==="enterprise"?f:void 0,y=p;if(y||(n$1?y="my-workspace":(process.stdin.isTTY&&!l&&a("create workspace"),y=(await b$1([{type:"input",name:"workspaceName",message:"Workspace name:",default:"my-workspace"}])).workspaceName)),!y||!y.trim())return process.stderr.write(`Workspace name is required.
|
|
292
293
|
`),1;try{j(y);}catch(k){if(k instanceof a$1)return process.stderr.write(`${k.message}
|
|
293
294
|
`),1;throw k}let E=await k(t,{hasYes:n$1}),A=i(y.trim(),{argv:t,outputParent:E});c$1||await M__default.ensureDir(b.dirname(A));let S=n(y.trim());if(!c$1&&(j$1(S,A,{outputParent:E})&&S&&await M__default.pathExists(S)||await M__default.pathExists(A)))return process.stderr.write(`\u274C Workspace "${y}" already exists
|
|
294
295
|
`),S&&S!==A&&process.stderr.write(` Found at: ${S}
|
|
295
|
-
`),1;let d=await c(),g=d.author||process.env.USER||"Workspai User";if(!n$1){let k=await b$1([{type:"input",name:"author",message:"Author name:",default:g}]);k.author?.trim()&&(g=k.author.trim());}let{createProject:w}=await import('./create-
|
|
296
|
+
`),1;let d=await c(),g=d.author||process.env.USER||"Workspai User";if(!n$1){let k=await b$1([{type:"input",name:"author",message:"Author name:",default:g}]);k.author?.trim()&&(g=k.author.trim());}let{createProject:w}=await import('./create-M3TWRHV6.js');return await w(y,{skipGit:a$2,skipPythonEngine:i$1,yes:n$1,dryRun:c$1,userConfig:{...d,author:g},installMethod:u,profile:P,parentDirectory:b.dirname(A),suppressReceipt:l,json:l}),l&&console.log(JSON.stringify(b$6("create workspace",{name:y.trim(),workspacePath:A,profile:P??"minimal",dryRun:c$1}),null,2)),0}catch(n){return n instanceof a$1?(process.stderr.write(`
|
|
296
297
|
\u274C ${n.message}
|
|
297
298
|
`),n.details&&process.stderr.write(`
|
|
298
299
|
${n.details}
|
|
299
300
|
`),e.debug("Create workspace error",{code:n.code,stack:n.stack})):(process.stderr.write(`Workspai CLI failed to create workspace: ${n?.message??n}
|
|
300
|
-
`),e.debug("Unexpected create workspace error",n)),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return wu(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitCategory:A}=await b$1([{type:"rawlist",name:"kitCategory",message:"What are you building?",choices:b$n()}]),{kitChoice:S
|
|
301
|
+
`),e.debug("Unexpected create workspace error",n)),1}try{if(t[0]==="create"&&t[1]==="project"){if(t.includes("--help")||t.includes("-h"))return wu(),0;if(!t[2]||t[2].startsWith("-")){process.stdin.isTTY&&a("create project");let{kitCategory:A}=await b$1([{type:"rawlist",name:"kitCategory",message:"What are you building?",choices:b$n()}]),{kitChoice:S}=await b$1([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:a$O(A)}]);if(K(S)||R(S)||d$1(S)||m$5(S)||s$2(S)){let w=Rs(S),{projectName:k}=await b$1([{type:"input",name:"projectName",message:"Project name:",default:w,validate:x=>x.trim().length>0||"Project name is required"}]),h=t.slice(2).filter(x=>x.startsWith("-")),v=["create","project",S,k.trim(),...h];return await Ls(S)?(await zn(v),K(S)?await mu(v):R(S)?await gu(v):m$5(S)?await fu(v):s$2(S)?await hu(v):await Hs(v)):1}let d=Rs(S),{projectName:g}=await b$1([{type:"input",name:"projectName",message:"Project name:",default:d,validate:w=>w.trim().length>0||"Project name is required"}]);t.splice(2,0,S,g.trim());}let a$1=t[2];if(K(a$1))return await zn(t,{requireWorkspace:true}),await mu(t);if(R(a$1))return await Ls(a$1)?(await zn(t),await gu(t)):1;let i=a$P({kitId:a$1,framework:a$1,runtime:a$1});if(b$o(i))return sh(i),1;if(!await Ls(t[2]||""))return 1;if(await zn(t),d$1(t[2]))return await Hs(t);if(m$5(t[2]))return await fu(t);if(s$2(t[2]))return await hu(t);if(t.includes("--skip-python-engine")||t.includes("--no-python-engine"))return process.stderr.write("`--skip-python-engine` is a workspace creation option. For projects, use `--skip-install` to scaffold first, then run `npx workspai init` when ready.\n"),1;if(t.includes("--dry-run"))return lh(t),0;let c=t[3],l=Re(t,"--output")||process.cwd(),p=c?b.resolve(l,c):void 0;if(p&&await M__default.pathExists(p))return process.stderr.write(`\u274C Project "${c}" already exists.
|
|
301
302
|
`),process.stderr.write(` Target: ${p}
|
|
302
303
|
`),process.stderr.write(`\u{1F4A1} Choose a different name, or inspect and move/remove the existing directory first.
|
|
303
|
-
`),1;let u=[...t.filter(A=>{let S=A.split("=")[0];return !o.has(A)&&!o.has(S)})],f=xe(process.cwd()),P=t.includes("--skip-install");P&&!u.includes("--skip-essentials")&&u.push("--skip-essentials");let E=P||!!f?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$8();let A=await e$2(u,{cwd:process.cwd(),env:E});if(A===0&&f&&!t.includes("--skip-install")&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init"))),A===0){await
|
|
304
|
-
`),e.debug(`Synced Python version ${v.trim()} from workspace to ${S}`);}}}catch(k){e.debug("Could not sync Python version from workspace:",k);}}return A}catch(A){let S=
|
|
305
|
-
`),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$8();let n=await e$2(t,{cwd:process.cwd()});if(n===0){let a=xe(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-
|
|
306
|
-
`),1)}return await d$8(),await e$2(t,{cwd:process.cwd()})}catch(n){let a=
|
|
307
|
-
`),1)}}var yu=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],ph=[...w$3,"autopilot","pipeline","import","adopt","snapshot","live","ai","config","product","infra","shell","commands"],dh=["init"],uh=r$1,ku=[...uh,...s$3];function mh(t){return !!t&&Uf.includes(t)}function
|
|
304
|
+
`),1;let u=[...t.filter(A=>{let S=A.split("=")[0];return !o.has(A)&&!o.has(S)})],f=xe(process.cwd()),P=t.includes("--skip-install");P&&!u.includes("--skip-essentials")&&u.push("--skip-essentials");let E=P||!!f?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await d$8();let A=await e$2(u,{cwd:process.cwd(),env:E});if(A===0&&f&&!t.includes("--skip-install")&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init"))),A===0){await si(t,process.cwd());let S=t[3],d=Re(t,"--output")||process.cwd(),g=S?b.resolve(d,S):void 0,w=S&&g?await or(t,g,S).catch(async k=>{throw await M__default.remove(g).catch(()=>{}),k}):f;if(w)try{if(S&&g){let k=b.join(w,".python-version"),h=b.join(g,".python-version");if($.existsSync(k)&&$.existsSync(g)){let v=$.readFileSync(k,"utf-8");$.writeFileSync(h,v.trim()+`
|
|
305
|
+
`),e.debug(`Synced Python version ${v.trim()} from workspace to ${S}`);}}}catch(k){e.debug("Could not sync Python version from workspace:",k);}}return A}catch(A){let S=Ds(A);return S?await Yn(t,S):(process.stderr.write(`Workspai failed to run the Python core engine: ${A?.message??A}
|
|
306
|
+
`),1)}}if(t[0]==="create"&&t[1]!=="project")try{await d$8();let n=await e$2(t,{cwd:process.cwd()});if(n===0){let a=xe(process.cwd());if(a){let{syncWorkspaceProjects:i}=await import('./workspace-AXU6ODER.js');await i(a,true);}}return n}catch(n){let a=Ds(n);return a?await Yn(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
|
|
307
|
+
`),1)}return await d$8(),await e$2(t,{cwd:process.cwd()})}catch(n){let a=Ds(n);return a?await Yn(t,a):(process.stderr.write(`Workspai failed to run the Python core engine: ${n?.message??n}
|
|
308
|
+
`),1)}}var yu=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],ph=[...w$3,"autopilot","pipeline","import","adopt","snapshot","live","ai","config","product","infra","shell","commands"],dh=["init"],uh=r$1,ku=[...uh,...s$3];function mh(t){return !!t&&Uf.includes(t)}function zs(t){let e=t[0],r=t[1];return e==="project"&&(r==="--help"||r==="-h"||r==="help")?true:Kf.some(([o,n])=>e!==o?false:r?r===n:true)}function Co(t){return t[0]==="project"&&t[1]&&!t[1].startsWith("-")&&t[1]!=="help"?zs(t):mh(t[0])||zs(t)}function gh(t){return !!t&&ph.includes(t)}function vu(t){return gh(t[0])||zs(t)}function Pu(t){return !!t&&js.includes(t)}async function bu(t,e){switch(t){case "bootstrap":return _h(e);case "setup":return Oh(e);case "cache":return $h(e);case "mirror":return Mh(e);default:{let r=t;throw new Error(`Unreachable npm-only manual command: ${String(r)}`)}}}function fh(t=process.env){let e=t.npm_config_user_agent||"",r=t.npm_execpath||"",o=t.npm_command||"";return e.includes(" npx/")||/(?:^|[/\\])npx(?:\.cmd)?$/i.test(r)||o==="exec"||o==="x"}function Iu(t={}){let e=D(process.cwd());if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai project command capabilities")),console.log(s.gray(`Project: ${e.projectRoot??"not detected"}`)),console.log(s.gray(`Runtime: ${e.runtime} (${e.runtimeSupportTier}) | Framework: ${e.frameworkDisplayName} (${e.frameworkSupportTier}) | Module support: ${e.moduleSupport?"yes":"no"}`)),console.log(s.gray(`Doctor support: ${e.runtimeDoctorSupport}`)),console.log(""),console.log(s.green(`Supported: ${e.supportedCommands.join(", ")||"none"}`)),console.log(s.yellow(`Global: ${e.globalCommands.join(", ")||"none"}`)),console.log(s.red(`Unsupported: ${e.unsupportedCommands.join(", ")||"none"}`));}function hh(){return {schemaVersion:Ld,cli:"workspai",version:h(),node:process.version,platform:process.platform,capabilitiesSchemaVersion:As,contracts:vo(),contractCatalog:Vn()}}function _u(){let t=Rd(he),e=[...t.topLevelCommands],r=[...a$5].filter(i=>!e.includes(i)),o=["init","dev","start","build","test","lint","format","help"],n=[...yo],a=[...Mn];return {schemaVersion:As,scope:"global",cli:"workspai",version:h(),cwd:process.cwd(),contracts:vo(),contractCatalog:Vn(),commands:{npmOwned:e,coreBacked:r,projectScoped:o},workspace:{command:"workspace",subcommands:n,intelligenceSubcommands:a},commandMap:Object.fromEntries([...e.map(i=>[i,{command:i,owner:"npm-wrapper",status:"supported",scope:i==="project"?"project-introspection":"workspace"}]),...r.map(i=>[i,{command:i,owner:"python-core",status:"delegated",scope:"core"}]),...o.map(i=>[i,{command:i,owner:"runtime-adapter",status:i==="help"?"supported":"runtime-dependent",scope:"project"}])]),runtimeInventory:t}}function wh(t={}){let e=_u();if(t.json){if(!e.runtimeInventory.integrity.ok)throw new Error(xd(e.runtimeInventory.integrity));console.log(JSON.stringify(e,null,2));return}console.log(s.bold("Workspai command capabilities")),console.log(s.gray(`CLI: ${e.cli} v${e.version}`)),console.log(""),console.log(s.green(`npm wrapper: ${e.commands.npmOwned.join(", ")}`)),console.log(s.cyan(`Python core: ${e.commands.coreBacked.join(", ")}`)),console.log(s.yellow(`Project runtime: ${e.commands.projectScoped.join(", ")}`)),console.log(s.magenta(`Workspace intelligence: ${e.workspace.intelligenceSubcommands.join(", ")}`)),console.log(""),console.log(s.gray("Tip: run `workspai project commands --json` inside a project."));}function Ys(t){return F$1(t)?(Iu({json:t.includes("--json")||t.includes("--ci")}),true):false}function Xs(t){let e=D(process.cwd());if(!e.projectRoot)return false;let r=E(t,process.cwd());if(!r||r.status!=="unsupported")return false;console.error(s.red(G(r,e))),process.exit(1);}function et(t){return $.existsSync(b.join(t,".workspai-workspace"))||$.existsSync(b.join(t,".workspai","workspace.json"))||$.existsSync(b.join(t,".rapidkit-workspace"))||$.existsSync(b.join(t,".rapidkit","workspace.json"))}function Ou(t){let e=t;for(;;){let r=u$1(e,"context.json").find(n=>$.existsSync(n));if(r)return r;let o=b.dirname(e);if(o===e)break;e=o;}return null}function Qs(t){let e=t,r=b.resolve(tmpdir());for(;;){let o=[b.join(e,".workspai-workspace"),b.join(e,".rapidkit-workspace")].find(a=>$.existsSync(a));if(o&&b.resolve(e)!==r)return o;let n=b.dirname(e);if(n===e)break;e=n;}return null}function xe(t){let e=b$5({startPath:t});return !e||b.resolve(e.workspacePath)===b.resolve(tmpdir())?null:e.workspacePath}function Zs(t){try{let r=b$5({startPath:t,strict:true})?.workspacePath??null;return {workspacePath:r&&b.resolve(r)!==b.resolve(tmpdir())?r:null,error:null}}catch(e){if(e instanceof a$2&&e.code==="project.workspace.unlinked")return {workspacePath:null,error:null};if(e instanceof a$2)return {workspacePath:null,error:e};throw e}}async function Mr(t,e){try{let{syncWorkspaceConsumerArtifacts:r}=await import('./workspace-onboarding-NH4WFJ5N.js');return await r(t,{silent:e?.silent})}catch(r){if(e?.strict)throw r;return e?.silent||(console.log(s.yellow(`\u26A0\uFE0F Workspace consumer sync skipped: ${r.message}`)),console.log(s.gray(" Retry: npx workspai workspace agent-sync --write --refresh-context --preset enterprise"))),null}}async function yh(t,e=process.cwd(),r=process.platform){if(!(!!t.workspaceFlag||t.scope==="workspace")||!b$3(r))return {detected:false};let n=v$1(e,r);for(let a of n){if(!await M__default.pathExists(a))continue;let i=a.toLowerCase();if(i.endsWith("rapidkit.cmd")||i.endsWith("rapidkit.exe"))return {detected:true,candidatePath:a,reason:"Found workspace-local rapidkit launcher on Windows."}}return {detected:false}}function kh(t){let e=t;for(;;){let r=b.join(e,".rapidkit-workspace"),o=b.join(e,".rapidkit","workspace.json");if(!$.existsSync(r)&&$.existsSync(o))return e;let n=b.dirname(e);if(n===e)break;e=n;}return null}var Nu={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function vh(t){return t&&t.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function bo(t,e){let r=t.match(new RegExp(`^[\\t ]*${e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return r?r[1]==="true":Nu[e]}function ju(t){let e=t??"";return {mode:vh(e),dependency_sharing_mode:$u(e),rules:{enforce_workspace_marker:bo(e,"enforce_workspace_marker"),enforce_toolchain_lock:bo(e,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:bo(e,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:bo(e,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:bo(e,"require_mirror_lock_for_offline")}}}function Cu(t,e,r){let o=`${e}: ${r}`,n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^[\\t ]*${n}:\\s*.*$`,"m");if(a.test(t))return t.replace(a,o);let i=/^[\t ]*rules:\s*(?:#.*)?$/m;return i.test(t)?t.replace(i,`${o}
|
|
308
309
|
rules:`):`${t.endsWith(`
|
|
309
310
|
`)?t:`${t}
|
|
310
311
|
`}${o}
|
|
@@ -324,21 +325,21 @@ ${o}
|
|
|
324
325
|
`),d(124);}},S)),y||(v.stdout?.on("data",j=>{g.push(j);}),v.stderr?.on("data",j=>{w.push(j);})),v.on("close",j=>{if(k)return;k=true,h&&clearTimeout(h);let R=Buffer.concat(g),C=Buffer.concat(w),_=!y&&j&&j!==0&&R.length===0&&C.length===0&&t==="npm"?E():"";$r()&&process.stderr.write(`[workspai-cli] runCommandInCwd.close=${JSON.stringify({code:j,stdoutBytes:R.length,stderrBytes:C.length,npmFailureExcerptBytes:_.length})}
|
|
325
326
|
`),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&(R.length>0&&process.stdout.write(R),C.length>0?process.stderr.write(C):_&&process.stderr.write(`${_}
|
|
326
327
|
`)),d(j??1);}),v.on("error",j=>{k||(k=true,h&&clearTimeout(h),process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT!=="1"&&process.stderr.write(`Workspai could not execute ${l}: ${j.message}. Install the required runtime or tool and ensure it is available on PATH.
|
|
327
|
-
`),d(1));});})}function Eh(t,e,r){if(t!=="npm")return null;let o=e[0];if(o!=="run"&&o!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=b.join(r,"package.json");if(!$.existsSync(a))return null;try{let c=JSON.parse($.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:Sh(c)}catch{return null}}function Sh(t){let e=t.trim(),r=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(r)return r[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let o=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return o?o[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function
|
|
328
|
-
`,"utf-8");}function Ah(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function Rh(t,e,r){let o=Gt(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":b.basename(e),n=Ah(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=b.join(t,i);if(!await M__default.pathExists(c))return c;a+=1;}}async function Qs(t,e,r){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?b.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:Xs(process.cwd()),i=a.workspacePath,c=false,l=false,p=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!et(n)){let f=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:f},null,2)):console.log(s.red(`\u274C ${f}`)),1}}else (!i||!et(i))&&(i=p$2(),c=true,p=true);if(!i||!et(i)&&!p){let f="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:f},null,2)):(console.log(s.red(`\u274C ${f}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let m="npx workspai project workspace status --json",u;try{let f=await Rh(i,t,e.name);if(u=await Zn(i,{ownedDestination:f,ownedWorkspace:p?i:void 0}),p){let y=await si({silent:e.json});i=y.workspacePath,l=y.created;}let P=await Qd({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});P.path!==f&&u.registerCompensation(()=>M__default.remove(P.path));try{if(r?.syncWorkspaceProjects)await r.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:y,registerWorkspaceStrict:E}=await import('./workspace-A33YMF2N.js'),{resolveWorkspaceRegistrationName:A}=await import('./workspace-marker-7U3NYRPJ.js');await E(i,await A(i)),await y(i,P.name,P.path);}await u.commit(),await Mr(i,{silent:e.json});}catch(y){try{await Tr(u,y);}catch(E){if(E!==y)throw E}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${y instanceof Error?y.message:String(y)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?l:false,projectWorkspaceCommand:m,commandsResolveWorkspaceFromProject:true,plan:P.ingestionPlan,importedProject:P},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),l&&console.log(s.green("\u2713 Workspace ready \xB7 1 registered project \xB7 model + graph + agent grounding sealed")),console.log(s.green(`\u2714 Imported project: ${P.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${P.path}`)),console.log(s.gray(` Stack: ${P.stack} (${P.confidence})`)),console.log(s.gray(` Source: ${e.git===true||Gt(t)?"git-url":"local-folder"}`)),!P.profileCompatibility.ok){let y=$$1(P.profileCompatibility);console.log(s.yellow(` Profile warning: ${P.profileCompatibility.message}`)),y&&console.log(s.gray(` ${y}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${m}`)),0}catch(f){if(u)try{await Tr(u,f);}catch(y){y!==f&&(f=y);}let P=f instanceof Error?f.message:String(f);return e.json?console.log(JSON.stringify({error:P},null,2)):console.log(s.red(`\u274C Import failed: ${P}`)),1}}async function Wu(t,e,r){let o,n,a=(j,R)=>{n=j,o&&(o.text=R),c$7({blockId:j,status:"running",message:R,component:"adopt"});},i=(j,R)=>{c$7({blockId:j,status:"succeeded",message:R,component:"adopt"}),n===j&&(n=void 0);},c=(j,R)=>{c$7({blockId:j,status:"skipped",message:R,component:"adopt"});},l=j=>{n&&(c$7({blockId:n,status:"failed",message:j,component:"adopt"}),n=void 0);};a("adopt.resolve","Resolving project and workspace");let p=b.resolve(t||process.cwd()),m=e.workspace?b.resolve(e.workspace):null,u=null,f="nearest",P=false,y=false,E=false,A=false,S=false,d=null,g=m?{workspacePath:null,error:null}:Xs(process.cwd());if(!m&&!g.error&&!g.workspacePath&&(g=Xs(p)),g.error)return l(g.error.message),e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:g.error.code,message:g.error.message,context:g.error.context}),null,2)):console.log(s.red(`\u274C ${g.error.message}`)),1;if(m){let j=await ou(m,{dryRun:e.dryRun});if(!j.ok)return l(j.message),e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:j.code,message:j.message}),null,2)):console.log(s.red(`\u274C ${j.message}`)),1;({workspacePath:u,resolution:f,usedDefaultWorkspace:P,willCreateDefaultWorkspace:E,willBootstrapWorkspace:A,bootstrapTargetPath:d}=j.result);}else if(g.workspacePath&&et(g.workspacePath))u=g.workspacePath,f="nearest";else {let j=await oh(p,{json:e.json,explicitWorkspace:false}),R=await nu({sourcePath:p,outsideWorkspaceMode:j,dryRun:e.dryRun});if(!R.ok)return l(R.message),e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:R.code,message:R.message}),null,2)):console.log(s.red(`\u274C ${R.message}`)),1;({workspacePath:u,resolution:f,usedDefaultWorkspace:P,willCreateDefaultWorkspace:E,willBootstrapWorkspace:A,bootstrapTargetPath:d}=R.result);}let w=f==="explicit-bootstrap"||f==="parent-bootstrap",k=P&&(e.dryRun===true||E)||w&&(e.dryRun===true||A)||u!==null&&et(u);if(!u||!et(u)&&!k){let j="Not inside a Workspai workspace";return l(j),e.json?console.log(JSON.stringify({error:j},null,2)):(console.log(s.red(`\u274C ${j}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let h=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),v,I=null,x=null;try{if(e.dryRun!==true){if(v=await Zn(u,{projectPath:p,ownedWorkspace:E||A?u:void 0}),E){let D=await si({silent:e.json});u=D.workspacePath,y=D.created;}A&&d&&(await nh(d,v),S=true);}!e.json&&process.stdout.isTTY&&(o=b$8("Analyzing project for adoption",{component:"adopt",phase:"adopt.lifecycle",metadata:{dryRun:e.dryRun===true,workspaceResolution:f}})),i("adopt.resolve","Project and workspace resolved"),a("adopt.detect","Detecting architecture and adoption effects");let j=await Rs(u,p),R=await xs({workspacePath:u,source:p,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:j});i("adopt.detect","Architecture and adoption effects detected");let C="npx workspai project workspace status --json",_=e.dryRun===true?b$5({startPath:p}):null,N=e.dryRun!==true||_!==null&&b.resolve(_.workspacePath)===b.resolve(u)&&(!_.projectPath||b.resolve(_.projectPath)===p);if(e.dryRun!==true){a("adopt.link","Linking project to workspace");try{if(r?.registerWorkspace||r?.registerProjectInWorkspace||r?.syncWorkspaceProjects)r.registerWorkspace&&await r.registerWorkspace(u,b.basename(u)),r.registerProjectInWorkspace&&await r.registerProjectInWorkspace(u,R.name,R.path),r.syncWorkspaceProjects&&await r.syncWorkspaceProjects(u);else {let{registerProjectInWorkspaceStrict:q,registerWorkspaceStrict:J}=await import('./workspace-A33YMF2N.js'),{resolveWorkspaceRegistrationName:ae}=await import('./workspace-marker-7U3NYRPJ.js');if(await J(u,await ae(u)),await q(u,R.name,R.path),h)throw new Error("forced sync failure for command-level adopt rollback test")}if(i("adopt.link","Project linked to workspace"),a("adopt.publish","Sealing workspace intelligence"),I=await Mr(u,{silent:e.json,strict:true}),!I?.freshnessSealed)throw new Error("Workspace consumer artifacts were generated without a freshness seal.");i("adopt.publish","Workspace intelligence freshness sealed"),a("adopt.ground","Building the project agent entry");let{buildAgentBootstrapReceipt:D}=await import('./project-agent-entry-5TYKK5IV.js');if(x=await D({startPath:p,forAgent:"generic",validateLiveInputs:true}),x.status==="blocked"){let q=x.checks.filter(J=>J.status==="failed").map(J=>`${J.id}: ${J.message}`).join("; ");throw new Error(`Adopted project did not produce a usable agent-grounding route${q?` (${q})`:"; inspect the bootstrap checks."}`)}await v?.commit(),i("adopt.ground","Project agent entry is ready");}catch(D){if(v)try{await Tr(v,D);}catch(q){if(q!==D)throw q}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${D instanceof Error?D.message:String(D)}`)}}else c("adopt.link","Dry run: workspace link not written"),c("adopt.publish","Dry run: workspace intelligence not published"),c("adopt.ground","Dry run: project agent entry not written");if(o?.succeed(e.dryRun===true?"Adoption preview ready":"Project adoption ready"),o=void 0,e.json)return console.log(JSON.stringify({workspacePath:u,workspaceResolution:f,defaultWorkspaceCreated:P?y:false,workspaceBootstrapped:S,wouldCreateDefaultWorkspace:P&&e.dryRun===true?!et(u):false,wouldBootstrapWorkspace:w&&e.dryRun===true?!et(u):false,projectWorkspaceCommand:C,commandsResolveWorkspaceFromProject:N,dryRun:e.dryRun===true,plan:R.ingestionPlan,adoptedProject:R,consumerArtifacts:e.dryRun===true||!I?null:{freshnessSealed:I.freshnessSealed,reconciledAfterGrounding:I.reconciledAfterGrounding,warnings:I.warnings},agentBootstrap:x},null,2)),0;P?console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${u}`)):S&&console.log(s.green(`\u2714 Workspace bootstrapped at: ${u}`)),y&&e.dryRun!==true&&console.log(s.green("\u2713 Workspace ready \xB7 1 registered project \xB7 model + graph + agent grounding sealed")),e.dryRun===true&&(console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.gray(" Planned effects: project metadata + workspace registration + model, graph, and agent-grounding sync.")),R.effects.repositoryControlFiles.length>0&&console.log(s.gray(` Repository controls may be reconciled: ${R.effects.repositoryControlFiles.map(D=>D.path).join(", ")}.`))),console.log(s.green(`\u2714 Adopted project: ${R.name}`)),console.log(s.gray(` Workspace: ${u}`)),console.log(s.gray(` Project: ${R.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)"));let V=R.stack==="unknown"?R.frameworkDisplayName||R.runtime:R.stack;if(console.log(s.gray(` Stack: ${V} (${R.confidence})`)),!R.profileCompatibility.ok){let D=$$1(R.profileCompatibility);console.log(s.yellow(` Profile warning: ${R.profileCompatibility.message}`)),D&&console.log(s.gray(` ${D}`));}return console.log(s.gray(` Report: ${R.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Consumer evidence: ${I?.freshnessSealed?"freshness sealed":"not sealed"}${I?.reconciledAfterGrounding?" after grounding reconciliation":""}.`)),console.log(s.gray(` Agent grounding: ${x?.status??"unknown"}; project environment: ${x?.readiness.projectEnvironment??"unknown"}; release: ${x?.readiness.release??"not-verified"}.`)),console.log(s.gray(` Check: ${C}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(j){if(v)try{await Tr(v,j);}catch(C){C!==j&&(j=C);}let R=j instanceof Error?j.message:String(j);return l(R),o?.fail("Project adoption failed"),o=void 0,e.json?console.log(JSON.stringify({error:R},null,2)):console.log(s.red(`\u274C Adopt failed: ${R}`)),1}}async function Zs(t){let e=new Set(["python-only","polyglot","enterprise"]),r=xh(),o="minimal",n=false;try{let l=t$1(t,"workspace.json").find(m=>$.existsSync(m))??q$1(t,"workspace.json"),p=JSON.parse(await $.promises.readFile(l,"utf-8"));o=p.profile??"minimal",n=p.bootstrap_note==="python-engine-skipped"||p.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(V(o)&&o!=="minimal")return false;if(!n&&e.has(o))return true;let l$1=await ei(t);if(l$1.length===0)return false;for(let p of l$1){let m=j$2(p),u=m?.module_support,f=typeof m?.kit_name=="string"?m.kit_name:typeof m?.kit=="string"?m.kit:void 0,P=f?a$3(f):null;if(n||o==="minimal"){if(P?.workspacePythonEngine==="required")return true;continue}if(!(k$2(m,p)||m$1(m,p)||n$1(m,p))&&u!==false)return o$1(m,p)||l(m,p),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:l}=await import('./workspace-marker-7U3NYRPJ.js'),m=(await l(t))?.metadata?.npm?.installMethod;(m==="poetry"||m==="venv"||m==="pipx"||m==="pip")&&(i=m);}catch{}let c=async()=>{let l=zf(t),p=await Zf(t);if(p!==0)return p;let m=f$3("DEV_PATH"),f=(m?await M__default.pathExists(m):false)&&m?["-m","pip","install",m,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await Ie(l,f,t,{timeoutMs:r})};if(i==="venv"){let l=await c();if(l!==0)return l}else if(i==="poetry"){let l=b.join(t,"pyproject.toml"),p=false;try{p=(await $.promises.readFile(l,"utf-8")).includes("rapidkit-core");}catch{p=false;}if(p){let m=await c();if(m!==0)return m}else {let m=await Ie("poetry",["install","--no-root"],t,{timeoutMs:r});if(m!==0)return m;let u=await Ie("poetry",["add","rapidkit-core"],t,{timeoutMs:r});if(u!==0)return u}}else return 0;try{let{writeWorkspaceLauncher:l}=await import('./create-YPAZJYCE.js');await l(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:l}=await import('./workspace-python-engine-state-VCOLSEWV.js');await l(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function xh(){let t=process.env.RAPIDKIT_WORKSPACE_DEPS_TIMEOUT_MS;if(t){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 12e4}async function ei(t){let e=[],r=new Set,o=[t];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await $.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){if(!i.isDirectory()||i.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(i.name))continue;let c=b.join(n,i.name);if((await Promise.all([...u$1(c,"context.json"),...u$1(c,"project.json")].map(p=>M__default.pathExists(p)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function Ih(t){return o$4(t)}async function si(t={}){let e=p$2(),r=b.basename(e),o=et(e);if(!o){let{createProject:n}=await import('./create-YPAZJYCE.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c$1=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:b.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await c(),suppressReceipt:true});}finally{t.silent&&(console.log=i,console.warn=c$1,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function Fs(t){let r=await Ze("go",{runCommandInCwd:Ie,runCoreRapidkit:e$2}).initProject(t);return ce(r)}function ce(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function tr(t,e){let r=Ze("node",{runCommandInCwd:Ie,runCoreRapidkit:e$2});if(t==="init"){let n=await r.initProject(e);return ce(n)}if(t==="dev"){let n=await r.runDev(e);return ce(n)}if(t==="test"){let n=await r.runTest(e);return ce(n)}if(t==="build"){let n=await r.runBuild(e);return ce(n)}if(t==="lint"){let n=await r.runLint?.(e);return ce(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return ce(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return ce(o)}async function Rt(t,e){let r=Ze("java",{runCommandInCwd:Ie,runCoreRapidkit:e$2});if(t==="init"){let n=await r.initProject(e);return ce(n)}if(t==="dev"){let n=await r.runDev(e);return ce(n)}if(t==="test"){let n=await r.runTest(e);return ce(n)}if(t==="build"){let n=await r.runBuild(e);return ce(n)}if(t==="lint"){let n=await r.runLint?.(e);return ce(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return ce(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return ce(o)}function Gs(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$7(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$e()})}async function _h(t$2,e=ti){if(t$2.includes("--help")||t$2.includes("-h")||t$2.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(O){if(!O)return null;let B=O.trim().toLowerCase();return B==="minimal"||B==="java-only"||B==="go-only"||B==="dotnet-only"||B==="python-only"||B==="node-only"||B==="polyglot"||B==="enterprise"?B:null},i=function(O){let De=O.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",Le=(_e,tt)=>{let dt=O.match(new RegExp(`^\\s*${_e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return dt?dt[1].toLowerCase()==="true":tt};return {mode:De,dependency_sharing_mode:$u(O),rules:{enforce_workspace_marker:Le("enforce_workspace_marker",true),enforce_toolchain_lock:Le("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:Le("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:Le("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:Le("require_mirror_lock_for_offline",true)}}};let c=["init"],l$1,p=false,m=false,u=false,f=false;for(let O=1;O<t$2.length;O+=1){let B=t$2[O];if(B==="--ci"){p=true;continue}if(B==="--offline"){m=true;continue}if(B==="--json"){u=true;continue}if(B==="--compliance-only"){f=true;continue}if(B==="--profile"){let H=t$2[O+1];if(!H||H.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;l$1=H,O+=1;continue}if(B.startsWith("--profile=")){l$1=B.slice(10);continue}c.push(B);}let P=a(l$1);if(l$1&&!P)return console.log(s.red(`Invalid profile: ${l$1}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let y=process.cwd(),E=c.slice(1).filter(O=>!O.startsWith("-"));if(E.length>0){let O=b.resolve(y,E[0]),B=j$2(O),H=$.existsSync(O)?await rr(O):"unknown";if(!et(O)&&(k$2(B,O)||m$1(B,O)||n$1(B,O)||l(B,O)||o$1(B,O)||H!=="unknown"))return await e(c)}let A=b.join(y,".rapidkit-workspace"),S=b.join(y,".rapidkit","workspace.json"),d;!$.existsSync(A)&&$.existsSync(S)?d=y:(d=xe(y),d||(d=kh(y)));let g=[],w=null,k=null;if(d)try{let O=t$1(d,"workspace.json").find(De=>$.existsSync(De))??q$1(d,"workspace.json"),B=await $.promises.readFile(O,"utf-8"),H=JSON.parse(B);k=a(H.profile);}catch{k=null;}let h=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],v={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},I=P;if(!!d&&!P&&!p&&!u&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let O=k||"minimal",{chosenProfile:B}=await b$1([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${O})`,choices:h.map(H=>({name:H===O?`${v[H]} \u2190 current`:v[H],value:H})),default:h.indexOf(O)}]);I=B;}let j=I||k||"minimal";if(d&&!f)try{let B=j==="python-only"||j==="polyglot"||j==="enterprise"?"poetry":"venv",H;try{let tt=(await $.promises.readFile(b.join(d,".python-version"),"utf-8")).trim();tt&&(H=tt);}catch{}let{syncWorkspaceFoundationFiles:De}=await import('./create-YPAZJYCE.js'),Le=await De(d,{workspaceName:b.basename(d),installMethod:B,pythonVersion:H,profile:j,writeMarker:true,writeGitignore:true,onlyIfMissing:true});g.push({id:"workspace.foundation.sync",status:Le.length>0?"passed":"skipped",message:Le.length>0?`Workspace foundation synchronized: ${Le.join(", ")}`:"Workspace foundation files are already up to date."});}catch(O){g.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${O.message}`});}else d&&g.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(d&&!f&&I)try{let O=q$1(d,"workspace.json"),B=await $.promises.readFile(O,"utf-8"),H=JSON.parse(B);if(H.profile=I,U.has(I)){delete H.bootstrap_note;let Le=H.engine&&typeof H.engine=="object"?H.engine:void 0;Le&&delete Le.python_core;}await M__default.ensureDir(b.dirname(O)),await $.promises.writeFile(O,JSON.stringify(H,null,2)+`
|
|
329
|
-
`,"utf-8");let{syncWorkspaceContract:De}=await import('./workspace-contract-
|
|
330
|
-
`):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${J}`))),1}if(u&&j==="enterprise"&&!p&&!f){let O=
|
|
331
|
-
`),1}let Ye=async O=>{let B=process.stdout.write.bind(process.stdout),H=process.stderr.write.bind(process.stderr),De=[],Le=[];process.stdout.write=((_e,tt,dt)=>{let Wr=typeof tt=="function"?tt:typeof dt=="function"?dt:void 0;return De.push(typeof _e=="string"?_e:_e instanceof Uint8Array?Buffer.from(_e).toString("utf8"):String(_e)),Wr?.(),true}),process.stderr.write=((_e,tt,dt)=>{let Wr=typeof tt=="function"?tt:typeof dt=="function"?dt:void 0;return Le.push(typeof _e=="string"?_e:_e instanceof Uint8Array?Buffer.from(_e).toString("utf8"):String(_e)),Wr?.(),true});try{return {exitCode:await O(),stdout:De.join(""),stderr:Le.join("")}}finally{process.stdout.write=B,process.stderr.write=H;}},Ee=O=>{let B=O.split(/\r?\n/).map(H=>H.trim()).filter(Boolean);return {bytes:Buffer.byteLength(O),excerpt:B.slice(0,12)}},L=0,G;if(!f)if(u){let O=await Ye(()=>e(c));L=O.exitCode,G={captured:true,stdout:Ee(O.stdout),stderr:Ee(O.stderr)};}else L=await e(c);let te=g.filter(O=>O.status==="failed").length,z=L!==0?"failed":te>0?"ok_with_warnings":"ok",ee=L!==0?L:te>0?1:0,Y=
|
|
328
|
+
`),d(1));});})}function Eh(t,e,r){if(t!=="npm")return null;let o=e[0];if(o!=="run"&&o!=="run-script")return null;let n=e.find((i,c)=>c>0&&!i.startsWith("-"));if(!n)return null;let a=b.join(r,"package.json");if(!$.existsSync(a))return null;try{let c=JSON.parse($.readFileSync(a,"utf8")).scripts?.[n];return typeof c!="string"?null:Sh(c)}catch{return null}}function Sh(t){let e=t.trim(),r=e.match(/^node\s+(?:-e|--eval)\s+"((?:\\.|[^"\\])*)"$/);if(r)return r[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let o=e.match(/^node\s+(?:-e|--eval)\s+'((?:\\.|[^'\\])*)'$/);return o?o[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}async function ta(t,e){await M__default.outputFile(t,`${JSON.stringify(e,null,2)}
|
|
329
|
+
`,"utf-8");}function Ah(t){return t.trim().toLowerCase().replace(/\.git$/i,"").replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)}async function Rh(t,e,r){let o=Gt(e)?e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop()?.split(":").pop()||"imported-project":b.basename(e),n=Ah(r||o)||"imported-project",a=0;for(;;){let i=a===0?n:a===1?`${n}-imported`:`${n}-imported-${a}`,c=b.join(t,i);if(!await M__default.pathExists(c))return c;a+=1;}}async function ei(t,e,r){let o=process.env.RAPIDKIT_TEST_IMPORT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),n=e.workspace?b.resolve(e.workspace):null,a=n?{workspacePath:n,error:null}:Zs(process.cwd()),i=a.workspacePath,c=false,l=false,p=false;if(a.error)return e.json?console.log(JSON.stringify(c$1({operation:"import",code:a.error.code,message:a.error.message,context:a.error.context}),null,2)):console.log(s.red(`\u274C ${a.error.message}`)),1;if(n){if(!et(n)){let f=`Workspace path is not a valid Workspai workspace: ${n}`;return e.json?console.log(JSON.stringify({error:f},null,2)):console.log(s.red(`\u274C ${f}`)),1}}else (!i||!et(i))&&(i=p$2(),c=true,p=true);if(!i||!et(i)&&!p){let f="Not inside a Workspai workspace";return e.json?console.log(JSON.stringify({error:f},null,2)):(console.log(s.red(`\u274C ${f}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let m="npx workspai project workspace status --json",u;try{let f=await Rh(i,t,e.name);if(u=await ea(i,{ownedDestination:f,ownedWorkspace:p?i:void 0}),p){let y=await ci({silent:e.json});i=y.workspacePath,l=y.created;}let P=await Qd({workspacePath:i,source:t,name:e.name,sourceType:e.git===true?"git-url":void 0,projectGrounding:e.projectGrounding});P.path!==f&&u.registerCompensation(()=>M__default.remove(P.path));try{if(r?.syncWorkspaceProjects)await r.syncWorkspaceProjects(i);else {if(o)throw new Error("forced sync failure for command-level import rollback test");let{registerProjectInWorkspaceStrict:y,registerWorkspaceStrict:E}=await import('./workspace-AXU6ODER.js'),{resolveWorkspaceRegistrationName:A}=await import('./workspace-marker-7U3NYRPJ.js');await E(i,await A(i)),await y(i,P.name,P.path);}await u.commit(),await Mr(i,{silent:e.json});}catch(y){try{await Tr(u,y);}catch(E){if(E!==y)throw E}throw new Error(`Workspace sync failed after import and the imported project was rolled back: ${y instanceof Error?y.message:String(y)}`)}if(e.json)return console.log(JSON.stringify({workspacePath:i,workspaceResolution:c?"default-auto":n?"explicit":"nearest",defaultWorkspaceCreated:c?l:false,projectWorkspaceCommand:m,commandsResolveWorkspaceFromProject:true,plan:P.ingestionPlan,importedProject:P},null,2)),0;if(c&&console.log(s.yellow(`\u2139 Imported outside a workspace, so Workspai used the default workspace: ${i}`)),l&&console.log(s.green("\u2713 Workspace ready \xB7 1 registered project \xB7 model + graph + agent grounding sealed")),console.log(s.green(`\u2714 Imported project: ${P.name}`)),console.log(s.gray(` Workspace: ${i}`)),console.log(s.gray(` Destination: ${P.path}`)),console.log(s.gray(` Stack: ${P.stack} (${P.confidence})`)),console.log(s.gray(` Source: ${e.git===true||Gt(t)?"git-url":"local-folder"}`)),!P.profileCompatibility.ok){let y=_(P.profileCompatibility);console.log(s.yellow(` Profile warning: ${P.profileCompatibility.message}`)),y&&console.log(s.gray(` ${y}`));}return console.log(s.gray(" Workspai commands now resolve this workspace directly from the imported project.")),console.log(s.gray(` Check: ${m}`)),0}catch(f){if(u)try{await Tr(u,f);}catch(y){y!==f&&(f=y);}let P=f instanceof Error?f.message:String(f);return e.json?console.log(JSON.stringify({error:P},null,2)):console.log(s.red(`\u274C Import failed: ${P}`)),1}}async function Wu(t,e,r){let o,n,a=(j,R)=>{n=j,o&&(o.text=R),c$7({blockId:j,status:"running",message:R,component:"adopt"});},i=(j,R)=>{c$7({blockId:j,status:"succeeded",message:R,component:"adopt"}),n===j&&(n=void 0);},c=(j,R)=>{c$7({blockId:j,status:"skipped",message:R,component:"adopt"});},l=j=>{n&&(c$7({blockId:n,status:"failed",message:j,component:"adopt"}),n=void 0);};a("adopt.resolve","Resolving project and workspace");let p=b.resolve(t||process.cwd()),m=e.workspace?b.resolve(e.workspace):null,u=null,f="nearest",P=false,y=false,E=false,A=false,S=false,d=null,g=m?{workspacePath:null,error:null}:Zs(process.cwd());if(!m&&!g.error&&!g.workspacePath&&(g=Zs(p)),g.error)return l(g.error.message),e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:g.error.code,message:g.error.message,context:g.error.context}),null,2)):console.log(s.red(`\u274C ${g.error.message}`)),1;if(m){let j=await ou(m,{dryRun:e.dryRun});if(!j.ok)return l(j.message),e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:j.code,message:j.message}),null,2)):console.log(s.red(`\u274C ${j.message}`)),1;({workspacePath:u,resolution:f,usedDefaultWorkspace:P,willCreateDefaultWorkspace:E,willBootstrapWorkspace:A,bootstrapTargetPath:d}=j.result);}else if(g.workspacePath&&et(g.workspacePath))u=g.workspacePath,f="nearest";else {let j=await oh(p,{json:e.json,explicitWorkspace:false}),R=await nu({sourcePath:p,outsideWorkspaceMode:j,dryRun:e.dryRun});if(!R.ok)return l(R.message),e.json?console.log(JSON.stringify(c$1({operation:"adopt",code:R.code,message:R.message}),null,2)):console.log(s.red(`\u274C ${R.message}`)),1;({workspacePath:u,resolution:f,usedDefaultWorkspace:P,willCreateDefaultWorkspace:E,willBootstrapWorkspace:A,bootstrapTargetPath:d}=R.result);}let w=f==="explicit-bootstrap"||f==="parent-bootstrap",k=P&&(e.dryRun===true||E)||w&&(e.dryRun===true||A)||u!==null&&et(u);if(!u||!et(u)&&!k){let j="Not inside a Workspai workspace";return l(j),e.json?console.log(JSON.stringify({error:j},null,2)):(console.log(s.red(`\u274C ${j}`)),console.log(s.gray("\u{1F4A1} Run this command from a workspace root or pass --workspace <path>."))),1}let h=process.env.RAPIDKIT_TEST_ADOPT_SYNC_FAIL==="1"&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"),v,I=null,x=null;try{if(e.dryRun!==true){if(v=await ea(u,{projectPath:p,ownedWorkspace:E||A?u:void 0}),E){let D=await ci({silent:e.json});u=D.workspacePath,y=D.created;}A&&d&&(await nh(d,v),S=true);}!e.json&&process.stdout.isTTY&&(o=b$8("Analyzing project for adoption",{component:"adopt",phase:"adopt.lifecycle",metadata:{dryRun:e.dryRun===true,workspaceResolution:f}})),i("adopt.resolve","Project and workspace resolved"),a("adopt.detect","Detecting architecture and adoption effects");let j=await Is(u,p),R=await _s({workspacePath:u,source:p,name:e.name,dryRun:e.dryRun===true,projectGrounding:e.projectGrounding,rollbackSnapshot:j});i("adopt.detect","Architecture and adoption effects detected");let C="npx workspai project workspace status --json",_$1=e.dryRun===true?b$5({startPath:p}):null,N=e.dryRun!==true||_$1!==null&&b.resolve(_$1.workspacePath)===b.resolve(u)&&(!_$1.projectPath||b.resolve(_$1.projectPath)===p);if(e.dryRun!==true){a("adopt.link","Linking project to workspace");try{if(r?.registerWorkspace||r?.registerProjectInWorkspace||r?.syncWorkspaceProjects)r.registerWorkspace&&await r.registerWorkspace(u,b.basename(u)),r.registerProjectInWorkspace&&await r.registerProjectInWorkspace(u,R.name,R.path),r.syncWorkspaceProjects&&await r.syncWorkspaceProjects(u);else {let{registerProjectInWorkspaceStrict:q,registerWorkspaceStrict:J}=await import('./workspace-AXU6ODER.js'),{resolveWorkspaceRegistrationName:ae}=await import('./workspace-marker-7U3NYRPJ.js');if(await J(u,await ae(u)),await q(u,R.name,R.path),h)throw new Error("forced sync failure for command-level adopt rollback test")}if(i("adopt.link","Project linked to workspace"),a("adopt.publish","Sealing workspace intelligence"),I=await Mr(u,{silent:e.json,strict:true}),!I?.freshnessSealed)throw new Error("Workspace consumer artifacts were generated without a freshness seal.");i("adopt.publish","Workspace intelligence freshness sealed"),a("adopt.ground","Building the project agent entry");let{buildAgentBootstrapReceipt:D}=await import('./project-agent-entry-6O7FKWSL.js');if(x=await D({startPath:p,forAgent:"generic",validateLiveInputs:true}),x.status==="blocked"){let q=x.checks.filter(J=>J.status==="failed").map(J=>`${J.id}: ${J.message}`).join("; ");throw new Error(`Adopted project did not produce a usable agent-grounding route${q?` (${q})`:"; inspect the bootstrap checks."}`)}await v?.commit(),i("adopt.ground","Project agent entry is ready");}catch(D){if(v)try{await Tr(v,D);}catch(q){if(q!==D)throw q}throw new Error(`Workspace sync failed after adopt and adoption metadata was rolled back: ${D instanceof Error?D.message:String(D)}`)}}else c("adopt.link","Dry run: workspace link not written"),c("adopt.publish","Dry run: workspace intelligence not published"),c("adopt.ground","Dry run: project agent entry not written");if(o?.succeed(e.dryRun===true?"Adoption preview ready":"Project adoption ready"),o=void 0,e.json)return console.log(JSON.stringify({workspacePath:u,workspaceResolution:f,defaultWorkspaceCreated:P?y:false,workspaceBootstrapped:S,wouldCreateDefaultWorkspace:P&&e.dryRun===true?!et(u):false,wouldBootstrapWorkspace:w&&e.dryRun===true?!et(u):false,projectWorkspaceCommand:C,commandsResolveWorkspaceFromProject:N,dryRun:e.dryRun===true,plan:R.ingestionPlan,adoptedProject:R,consumerArtifacts:e.dryRun===true||!I?null:{freshnessSealed:I.freshnessSealed,reconciledAfterGrounding:I.reconciledAfterGrounding,warnings:I.warnings},agentBootstrap:x},null,2)),0;P?console.log(s.yellow(`\u2139 Adopted outside a workspace, so Workspai used the default workspace: ${u}`)):S&&console.log(s.green(`\u2714 Workspace bootstrapped at: ${u}`)),y&&e.dryRun!==true&&console.log(s.green("\u2713 Workspace ready \xB7 1 registered project \xB7 model + graph + agent grounding sealed")),e.dryRun===true&&(console.log(s.yellow("\u2139 Dry run: no adoption files were written.")),console.log(s.gray(" Planned effects: project metadata + workspace registration + model, graph, and agent-grounding sync.")),R.effects.repositoryControlFiles.length>0&&console.log(s.gray(` Repository controls may be reconciled: ${R.effects.repositoryControlFiles.map(D=>D.path).join(", ")}.`))),console.log(s.green(`\u2714 Adopted project: ${R.name}`)),console.log(s.gray(` Workspace: ${u}`)),console.log(s.gray(` Project: ${R.path}`)),console.log(s.gray(" Mode: linked (source was not moved or copied)"));let V=R.stack==="unknown"?R.frameworkDisplayName||R.runtime:R.stack;if(console.log(s.gray(` Stack: ${V} (${R.confidence})`)),!R.profileCompatibility.ok){let D=_(R.profileCompatibility);console.log(s.yellow(` Profile warning: ${R.profileCompatibility.message}`)),D&&console.log(s.gray(` ${D}`));}return console.log(s.gray(` Report: ${R.adoptReadinessPath}`)),e.dryRun!==true&&(console.log(s.gray(" Workspai commands now resolve this workspace directly from the project.")),console.log(s.gray(` Consumer evidence: ${I?.freshnessSealed?"freshness sealed":"not sealed"}${I?.reconciledAfterGrounding?" after grounding reconciliation":""}.`)),console.log(s.gray(` Agent grounding: ${x?.status??"unknown"}; project environment: ${x?.readiness.projectEnvironment??"unknown"}; release: ${x?.readiness.release??"not-verified"}.`)),console.log(s.gray(` Check: ${C}`)),console.log(s.gray(" Then: npx workspai workspace intelligence run --for-agent generic --strict --json"))),0}catch(j){if(v)try{await Tr(v,j);}catch(C){C!==j&&(j=C);}let R=j instanceof Error?j.message:String(j);return l(R),o?.fail("Project adoption failed"),o=void 0,e.json?console.log(JSON.stringify({error:R},null,2)):console.log(s.red(`\u274C Adopt failed: ${R}`)),1}}async function ti(t){let e=new Set(["python-only","polyglot","enterprise"]),r=xh(),o="minimal",n=false;try{let l=t$1(t,"workspace.json").find(m=>$.existsSync(m))??q$1(t,"workspace.json"),p=JSON.parse(await $.promises.readFile(l,"utf-8"));o=p.profile??"minimal",n=p.bootstrap_note==="python-engine-skipped"||p.engine?.python_core?.status==="skipped";}catch{o="minimal";}if(!await(async()=>{if(U(o)&&o!=="minimal")return false;if(!n&&e.has(o))return true;let l$1=await ri(t);if(l$1.length===0)return false;for(let p of l$1){let m=j$2(p),u=m?.module_support,f=typeof m?.kit_name=="string"?m.kit_name:typeof m?.kit=="string"?m.kit:void 0,P=f?a$3(f):null;if(n||o==="minimal"){if(P?.workspacePythonEngine==="required")return true;continue}if(!(k$2(m,p)||m$1(m,p)||n$1(m,p))&&u!==false)return o$1(m,p)||l(m,p),true}return false})())return 0;let i="poetry";try{let{readWorkspaceMarker:l}=await import('./workspace-marker-7U3NYRPJ.js'),m=(await l(t))?.metadata?.npm?.installMethod;(m==="poetry"||m==="venv"||m==="pipx"||m==="pip")&&(i=m);}catch{}let c=async()=>{let l=zf(t),p=await Zf(t);if(p!==0)return p;let m=f$3("DEV_PATH"),f=(m?await M__default.pathExists(m):false)&&m?["-m","pip","install",m,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"];return await Ie(l,f,t,{timeoutMs:r})};if(i==="venv"){let l=await c();if(l!==0)return l}else if(i==="poetry"){let l=b.join(t,"pyproject.toml"),p=false;try{p=(await $.promises.readFile(l,"utf-8")).includes("rapidkit-core");}catch{p=false;}if(p){let m=await c();if(m!==0)return m}else {let m=await Ie("poetry",["install","--no-root"],t,{timeoutMs:r});if(m!==0)return m;let u=await Ie("poetry",["add","rapidkit-core"],t,{timeoutMs:r});if(u!==0)return u}}else return 0;try{let{writeWorkspaceLauncher:l}=await import('./create-M3TWRHV6.js');await l(t,i==="venv"?"venv":"poetry");}catch{}try{let{markWorkspacePythonEngineInstalled:l}=await import('./workspace-python-engine-state-VCOLSEWV.js');await l(t,{installMethod:i==="venv"?"venv":"poetry",venvPath:".venv"});}catch{}return 0}function xh(){let t=process.env.RAPIDKIT_WORKSPACE_DEPS_TIMEOUT_MS;if(t){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 12e4}async function ri(t){let e=[],r=new Set,o=[t];for(;o.length>0;){let n=o.pop();if(!n||r.has(n))continue;r.add(n);let a=[];try{a=await $.promises.readdir(n,{withFileTypes:true});}catch{continue}for(let i of a){if(!i.isDirectory()||i.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(i.name))continue;let c=b.join(n,i.name);if((await Promise.all([...u$1(c,"context.json"),...u$1(c,"project.json")].map(p=>M__default.pathExists(p)))).some(Boolean)){e.push(c);continue}o.push(c);}}return e}function Ih(t){return o$4(t)}async function ci(t={}){let e=p$2(),r=b.basename(e),o=et(e);if(!o){let{createProject:n}=await import('./create-M3TWRHV6.js'),a=process.env.WORKSPAI_LOG_FORMAT,i=console.log,c$1=console.warn;t.silent&&(process.env.WORKSPAI_LOG_FORMAT="json",console.log=()=>{},console.warn=()=>{});try{await n(r,{parentDirectory:b.dirname(e),profile:"minimal",skipPythonEngine:true,skipGit:true,yes:true,userConfig:await c(),suppressReceipt:true});}finally{t.silent&&(console.log=i,console.warn=c$1,a===void 0?delete process.env.WORKSPAI_LOG_FORMAT:process.env.WORKSPAI_LOG_FORMAT=a);}}return {workspacePath:e,created:!o}}async function Vs(t){let r=await Ze("go",{runCommandInCwd:Ie,runCoreRapidkit:e$2}).initProject(t);return ce(r)}function ce(t){return t.message&&console.log(s.red(`\u274C ${t.message}`)),t.exitCode}async function tr(t,e){let r=Ze("node",{runCommandInCwd:Ie,runCoreRapidkit:e$2});if(t==="init"){let n=await r.initProject(e);return ce(n)}if(t==="dev"){let n=await r.runDev(e);return ce(n)}if(t==="test"){let n=await r.runTest(e);return ce(n)}if(t==="build"){let n=await r.runBuild(e);return ce(n)}if(t==="lint"){let n=await r.runLint?.(e);return ce(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return ce(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return ce(o)}async function Rt(t,e){let r=Ze("java",{runCommandInCwd:Ie,runCoreRapidkit:e$2});if(t==="init"){let n=await r.initProject(e);return ce(n)}if(t==="dev"){let n=await r.runDev(e);return ce(n)}if(t==="test"){let n=await r.runTest(e);return ce(n)}if(t==="build"){let n=await r.runBuild(e);return ce(n)}if(t==="lint"){let n=await r.runLint?.(e);return ce(n??{exitCode:1,message:"Lint is not supported."})}if(t==="format"){let n=await r.runFormat?.(e);return ce(n??{exitCode:1,message:"Format is not supported."})}let o=await r.runStart(e);return ce(o)}function Js(t,e,r){let o=r.filter(n=>n.status==="failed").map(n=>{let a=n.id||"check";return n.message?`${a}: ${n.message}`:a}).slice(0,12);return f$7(t,{commandId:"bootstrap",exitCode:e,generatedAt:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),blockers:o,runId:e$e()})}async function _h(t$2,e=oi){if(t$2.includes("--help")||t$2.includes("-h")||t$2.includes("help"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),0;let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let a=function(O){if(!O)return null;let B=O.trim().toLowerCase();return B==="minimal"||B==="java-only"||B==="go-only"||B==="dotnet-only"||B==="python-only"||B==="node-only"||B==="polyglot"||B==="enterprise"?B:null},i=function(O){let De=O.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",Le=(_e,tt)=>{let dt=O.match(new RegExp(`^\\s*${_e}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return dt?dt[1].toLowerCase()==="true":tt};return {mode:De,dependency_sharing_mode:$u(O),rules:{enforce_workspace_marker:Le("enforce_workspace_marker",true),enforce_toolchain_lock:Le("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:Le("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:Le("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:Le("require_mirror_lock_for_offline",true)}}};let c=["init"],l$1,p=false,m=false,u=false,f=false;for(let O=1;O<t$2.length;O+=1){let B=t$2[O];if(B==="--ci"){p=true;continue}if(B==="--offline"){m=true;continue}if(B==="--json"){u=true;continue}if(B==="--compliance-only"){f=true;continue}if(B==="--profile"){let H=t$2[O+1];if(!H||H.startsWith("-"))return console.log(s.yellow("Usage: workspai bootstrap [path] [--profile <minimal|java-only|go-only|dotnet-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json] [--compliance-only]")),1;l$1=H,O+=1;continue}if(B.startsWith("--profile=")){l$1=B.slice(10);continue}c.push(B);}let P=a(l$1);if(l$1&&!P)return console.log(s.red(`Invalid profile: ${l$1}. Use one of: minimal, java-only, go-only, dotnet-only, python-only, node-only, polyglot, enterprise.`)),1;let y=process.cwd(),E=c.slice(1).filter(O=>!O.startsWith("-"));if(E.length>0){let O=b.resolve(y,E[0]),B=j$2(O),H=$.existsSync(O)?await rr(O):"unknown";if(!et(O)&&(k$2(B,O)||m$1(B,O)||n$1(B,O)||l(B,O)||o$1(B,O)||H!=="unknown"))return await e(c)}let A=b.join(y,".rapidkit-workspace"),S=b.join(y,".rapidkit","workspace.json"),d;!$.existsSync(A)&&$.existsSync(S)?d=y:(d=xe(y),d||(d=kh(y)));let g=[],w=null,k=null;if(d)try{let O=t$1(d,"workspace.json").find(De=>$.existsSync(De))??q$1(d,"workspace.json"),B=await $.promises.readFile(O,"utf-8"),H=JSON.parse(B);k=a(H.profile);}catch{k=null;}let h=["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"],v={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","java-only":"java-only \u2014 Java runtime (Spring Boot services)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)","dotnet-only":"dotnet-only \u2014 .NET runtime (ASP.NET Core services)",polyglot:"polyglot \u2014 Python + Node.js + Go + Java + .NET multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},I=P;if(!!d&&!P&&!p&&!u&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&process.env.VITEST!=="true"&&process.env.VITEST!=="1"){let O=k||"minimal",{chosenProfile:B}=await b$1([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${O})`,choices:h.map(H=>({name:H===O?`${v[H]} \u2190 current`:v[H],value:H})),default:h.indexOf(O)}]);I=B;}let j=I||k||"minimal";if(d&&!f)try{let B=j==="python-only"||j==="polyglot"||j==="enterprise"?"poetry":"venv",H;try{let tt=(await $.promises.readFile(b.join(d,".python-version"),"utf-8")).trim();tt&&(H=tt);}catch{}let{syncWorkspaceFoundationFiles:De}=await import('./create-M3TWRHV6.js'),Le=await De(d,{workspaceName:b.basename(d),installMethod:B,pythonVersion:H,profile:j,writeMarker:true,writeGitignore:true,onlyIfMissing:true});g.push({id:"workspace.foundation.sync",status:Le.length>0?"passed":"skipped",message:Le.length>0?`Workspace foundation synchronized: ${Le.join(", ")}`:"Workspace foundation files are already up to date."});}catch(O){g.push({id:"workspace.foundation.sync",status:"failed",message:`Failed to synchronize workspace foundation files: ${O.message}`});}else d&&g.push({id:"workspace.foundation.sync",status:"skipped",message:"Workspace foundation synchronization skipped by --compliance-only."});if(d&&!f&&I)try{let O=q$1(d,"workspace.json"),B=await $.promises.readFile(O,"utf-8"),H=JSON.parse(B);if(H.profile=I,T.has(I)){delete H.bootstrap_note;let Le=H.engine&&typeof H.engine=="object"?H.engine:void 0;Le&&delete Le.python_core;}await M__default.ensureDir(b.dirname(O)),await $.promises.writeFile(O,JSON.stringify(H,null,2)+`
|
|
330
|
+
`,"utf-8");let{syncWorkspaceContract:De}=await import('./workspace-contract-N2BJCAJ7.js');await De({workspacePath:d}),g.push({id:"workspace.profile.sync",status:"passed",message:`Workspace profile synchronized to ${I} across canonical artifacts.`});}catch(O){g.push({id:"workspace.profile.sync",status:"failed",message:`Failed to synchronize workspace profile across canonical artifacts: ${O instanceof Error?O.message:String(O)}`});}let R={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},C=null;if(d)try{let O=t$1(d,"policies.yml").find(H=>$.existsSync(H));if(!O)throw new Error("policy file missing");let B=await $.promises.readFile(O,"utf-8");C=B,R=i(B);}catch{g.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else g.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(d){let O=Tu(C);R.dependency_sharing_mode=O.mode,g.push({id:"policy.schema.dependency_sharing_mode",status:O.status,message:O.message}),g.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:R.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":R.dependency_sharing_mode==="shared-node-deps"?"Effective dependency mode: shared-node-deps (Node projects share workspace-level caches).":"Effective dependency mode: shared-runtime-caches (Node/Python/Go share workspace-level caches)."});let B=$.existsSync(b.join(d,".workspai-workspace"))||$.existsSync(b.join(d,".rapidkit-workspace"));g.push({id:"policy.enforce_workspace_marker",status:!R.rules.enforce_workspace_marker||B?"passed":"failed",message:!R.rules.enforce_workspace_marker||B?"Workspace marker policy satisfied.":"Workspace marker policy failed: .workspai-workspace is missing."});let H=t$1(d,"toolchain.lock").some(Fe=>$.existsSync(Fe));g.push({id:"policy.enforce_toolchain_lock",status:!R.rules.enforce_toolchain_lock||H?"passed":"failed",message:!R.rules.enforce_toolchain_lock||H?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .workspai/toolchain.lock is missing."});let De=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||t$1(d,"trusted-sources.lock").some(Fe=>$.existsSync(Fe));g.push({id:"policy.disallow_untrusted_tool_sources",status:!R.rules.disallow_untrusted_tool_sources||De?"passed":"failed",message:!R.rules.disallow_untrusted_tool_sources||De?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .workspai/trusted-sources.lock."});let Le=t$1(d,"compatibility-matrix.json").find(Fe=>$.existsSync(Fe))??q$1(d,"compatibility-matrix.json"),_e=$.existsSync(Le),tt=R.rules.enforce_compatibility_matrix;if(g.push({id:"policy.enforce_compatibility_matrix",status:!tt||_e?"passed":"failed",message:!tt||_e?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .workspai/compatibility-matrix.json is missing."}),_e)try{let Fe=await $.promises.readFile(Le,"utf-8"),St=JSON.parse(Fe),pi=!!St&&typeof St=="object";g.push({id:"compatibility.matrix.parse",status:pi?"passed":"failed",message:pi?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{g.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let dt=t$1(d,"mirror-config.json").find(Fe=>$.existsSync(Fe))??q$1(d,"mirror-config.json"),Wr=t$1(d,"mirror.lock").find(Fe=>$.existsSync(Fe))??q$1(d,"mirror.lock"),oa=$.existsSync(dt),na=$.existsSync(Wr),li={};if(oa)try{li=JSON.parse(await $.promises.readFile(dt,"utf-8")),g.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{g.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .workspai/mirror-config.json."});}if(f)g.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror synchronization lifecycle skipped by --compliance-only."});else {let Fe=await xs(d,{ciMode:p,offlineMode:m});g.push(...Fe.checks.map(St=>({id:St.id,status:St.status,message:St.message}))),w=Fe.details,Fe.details.lockWritten&&(na=true);}if(m){let Fe=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||li.enabled===true;g.push({id:"offline.mirror.enabled",status:Fe?"passed":"failed",message:Fe?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .workspai/mirror-config.json {"enabled": true}).'});let St=R.rules.require_mirror_lock_for_offline;g.push({id:"offline.mirror.lock",status:!St||na?"passed":"failed",message:!St||na?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .workspai/mirror.lock is missing."});}else g.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Eo=V({profile:j,runtimes:await Z(d),mode:R.mode});Eo.profile!=="enterprise"?g.push({id:Eo.checkId,status:Eo.status,message:Eo.message}):(g.push({id:"profile.enterprise.ci",status:p?"passed":f?"skipped":"failed",message:p?"enterprise profile running with --ci.":f?"Enterprise runtime execution skipped by --compliance-only; --ci is not required.":"enterprise profile expects --ci for deterministic non-interactive mode."}),g.push({id:"profile.enterprise.compatibility-matrix",status:_e?"passed":"failed",message:_e?"enterprise profile has compatibility matrix.":"enterprise profile requires .workspai/compatibility-matrix.json."}),g.push({id:"profile.enterprise.mirror-config",status:oa?"passed":"failed",message:oa?"enterprise profile has mirror configuration.":"enterprise profile requires .workspai/mirror-config.json."}));}p&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),m&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let N=g.some(O=>O.id.startsWith("policy.schema.")&&O.status==="failed")||R.mode==="strict"&&g.some(O=>O.status==="failed"),D=q$1(d||y,"reports"),q=new Date().toISOString().replace(/[:.]/g,"-"),J=b.join(D,`bootstrap-compliance-${q}.json`),ae=b.join(D,"bootstrap-compliance.latest.json"),pe={schemaVersion:s$1.bootstrapCompliance.schemaVersion,command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:d,profile:j,options:{ci:p,offline:m,strict:R.mode==="strict",complianceOnly:f},policyMode:R.mode,policyRules:R.rules,mirrorLifecycle:w,checks:g},se=async O=>{b$q(`.workspai/reports/${b.basename(J)}`,O),b$q(t.bootstrapCompliance,O),await M__default.ensureDir(D),await ta(J,O),await ta(ae,O);};if(N){let O=Js({...pe,result:"blocked",initExitCode:null},1,g);return await se(O),u?process.stdout.write(`${JSON.stringify(O,null,2)}
|
|
331
|
+
`):(console.log(s.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(s.gray(`Compliance report: ${J}`))),1}if(u&&j==="enterprise"&&!p&&!f){let O=Js({...pe,result:"blocked",initExitCode:null,complianceOnly:false,bootstrapRuntimeSkipped:{reason:"enterprise JSON bootstrap requires --ci for deterministic non-interactive execution.",nextAction:"npx workspai bootstrap --profile enterprise --ci --json"}},1,g);return await se(O),process.stdout.write(`${JSON.stringify(O,null,2)}
|
|
332
|
+
`),1}let Ye=async O=>{let B=process.stdout.write.bind(process.stdout),H=process.stderr.write.bind(process.stderr),De=[],Le=[];process.stdout.write=((_e,tt,dt)=>{let Wr=typeof tt=="function"?tt:typeof dt=="function"?dt:void 0;return De.push(typeof _e=="string"?_e:_e instanceof Uint8Array?Buffer.from(_e).toString("utf8"):String(_e)),Wr?.(),true}),process.stderr.write=((_e,tt,dt)=>{let Wr=typeof tt=="function"?tt:typeof dt=="function"?dt:void 0;return Le.push(typeof _e=="string"?_e:_e instanceof Uint8Array?Buffer.from(_e).toString("utf8"):String(_e)),Wr?.(),true});try{return {exitCode:await O(),stdout:De.join(""),stderr:Le.join("")}}finally{process.stdout.write=B,process.stderr.write=H;}},Ee=O=>{let B=O.split(/\r?\n/).map(H=>H.trim()).filter(Boolean);return {bytes:Buffer.byteLength(O),excerpt:B.slice(0,12)}},L=0,G;if(!f)if(u){let O=await Ye(()=>e(c));L=O.exitCode,G={captured:true,stdout:Ee(O.stdout),stderr:Ee(O.stderr)};}else L=await e(c);let te=g.filter(O=>O.status==="failed").length,z=L!==0?"failed":te>0?"ok_with_warnings":"ok",ee=L!==0?L:te>0?1:0,Y=Js({...pe,result:z,initExitCode:L,complianceOnly:f,...G?{initOutput:G}:{}},ee,g);if(await se(Y),d&&!f&&L===0)try{let{syncWorkspaceProjects:O}=await import('./workspace-AXU6ODER.js');await O(d,u),await Mr(d,{silent:u});}catch{}if(u)process.stdout.write(`${JSON.stringify(Y,null,2)}
|
|
332
333
|
`);else {let O=g.filter(B=>B.status==="failed").length;O>0&&console.log(s.yellow(`\u26A0\uFE0F Bootstrap completed with ${O} policy/profile warnings.`)),console.log(s.gray(`Compliance report: ${J}`));}return ee}finally{typeof r>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=r;}}async function Oh(t,e=Ie){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),0;let r=(t[1]||"").toLowerCase(),o=t.includes("--json"),n=t.includes("--warm-deps")||t.includes("--warm-dependencies");if(!r||!["python","node","go","java","dotnet","rust","php"].includes(r))return o?process.stdout.write(`${JSON.stringify({command:"setup",result:"error",error:"Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]"},null,2)}
|
|
333
334
|
`):console.log(s.yellow("Usage: workspai setup <python|node|go|java|dotnet|rust|php> [--warm-deps]")),1;let a=async(P,y)=>{if(P==="node"){if(!$.existsSync(b.join(y,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let A=$.existsSync(b.join(y,"pnpm-lock.yaml")),S=$.existsSync(b.join(y,"yarn.lock"));return A?{exitCode:await e("pnpm",["install","--lockfile-only","--ignore-scripts"],y)}:S?{exitCode:await e("yarn",["install","--ignore-scripts"],y)}:{exitCode:await e("npm",["install","--package-lock-only","--ignore-scripts"],y)}}if(P==="go")return $.existsSync(b.join(y,"go.mod"))?{exitCode:await e("go",["mod","download"],y)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."};if(P==="java"){let E=$.existsSync(b.join(y,"pom.xml")),A=$.existsSync(b.join(y,"build.gradle"))||$.existsSync(b.join(y,"build.gradle.kts")),S=b.join(y,process.platform==="win32"?"gradlew.bat":"gradlew"),d=$.existsSync(S);return !E&&!A?{exitCode:0,message:"Java warm-up skipped: pom.xml or build.gradle not found in current directory."}:E?{exitCode:await e("mvn",["-B","-q","-DskipTests","dependency:go-offline"],y)}:{exitCode:await e(d?S:"gradle",["--no-daemon","dependencies"],y)}}return P==="dotnet"?(()=>{let A=[{dir:y,depth:0}],S=new Set(["bin","obj",".git","node_modules",".workspai",".rapidkit"]);for(;A.length>0;){let d=A.shift();if(!d||d.depth>3)continue;let g=[];try{g=$.readdirSync(d.dir,{withFileTypes:true});}catch{continue}for(let w of g)if(w.isFile()){let k=w.name.toLowerCase();if(k.endsWith(".sln")||k.endsWith(".csproj"))return true}else w.isDirectory()&&!S.has(w.name)&&A.push({dir:b.join(d.dir,w.name),depth:d.depth+1});}return false})()?{exitCode:await e("dotnet",["restore"],y)}:{exitCode:0,message:".NET warm-up skipped: .sln or *.csproj not found in current project tree."}:P==="rust"?$.existsSync(b.join(y,"Cargo.toml"))?{exitCode:await e("cargo",["fetch"],y)}:{exitCode:0,message:"Rust warm-up skipped: Cargo.toml not found in current directory."}:P==="php"?$.existsSync(b.join(y,"composer.json"))?{exitCode:await e("composer",["install","--no-interaction","--no-scripts"],y)}:{exitCode:0,message:"PHP warm-up skipped: composer.json not found in current directory."}:{exitCode:0,message:"Dependency warm-up is not available for this runtime."}};if(o){let P=process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT;process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT="1";try{let E=await Ze(r,{runCommandInCwd:e,runCoreRapidkit:async(w,k)=>(await g$9(w,{...k,cwd:void 0})).exitCode}).checkPrereqs(),A=xe(process.cwd()),S=A||process.cwd(),d=null;if(r==="node"&&E.exitCode===0&&(d=process.version),A&&d){let w=t$1(A,"toolchain.lock").find(v=>$.existsSync(v))??q$1(A,"toolchain.lock"),k=q$1(A,"toolchain.lock"),h={};try{h=JSON.parse(await $.promises.readFile(w,"utf-8"));}catch{}(!h.runtime||typeof h.runtime!="object")&&(h.runtime={}),h.runtime[r]={version:d,detectedAt:new Date().toISOString()},await M__default.ensureDir(b.dirname(k)),await $.promises.writeFile(k,JSON.stringify(h,null,2)+`
|
|
334
|
-
`,"utf-8");}let g={requested:n,status:"not-requested",exitCode:null,targets:0,messages:[]};if(n&&E.exitCode===0){let w=[S];if(r==="java"&&A){let x=(await
|
|
335
|
-
`),E.exitCode}finally{typeof P>"u"?delete process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT:process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT=P;}}let i=Ze(r,{runCommandInCwd:e,runCoreRapidkit:(P,y)=>e$2(P,{...y,cwd:void 0})}),c=await i.checkPrereqs(),l=await i.doctorHints(process.cwd()),p=xe(process.cwd()),m=p||process.cwd(),u=null,f=async()=>r!=="java"||!p?[]:u||(u=(await
|
|
335
|
+
`,"utf-8");}let g={requested:n,status:"not-requested",exitCode:null,targets:0,messages:[]};if(n&&E.exitCode===0){let w=[S];if(r==="java"&&A){let x=(await ri(A)).filter(j=>{let R=j$2(j);return m$1(R,j)});x.length>0&&(w=x);}let k=[];for(let I of w)k.push(await a(r,I));let h=k.filter(I=>I.exitCode!==0),v=k.filter(I=>I.exitCode===0&&!/skipped/i.test(I.message||""));g.status=h.length>0?"failed":v.length>0?"passed":"skipped",g.exitCode=h[0]?.exitCode??0,g.targets=w.length,g.messages=k.map(I=>I.message).filter(I=>typeof I=="string");}return process.stdout.write(`${JSON.stringify({command:"setup",runtime:r,result:E.exitCode===0?"ok":"failed",exitCode:E.exitCode,workspacePath:A,version:d,warmDeps:n,warmDependencies:g},null,2)}
|
|
336
|
+
`),E.exitCode}finally{typeof P>"u"?delete process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT:process.env.RAPIDKIT_SUPPRESS_RUN_COMMAND_OUTPUT=P;}}let i=Ze(r,{runCommandInCwd:e,runCoreRapidkit:(P,y)=>e$2(P,{...y,cwd:void 0})}),c=await i.checkPrereqs(),l=await i.doctorHints(process.cwd()),p=xe(process.cwd()),m=p||process.cwd(),u=null,f=async()=>r!=="java"||!p?[]:u||(u=(await ri(p)).filter(y=>{let E=j$2(y);return m$1(E,y)}),u);if(c.exitCode===0){console.log(s.green(`\u2705 ${r} prerequisites look good.`));let P=["python","node","go","java","dotnet","rust","php"].filter(y=>y!==r).join("/");if(console.log(s.gray(` Scope: validated ${r} runtime only. ${P} checks are optional unless your workspace profile uses them.`)),r==="python"&&console.log(s.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),i.warmSetupCache&&((await i.warmSetupCache(m)).exitCode===0?console.log(s.gray(` ${r} cache warm-up completed.`)):console.log(s.yellow(` ${r} cache warm-up skipped (non-fatal).`))),n)if(r==="java"&&p){let y=await f();if(y.length>0){let E=0,A=0,S=0;for(let d of y){let g=await a("java",d),w=/skipped/i.test(g.message||""),k=b.relative(p,d)||b.basename(d);g.message&&console.log(s.gray(` [${k}] ${g.message}`)),g.exitCode===0&&!w?E+=1:g.exitCode===0&&w?S+=1:A+=1;}E>0&&console.log(s.gray(` java dependency warm-up completed for ${E} project(s) (--warm-deps).`)),A>0&&console.log(s.yellow(` java dependency warm-up failed for ${A} project(s) (non-fatal).`)),E===0&&A===0&&S>0&&console.log(s.gray(" java dependency warm-up skipped for discovered workspace projects."));}else {let E=await a("java",m),A=/skipped/i.test(E.message||"");E.message&&console.log(s.gray(` ${E.message}`)),E.exitCode===0&&!A?console.log(s.gray(` ${r} dependency warm-up completed (--warm-deps).`)):E.exitCode!==0&&console.log(s.yellow(` ${r} dependency warm-up failed (non-fatal).`));}}else {let y=await a(r,m),E=/skipped/i.test(y.message||"");y.message&&console.log(s.gray(` ${y.message}`)),y.exitCode===0&&!E?console.log(s.gray(` ${r} dependency warm-up completed (--warm-deps).`)):y.exitCode!==0&&console.log(s.yellow(` ${r} dependency warm-up failed (non-fatal).`));}if(p)try{let y=t$1(p,"toolchain.lock").find(d=>$.existsSync(d))??q$1(p,"toolchain.lock"),E=q$1(p,"toolchain.lock"),A={};try{A=JSON.parse(await $.promises.readFile(y,"utf-8"));}catch{}(!A.runtime||typeof A.runtime!="object")&&(A.runtime={});let S=A.runtime;if(r==="python"){let d=null;try{let{execa:g}=await import('execa');for(let w of ii()){let h=await g(w,w==="py"?["-3","--version"]:["--version"],{cwd:p,stdio:"pipe",reject:false,timeout:3e3});if(h.exitCode===0){let I=(h.stdout||h.stderr||"").match(/Python\s+(\S+)/);if(d=I?I[1]:null,d)break}}}catch{}S.python={...S.python||{},version:d,last_setup:new Date().toISOString()};}else if(r==="node")S.node={...S.node||{},version:process.version,last_setup:new Date().toISOString()};else if(r==="go"){let d=null;try{let{execa:g}=await import('execa'),k=((await g("go",["version"],{cwd:p,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);d=k?k[1]:null;}catch{}S.go={...S.go||{},version:d,last_setup:new Date().toISOString()};}else if(r==="java"){let d=null,g=null,w=null,k=await f(),v=$.existsSync(b.join(m,"pom.xml"))||$.existsSync(b.join(m,"build.gradle"))||$.existsSync(b.join(m,"build.gradle.kts"))?m:k[0]||m;try{let{execa:I}=await import('execa'),x=await I("java",["-version"],{cwd:p,stdio:"pipe",reject:false,timeout:3e3}),R=`${x.stdout||""}
|
|
336
337
|
${x.stderr||""}`.match(/version\s+"([^"]+)"/i);d=R?R[1]:null;let C=$.existsSync(b.join(v,"pom.xml")),_=$.existsSync(b.join(v,"build.gradle"))||$.existsSync(b.join(v,"build.gradle.kts"));if(C){g="maven";let N=(()=>{let J=b.join(v,"mvnw.cmd");if(process.platform==="win32"&&$.existsSync(J))return J;let ae=b.join(v,"mvnw");return $.existsSync(ae)?ae:"mvn"})(),V=await I(N,["-version"],{cwd:v,stdio:"pipe",reject:false,timeout:3e3}),q=`${V.stdout||""}
|
|
337
338
|
${V.stderr||""}`.match(/Apache Maven\s+(\S+)/i);w=q?q[1]:null;}else if(_){g="gradle";let N=(()=>{let J=b.join(v,"gradlew.bat");if(process.platform==="win32"&&$.existsSync(J))return J;let ae=b.join(v,"gradlew");return $.existsSync(ae)?ae:"gradle"})(),V=await I(N,["--version"],{cwd:v,stdio:"pipe",reject:false,timeout:3e3}),q=`${V.stdout||""}
|
|
338
339
|
${V.stderr||""}`.match(/Gradle\s+(\S+)/i);w=q?q[1]:null;}}catch{}S.java={...S.java||{},version:d,build_tool:g,build_tool_version:w,last_setup:new Date().toISOString()};}else if(r==="dotnet"){let d=null;try{let{execa:g}=await import('execa'),k=((await g("dotnet",["--version"],{cwd:p,stdio:"pipe",reject:false,timeout:3e3})).stdout||"").trim();d=k.length>0?k:null;}catch{}S.dotnet={...S.dotnet||{},version:d,sdk:d,last_setup:new Date().toISOString()};}A.updated_at=new Date().toISOString(),await $.promises.writeFile(E,JSON.stringify(A,null,2)+`
|
|
339
340
|
`,"utf-8"),console.log(s.gray(" toolchain.lock updated (.workspai/toolchain.lock)"));}catch{}}else console.log(s.red(`\u274C ${r} prerequisites check failed.`));if(l.length>0){console.log(s.gray(`
|
|
340
341
|
Hints:`));for(let P of l)console.log(s.gray(`- ${P}`));}return c.exitCode}function Nh(t){let e={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let r of t.split(`
|
|
341
|
-
`)){let o=r.trim(),n=o.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]/g,""));let a=o.match(/^prune_on_bootstrap:\s*(true|false)/);a&&(e.prune_on_bootstrap=a[1]==="true");let i=o.match(/^self_heal:\s*(true|false)/);i&&(e.self_heal=i[1]==="true");let c=o.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function $h(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=t.includes("--dry-run"),n
|
|
342
|
+
`)){let o=r.trim(),n=o.match(/^strategy:\s*(\S+)/);n&&(e.strategy=n[1].replace(/['"]/g,""));let a=o.match(/^prune_on_bootstrap:\s*(true|false)/);a&&(e.prune_on_bootstrap=a[1]==="true");let i=o.match(/^self_heal:\s*(true|false)/);i&&(e.self_heal=i[1]==="true");let c=o.match(/^verify_integrity:\s*(true|false)/);c&&(e.verify_integrity=c[1]==="true");}return e}async function $h(t){if(t.includes("--help")||t.includes("-h"))return console.log(s.yellow("Usage: workspai cache <status|clear|prune|repair>")),0;let e=(t[1]||"status").toLowerCase(),r=t.includes("--json"),o=t.includes("--dry-run"),n=Tn.getInstance(),a=xe(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(a)try{let c=t$1(a,"cache-config.yml").find(p=>$.existsSync(p));if(!c)throw new Error("cache config missing");let l=await $.promises.readFile(c,"utf-8");i=Nh(l);}catch{}if(e==="status"){let c={command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{enabled:true,strategy:i.strategy,selfHeal:i.self_heal,pruneOnBootstrap:i.prune_on_bootstrap,verifyIntegrity:i.verify_integrity,inMemory:true}};return r?(process.stdout.write(`${JSON.stringify(c,null,2)}
|
|
342
343
|
`),0):(console.log(s.cyan("Workspai cache is enabled")),console.log(s.cyan("Workspai cache status")),a?(console.log(s.gray(` Workspace: ${a}`)),console.log(s.gray(` Strategy: ${i.strategy}`)),console.log(s.gray(` Self-heal: ${i.self_heal}`)),console.log(s.gray(` Prune on bootstrap:${i.prune_on_bootstrap}`)),console.log(s.gray(` Verify integrity: ${i.verify_integrity}`))):console.log(s.gray(" (not inside a workspace \u2014 showing in-memory cache only)")),console.log(s.gray(" In-memory cache: enabled")),console.log(s.gray(" Use: workspai cache clear|prune|repair")),0)}return e==="clear"?(await n.clear(),r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{cleared:true,strategy:i.strategy}},null,2)}
|
|
343
344
|
`),0):(console.log(s.green("Cache clear completed")),console.log(s.green("\u2705 Cache cleared (all entries removed).")),0)):e==="prune"?(o||await n.clear(),r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,dryRun:o,cache:{pruned:!o,strategy:i.strategy,pruneOnBootstrap:i.prune_on_bootstrap},nextActions:i.prune_on_bootstrap?[]:["Set prune_on_bootstrap: true in .workspai/cache-config.yml to auto-prune on bootstrap."]},null,2)}
|
|
344
345
|
`),0):o?(console.log(s.green("Cache prune dry run completed")),console.log(s.gray(" No cache entries were removed.")),0):(console.log(s.green("\u2705 Cache pruned (stale entries removed).")),i.prune_on_bootstrap||console.log(s.gray(" Tip: set prune_on_bootstrap: true in .workspai/cache-config.yml to auto-prune on every bootstrap.")),0)):e==="repair"?i.self_heal?(await n.clear(),r?(process.stdout.write(`${JSON.stringify({command:"cache",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:a,cache:{repaired:true,selfHeal:i.self_heal,verifyIntegrity:i.verify_integrity}},null,2)}
|
|
@@ -352,16 +353,16 @@ Hints:`));for(let P of l)console.log(s.gray(`- ${P}`));}return c.exitCode}functi
|
|
|
352
353
|
`),1):(console.log(s.red(`\u274C Unknown policy rule: ${u}`)),1);let f=Ch(o);if(f===null)return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.invalid_boolean",message:"Rule values must be boolean: true | false"}},null,2)}
|
|
353
354
|
`),1):(console.log(s.red("\u274C Rule values must be boolean: true | false")),1);p=Ph(p,u,f);}else return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"error",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,error:{code:"workspace.policy.unknown_key",message:`Unknown policy key: ${c}`}},null,2)}
|
|
354
355
|
`),1):(console.log(s.red(`\u274C Unknown policy key: ${c}`)),1);await jh(t,p);let m=ju(p);return n?(process.stdout.write(`${JSON.stringify({command:"workspace policy",action:a,result:"ok",timestamp:new Date().toISOString(),workspacePath:t,policyPath:i,updatedKey:c,policy:m},null,2)}
|
|
355
|
-
`),0):(console.log(s.green(`\u2705 Updated ${c} in .workspai/policies.yml`)),console.log(s.gray(` mode: ${m.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${m.dependency_sharing_mode}`)),console.log(s.gray(" Tip: run `npx workspai workspace policy show` to inspect all values.")),0)}async function Mh(t$2){if(t$2.includes("--help")||t$2.includes("-h"))return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),0;let e=(t$2[1]||"status").toLowerCase(),r=t$2.includes("--json"),o=xe(process.cwd());if(!o)return console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let n=t$1(o,"mirror-config.json").find(u=>$.existsSync(u))??q$1(o,"mirror-config.json"),a=t$1(o,"mirror.lock").find(u=>$.existsSync(u))??q$1(o,"mirror.lock"),i=q$1(o,"mirror","artifacts"),c=q$1(o,"reports");async function l(u){if(!await M__default.pathExists(u))return 0;let f=0,P=[u];for(;P.length>0;){let y=P.shift();if(!y)continue;let E=await $.promises.readdir(y,{withFileTypes:true});for(let A of E)A.isFile()?f+=1:A.isDirectory()&&P.push(b.join(y,A.name));}return f}async function p(u){let f=new Date().toISOString().replace(/[:.]/g,"-"),P=b.join(c,`mirror-ops-${f}.json`),y=b.join(c,"mirror-ops.latest.json"),E={schemaVersion:s$1.mirrorOps.schemaVersion,...u};b$q(`.workspai/reports/${b.basename(P)}`,E),b$q(t.mirrorOps,E),await M__default.ensureDir(c),await
|
|
356
|
-
`),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Config: ${u?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${f?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${P}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let u=await
|
|
356
|
+
`),0):(console.log(s.green(`\u2705 Updated ${c} in .workspai/policies.yml`)),console.log(s.gray(` mode: ${m.mode}`)),console.log(s.gray(` dependency_sharing_mode: ${m.dependency_sharing_mode}`)),console.log(s.gray(" Tip: run `npx workspai workspace policy show` to inspect all values.")),0)}async function Mh(t$2){if(t$2.includes("--help")||t$2.includes("-h"))return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),0;let e=(t$2[1]||"status").toLowerCase(),r=t$2.includes("--json"),o=xe(process.cwd());if(!o)return console.log(s.red("\u274C Not inside a Workspai workspace")),console.log(s.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let n=t$1(o,"mirror-config.json").find(u=>$.existsSync(u))??q$1(o,"mirror-config.json"),a=t$1(o,"mirror.lock").find(u=>$.existsSync(u))??q$1(o,"mirror.lock"),i=q$1(o,"mirror","artifacts"),c=q$1(o,"reports");async function l(u){if(!await M__default.pathExists(u))return 0;let f=0,P=[u];for(;P.length>0;){let y=P.shift();if(!y)continue;let E=await $.promises.readdir(y,{withFileTypes:true});for(let A of E)A.isFile()?f+=1:A.isDirectory()&&P.push(b.join(y,A.name));}return f}async function p(u){let f=new Date().toISOString().replace(/[:.]/g,"-"),P=b.join(c,`mirror-ops-${f}.json`),y=b.join(c,"mirror-ops.latest.json"),E={schemaVersion:s$1.mirrorOps.schemaVersion,...u};b$q(`.workspai/reports/${b.basename(P)}`,E),b$q(t.mirrorOps,E),await M__default.ensureDir(c),await ta(P,E),await ta(y,E);}async function m(){let u=await M__default.pathExists(n),f=await M__default.pathExists(a),P=await l(i);return {configExists:u,lockExists:f,artifactsCount:P}}if(e==="status"){let u=await M__default.pathExists(n),f=await M__default.pathExists(a),P=await l(i),y={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:{configExists:u,lockExists:f,artifactsCount:P}};return await p(y),r?(process.stdout.write(`${JSON.stringify(y,null,2)}
|
|
357
|
+
`),0):(console.log(s.cyan("Workspai mirror status")),console.log(s.gray(`Workspace: ${o}`)),console.log(s.gray(`Config: ${u?"present":"missing"} (${n})`)),console.log(s.gray(`Lock: ${f?"present":"missing"} (${a})`)),console.log(s.gray(`Artifacts: ${P}`)),0)}if(e==="sync"||e==="verify"||e==="rotate"){let u=await xs(o,{ciMode:true,offlineMode:e==="verify",forceRun:true}),f=u.checks.filter(E=>E.status==="failed"),P=u.checks.some(E=>E.id.startsWith("mirror.verify.")&&E.status==="failed");if(e==="verify"&&P){let E={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await m(),details:u.details,checks:u.checks};if(await p(E),r)return process.stdout.write(`${JSON.stringify(E,null,2)}
|
|
357
358
|
`),1;console.log(s.red("\u274C Mirror verify failed."));for(let A of u.checks.filter(S=>S.id.startsWith("mirror.verify.")))console.log(s.gray(`- ${A.id}: ${A.message}`));return 1}if(f.length>0){let E={command:"mirror",action:e,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,mirror:await m(),details:u.details,checks:u.checks};if(await p(E),r)return process.stdout.write(`${JSON.stringify(E,null,2)}
|
|
358
359
|
`),1;console.log(s.yellow(`\u26A0\uFE0F Mirror ${e} completed with ${f.length} issue(s).`));for(let A of f)console.log(s.gray(`- ${A.id}: ${A.message}`));return 1}let y={command:"mirror",action:e,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:await m(),details:u.details,checks:u.checks};return await p(y),r?(process.stdout.write(`${JSON.stringify(y,null,2)}
|
|
359
|
-
`),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${u.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${u.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${u.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function
|
|
360
|
-
`).toLowerCase(),h=k.includes("\\.rapidkit\\rapidkit"),v=k.includes("\\.rapidkit\\rapidkit.cmd")||k.includes("\\.rapidkit\\rapidkit.exe")||k.includes("\\.venv\\scripts\\rapidkit.exe");return h&&!v}catch{return false}},e$1=process.cwd(),r=process.argv.slice(2),o=r[0],n=o==="init",a=new Set(r$1),i=!o||o==="--help"||o==="-h"||o==="help",c=et(e$1),l$1=u$1(e$1,"project.json").some(g=>$.existsSync(g)),p=j$2(e$1),m=await rr(e$1),u=k$2(p,e$1)||l(p,e$1)||o$1(p,e$1)||m$1(p,e$1)||n$1(p,e$1)||h$4(m??void 0),f=!!o&&a.has(o)&&u,P=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Co(r)||r[0]==="create")return false;if(
|
|
360
|
+
`),0):e==="rotate"?(console.log(s.green(`\u2705 Mirror rotate completed. Rotated files: ${u.details.rotatedFiles}.`)),0):e==="verify"?(console.log(s.green(`\u2705 Mirror verify completed. Verified artifacts: ${u.details.verifiedArtifacts}.`)),0):(console.log(s.green(`\u2705 Mirror sync completed. Synced artifacts: ${u.details.syncedArtifacts}.`)),0)}return console.log(s.yellow("Usage: workspai mirror <status|sync|verify|rotate> [--json]")),1}async function oi(t){let e=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof e>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let r=process.cwd(),o=await Mu(r,async()=>{let n=xe(r),a=Ze("python",{runCommandInCwd:Ie,runCoreRapidkit:e$2}),i=Ze("dotnet",{runCommandInCwd:Ie,runCoreRapidkit:e$2}),c$1=Ze("rust",{runCommandInCwd:Ie,runCoreRapidkit:e$2}),l$1=Ze("php",{runCommandInCwd:Ie,runCoreRapidkit:e$2}),p=t.slice(1).filter(A=>!A.startsWith("-"));if(p.length>0){let A=b.resolve(r,p[0]),S=j$2(A),d=await rr(A);return k$2(S,A)||d==="go"?await Vs(A):m$1(S,A)||d==="java"?await Rt("init",A):n$1(S,A)||d==="dotnet"?ce(await i.initProject(A)):l(S,A)||d==="node"?await Gs(A):o$1(S,A)||d==="python"?await Fs(A,a):d==="rust"?ce(await c$1.initProject(A)):d==="php"?ce(await l$1.initProject(A)):await e$2(t,{cwd:r})}let m=j$2(r),u=!!xe(r)&&r===xe(r);if(!u&&k$2(m,r))return await Vs(r);let f=await rr(r);if(!u&&(m$1(m,r)||f==="java"))return await Rt("init",r);if(!u&&(n$1(m,r)||f==="dotnet"))return ce(await i.initProject(r));if(!u&&(l(m,r)||f==="node"))return await Gs(r);if(!u&&(o$1(m,r)||f==="python"))return await Fs(r,a);if(!u&&f==="rust")return ce(await c$1.initProject(r));if(!u&&f==="php")return ce(await l$1.initProject(r));let P=n||xe(r),y=Ou(r),E=y?b.dirname(b.dirname(y)):null;if(E&&E!==P){let A=j$2(E),S=await rr(E);return k$2(A,E)||S==="go"?await Vs(E):m$1(A,E)||S==="java"?await Rt("init",E):n$1(A,E)||S==="dotnet"?ce(await i.initProject(E)):l(A,E)||S==="node"?await Gs(E):o$1(A,E)||S==="python"?await Fs(E,a):S==="rust"?ce(await c$1.initProject(E)):S==="php"?ce(await l$1.initProject(E)):await e$2(["init"],{cwd:E})}if(P&&r===P){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 A=await ti(P);if(A!==0)return A;let{runWorkspaceStage:S}=await import('./workspace-run-VDQ6BYLS.js');return (await S({workspacePath:P,stage:"init",affected:false,blastRadius:false,parallel:false,continueOnError:true,strict:false,json:false,enforceGates:false})).summary.exitCode}if(!P){let A=await c(),S=l$6(),{name:d}=Ih(S);await M__default.ensureDir(S);let{createProject:g}=await import('./create-M3TWRHV6.js');return await g(d,{yes:true,userConfig:A,parentDirectory:S}),0}return await e$2(t,{cwd:r})});return o.ok?o.value:o.code}finally{typeof e>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=e;}}async function Su(t){let e=xe(t);if(!e)return [];let r="warn";try{let l=t$1(e,"policies.yml").find(u=>$.existsSync(u));if(!l)return [];let p=await $.promises.readFile(l,"utf-8");(p.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??p.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]==="strict"&&(r="strict");}catch{return []}if(r!=="strict")return [];let o=[],n=t$1(e,"toolchain.lock").find(l=>$.existsSync(l));if(!n||!$.existsSync(n))return o.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain)."),o;let a={};try{a=JSON.parse(await $.promises.readFile(n,"utf-8"));}catch{return o.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode."),o}let i=a.runtime??{},c=j$2(t);k$2(c,t)&&!i.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."):l(c,t)&&!i.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."):m$1(c,t)&&!i.java?.version?o.push("java.version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."):n$1(c,t)&&!i.dotnet?.version?o.push("dotnet.version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."):o$1(c,t)&&!i.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");try{let l=t$1(e,"workspace.json").find(P=>$.existsSync(P));if(!l)throw new Error("workspace manifest missing");let m=JSON.parse(await $.promises.readFile(l,"utf-8")).profile??"",u=m$2(t,c),f=W({profile:m,runtime:u.runtime,subjectLabel:b.basename(t),mode:"strict"});f.ok||o.push(`${f.message} Update the workspace profile or use a polyglot workspace.`);}catch{}return o}async function Wh(){let t=async g=>{if(!b$3()||!g.toLowerCase().endsWith(".cmd"))return false;try{let k=(await M__default.readFile(g,"utf8")).replace(/\r\n/g,`
|
|
361
|
+
`).toLowerCase(),h=k.includes("\\.rapidkit\\rapidkit"),v=k.includes("\\.rapidkit\\rapidkit.cmd")||k.includes("\\.rapidkit\\rapidkit.exe")||k.includes("\\.venv\\scripts\\rapidkit.exe");return h&&!v}catch{return false}},e$1=process.cwd(),r=process.argv.slice(2),o=r[0],n=o==="init",a=new Set(r$1),i=!o||o==="--help"||o==="-h"||o==="help",c=et(e$1),l$1=u$1(e$1,"project.json").some(g=>$.existsSync(g)),p=j$2(e$1),m=await rr(e$1),u=k$2(p,e$1)||l(p,e$1)||o$1(p,e$1)||m$1(p,e$1)||n$1(p,e$1)||h$4(m??void 0),f=!!o&&a.has(o)&&u,P=process.env.RAPIDKIT_LOCAL_LAUNCHER_BYPASS==="1";if(Co(r)||r[0]==="create")return false;if(Ys(r))return true;if(r[0]==="init"&&c&&!l$1)return false;if(Xs(r))return true;try{let g=o==="shell"&&r[1]==="activate",w=o==="create",k=await Kl(e$1,{cwd:e$1,timeoutMs:1200});if(k.ok&&k.data?.isRapidkitProject&&k.data.engine==="python"){let h=w||Co(r);if(!i&&!g&&!h&&!n&&!f&&Na(r)){if(o&&ku.includes(o)){let I=await Su(e$1).catch(()=>[]);if(I.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
|
|
361
362
|
`);for(let x of I)process.stderr.write(s.red(` \u2022 ${x}`)+`
|
|
362
363
|
`);process.exit(1);}}let v=await e$2(process.argv.slice(2),{cwd:e$1});process.exit(v);}}}catch{}let y=Ou(e$1),E=b$3(),A=P?[]:v$1(e$1),S=null;for(let g of A)if(await M__default.pathExists(g)){if(await t(g)){e.warn(`Skipping legacy/broken Windows launcher candidate: ${g}. Falling back to core bridge.`);continue}S=g;break}let d=o==="create";if(o==="init"&&c&&!l$1)return false;if(o&&ku.includes(o)){let g=await Su(e$1);if(g.length>0){process.stderr.write(s.red("\u274C Strict policy violations prevent running this command:")+`
|
|
363
364
|
`);for(let w of g)process.stderr.write(s.red(` \u2022 ${w}`)+`
|
|
364
|
-
`);process.exit(1);}}if(S&&o&&yu.includes(o)&&!d&&!n&&!f){e.debug(`Delegating to local CLI: ${S} ${r.join(" ")}`);let g=o==="init"?
|
|
365
|
+
`);process.exit(1);}}if(S&&o&&yu.includes(o)&&!d&&!n&&!f){e.debug(`Delegating to local CLI: ${S} ${r.join(" ")}`);let g=o==="init"?Bs():process.env,w=spawn(S,r,{stdio:"inherit",cwd:e$1,shell:E,env:g});return w.on("close",k=>{process.exit(k??0);}),w.on("error",k=>{e.error(`Failed to run local rapidkit: ${k.message}`),process.exit(1);}),true}if(y&&await M__default.pathExists(y))try{let g=await M__default.readJson(y);if(ro(g.engine)){let w=r[0],k=P?[]:v$1(e$1),h=null;for(let v of k)if(await M__default.pathExists(v)){if(await t(v)){e.warn(`Skipping legacy/broken Windows launcher candidate: ${v}. Falling back to core bridge.`);continue}h=v;break}if(h&&w&&yu.includes(w)&&w!=="init"&&!f){e.debug(`Delegating to local CLI (early detection): ${h} ${r.join(" ")}`);let v=w==="init"?Bs():process.env,I=spawn(h,r,{stdio:"inherit",cwd:e$1,shell:E,env:v});return I.on("close",x=>process.exit(x??0)),I.on("error",x=>{e.error(`Failed to run local rapidkit: ${x.message}`),process.exit(1);}),true}if(w==="shell"&&r[1]==="activate"){let v=b$3()?`# RapidKit Core activation snippet (PowerShell)
|
|
365
366
|
$venv = ".venv"
|
|
366
367
|
if (Test-Path "$venv\\Scripts\\Activate.ps1") { . "$venv\\Scripts\\Activate.ps1" }
|
|
367
368
|
$env:RAPIDKIT_PROJECT_ROOT = (Get-Location).Path
|
|
@@ -383,13 +384,13 @@ export PATH="$(pwd)/.workspai:$(pwd)/.rapidkit:$(pwd):$PATH"
|
|
|
383
384
|
\u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
|
|
384
385
|
`)),console.log(v),console.log(s.gray(`
|
|
385
386
|
\u{1F4A1} After activation you can run: workspai dev
|
|
386
|
-
`)),process.exit(0);}if(!i&&!Co(r)&&w!=="init"&&!f&&
|
|
387
|
+
`)),process.exit(0);}if(!i&&!Co(r)&&w!=="init"&&!f&&Na(r)){let v=await e$2(r,{cwd:e$1});process.exit(v);}}}catch{}return false}var Jt=null,Xn=false,Dh=Bf(),ni="workspai",Ks="npx workspai",he=new Command;he.enablePositionalOptions();var Lh=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function Fh(t){if(t.length===0)return false;let e=t[0],r=t[1];if(F$1(t)||dh.includes(e))return false;if(s$3.includes(e)){if(e==="lint"||e==="format"){let n=j$2(process.cwd()),a=await rr(process.cwd());if(l(n,process.cwd())||a==="node"){let i=m$2(process.cwd(),n);if(u$2(process.cwd(),e,{framework:i.key})!==null)return false}if(o$1(n,process.cwd())||a==="python")return true;if(C(process.cwd()))return false}return true}if(Co(t)||e==="shell"&&r==="activate")return false;if(t.includes("--tui"))return true;if(e==="--help"||e==="-h"||e==="help"||e==="version"||e==="--version"||e==="-V"||e==="-v"||t.includes("--template")||t.includes("-t"))return false;let o=await i$3();return Oa(e,o)?true:t.some(n=>_a.has(n))?false:o?o.has(e):!!(a$5.has(e)||t.length>1)}he.name(ni).description("Workspai workspace intelligence CLI").version(h());he.addHelpText("beforeAll",`Workspai CLI
|
|
387
388
|
|
|
388
389
|
Workspace Intelligence for software systems.
|
|
389
390
|
`);he.addHelpText("afterAll",`
|
|
390
391
|
Discover more:
|
|
391
|
-
${
|
|
392
|
-
${
|
|
392
|
+
${ni} --help Product overview and first steps
|
|
393
|
+
${ni} commands --json Complete machine-readable command inventory
|
|
393
394
|
https://workspai.dev Guides, contracts, and examples
|
|
394
395
|
`);he.command("live [target]").description("Open a live cross-terminal execution graph for Workspai activity").option("--global","Monitor activity across all local Workspai projects and workspaces").option("--run <runId>","Show only one activity run").option("--once","Render one snapshot and exit").option("--json","Emit monitor snapshots as JSON").addOption(new Option("--projection <projection>","JSON projection: monitor or renderer-neutral board").choices(["monitor","board"]).default("monitor")).option("--refresh-ms <milliseconds>","Live refresh interval (100-5000ms)","250").option("--max-runs <count>","Maximum runs rendered in the terminal","6").option("--max-scopes <count>","Maximum local scopes discovered by --global","12").option("--classic","Use the compatibility line-oriented renderer").option("--no-color","Disable terminal colors").option("--no-motion","Disable animated flow indicators").option("--ascii","Use ASCII-only symbols and connectors").option("--accessible","Use a stable screen-reader-friendly linear view").option("--capture <file>","Write a deterministic product-ready SVG snapshot and exit").option("--capture-preset <preset>","Capture size: github, linkedin, x, square, wide","github").option("--capture-theme <theme>","Capture theme: obsidian, light, mono","obsidian").option("--no-capture-redact","Keep local workspace, project, run and argument labels in capture").option("--replay <runId>","Replay a durable activity run with pause and step controls").option("--replay-speed <multiplier>","Replay speed from 0.25 to 64","4").action(async(t,e)=>{let r=Number.parseInt(e.refreshMs??"250",10),o=Number.parseInt(e.maxRuns??"6",10),n=Number.parseInt(e.maxScopes??"12",10),a=Number.parseFloat(e.replaySpeed??"4");if(!Number.isFinite(r)||r<100||r>5e3)throw new Error("--refresh-ms must be an integer from 100 to 5000.");if(!Number.isFinite(o)||o<1||o>50)throw new Error("--max-runs must be an integer from 1 to 50.");if(!Number.isFinite(n)||n<1||n>50)throw new Error("--max-scopes must be an integer from 1 to 50.");if(!Number.isFinite(a)||a<.25||a>64)throw new Error("--replay-speed must be a number from 0.25 to 64.");if(e.projection==="board"&&e.json!==true)throw new Error("--projection board requires --json.");if(e.projection==="board"&&e.capture)throw new Error("--projection board cannot be combined with --capture; capture already uses the Activity Board internally.");if(e.global===true&&t)throw new Error("A target path cannot be combined with --global.");if(e.replay&&e.global===true)throw new Error("--replay cannot be combined with --global.");if(e.replay&&e.capture)throw new Error("--replay cannot be combined with --capture.");if(!["github","linkedin","x","square","wide"].includes(e.capturePreset??""))throw new Error("--capture-preset must be github, linkedin, x, square, or wide.");if(!["obsidian","light","mono"].includes(e.captureTheme??""))throw new Error("--capture-theme must be obsidian, light, or mono.");let{runLiveCommand:i}=await import('./live-command-GNAASZ7U.js');await i({targetPath:t,runId:e.run,once:e.once===true,json:e.json===true,projection:e.projection??"monitor",refreshMs:r,maxRuns:o,classic:e.classic===true,color:e.color===false?false:void 0,motion:e.motion===false?false:void 0,ascii:e.ascii===true?true:void 0,accessible:e.accessible===true,global:e.global===true,maxScopes:n,capturePath:e.capture,capturePreset:e.capturePreset,captureTheme:e.captureTheme,captureRedact:e.captureRedact!==false,replayRunId:e.replay,replaySpeed:a});});he.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs, springboot, gofiber, gogin, dotnet) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").option("--author <name>","Author/team name for workspace metadata").option("--here","Create workspace in the current directory (same as --output .)").option("--output <dir>","Parent directory for the new workspace folder").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-python-engine","Create a Python-aware workspace without installing rapidkit-core now").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, java-only, python-only, node-only, go-only, dotnet-only, polyglot, enterprise").choices(["minimal","java-only","python-only","node-only","go-only","dotnet-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not link it to any workspace").hideHelp()).option("--no-update-check","Skip checking for updates").option("--trust-config","Trust and execute workspai.config.js/mjs/cjs discovered in this tree").action(async(t,e$3)=>{try{e$3.debug&&(e.setDebug(true),e.debug("Debug mode enabled"));let r=await c();e.debug("User config loaded",{...r,openaiApiKey:r.openaiApiKey?"[REDACTED]":void 0});let o=await d(process.cwd(),{trustExecutableConfig:e$3.trustConfig===true||process.env.WORKSPAI_TRUST_CONFIG==="1"});e.debug("Workspai config loaded",o);let n$1=e$1(r,o,{author:e$3.author,pythonVersion:void 0,skipGit:e$3.skipGit});e.debug("Merged config",n$1),e$3.updateCheck!==false&&await g(),a("workspace"),t||(Fu(),process.exit(0));try{j(t);}catch(l){throw l instanceof a$1&&(e.error(`
|
|
395
396
|
\u274C ${l.message}`),l.details&&e.warn(`\u{1F4A1} ${l.details}
|
|
@@ -399,11 +400,11 @@ Discover more:
|
|
|
399
400
|
`)),process.exit(1));}if(e$3.dryRun){console.log(s.cyan(`
|
|
400
401
|
\u{1F50D} Dry-run mode - showing what would be created:
|
|
401
402
|
`)),console.log(s.white("\u{1F4C2} Path:"),c$1),console.log(s.white("\u{1F4E6} Type:"),a$2?`Project (${e$3.template})`:"Workspace"),console.log();return}if(!e$3.yes&&!a$2?await b$1([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"Workspai User"}]):e$3.yes&&console.log(s.gray(`Using default values (--yes flag)
|
|
402
|
-
`)),a$2){let l=String(e$3.template||"").trim(),p=b$2(l);if(d$1(p)){let d=await
|
|
403
|
+
`)),a$2){let l=String(e$3.template||"").trim(),p=b$2(l);if(d$1(p)){let d=await Hs(["create","project",p,t,...e$3.skipGit?["--skip-git"]:[],...e$3.skipInstall?["--skip-install"]:[]]);d!==0&&process.exit(d);return}if(!!!Qs(process.cwd())){let{registerWorkspaceAtPath:d}=await import('./create-M3TWRHV6.js');if(e$3.createWorkspace)await d(process.cwd(),{skipGit:e$3.skipGit,yes:e$3.yes,userConfig:r});else if(!e$3.noWorkspace)if(e$3.yes)await d(process.cwd(),{skipGit:e$3.skipGit,yes:true,userConfig:r});else {let{createWs:g}=await b$1([{type:"confirm",name:"createWs",message:"This project will be created outside a Workspai workspace. Create and register a workspace here?",default:true}]);g&&await d(process.cwd(),{skipGit:e$3.skipGit,yes:false,userConfig:r});}}let u=["create","project",p,t,"--output",process.cwd()];e$3.yes&&u.push("--yes");let f$1=xe(process.cwd()),P=!!e$3.skipInstall,y=P||!!f$1;P&&u.push("--skip-essentials");let E=y?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,A=await f(u,{cwd:process.cwd(),env:E});A!==0&&process.exit(A),f$1&&!e$3.skipInstall&&(console.log(s.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(s.white(" Next: cd <project-name> && npx workspai init")));let S=Qs(process.cwd());if(S){let d=b.dirname(S),g=b.join(d,".python-version"),w=b.join(c$1,".python-version");try{if(await M__default.pathExists(g)){let k=$.readFileSync(g,"utf-8");$.writeFileSync(w,k.trim()+`
|
|
403
404
|
`),e.debug(`Synced Python version ${k.trim()} from workspace to project`);}}catch(k){e.debug("Could not sync Python version from workspace:",k);}}if(!e$3.skipInstall){let d=await e$2(["init",c$1],{cwd:process.cwd()});if(d!==0&&process.exit(d),S){let g=b.dirname(S),w=b.join(g,".python-version"),k=b.join(c$1,".python-version");try{if(await M__default.pathExists(w)){let h=$.readFileSync(w,"utf-8");$.writeFileSync(k,h.trim()+`
|
|
404
|
-
`),e.debug(`Re-synced Python version ${h.trim()} after init`);}}catch(h){e.debug("Could not re-sync Python version after init:",h);}}}}else {let{createProject:l}=await import('./create-
|
|
405
|
+
`),e.debug(`Re-synced Python version ${h.trim()} after init`);}}catch(h){e.debug("Could not re-sync Python version after init:",h);}}}}else {let{createProject:l}=await import('./create-M3TWRHV6.js');await l(t,{skipGit:e$3.skipGit,skipPythonEngine:e$3.skipPythonEngine,dryRun:e$3.dryRun,yes:e$3.yes,userConfig:n$1,installMethod:e$3.installMethod,profile:e$3.profile,parentDirectory:b.dirname(c$1)});}}catch(r){r instanceof a$1?(e.error(`
|
|
405
406
|
\u274C ${r.message}`),r.details&&e.warn(`\u{1F4A1} ${r.details}`),e.debug("Error code:",r.code)):(e.error(`
|
|
406
|
-
\u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Jt=null;}});dp(he);ed(he);wp(he);Xp(he);he.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{wh({json:t.json});});he.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-TJM66CPF.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);}});Hl(he);he.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function r(l){let p=l;for(;;){let m=u$1(p,"context.json").find(f=>$.existsSync(f));if(m)return m;let u=b.dirname(p);if(u===p)break;p=u;}return null}let o=r(e);function n(l){let p=l;for(;;){let m=b.join(p,".venv"),u=[b.join(p,".workspai","activate"),b.join(p,".rapidkit","activate")].find(P=>$.existsSync(P))??b.join(p,".workspai","activate");if($.existsSync(u)||$.existsSync(m))return {venv:m,activateFile:u};let f=b.dirname(p);if(f===p)break;p=f;}return null}let a=n(e);!o&&!a&&(console.log(s.yellow(bd(e))),process.exit(1));let i;a&&$.existsSync(a.activateFile)?i=a.activateFile:a&&$.existsSync(a.venv)?i=u(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$3();console.log(c?`call "${i}"`:`. "${i}"`);});he.command(v.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$4({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});he.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-LW3SW2WT.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});});he.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=Js({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-C7Q4OTPY.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);});he.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 Qs(t,e);r!==0&&process.exit(r);});he.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (valid workspace, or an existing empty directory to bootstrap)").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 Wu(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);});he.command("goal [intent]").description("Compile a plain-language engineering intent into a governed, evidence-bound Goal Pack").option("--workspace <path>","Explicit canonical workspace path").option("--scope <scope>","Bound the Goal to workspace, project:<name>, or projects:<name>,<name>").addOption(new Option("--runtime <runtime>","Bind a coverage Goal to a canonical runtime in its scope").choices(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"])).addOption(new Option("--for-agent <consumer>","Portable handoff consumer").choices(["generic","claude","codex"]).default("generic")).option("--max-attempts <count>","Maximum bounded proposal attempts","5").option("--refresh","Refresh the canonical Workspace Intelligence chain before planning").option("--dry-run","Validate and preview the Goal Pack without writing artifacts").option("--status [goal-id]","Inspect the active or named Goal Pack and validate its bindings").option("--list","List registered Goal Packs in the resolved workspace").option("--activate <goal-id>","Make a registered Goal Pack the active agent objective").option("--cancel <goal-id>","Cancel a registered Goal Pack without deleting evidence").option("--prepare <goal-id>","Create and link the deterministic CLI verification contract").option("--verify <goal-id>","Run CLI-owned verification for a prepared Goal Pack").option("--no-run","Read verification evidence without executing producer commands").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let{validateGoalCommandSelection:r}=await import('./goal-command-contract-43E22XQD.js'),o=r({intent:t,...e});if(o.operation!=="plan"){let u=b$5({startPath:process.cwd(),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!u)throw new Error("No canonical Workspai workspace could be resolved.");let{buildGoalLifecycleResult:f,inspectGoalLifecycle:P,prepareGoalVerification:y,transitionGoalLifecycle:E,verifyGoalLifecycle:A}=await import('./goal-lifecycle-5R55CA7H.js'),S=e.prepare?await y({workspacePath:u.workspacePath,goalId:e.prepare}):null,d=e.verify?await A({workspacePath:u.workspacePath,goalId:e.verify,run:e.run!==false}):null,g=e.activate?await E({workspacePath:u.workspacePath,goalId:e.activate,action:"activate"}):e.cancel?await E({workspacePath:u.workspacePath,goalId:e.cancel,action:"cancel"}):null,w=await P({workspacePath:u.workspacePath,goalId:typeof e.status=="string"?e.status:g?.goal.id??S?.goal.id??d?.goal.id,validateBindings:!(e.list||e.cancel)}),k=f({operation:o.operation,activeGoalId:w.index.activeGoalId,goal:w.active,goals:w.index.goals,goalPack:w.goalPack,verifiedGoalId:d?.verifiedGoalId??S?.verifiedGoalId??null,verification:d?.verification??null});if(e.json)console.log(JSON.stringify(k,null,2));else if(e.list){console.log(s.bold(`Goals \xB7 ${w.index.goals.length}`));for(let h of w.index.goals)console.log(`${h.id===w.index.activeGoalId?s.green("\u25CF"):s.gray("\u25CB")} ${h.objective} \xB7 ${h.lifecycle} \xB7 ${h.state}`);}else w.active?(console.log(s.bold(w.active.objective)),console.log(s.gray(` Goal: ${w.active.id}`)),console.log(s.gray(` Lifecycle: ${w.active.lifecycle}`)),console.log(s.gray(` Planning state: ${w.active.state}`))):console.log(s.yellow("No active Goal Pack is registered."));return}let n=Number(e.maxAttempts??5),{planGoalPack:a}=await import('./goal-pack-IS6GGJPH.js'),c=e.json!==true&&process.stdin.isTTY===true&&process.stdout.isTTY===true?await import('./goal-interactive-selection-6YJOK4WC.js'):null,l=await a({startPath:process.cwd(),intent:o.intent,workspacePath:e.workspace,scope:e.scope,runtime:e.runtime,consumer:e.forAgent,maxAttempts:n,refresh:e.refresh===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),...c?{selectScope:c.selectGoalScopeInteractively,selectCoverageRuntime:c.selectGoalCoverageRuntimeInteractively}:{}});if(e.json){console.log(JSON.stringify(l,null,2));return}let p=l.goalPack,m=p.state==="ready-to-plan"?s.green("\u2714 Governed Goal Pack ready to plan"):p.state==="blocked"?s.red("\u25A0 Goal Pack blocked by missing bounded evidence"):p.state==="needs-evidence"?s.yellow("\u25C6 Goal Pack needs measurement evidence"):s.yellow("\u25C6 Goal Pack needs clarification");console.log(m),console.log(s.bold(` ${p.intent.statement}`)),console.log(s.gray(` Goal: ${p.id}`)),console.log(s.gray(` Scope: ${p.scope.kind} \xB7 ${p.scope.projects.length} project(s) \xB7 ${p.baseline.runtimes.length} runtime(s)`)),console.log(s.gray(` Evidence: ${p.baseline.graph.entities} entities \xB7 ${p.baseline.graph.relationships} relationships \xB7 ${p.baseline.graph.proofCoveragePercent}% relation proof coverage`)),console.log(s.gray(" Mutation: proposal only \xB7 explicit approval \xB7 CLI-owned verify/rollback")),p.decision&&console.log(s.yellow(` Decision: ${p.decision.question}`)),l.dryRun?console.log(s.cyan(" Preview only; no artifacts were written.")):(console.log(s.gray(` Goal Pack: ${p.artifacts.goalPack}`)),console.log(s.gray(` Agent handoff: ${p.artifacts.agentHandoff}`))),console.log(s.gray(` Next: ${p.commands.planVerifiedGoal??p.commands.inspectGraph}`));}catch(r){let o=r instanceof Error?r.message:String(r),n=e.verify?"verify":e.prepare?"prepare":e.activate?"activate":e.cancel?"cancel":e.list?"list":e.status!==void 0?"status":null;e.json?console.log(JSON.stringify(c$1({operation:n?`goal.${n}`:"goal.plan",code:n?`goal.${n}.failed`:"goal.plan.failed",message:o,context:{scope:e.scope??null,runtime:e.runtime??null,refresh:e.refresh===true,goalId:e.prepare??e.verify??e.activate??e.cancel??(typeof e.status=="string"?e.status:null)}}),null,2)):console.log(s.red(`\u274C Goal ${n?`${n} operation`:"planning"} failed: ${o}`)),process.exit(1);}});var ta=he.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");ta.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 hn({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot create",code:"snapshot.create.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});ta.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 Sp({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){t.json&&(console.log(JSON.stringify(c$1({operation:"snapshot list",code:"snapshot.list.failed",message:e.message,context:{workspacePath:t.workspace??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});ta.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 Ep({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot inspect",code:"snapshot.inspect.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});ta.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 Rp({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot restore",code:"snapshot.restore.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});function Gh(t){return (t instanceof Error?t.message:String(t)).replace(/file:\/\/\/[^\s"']+/g,"<local-path>").replace(/\\\\[^\\\s"']+[\\][^\s"']+/g,"<local-path>").replace(/[A-Za-z]:[\\/][^\s"']+/g,"<local-path>").replace(/\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\/[^\s"']+/g,"<local-path>")}async function Du(t){try{let{buildAgentBootstrapReceipt:e}=await import('./project-agent-entry-5TYKK5IV.js'),r=await e({startPath:t.project,forAgent:t.forAgent,validateLiveInputs:t.liveInputs!==false});if(t.json)console.log(JSON.stringify(r,null,2));else {let o=r.status==="ready"?s.green:r.status==="degraded"?s.yellow:s.red;console.log(o(`Agent entry: ${r.status}`)),console.log(s.gray(` Project: ${r.project.name}`)),console.log(s.gray(` Workspace: ${r.workspace.name}`)),console.log(s.gray(` Consumer: ${r.resolvedHost}`)),console.log(s.gray(` Receipt: ${r.receiptId.slice(0,16)}`));for(let n of r.checks.filter(a=>a.status!=="passed"))console.log((n.status==="failed"?s.red:s.yellow)(` ${n.id}: ${n.message}`));console.log(s.gray(` Next: ${r.nextActions[0]}`));}(r.status==="blocked"||t.strict&&r.status!=="ready")&&process.exit(2);}catch(e){let r=Gh(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"agent.entry.bootstrap.failed",message:r}),null,2)):console.log(s.red(`Agent entry failed: ${r}`)),process.exit(1);}}var Lu=he.command("agent").description("Bootstrap coding agents from canonical Workspai project evidence");Lu.command("bootstrap").description("Issue a portable canonical-first grounding receipt for the current project").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier","generic").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless the complete entry receipt is ready").option("--json","Emit the versioned machine-readable receipt").action(async t=>Du({...t,operation:"agent bootstrap"}));wd(Lu);var Kt=he.command("project").description("Safe workspace project lifecycle operations");Kt.command("agent-entry [action]").description("Verify canonical-first project entry coverage for supported agent hosts").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier or all","all").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless all selected entry checks are ready").option("--json","Emit the versioned machine-readable receipt").action(async(t,e)=>{let r=t??"verify";if(r!=="verify"){let o=`Unknown project agent-entry action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project agent-entry",code:"project.agent-entry.action.invalid",message:o}),null,2)):(console.log(s.red(o)),console.log(s.gray(" workspai project agent-entry verify [--for-agent <agent|all>] [--strict] [--json]"))),process.exit(1);}await Du({...e,operation:"project agent-entry verify"});});Kt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{Iu({json:t.json});});Kt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$5({startPath: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$1),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json",pathPolicy:{classification:"machine-local",portable:false,persistence:"forbidden",disclosure:"forbidden",purpose:"runtime-workspace-resolution"}};if(Wd(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);}});Kt.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-T4TIWGKN.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 l of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${l.path}: ${l.percent===null?"unknown":`${l.percent}%`} (${l.uncovered} uncovered)`));}for(let l of o.diagnostics)console.log(s.gray(` ${l}`));}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);}});Kt.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 qa({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);}});Kt.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 za({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);}});Kt.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 $p({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);}});Kt.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 Np({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);}});he.command(v.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json [mode]","Output JSON: full (default) or summary").option("--fresh","Bypass Doctor project scan cache and refresh live evidence").option("--verbose","Show every probe, lifecycle capability, and detailed project signal").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate an action or lifecycle plan without applying or executing changes").option("--apply","Apply remediation plan non-interactively").option("--runtime <runtime>","Filter Doctor capability truth by runtime family").option("--framework <framework>","Filter Doctor capability truth by framework").option("--validate","Run the versioned Doctor disease validation corpus").option("--write","Write Doctor capability/validation artifacts inside the workspace").action(async(t,e)=>{if(t&&t!=="workspace"&&t!=="project"&&t!=="capabilities"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project, capabilities")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project | npx workspai doctor capabilities")),process.exit(1)),typeof e.json=="string"&&!["full","summary"].includes(e.json)&&(console.log(s.red(`Invalid Doctor JSON mode: ${e.json}. Use full or summary.`)),process.exit(1)),t==="capabilities"){(e.fix||e.plan||e.apply||e.project)&&(console.log(s.red("Doctor capability inspection cannot be combined with repair or project-scope flags.")),process.exit(1));let{runDoctorCapabilities:i}=await import('./capabilities-command-TIBIKWPK.js'),c=await i({runtime:e.runtime,framework:e.framework,validate:e.validate===true,write:e.write===true,workspace:typeof e.workspace=="string"?e.workspace:void 0,json:!!e.json});c!==0&&process.exit(c);return}(e.runtime||e.framework||e.validate||e.write)&&(console.log(s.red('Doctor capability flags require the "doctor capabilities" scope.')),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await yh({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-W5PXJ5FL.js'),a=await n({...e,json:e.json==="summary"?"summary":!!e.json,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});he.command(v.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
|
|
407
|
+
\u274C An unexpected error occurred:`),console.error(r)),process.exit(1);}finally{Jt=null;}});dp(he);ed(he);wp(he);Xp(he);he.command("commands").description("Show effective Workspai command ownership and runtime support").option("--json","Emit machine-readable JSON output").action(async t=>{wh({json:t.json});});he.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-SKOIUD6F.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);}});Hl(he);he.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async t=>{t!=="activate"&&(console.log(s.red(`Unknown shell command: ${t}`)),process.exit(1));let e=process.cwd();function r(l){let p=l;for(;;){let m=u$1(p,"context.json").find(f=>$.existsSync(f));if(m)return m;let u=b.dirname(p);if(u===p)break;p=u;}return null}let o=r(e);function n(l){let p=l;for(;;){let m=b.join(p,".venv"),u=[b.join(p,".workspai","activate"),b.join(p,".rapidkit","activate")].find(P=>$.existsSync(P))??b.join(p,".workspai","activate");if($.existsSync(u)||$.existsSync(m))return {venv:m,activateFile:u};let f=b.dirname(p);if(f===p)break;p=f;}return null}let a=n(e);!o&&!a&&(console.log(s.yellow(bd(e))),process.exit(1));let i;a&&$.existsSync(a.activateFile)?i=a.activateFile:a&&$.existsSync(a.venv)?i=u(a.venv):(console.log(s.yellow("No virtual environment found")),process.exit(1));let c=b$3();console.log(c?`call "${i}"`:`. "${i}"`);});he.command(v.readiness).description("\u{1F6A6} Generate machine-readable release readiness summary (env + doctor + analyze + verify + dependency)").option("--workspace <path>","Workspace root to evaluate instead of the current directory").option("--json","Output readiness result in JSON format").option("--strict","Exit with code 1 unless overall readiness is pass").option("--skip-verify","Skip verify gate (use for workspaces without extension verify artifacts)").action(async t=>{await b$4({workspace:t.workspace,json:t.json,strict:t.strict,skipVerify:t.skipVerify});});he.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-V5P2FX2P.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});});he.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=Us({raw:e.maxWorkers,operation:"autopilot release",json:e.json===true}),{runAutopilotRelease:n}=await import('./autopilot-release-MDMVMU67.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);});he.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 ei(t,e);r!==0&&process.exit(r);});he.command("adopt [source]").description("Adopt an existing local project into a Workspai workspace without moving or copying source").option("--workspace <path>","Workspace root path (valid workspace, or an existing empty directory to bootstrap)").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 Wu(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);});he.command("goal [intent]").description("Compile a plain-language engineering intent into a governed, evidence-bound Goal Pack").option("--workspace <path>","Explicit canonical workspace path").option("--scope <scope>","Bound the Goal to workspace, project:<name>, or projects:<name>,<name>").addOption(new Option("--runtime <runtime>","Bind a coverage Goal to a canonical runtime in its scope").choices(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"])).addOption(new Option("--for-agent <consumer>","Portable handoff consumer").choices(["generic","claude","codex"]).default("generic")).option("--max-attempts <count>","Maximum bounded proposal attempts","5").option("--refresh","Refresh the canonical Workspace Intelligence chain before planning").option("--dry-run","Validate and preview the Goal Pack without writing artifacts").option("--status [goal-id]","Inspect the active or named Goal Pack and validate its bindings").option("--list","List registered Goal Packs in the resolved workspace").option("--activate <goal-id>","Make a registered Goal Pack the active agent objective").option("--cancel <goal-id>","Cancel a registered Goal Pack without deleting evidence").option("--prepare <goal-id>","Create and link the deterministic CLI verification contract").option("--verify <goal-id>","Run CLI-owned verification for a prepared Goal Pack").option("--no-run","Read verification evidence without executing producer commands").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{try{let{validateGoalCommandSelection:r}=await import('./goal-command-contract-43E22XQD.js'),o=r({intent:t,...e});if(o.operation!=="plan"){let u=b$5({startPath:process.cwd(),explicitWorkspacePath:e.workspace,strict:true,requireProjectMembership:true});if(!u)throw new Error("No canonical Workspai workspace could be resolved.");let{buildGoalLifecycleResult:f,inspectGoalLifecycle:P,prepareGoalVerification:y,transitionGoalLifecycle:E,verifyGoalLifecycle:A}=await import('./goal-lifecycle-O4MYYTRU.js'),S=e.prepare?await y({workspacePath:u.workspacePath,goalId:e.prepare}):null,d=e.verify?await A({workspacePath:u.workspacePath,goalId:e.verify,run:e.run!==false}):null,g=e.activate?await E({workspacePath:u.workspacePath,goalId:e.activate,action:"activate"}):e.cancel?await E({workspacePath:u.workspacePath,goalId:e.cancel,action:"cancel"}):null,w=await P({workspacePath:u.workspacePath,goalId:typeof e.status=="string"?e.status:g?.goal.id??S?.goal.id??d?.goal.id,validateBindings:!(e.list||e.cancel)}),k=f({operation:o.operation,activeGoalId:w.index.activeGoalId,goal:w.active,goals:w.index.goals,goalPack:w.goalPack,verifiedGoalId:d?.verifiedGoalId??S?.verifiedGoalId??null,verification:d?.verification??null});if(e.json)console.log(JSON.stringify(k,null,2));else if(e.list){console.log(s.bold(`Goals \xB7 ${w.index.goals.length}`));for(let h of w.index.goals)console.log(`${h.id===w.index.activeGoalId?s.green("\u25CF"):s.gray("\u25CB")} ${h.objective} \xB7 ${h.lifecycle} \xB7 ${h.state}`);}else w.active?(console.log(s.bold(w.active.objective)),console.log(s.gray(` Goal: ${w.active.id}`)),console.log(s.gray(` Lifecycle: ${w.active.lifecycle}`)),console.log(s.gray(` Planning state: ${w.active.state}`))):console.log(s.yellow("No active Goal Pack is registered."));return}let n=Number(e.maxAttempts??5),{planGoalPack:a}=await import('./goal-pack-NUDKANPM.js'),c=e.json!==true&&process.stdin.isTTY===true&&process.stdout.isTTY===true?await import('./goal-interactive-selection-6YJOK4WC.js'):null,l=await a({startPath:process.cwd(),intent:o.intent,workspacePath:e.workspace,scope:e.scope,runtime:e.runtime,consumer:e.forAgent,maxAttempts:n,refresh:e.refresh===true,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),...c?{selectScope:c.selectGoalScopeInteractively,selectCoverageRuntime:c.selectGoalCoverageRuntimeInteractively}:{}});if(e.json){console.log(JSON.stringify(l,null,2));return}let p=l.goalPack,m=p.state==="ready-to-plan"?s.green("\u2714 Governed Goal Pack ready to plan"):p.state==="blocked"?s.red("\u25A0 Goal Pack blocked by missing bounded evidence"):p.state==="needs-evidence"?s.yellow("\u25C6 Goal Pack needs measurement evidence"):s.yellow("\u25C6 Goal Pack needs clarification");console.log(m),console.log(s.bold(` ${p.intent.statement}`)),console.log(s.gray(` Goal: ${p.id}`)),console.log(s.gray(` Scope: ${p.scope.kind} \xB7 ${p.scope.projects.length} project(s) \xB7 ${p.baseline.runtimes.length} runtime(s)`)),console.log(s.gray(` Evidence: ${p.baseline.graph.entities} entities \xB7 ${p.baseline.graph.relationships} relationships \xB7 ${p.baseline.graph.proofCoveragePercent}% relation proof coverage`)),console.log(s.gray(" Mutation: proposal only \xB7 explicit approval \xB7 CLI-owned verify/rollback")),p.decision&&console.log(s.yellow(` Decision: ${p.decision.question}`)),l.dryRun?console.log(s.cyan(" Preview only; no artifacts were written.")):(console.log(s.gray(` Goal Pack: ${p.artifacts.goalPack}`)),console.log(s.gray(` Agent handoff: ${p.artifacts.agentHandoff}`))),console.log(s.gray(` Next: ${p.commands.planVerifiedGoal??p.commands.inspectGraph}`));}catch(r){let o=r instanceof Error?r.message:String(r),n=e.verify?"verify":e.prepare?"prepare":e.activate?"activate":e.cancel?"cancel":e.list?"list":e.status!==void 0?"status":null;e.json?console.log(JSON.stringify(c$1({operation:n?`goal.${n}`:"goal.plan",code:n?`goal.${n}.failed`:"goal.plan.failed",message:o,context:{scope:e.scope??null,runtime:e.runtime??null,refresh:e.refresh===true,goalId:e.prepare??e.verify??e.activate??e.cancel??(typeof e.status=="string"?e.status:null)}}),null,2)):console.log(s.red(`\u274C Goal ${n?`${n} operation`:"planning"} failed: ${o}`)),process.exit(1);}});var ra=he.command("snapshot").description("Create, list, and restore Workspai workspace snapshots");ra.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 wn({workspacePath:e.workspace,name:t,reason:e.reason,includeProjects:e.includeProjects===true});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.green(`\u2714 Workspace snapshot created: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot create",code:"snapshot.create.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot create failed: ${r.message}`)),process.exit(1);}});ra.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 Sp({workspacePath:t.workspace});if(t.json){console.log(JSON.stringify({snapshots:e},null,2));return}if(e.length===0){console.log(s.yellow("No workspace snapshots found."));return}for(let r of e)console.log(s.cyan(r.name)),console.log(s.gray(` ${r.createdAt} | ${r.mode} | ${r.projects.length} project(s)`)),console.log(s.gray(` ${r.snapshotPath}`));}catch(e){t.json&&(console.log(JSON.stringify(c$1({operation:"snapshot list",code:"snapshot.list.failed",message:e.message,context:{workspacePath:t.workspace??null}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot list failed: ${e.message}`)),process.exit(1);}});ra.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 Ep({workspacePath:e.workspace,name:t});if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(s.cyan(`Snapshot: ${r.manifest.name}`)),console.log(s.gray(` Mode: ${r.manifest.mode}`)),console.log(s.gray(` Created: ${r.manifest.createdAt}`)),console.log(s.gray(` Projects: ${r.manifest.projects.length}`)),console.log(s.gray(` Files: ${r.estimatedFileCount}`)),console.log(s.gray(` Bytes: ${r.estimatedBytes}`)),console.log(s.gray(` Path: ${r.snapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot inspect",code:"snapshot.inspect.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot inspect failed: ${r.message}`)),process.exit(1);}});ra.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 Rp({workspacePath:e.workspace,name:t,reason:e.reason,dryRun:e.dryRun===true||process.argv.includes("--dry-run"),force:e.force===true,safetySnapshot:e.safetySnapshot});if(e.json){console.log(JSON.stringify(r,null,2));return}r.dryRun?console.log(s.cyan(`Snapshot restore dry-run: ${t}`)):console.log(s.green(`\u2714 Workspace snapshot restored: ${t}`)),console.log(s.gray(` Snapshot: ${r.snapshotPath}`)),console.log(s.gray(` Restored paths: ${r.restoredPaths.join(", ")}`)),r.safetySnapshotPath&&console.log(s.gray(` Safety snapshot: ${r.safetySnapshotPath}`));}catch(r){e.json&&(console.log(JSON.stringify(c$1({operation:"snapshot restore",code:"snapshot.restore.failed",message:r.message,context:{workspacePath:e.workspace??null,name:t}}),null,2)),process.exit(1)),console.log(s.red(`\u274C Snapshot restore failed: ${r.message}`)),process.exit(1);}});function Gh(t){return (t instanceof Error?t.message:String(t)).replace(/file:\/\/\/[^\s"']+/g,"<local-path>").replace(/\\\\[^\\\s"']+[\\][^\s"']+/g,"<local-path>").replace(/[A-Za-z]:[\\/][^\s"']+/g,"<local-path>").replace(/\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\/[^\s"']+/g,"<local-path>")}async function Du(t){try{let{buildAgentBootstrapReceipt:e}=await import('./project-agent-entry-6O7FKWSL.js'),r=await e({startPath:t.project,forAgent:t.forAgent,validateLiveInputs:t.liveInputs!==false});if(t.json)console.log(JSON.stringify(r,null,2));else {let o=r.status==="ready"?s.green:r.status==="degraded"?s.yellow:s.red;console.log(o(`Agent entry: ${r.status}`)),console.log(s.gray(` Project: ${r.project.name}`)),console.log(s.gray(` Workspace: ${r.workspace.name}`)),console.log(s.gray(` Consumer: ${r.resolvedHost}`)),console.log(s.gray(` Receipt: ${r.receiptId.slice(0,16)}`));for(let n of r.checks.filter(a=>a.status!=="passed"))console.log((n.status==="failed"?s.red:s.yellow)(` ${n.id}: ${n.message}`));console.log(s.gray(` Next: ${r.nextActions[0]}`));}(r.status==="blocked"||t.strict&&r.status!=="ready")&&process.exit(2);}catch(e){let r=Gh(e);t.json?console.log(JSON.stringify(c$1({operation:t.operation,code:"agent.entry.bootstrap.failed",message:r}),null,2)):console.log(s.red(`Agent entry failed: ${r}`)),process.exit(1);}}var Lu=he.command("agent").description("Bootstrap coding agents from canonical Workspai project evidence");Lu.command("bootstrap").description("Issue a portable canonical-first grounding receipt for the current project").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier","generic").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless the complete entry receipt is ready").option("--json","Emit the versioned machine-readable receipt").action(async t=>Du({...t,operation:"agent bootstrap"}));wd(Lu);var Kt=he.command("project").description("Safe workspace project lifecycle operations");Kt.command("agent-entry [action]").description("Verify canonical-first project entry coverage for supported agent hosts").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--for-agent <agent>","Agent host identifier or all","all").option("--no-live-inputs","Skip live project input validation and return degraded evidence").option("--strict","Return exit 2 unless all selected entry checks are ready").option("--json","Emit the versioned machine-readable receipt").action(async(t,e)=>{let r=t??"verify";if(r!=="verify"){let o=`Unknown project agent-entry action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project agent-entry",code:"project.agent-entry.action.invalid",message:o}),null,2)):(console.log(s.red(o)),console.log(s.gray(" workspai project agent-entry verify [--for-agent <agent|all>] [--strict] [--json]"))),process.exit(1);}await Du({...e,operation:"project agent-entry verify"});});Kt.command("commands").description("Show effective commands supported by the current Workspai project").option("--json","Emit machine-readable JSON output").action(async t=>{Iu({json:t.json});});Kt.command("workspace [action]").description("Show or repair the canonical workspace binding for the current Workspai project").option("--workspace <path>","Explicit workspace for relink or validation").option("--project <path>","Project path (defaults to the current or nearest parent project)").option("--json","Emit machine-readable JSON output").action(async(t,e)=>{let r=t??"status";if(!["status","relink"].includes(r)){let o=`Unknown project workspace action: ${r}`;e.json?console.log(JSON.stringify(c$1({operation:"project workspace",code:"project.workspace.action.invalid",message:o}),null,2)):(console.log(s.red(`\u274C ${o}`)),console.log(s.gray(" npx workspai project workspace [status|relink] [--workspace <path>] [--json]"))),process.exit(1);}try{let o=b$5({startPath: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$1),nextCommand:"npx workspai workspace intelligence run --for-agent generic --strict --json",pathPolicy:{classification:"machine-local",portable:false,persistence:"forbidden",disclosure:"forbidden",purpose:"runtime-workspace-resolution"}};if(Wd(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);}});Kt.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-EJ3MBSZ3.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 l of o.lowCoverageFiles.slice(0,10))console.log(s.gray(` \u2022 ${l.path}: ${l.percent===null?"unknown":`${l.percent}%`} (${l.uncovered} uncovered)`));}for(let l of o.diagnostics)console.log(s.gray(` ${l}`));}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);}});Kt.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 Ya({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);}});Kt.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 Xa({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);}});Kt.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 $p({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);}});Kt.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 Np({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);}});he.command(v.doctor).description("\u{1FA7A} Check Workspai system health by default; use workspace or project for scoped checks").option("--workspace [path]","Check entire workspace, optionally from an explicit workspace path").option("--project","Check only the current project (or nearest parent project)").option("--json [mode]","Output JSON: full (default) or summary").option("--fresh","Bypass Doctor project scan cache and refresh live evidence").option("--verbose","Show every probe, lifecycle capability, and detailed project signal").option("--strict","Exit 1 on health errors or warnings (workspace/project scope)").option("--ci","CI gate: exit 1 on errors, exit 2 on warnings only").option("--profile <profile>","Doctor policy profile: local | ci | release | enterprise-strict").option("--fix","Automatically fix common issues (with confirmation)").option("--plan","Generate an action or lifecycle plan without applying or executing changes").option("--apply","Apply remediation plan non-interactively").option("--runtime <runtime>","Filter Doctor capability truth by runtime family").option("--framework <framework>","Filter Doctor capability truth by framework").option("--validate","Run the versioned Doctor disease validation corpus").option("--write","Write Doctor capability/validation artifacts inside the workspace").action(async(t,e)=>{if(t&&t!=="workspace"&&t!=="project"&&t!=="capabilities"&&(console.log(s.red(`Unknown doctor scope: ${t}`)),console.log(s.gray("Available: workspace, project, capabilities")),console.log(s.gray("Usage: npx workspai doctor | npx workspai doctor workspace | npx workspai doctor project | npx workspai doctor capabilities")),process.exit(1)),typeof e.json=="string"&&!["full","summary"].includes(e.json)&&(console.log(s.red(`Invalid Doctor JSON mode: ${e.json}. Use full or summary.`)),process.exit(1)),t==="capabilities"){(e.fix||e.plan||e.apply||e.project)&&(console.log(s.red("Doctor capability inspection cannot be combined with repair or project-scope flags.")),process.exit(1));let{runDoctorCapabilities:i}=await import('./capabilities-command-TIBIKWPK.js'),c=await i({runtime:e.runtime,framework:e.framework,validate:e.validate===true,write:e.write===true,workspace:typeof e.workspace=="string"?e.workspace:void 0,json:!!e.json});c!==0&&process.exit(c);return}(e.runtime||e.framework||e.validate||e.write)&&(console.log(s.red('Doctor capability flags require the "doctor capabilities" scope.')),process.exit(1)),e.plan&&(e.fix||e.apply)&&(console.log(s.red("Invalid doctor flags: --plan cannot be combined with --fix or --apply")),process.exit(1));let r=new Set(["local","ci","release","enterprise-strict"]);e.profile&&!r.has(e.profile)&&(console.log(s.red(`Invalid doctor profile: ${e.profile}. Use local, ci, release, or enterprise-strict.`)),process.exit(1));let o=await yh({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-FF3WLJSP.js'),a=await n({...e,json:e.json==="summary"?"summary":!!e.json,workspace:e.workspace||t==="workspace",project:e.project||t==="project",strict:e.strict===true,ci:e.ci===true,profile:e.profile});a!==0&&process.exit(a);});he.command(v.workspace).description(`Manage Workspai workspaces (list, sync, policy, share, export, run, intelligence)
|
|
407
408
|
workspace run <stage> \u2014 fleet stage execution across discovered projects
|
|
408
409
|
stages: init | test | build | start | <custom-from-context>
|
|
409
410
|
workspace explain|why \u2014 blocker/project narrative (--write for artifact)
|
|
@@ -419,20 +420,20 @@ Workspace Actions:
|
|
|
419
420
|
Fleet lifecycle run | init
|
|
420
421
|
|
|
421
422
|
Use "workspai commands --json" for the contract-backed runtime inventory.
|
|
422
|
-
See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=d=>{let g=n.workspace?b.resolve(n.workspace):null,w=null,k=null;try{w=b$5({startPath:process.cwd(),explicitWorkspacePath:g,strict:true})?.workspacePath??null;}catch(I){if(I instanceof a$2)k=I;else throw I}if(!w||!et(w)){let I=k?.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 ${d}`,code:k?.code??"workspace.root.required",message:I,context:{cwd:b.resolve(process.cwd()),...g?{requestedWorkspace:g}:{},...k?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${I}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let h=b.resolve(process.cwd()),v=b.resolve(w);return h!==v&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${w} for "${d}" (current directory: ${h}).`)),w},i=d=>process.argv.includes(d),c=d=>Re(process.argv,d),l=()=>n.output||c("--output"),p$1=()=>{if(!n.scanDepth)return;let d=Number.parseInt(n.scanDepth,10);return Number.isFinite(d)?d:void 0},m=(d,g,w)=>{if(d===void 0)return;let k=Number.parseInt(d,10);if(!Number.isFinite(k)||k<1||k>w)throw new Error(`${g} must be an integer between 1 and ${w}.`);return k},u=()=>({...n.graphInventoryLimit!==void 0?{inventoryFileLimitPerProject:m(n.graphInventoryLimit,"--graph-inventory-limit",2e6)}:{},...n.graphSemanticBudget!==void 0?{semanticFilesPerProject:m(n.graphSemanticBudget,"--graph-semantic-budget",25e4)}:{},...n.graphDeepBudget!==void 0?{maxFilesPerProject:m(n.graphDeepBudget,"--graph-deep-budget",1e5)}:{},...n.graphSourceBudget!==void 0?{sourceFilesPerProject:m(n.graphSourceBudget,"--graph-source-budget",5e4)}:{}}),f=(d,g)=>{if(!d)return;let w=d.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!w)throw new Error(`${g} must be a byte size such as 500gb or 2tb.`);let k={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},h=Number(w[1])*k[w[2]||"b"];if(!Number.isSafeInteger(Math.floor(h))||h<=0)throw new Error(`${g} is outside the supported numeric range.`);return Math.floor(h)},P=()=>{let d=n.downloadTimeoutMs,g=d===void 0?void 0:Number.parseInt(d,10);if(g!==void 0&&(!Number.isFinite(g)||g<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:f(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:f(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:g,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},y=new Set(Object.values(ko).flatMap(d=>[...d.flags])),E=new Set(process.argv.slice(2).filter(d=>d.startsWith("--")).map(d=>d.split("=",1)[0]).filter(d=>y.has(d))),A=ko[t]?.flags,S=A?[...E].filter(d=>!A.includes(d)):[];if(S.length>0){let d=`${S.join(", ")} ${S.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||E.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:d,exitCode:2,context:{action:t,unsupportedFlags:S,allowedFlags:A}}),null,2)):(console.log(s.red(`\u274C ${d}`)),console.log(s.gray(` Allowed flags: ${A.join(", ")||"none"}`))),process.exit(2);}if((Ed(t)||t==="trace"||t==="feedback"||t==="mcp")&&c$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:d}=await import('./workspace-A33YMF2N.js');await d({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 d=a("intelligence"),{runWorkspaceIntelligenceChain:g}=await import('./workspace-intelligence-runner-3K2JZH6Q.js'),w=await g({workspacePath:d,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(w,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${w.status}`));for(let k of w.stages)console.log(s.gray(` ${k.id}: ${k.status} \u2014 ${k.message}`));console.log(s.gray(` Evidence: ${w.artifactPath}`));}w.exitCode!==0&&process.exit(w.exitCode);}else if(t==="model"){let d=a("model"),{buildWorkspaceModelCached:g,buildWorkspaceModelIncremental:w,createWorkspaceModelBuildProvenance:k,writeWorkspaceModel:h}=await import('./workspace-model-POCPMNRT.js'),v=n.incremental===true||i("--incremental"),I=n.cache===true||i("--cache")||v,x={workspacePath:d,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1(),strict:n.strict===true||i("--strict")},j,R;if(v){let N=await w(x);j=N.model,R=N.mode;}else {let N=await g({...x,cache:I});j=N.model,R=N.cache;}j={...j,build:k({mode:v?"incremental":I?"cache":"full",engineStatus:R})};let C;(n.write===true||i("--write"))&&(C=await h(j,d));let _=(n.strict===true||i("--strict"))&&j.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...j,...C?{outputPath:C}:{}},null,2)),_&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${j.workspace.name}`)),v?console.log(s.gray(` Build: ${R} (incremental)`)):I&&console.log(s.gray(` Cache: ${R}`)),console.log(s.gray(` Projects: ${j.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${j.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${j.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${j.identity.workspaceType}`)),console.log(s.gray(` Validation: ${j.validation?.status??"unknown"} (${j.validation?.errors??0} error, ${j.validation?.warnings??0} warning)`)),console.log(C?s.gray(` Written: ${C}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),_&&process.exit(1);}else if(t==="agent-sync"){let d=a("agent-sync"),{syncWorkspaceAgentGrounding:g,parseAgentGroundingTargets:w}=await import('./workspace-agent-sync-VCA4G4DT.js'),k=n.strict===true||i("--strict"),h=n.write===true||i("--write"),v=i("--dry-run"),I=await g({workspacePath:d,scope:n.scope,agent:n.forAgent,write:h&&!v,dryRun:v,strict:k,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:w(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(I,null,2));else {console.log(s.green(`\u2714 Agent grounding ${h&&!v?"synced":"planned"}`)),console.log(s.gray(` Index: ${I.indexPath}`)),I.contextPath&&console.log(s.gray(` Context: ${I.contextPath}`)),I.blockers.length>0&&console.log(s.yellow(` Blockers: ${I.blockers.slice(0,3).join(" \xB7 ")}`));let x=h&&!v?I.writtenFiles:I.skippedFiles;if(x.length>0&&console.log(s.gray(` Files: ${x.join(", ")}`)),I.strictViolations.length>0)for(let j of I.strictViolations)console.log(s.red(`\u274C ${j}`));}k&&I.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let d=e??"status",{approveWorkspaceRepair:g,cancelWorkspaceRepair:w,decideWorkspaceRepair:k,executeWorkspaceRepair:h,inspectWorkspaceRepairCapabilities:v,listWorkspaceRepairTransactions:I,planWorkspaceRepair:x,planWorkspaceRepairProposal:j,readWorkspaceRepairTransaction:R,rollbackWorkspaceRepair:C}=await import('./workspace-repair-engine-2VGN42QD.js');if(d==="capabilities"){let J,ae;if(n.workspace)J=a("repair capabilities");else try{let se=b$5({startPath:process.cwd(),strict:false});se&&et(se.workspacePath)&&(J=se.workspacePath,ae=se.projectPath??void 0);}catch{}let pe=await v(J?{workspacePath:J,project:n.project,projectPath:n.project?void 0:ae}:n.project?{project:n.project}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(pe,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${pe.adapters.length}`));for(let se of pe.adapters)console.log(s.gray(` ${se.id.padEnd(14)} ${se.support.padEnd(11)} ${se.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let _=a("repair"),N=n.transaction??(["plan","propose","capabilities"].includes(d)?void 0:r),V=()=>{if(!N?.trim())throw new Error(`workspace repair ${d} requires --transaction <id> (or the id as the next positional argument).`);return N.trim()},D;if(d==="plan"){let J=n.card??r;if(!J?.trim())throw new Error("workspace repair plan requires --card <id>.");D=await x({workspacePath:_,cardId:J.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(d==="propose"){let J=n.proposal??r;if(!J?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let ae=b.resolve(_,J.trim()),pe=b.relative(_,ae);if(pe.startsWith("..")||b.isAbsolute(pe))throw new Error("The repair proposal file must be inside the canonical workspace.");let se=await M__default.lstat(ae).catch(()=>{});if(!se?.isFile()||se.isSymbolicLink()||se.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");D=await j({workspacePath:_,proposal:await M__default.readJson(ae),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(d==="approve")D=await g({workspacePath:_,transactionId:V(),approvedBy:n.approvedBy});else if(d==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");D=await k({workspacePath:_,transactionId:V(),decision:n.decision});}else if(d==="execute"||d==="resume")D=await h({workspacePath:_,transactionId:V()});else if(d==="status")D=await R({workspacePath:_,transactionId:V()});else if(d==="list")D=await I(_);else if(d==="rollback")D=await C({workspacePath:_,transactionId:V()});else if(d==="cancel")D=await w({workspacePath:_,transactionId:V()});else throw new Error(`Unknown workspace repair action: ${d}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let q=b.join(_,p.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$6(`workspace repair ${d}`,D,q),null,2));else if(Array.isArray(D)){console.log(s.green(`\u2714 Workspace repair transactions: ${D.length}`));for(let J of D.slice(0,20))console.log(s.gray(` ${J.transactionId} \xB7 ${J.target.cardId} \xB7 ${J.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${D.state}`)),console.log(s.gray(` Transaction: ${D.transactionId}`)),console.log(s.gray(` Target: ${D.target.cardId}`));for(let J of D.stages)console.log(s.gray(` ${J.status.padEnd(8)} ${J.kind}: ${J.summary}`));D.decision&&console.log(s.yellow(` Decision: ${D.decision.reason}`)),console.log(s.gray(` Evidence: ${p.repairTransaction}`));}Array.isArray(D)||(D.state==="decision-required"&&process.exit(2),(D.state==="rolled-back"||D.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let d=a("remediation-plan"),{buildArtifactRemediationPlan:g,writeArtifactRemediationPlan:w}=await import('./artifact-remediation-plan-SRH2Q6N2.js'),k=await g({workspacePath:d,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),h;if((n.write===true||i("--write"))&&(h=await w(k,d)),n.json===true||i("--json")){console.log(JSON.stringify(b$6("workspace remediation-plan",k,h),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${k.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${k.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${k.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${k.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${k.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${k.summary.risk.safe}, guarded=${k.summary.risk.guarded}, invasive=${k.summary.risk.invasive}`));for(let v of k.actions.slice(0,8))console.log(s.gray(` \u2022 ${v.cardId}: ${v.title} (${v.mode}, ${v.risk})`));k.actions.length>8&&console.log(s.gray(` \u2026 ${k.actions.length-8} more action(s)`)),console.log(h?s.gray(` Written: ${h}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let d=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:g,writeWorkspaceAgentContext:w}=await import('./workspace-context-YBWLSKR6.js'),k=n.strict===true||i("--strict"),h=await g({workspacePath:d,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1(),strict:false}),v,I;if((n.write===true||i("--write"))&&(v=await w(h,d),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:R,parseAgentGroundingTargets:C}=await import('./workspace-agent-sync-VCA4G4DT.js');if(I=await R({workspacePath:d,scope:n.scope,agent:h.agent,write:true,refreshContext:false,strict:k,preset:n.preset==="minimal"?"minimal":"enterprise",targets:C(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${I.writtenFiles.length} file(s) updated`)),k&&I.strictViolations.length>0){for(let _ of I.strictViolations)console.log(s.red(`\u274C ${_}`));process.exit(1);}}let x=k&&h.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...h,...v?{outputPath:v}:{},...I?{agentGroundingSync:I}:{}},null,2)),x&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${h.workspace.name}`)),console.log(s.gray(` Agent: ${h.agent}`)),console.log(s.gray(` Scope: ${h.scope.activeProject??h.scope.requested}`)),console.log(s.gray(` Projects included: ${h.projects.length}`)),console.log(s.gray(` Safe commands: ${h.safeCommands.length}`)),console.log(s.gray(` Validation: ${h.validation.status} (${h.validation.errors} error, ${h.validation.warnings} warning)`)),console.log(v?s.gray(` Written: ${v}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),x){for(let j of h.validation.issues)console.log(s.red(`\u274C ${j.severity}:${j.code}:${j.target}`));process.exit(1);}}else if(t==="snapshot"){let d=a("snapshot"),{buildWorkspaceModelSnapshot:g,writeWorkspaceModelSnapshot:w}=await import('./workspace-intelligence-FKYQQDJ6.js'),k=await g({workspacePath:d,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()}),h=await w(k,d);if(n.json){console.log(JSON.stringify(b$6("workspace snapshot",k,h),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${k.model.workspace.name}`)),console.log(s.gray(` Hash: ${k.modelHash}`)),console.log(s.gray(` Projects: ${k.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${k.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${h}`));}else if(t==="diff"){let d=a("diff"),g=n.from||e;g||((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:d},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:w,writeWorkspaceModelDiff:k}=await import('./workspace-intelligence-FKYQQDJ6.js'),h;try{h=await w({workspacePath:d,fromPath:g,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:x.message,context:{workspacePath:d,fromPath:g},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),x}let v=await k(h,d);if(n.json){console.log(JSON.stringify(b$6("workspace diff",h,v),null,2));return}let I=h.summary.changed?s.yellow:s.green;console.log(I(`\u2714 Workspace model diff: ${h.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${h.fromRef}`)),console.log(s.gray(` Added projects: ${h.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${h.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${h.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${h.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${h.summary.validationChanges}`)),h.git?.available&&console.log(s.gray(` Git: ${h.git.dirty?"dirty":"clean"} (${h.summary.gitChangedFiles} mapped change(s))`));for(let x of h.changes.slice(0,12))console.log(s.gray(` \u2022 ${x.type} ${x.target}: ${x.message}`));h.changes.length>12&&console.log(s.gray(` \u2026 ${h.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="impact"){let d=a("impact"),g=n.from||e;g||((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:d},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:w,writeWorkspaceImpact:k}=await import('./workspace-intelligence-FKYQQDJ6.js'),h;try{h=await w({workspacePath:d,fromPath:g,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:x.message,context:{workspacePath:d,fromPath:g},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)),x}let v=await k(h,d);if(n.json){console.log(JSON.stringify(b$6("workspace impact",h,v),null,2));return}let I=h.summary.risk==="critical"||h.summary.risk==="high"?s.red:h.summary.risk==="medium"?s.yellow:s.green;console.log(I(`\u2714 Workspace impact: ${h.summary.risk}`)),console.log(s.gray(` From: ${h.fromRef}`)),console.log(s.gray(` Affected projects: ${h.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${h.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${h.summary.recommendedCommands}`));for(let x of h.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${x.title}: ${x.summary}`));h.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${h.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="verify"){let d=a("verify"),{buildWorkspaceVerify:g,writeWorkspaceVerify:w,evaluateWorkspaceVerifyGate:k}=await import('./workspace-verify-PLAKTF3J.js'),h=await g({workspacePath:d,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()}),v=await w(h,d),I=k(h,{strict:n.strict===true||i("--strict")}),x=I.exitCode,{recordWorkspaceHistory:j,historyEntryFromVerify:R}=await import('./workspace-history-EQG5UBKW.js');if(await j(d,R(h,I.passed)),n.json){console.log(JSON.stringify(b$6("workspace verify",{...h,gate:I},v,x),null,2)),x!==0&&process.exit(x);return}let C=h.summary.verdict==="ready"?s.green:h.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(C(`\u2714 Workspace verify: ${h.summary.verdict}`)),console.log(s.gray(` Freshness: ${h.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${h.impact.risk}`)),console.log(s.gray(` Steps: ${h.steps.length}`)),console.log(s.gray(` Passed ${h.summary.stepsPassed}, warn ${h.summary.stepsWarn}, failed ${h.summary.stepsFailed}, missing ${h.summary.stepsMissing}`));for(let _ of h.steps.slice(0,10))console.log(s.gray(` \u2022 ${_.id}: ${_.status} \u2014 ${_.message}`));if(h.steps.length>10&&console.log(s.gray(` \u2026 ${h.steps.length-10} more step(s)`)),h.policyViolations.length>0){console.log(s.gray(` Policy (${h.policyMode}): ${h.policyViolations.length} violation(s)`));for(let _ of h.policyViolations.slice(0,5)){let N=_.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${N} [${_.source}] ${_.code}: ${_.message}`);}}console.log(s.gray(` Gate (${I.mode}): ${I.passed?"passed":"blocked"}`));for(let _ of I.reasons.slice(0,5))console.log(s.red(` \u2717 ${_}`));console.log(s.gray(` Written: ${v}`)),x!==0&&process.exit(x);}else if(t==="graph"){let d=a("graph"),{buildWorkspaceModel:g,workspaceModelProjectTopology:w}=await import('./workspace-model-POCPMNRT.js'),{buildGraphEmit:k,renderGraphDot:h,renderGraphMermaid:v,explainGraphNode:I}=await import('./workspace-graph-2A5THUCI.js'),x=(e||"emit").toLowerCase(),j=["emit","dot","mermaid","jsonld","graphml","gexf","explain","entities","search","benchmark","benchmark-suite","evidence","path","overlay"];if(!j.includes(x)){let L=`Unknown workspace graph mode '${x}'.`;n.json?console.log(JSON.stringify(c$1({operation:`workspace graph ${x}`,code:"workspace.graph.mode.unsupported",message:L,exitCode:2,context:{mode:x,supportedModes:j},examples:["workspai workspace graph emit --json"]}),null,2)):(console.log(s.red(`\u274C ${L}`)),console.log(s.gray(` Supported: ${j.join(", ")}`))),process.exit(2);}let R=new Set(["benchmark","benchmark-suite","entities","evidence","path","search"]),C=n.refreshGraph===true||i("--refresh-graph"),_=R.has(x)&&!C?await(await import('./workspace-knowledge-graph-snapshot-67XDXUOT.js')).readWorkspaceKnowledgeGraphSnapshot(d):null,N=_?.status==="hit"?_.graph:null,V=_?.status==="hit"?_.model:await g({workspacePath:d,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()}),D=w(V);D||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:x,result:"error",workspacePath:d,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 q$1=async()=>{if(N)return N;let{buildWorkspaceKnowledgeGraph:L}=await import('./workspace-knowledge-graph-CPBKNXQI.js'),{hashWorkspaceModel:G}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:oe}=await import('./workspace-contract-3QUZDBMM.js'),te=null;try{te=(await oe({workspacePath:d})).contract;}catch{}return L({...u(),workspacePath:d,workspace:{name:V.workspace.name,...V.workspace.profile?{profile:V.workspace.profile}:{}},projects:V.projects.map(z=>({id:z.name,path:z.path,...z.absolutePath?{absolutePath:z.absolutePath}:{},runtime:z.runtime,runtimeCandidates:z.runtimeCandidates,framework:z.framework,kind:z.kind,category:z.category,...z.governance?{governance:z.governance}:{},...z.kit?{kit:z.kit}:{}})),projectTopology:D,contract:te,now:new Date(V.generatedAt),source:{kind:"workspace-model",artifact:p.model,hashAlgorithm:"sha256",hash:G(V)}})};if(x==="dot"||x==="mermaid"){let L=x==="dot"?h(D):v(D),G=l();if(G){let oe=b.resolve(d,G);await M__default.outputFile(oe,`${L}
|
|
423
|
+
See the command reference for action-specific required inputs and output artifacts.`).action(async function(t,e,r,o){let n=this.opts(),a=d=>{let g=n.workspace?b.resolve(n.workspace):null,w=null,k=null;try{w=b$5({startPath:process.cwd(),explicitWorkspacePath:g,strict:true})?.workspacePath??null;}catch(I){if(I instanceof a$2)k=I;else throw I}if(!w||!et(w)){let I=k?.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 ${d}`,code:k?.code??"workspace.root.required",message:I,context:{cwd:b.resolve(process.cwd()),...g?{requestedWorkspace:g}:{},...k?.context??{}}}),null,2)),process.exit(1)),console.log(s.red(`\u274C ${I}`)),console.log(s.gray("\u{1F4A1} Run from a workspace/project directory, or pass --workspace <path> to resolve ambiguity.")),process.exit(1);}let h=b.resolve(process.cwd()),v=b.resolve(w);return h!==v&&!n.json&&console.log(s.gray(`\u2139 Using workspace root ${w} for "${d}" (current directory: ${h}).`)),w},i=d=>process.argv.includes(d),c=d=>Re(process.argv,d),l=()=>n.output||c("--output"),p$1=()=>{if(!n.scanDepth)return;let d=Number.parseInt(n.scanDepth,10);return Number.isFinite(d)?d:void 0},m=(d,g,w)=>{if(d===void 0)return;let k=Number.parseInt(d,10);if(!Number.isFinite(k)||k<1||k>w)throw new Error(`${g} must be an integer between 1 and ${w}.`);return k},u=()=>({...n.graphInventoryLimit!==void 0?{inventoryFileLimitPerProject:m(n.graphInventoryLimit,"--graph-inventory-limit",2e6)}:{},...n.graphSemanticBudget!==void 0?{semanticFilesPerProject:m(n.graphSemanticBudget,"--graph-semantic-budget",25e4)}:{},...n.graphDeepBudget!==void 0?{maxFilesPerProject:m(n.graphDeepBudget,"--graph-deep-budget",1e5)}:{},...n.graphSourceBudget!==void 0?{sourceFilesPerProject:m(n.graphSourceBudget,"--graph-source-budget",5e4)}:{}}),f=(d,g)=>{if(!d)return;let w=d.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/);if(!w)throw new Error(`${g} must be a byte size such as 500gb or 2tb.`);let k={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4},h=Number(w[1])*k[w[2]||"b"];if(!Number.isSafeInteger(Math.floor(h))||h<=0)throw new Error(`${g} is outside the supported numeric range.`);return Math.floor(h)},P=()=>{let d=n.downloadTimeoutMs,g=d===void 0?void 0:Number.parseInt(d,10);if(g!==void 0&&(!Number.isFinite(g)||g<0))throw new Error("--download-timeout-ms must be zero or a positive integer.");return {maxDownloadBytes:f(n.maxDownloadSize,"--max-download-size"),maxExpandedBytes:f(n.maxExpandedSize,"--max-expanded-size"),downloadTimeoutMs:g,allowPrivateNetwork:n.allowPrivateNetwork===true||i("--allow-private-network")}},y=new Set(Object.values(ko).flatMap(d=>[...d.flags])),E=new Set(process.argv.slice(2).filter(d=>d.startsWith("--")).map(d=>d.split("=",1)[0]).filter(d=>y.has(d))),A=ko[t]?.flags,S=A?[...E].filter(d=>!A.includes(d)):[];if(S.length>0){let d=`${S.join(", ")} ${S.length===1?"is":"are"} not supported by workspace ${t}.`;n.json===true||E.has("--json")?console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.option.unsupported",message:d,exitCode:2,context:{action:t,unsupportedFlags:S,allowedFlags:A}}),null,2)):(console.log(s.red(`\u274C ${d}`)),console.log(s.gray(` Allowed flags: ${A.join(", ")||"none"}`))),process.exit(2);}if((Ed(t)||t==="trace"||t==="feedback"||t==="mcp")&&c$2({action:t,status:"started",message:`workspace ${t} started`,metadata:{json:n.json===true||i("--json"),strict:n.strict===true||i("--strict")}}),t==="list"){let{listWorkspaces:d}=await import('./workspace-AXU6ODER.js');await d({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 d=a("intelligence"),{runWorkspaceIntelligenceChain:g}=await import('./workspace-intelligence-runner-2EJ7GXG5.js'),w=await g({workspacePath:d,strict:n.strict===true||i("--strict"),agent:typeof n.forAgent=="string"?n.forAgent:"generic"});if(n.json===true||i("--json"))console.log(JSON.stringify(w,null,2));else {console.log(s.green(`\u2714 Workspace Intelligence: ${w.status}`));for(let k of w.stages)console.log(s.gray(` ${k.id}: ${k.status} \u2014 ${k.message}`));console.log(s.gray(` Evidence: ${w.artifactPath}`));}w.exitCode!==0&&process.exit(w.exitCode);}else if(t==="model"){let d=a("model"),{buildWorkspaceModelCached:g,buildWorkspaceModelIncremental:w,createWorkspaceModelBuildProvenance:k,writeWorkspaceModel:h}=await import('./workspace-model-LBICKRVI.js'),v=n.incremental===true||i("--incremental"),I=n.cache===true||i("--cache")||v,x={workspacePath:d,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1(),strict:n.strict===true||i("--strict")},j,R;if(v){let N=await w(x);j=N.model,R=N.mode;}else {let N=await g({...x,cache:I});j=N.model,R=N.cache;}j={...j,build:k({mode:v?"incremental":I?"cache":"full",engineStatus:R})};let C;(n.write===true||i("--write"))&&(C=await h(j,d));let _=(n.strict===true||i("--strict"))&&j.validation?.status!=="passed";if(n.json){console.log(JSON.stringify({...j,...C?{outputPath:C}:{}},null,2)),_&&process.exit(1);return}console.log(s.green(`\u2714 Workspace model: ${j.workspace.name}`)),v?console.log(s.gray(` Build: ${R} (incremental)`)):I&&console.log(s.gray(` Cache: ${R}`)),console.log(s.gray(` Projects: ${j.summary.projectCount}`)),console.log(s.gray(` Runtimes: ${j.summary.runtimes.join(", ")||"none"}`)),console.log(s.gray(` Frameworks: ${j.summary.frameworks.join(", ")||"none"}`)),console.log(s.gray(` Workspace type: ${j.identity.workspaceType}`)),console.log(s.gray(` Validation: ${j.validation?.status??"unknown"} (${j.validation?.errors??0} error, ${j.validation?.warnings??0} warning)`)),console.log(C?s.gray(` Written: ${C}`):s.gray(" Add --write to persist .workspai/reports/workspace-model.json")),_&&process.exit(1);}else if(t==="agent-sync"){let d=a("agent-sync"),{syncWorkspaceAgentGrounding:g,parseAgentGroundingTargets:w}=await import('./workspace-agent-sync-6427FNME.js'),k=n.strict===true||i("--strict"),h=n.write===true||i("--write"),v=i("--dry-run"),I=await g({workspacePath:d,scope:n.scope,agent:n.forAgent,write:h&&!v,dryRun:v,strict:k,preset:n.preset==="minimal"?"minimal":"enterprise",refreshContext:n.refreshContext===true||i("--refresh-context")||i("--refresh"),targets:w(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(I,null,2));else {console.log(s.green(`\u2714 Agent grounding ${h&&!v?"synced":"planned"}`)),console.log(s.gray(` Index: ${I.indexPath}`)),I.contextPath&&console.log(s.gray(` Context: ${I.contextPath}`)),I.blockers.length>0&&console.log(s.yellow(` Blockers: ${I.blockers.slice(0,3).join(" \xB7 ")}`));let x=h&&!v?I.writtenFiles:I.skippedFiles;if(x.length>0&&console.log(s.gray(` Files: ${x.join(", ")}`)),I.strictViolations.length>0)for(let j of I.strictViolations)console.log(s.red(`\u274C ${j}`));}k&&I.strictViolations.length>0&&process.exit(1);}else if(t==="repair"){let d=e??"status",{approveWorkspaceRepair:g,cancelWorkspaceRepair:w,decideWorkspaceRepair:k,executeWorkspaceRepair:h,inspectWorkspaceRepairCapabilities:v,listWorkspaceRepairTransactions:I,planWorkspaceRepair:x,planWorkspaceRepairProposal:j,readWorkspaceRepairTransaction:R,rollbackWorkspaceRepair:C}=await import('./workspace-repair-engine-ODTFFM6O.js');if(d==="capabilities"){let J,ae;if(n.workspace)J=a("repair capabilities");else try{let se=b$5({startPath:process.cwd(),strict:false});se&&et(se.workspacePath)&&(J=se.workspacePath,ae=se.projectPath??void 0);}catch{}let pe=await v(J?{workspacePath:J,project:n.project,projectPath:n.project?void 0:ae}:n.project?{project:n.project}:{});if(n.json===true||i("--json"))console.log(JSON.stringify(pe,null,2));else {console.log(s.green(`\u2714 Workspace repair adapters: ${pe.adapters.length}`));for(let se of pe.adapters)console.log(s.gray(` ${se.id.padEnd(14)} ${se.support.padEnd(11)} ${se.ecosystem}`));console.log(s.gray(" Missing tools and unsupported ecosystems fail closed."));}return}let _=a("repair"),N=n.transaction??(["plan","propose","capabilities"].includes(d)?void 0:r),V=()=>{if(!N?.trim())throw new Error(`workspace repair ${d} requires --transaction <id> (or the id as the next positional argument).`);return N.trim()},D;if(d==="plan"){let J=n.card??r;if(!J?.trim())throw new Error("workspace repair plan requires --card <id>.");D=await x({workspacePath:_,cardId:J.trim(),actionId:n.actionId,projectName:n.project,maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(d==="propose"){let J=n.proposal??r;if(!J?.trim())throw new Error("workspace repair propose requires --proposal <path>.");let ae=b.resolve(_,J.trim()),pe=b.relative(_,ae);if(pe.startsWith("..")||b.isAbsolute(pe))throw new Error("The repair proposal file must be inside the canonical workspace.");let se=await M__default.lstat(ae).catch(()=>{});if(!se?.isFile()||se.isSymbolicLink()||se.size>25*1024*1024)throw new Error("The repair proposal must be a regular JSON file no larger than 25 MiB.");D=await j({workspacePath:_,proposal:await M__default.readJson(ae),maxRisk:n.maxRisk,allowBreaking:n.allowBreaking===true,allowForce:n.allowForce===true,autoRollback:n.autoRollback!==false});}else if(d==="approve")D=await g({workspacePath:_,transactionId:V(),approvedBy:n.approvedBy});else if(d==="decide"){if(!n.decision)throw new Error("workspace repair decide requires --decision <choice>.");D=await k({workspacePath:_,transactionId:V(),decision:n.decision});}else if(d==="execute"||d==="resume")D=await h({workspacePath:_,transactionId:V()});else if(d==="status")D=await R({workspacePath:_,transactionId:V()});else if(d==="list")D=await I(_);else if(d==="rollback")D=await C({workspacePath:_,transactionId:V()});else if(d==="cancel")D=await w({workspacePath:_,transactionId:V()});else throw new Error(`Unknown workspace repair action: ${d}. Available: capabilities, plan, propose, approve, decide, execute, resume, status, list, rollback, cancel.`);let q=b.join(_,p.repairTransaction);if(n.json===true||i("--json"))console.log(JSON.stringify(b$6(`workspace repair ${d}`,D,q),null,2));else if(Array.isArray(D)){console.log(s.green(`\u2714 Workspace repair transactions: ${D.length}`));for(let J of D.slice(0,20))console.log(s.gray(` ${J.transactionId} \xB7 ${J.target.cardId} \xB7 ${J.state}`));}else {console.log(s.green(`\u2714 Workspace repair: ${D.state}`)),console.log(s.gray(` Transaction: ${D.transactionId}`)),console.log(s.gray(` Target: ${D.target.cardId}`));for(let J of D.stages)console.log(s.gray(` ${J.status.padEnd(8)} ${J.kind}: ${J.summary}`));D.decision&&console.log(s.yellow(` Decision: ${D.decision.reason}`)),console.log(s.gray(` Evidence: ${p.repairTransaction}`));}Array.isArray(D)||(D.state==="decision-required"&&process.exit(2),(D.state==="rolled-back"||D.state==="failed")&&process.exit(1));return}else if(t==="remediation-plan"){let d=a("remediation-plan"),{buildArtifactRemediationPlan:g,writeArtifactRemediationPlan:w}=await import('./artifact-remediation-plan-SRH2Q6N2.js'),k=await g({workspacePath:d,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),ciMode:n.ci===true||i("--ci")}),h;if((n.write===true||i("--write"))&&(h=await w(k,d)),n.json===true||i("--json")){console.log(JSON.stringify(b$6("workspace remediation-plan",k,h),null,2));return}console.log(s.green(`\u2714 Artifact remediation plan: ${k.workspace.name}`)),console.log(s.gray(` Artifacts scanned: ${k.summary.artifactsScanned}`)),console.log(s.gray(` Cards covered: ${k.summary.cardsCovered}`)),console.log(s.gray(` CI mode: ${k.source.ciMode?"yes":"no"}`)),console.log(s.gray(` Actions: ${k.summary.totalActions}`)),console.log(s.gray(` Risk: safe=${k.summary.risk.safe}, guarded=${k.summary.risk.guarded}, invasive=${k.summary.risk.invasive}`));for(let v of k.actions.slice(0,8))console.log(s.gray(` \u2022 ${v.cardId}: ${v.title} (${v.mode}, ${v.risk})`));k.actions.length>8&&console.log(s.gray(` \u2026 ${k.actions.length-8} more action(s)`)),console.log(h?s.gray(` Written: ${h}`):s.gray(" Add --write to persist .workspai/reports/artifact-remediation-plan-last-run.json"));}else if(t==="context"){let d=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:g,writeWorkspaceAgentContext:w}=await import('./workspace-context-VVZARI5K.js'),k=n.strict===true||i("--strict"),h=await g({workspacePath:d,agent:n.forAgent||r||e,scope:n.scope,includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1(),strict:false}),v,I;if((n.write===true||i("--write"))&&(v=await w(h,d),(n.agentSync===true||i("--agent-sync")||n.noAgentSync!==true)&&!i("--no-agent-sync"))){let{syncWorkspaceAgentGrounding:R,parseAgentGroundingTargets:C}=await import('./workspace-agent-sync-6427FNME.js');if(I=await R({workspacePath:d,scope:n.scope,agent:h.agent,write:true,refreshContext:false,strict:k,preset:n.preset==="minimal"?"minimal":"enterprise",targets:C(n.target),projectGrounding:n.projectGrounding??"managed"}),n.json||console.log(s.gray(` Agent grounding synced: ${I.writtenFiles.length} file(s) updated`)),k&&I.strictViolations.length>0){for(let _ of I.strictViolations)console.log(s.red(`\u274C ${_}`));process.exit(1);}}let x=k&&h.validation.status!=="passed";if(n.json){console.log(JSON.stringify({...h,...v?{outputPath:v}:{},...I?{agentGroundingSync:I}:{}},null,2)),x&&process.exit(1);return}if(console.log(s.green(`\u2714 Workspace context: ${h.workspace.name}`)),console.log(s.gray(` Agent: ${h.agent}`)),console.log(s.gray(` Scope: ${h.scope.activeProject??h.scope.requested}`)),console.log(s.gray(` Projects included: ${h.projects.length}`)),console.log(s.gray(` Safe commands: ${h.safeCommands.length}`)),console.log(s.gray(` Validation: ${h.validation.status} (${h.validation.errors} error, ${h.validation.warnings} warning)`)),console.log(v?s.gray(` Written: ${v}`):s.gray(" Add --write to persist .workspai/reports/workspace-context-agent.json")),x){for(let j of h.validation.issues)console.log(s.red(`\u274C ${j.severity}:${j.code}:${j.target}`));process.exit(1);}}else if(t==="snapshot"){let d=a("snapshot"),{buildWorkspaceModelSnapshot:g,writeWorkspaceModelSnapshot:w}=await import('./workspace-intelligence-ZTET7JHS.js'),k=await g({workspacePath:d,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()}),h=await w(k,d);if(n.json){console.log(JSON.stringify(b$6("workspace snapshot",k,h),null,2));return}console.log(s.green(`\u2714 Workspace model snapshot: ${k.model.workspace.name}`)),console.log(s.gray(` Hash: ${k.modelHash}`)),console.log(s.gray(` Projects: ${k.model.summary.projectCount}`)),console.log(s.gray(` Workspace type: ${k.model.identity.workspaceType}`)),console.log(s.gray(` Written: ${h}`));}else if(t==="diff"){let d=a("diff"),g=n.from||e;g||((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:d},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:w,writeWorkspaceModelDiff:k}=await import('./workspace-intelligence-ZTET7JHS.js'),h;try{h=await w({workspacePath:d,fromPath:g,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace diff",code:"workspace.diff.input_unreadable",message:x.message,context:{workspacePath:d,fromPath:g},nextActions:["npx workspai workspace snapshot --json","npx workspai workspace diff --from .workspai/reports/workspace-model-snapshot.json --json"]}),null,2)),process.exit(1)),x}let v=await k(h,d);if(n.json){console.log(JSON.stringify(b$6("workspace diff",h,v),null,2));return}let I=h.summary.changed?s.yellow:s.green;console.log(I(`\u2714 Workspace model diff: ${h.summary.changed?"changed":"clean"}`)),console.log(s.gray(` From: ${h.fromRef}`)),console.log(s.gray(` Added projects: ${h.summary.addedProjects}`)),console.log(s.gray(` Removed projects: ${h.summary.removedProjects}`)),console.log(s.gray(` Changed projects: ${h.summary.changedProjects}`)),console.log(s.gray(` Workspace changes: ${h.summary.workspaceChanges}`)),console.log(s.gray(` Validation changes: ${h.summary.validationChanges}`)),h.git?.available&&console.log(s.gray(` Git: ${h.git.dirty?"dirty":"clean"} (${h.summary.gitChangedFiles} mapped change(s))`));for(let x of h.changes.slice(0,12))console.log(s.gray(` \u2022 ${x.type} ${x.target}: ${x.message}`));h.changes.length>12&&console.log(s.gray(` \u2026 ${h.changes.length-12} more change(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="impact"){let d=a("impact"),g=n.from||e;g||((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:d},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:w,writeWorkspaceImpact:k}=await import('./workspace-intelligence-ZTET7JHS.js'),h;try{h=await w({workspacePath:d,fromPath:g,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()});}catch(x){throw (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:"workspace impact",code:"workspace.impact.input_unreadable",message:x.message,context:{workspacePath:d,fromPath:g},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)),x}let v=await k(h,d);if(n.json){console.log(JSON.stringify(b$6("workspace impact",h,v),null,2));return}let I=h.summary.risk==="critical"||h.summary.risk==="high"?s.red:h.summary.risk==="medium"?s.yellow:s.green;console.log(I(`\u2714 Workspace impact: ${h.summary.risk}`)),console.log(s.gray(` From: ${h.fromRef}`)),console.log(s.gray(` Affected projects: ${h.summary.affectedProjects}`)),console.log(s.gray(` Workspace items: ${h.summary.workspaceItems}`)),console.log(s.gray(` Recommended commands: ${h.summary.recommendedCommands}`));for(let x of h.affectedProjects.slice(0,8))console.log(s.gray(` \u2022 ${x.title}: ${x.summary}`));h.affectedProjects.length>8&&console.log(s.gray(` \u2026 ${h.affectedProjects.length-8} more project(s)`)),console.log(s.gray(` Written: ${v}`));}else if(t==="verify"){let d=a("verify"),{buildWorkspaceVerify:g,writeWorkspaceVerify:w,evaluateWorkspaceVerifyGate:k}=await import('./workspace-verify-UQWAFGNQ.js'),h=await g({workspacePath:d,fromImpactPath:n.fromImpact||e,scope:n.scope,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()}),v=await w(h,d),I=k(h,{strict:n.strict===true||i("--strict")}),x=I.exitCode,{recordWorkspaceHistory:j,historyEntryFromVerify:R}=await import('./workspace-history-EQG5UBKW.js');if(await j(d,R(h,I.passed)),n.json){console.log(JSON.stringify(b$6("workspace verify",{...h,gate:I},v,x),null,2)),x!==0&&process.exit(x);return}let C=h.summary.verdict==="ready"?s.green:h.summary.verdict==="needs-attention"?s.yellow:s.red;console.log(C(`\u2714 Workspace verify: ${h.summary.verdict}`)),console.log(s.gray(` Freshness: ${h.freshness.verdict}`)),console.log(s.gray(` Impact risk: ${h.impact.risk}`)),console.log(s.gray(` Steps: ${h.steps.length}`)),console.log(s.gray(` Passed ${h.summary.stepsPassed}, warn ${h.summary.stepsWarn}, failed ${h.summary.stepsFailed}, missing ${h.summary.stepsMissing}`));for(let _ of h.steps.slice(0,10))console.log(s.gray(` \u2022 ${_.id}: ${_.status} \u2014 ${_.message}`));if(h.steps.length>10&&console.log(s.gray(` \u2026 ${h.steps.length-10} more step(s)`)),h.policyViolations.length>0){console.log(s.gray(` Policy (${h.policyMode}): ${h.policyViolations.length} violation(s)`));for(let _ of h.policyViolations.slice(0,5)){let N=_.severity==="error"?s.red("\u2717"):s.yellow("!");console.log(` ${N} [${_.source}] ${_.code}: ${_.message}`);}}console.log(s.gray(` Gate (${I.mode}): ${I.passed?"passed":"blocked"}`));for(let _ of I.reasons.slice(0,5))console.log(s.red(` \u2717 ${_}`));console.log(s.gray(` Written: ${v}`)),x!==0&&process.exit(x);}else if(t==="graph"){let d=a("graph"),{buildWorkspaceModel:g,workspaceModelProjectTopology:w}=await import('./workspace-model-LBICKRVI.js'),{buildGraphEmit:k,renderGraphDot:h,renderGraphMermaid:v,explainGraphNode:I}=await import('./workspace-graph-2A5THUCI.js'),x=(e||"emit").toLowerCase(),j=["emit","dot","mermaid","jsonld","graphml","gexf","explain","entities","search","benchmark","benchmark-suite","evidence","path","overlay"];if(!j.includes(x)){let L=`Unknown workspace graph mode '${x}'.`;n.json?console.log(JSON.stringify(c$1({operation:`workspace graph ${x}`,code:"workspace.graph.mode.unsupported",message:L,exitCode:2,context:{mode:x,supportedModes:j},examples:["workspai workspace graph emit --json"]}),null,2)):(console.log(s.red(`\u274C ${L}`)),console.log(s.gray(` Supported: ${j.join(", ")}`))),process.exit(2);}let R=new Set(["benchmark","benchmark-suite","entities","evidence","path","search"]),C=n.refreshGraph===true||i("--refresh-graph"),_=R.has(x)&&!C?await(await import('./workspace-knowledge-graph-snapshot-UTJHALST.js')).readWorkspaceKnowledgeGraphSnapshot(d):null,N=_?.status==="hit"?_.graph:null,V=_?.status==="hit"?_.model:await g({workspacePath:d,includeAbsolutePaths:n.includePaths===true||i("--include-paths"),includeEvidence:n.includeEvidence===true||i("--include-evidence"),observableScanDepth:p$1()}),D=w(V);D||(n.json&&(console.log(JSON.stringify({command:"workspace graph",action:x,result:"error",workspacePath:d,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 q$1=async()=>{if(N)return N;let{buildWorkspaceKnowledgeGraph:L}=await import('./workspace-knowledge-graph-4RSZTEFJ.js'),{hashWorkspaceModel:G}=await import('./workspace-model-hash-ZXYPIGCW.js'),{readWorkspaceContract:oe}=await import('./workspace-contract-N2BJCAJ7.js'),te=null;try{te=(await oe({workspacePath:d})).contract;}catch{}return L({...u(),workspacePath:d,workspace:{name:V.workspace.name,...V.workspace.profile?{profile:V.workspace.profile}:{}},projects:V.projects.map(z=>({id:z.name,path:z.path,...z.absolutePath?{absolutePath:z.absolutePath}:{},runtime:z.runtime,runtimeCandidates:z.runtimeCandidates,framework:z.framework,kind:z.kind,category:z.category,...z.governance?{governance:z.governance}:{},...z.kit?{kit:z.kit}:{}})),projectTopology:D,contract:te,now:new Date(V.generatedAt),source:{kind:"workspace-model",artifact:p.model,hashAlgorithm:"sha256",hash:G(V)}})};if(x==="dot"||x==="mermaid"){let L=x==="dot"?h(D):v(D),G=l();if(G){let oe=b.resolve(d,G);await M__default.outputFile(oe,`${L}
|
|
423
424
|
`,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${x}`,{format:x,nodeCount:D.stats.nodeCount,edgeCount:D.stats.edgeCount},oe),null,2)):(console.log(s.green(`\u2714 Workspace dependency graph exported as ${x}`)),console.log(s.gray(` Written: ${oe}`)));return}console.log(L);return}if(x==="jsonld"||x==="graphml"||x==="gexf"){let L=await q$1(),{renderWorkspaceKnowledgeGraphGexf:G,renderWorkspaceKnowledgeGraphGraphMl:oe,renderWorkspaceKnowledgeGraphJsonLd:te}=await import('./workspace-knowledge-graph-export-UYAYFTWX.js'),z=x==="jsonld"?te(L):x==="graphml"?oe(L):G(L),ee=l();if(ee){let Y=b.resolve(d,ee);await M__default.outputFile(Y,`${z}
|
|
424
|
-
`,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${x}`,{format:x,entityCount:L.entities.length,relationCount:L.relations.length,proofCount:L.proofs.length},Y),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${x}`)),console.log(s.gray(` Written: ${Y}`)));return}console.log(z);return}if(x==="explain"){let L=(n.scope?.replace(/^project:/,"")||r||"").trim();L||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:d,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let G=I(D,L);if(n.json){console.log(JSON.stringify(G,null,2)),G.found||process.exit(1);return}G.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${L}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${G.project}`)),G.centrality&&console.log(s.gray(` Centrality: fanIn ${G.centrality.fanIn}, fanOut ${G.centrality.fanOut}, reach ${G.centrality.reach}, betweenness ${G.centrality.betweenness}${G.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${G.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${G.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${G.transitiveDependents.length}`));for(let oe of G.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${oe.id} (d${oe.distance}, via ${oe.via??"\u2014"})`));return}if(x==="entities"){let L=await q$1(),{queryKnowledgeEntities:G}=await import('./workspace-knowledge-graph-query-BROIV27M.js'),oe=(r||n.kind||"").trim()||void 0;if(oe){let{WORKSPACE_KNOWLEDGE_ENTITY_KINDS:B}=await import('./workspace-knowledge-graph-contract-FVX5T7SU.js');B.includes(oe)||(console.log(s.red(`\u274C Unknown graph entity kind: ${oe}`)),console.log(s.gray(` Supported: ${B.join(", ")}`)),process.exit(1));}let te=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,z=G(L,oe,te),ee=n.limit??c("--limit"),Y=ee===void 0?void 0:Number.parseInt(ee,10);Y!==void 0&&(!Number.isFinite(Y)||Y<1||Y>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let O=Y===void 0?z:z.slice(0,Y);if(n.json){console.log(JSON.stringify({schemaVersion:L.schemaVersion,generatedAt:L.generatedAt,kind:oe??null,...te?{projectId:te}:{},count:O.length,totalMatches:z.length,truncated:O.length<z.length,entities:O},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${oe?`: ${oe}`:""}`)),console.log(s.gray(` Count: ${O.length}/${z.length}${O.length<z.length?" (bounded)":""}`));for(let B of O)console.log(s.gray(` \u2022 ${B.kind}: ${B.label} [${B.id}]`));return}if(x==="benchmark-suite"){let L=(r||"agent-core.v1").trim(),{WORKSPACE_INTELLIGENCE_BENCHMARK_REPORT_PATH:G,WORKSPACE_INTELLIGENCE_BENCHMARK_SUITES:oe,buildWorkspaceIntelligenceBenchmark:te,writeWorkspaceIntelligenceBenchmark:z}=await import('./workspace-intelligence-benchmark-V6AEVDMB.js');L in oe||(console.log(s.red(`\u274C Unknown benchmark suite: ${L}`)),console.log(s.gray(` Supported: ${Object.keys(oe).join(", ")}`)),process.exit(2));let ee=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(ee)||ee<1||ee>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let Y=await q$1(),O=await te({workspacePath:d,graph:Y,suite:L,limit:ee,...n.from?{baselineEvaluationPath:n.from}:{}}),H=n.write===true||i("--write")||!!l()?await z(d,O,l()??G):void 0;if(n.json){console.log(JSON.stringify(b$6("workspace graph benchmark-suite",O,H),null,2));return}console.log(s.green(`\u2714 Workspace Intelligence benchmark: ${O.suite.title}`)),console.log(s.gray(` Scenarios: ${O.retrievalSummary.matchedScenarioCount}/${O.retrievalSummary.scenarioCount} matched \xB7 ${O.retrievalSummary.status}`)),console.log(s.gray(` Median estimated retrieval: ${O.retrievalSummary.medianRetrievalEstimatedTokens} tokens \xB7 p95 ${O.retrievalSummary.p95RetrievalEstimatedTokens}`)),console.log(s.gray(` Median estimated payload reduction: ${O.retrievalSummary.medianEstimatedReductionPercent}%`)),console.log(s.gray(` Model evaluation: ${O.evaluation.availability} (${O.evaluation.provenance})`)),console.log(s.yellow(` ${O.methodology.claimBoundary}`)),H&&console.log(s.gray(` Written: ${H}`));return}if(x==="search"||x==="benchmark"){let L=(r||"").trim();L||(console.log(s.red(`\u274C workspace graph ${x} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${x} "authentication endpoint" --json`)),process.exit(1));let G=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(G)||G<1||G>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let oe=await q$1();if(x==="benchmark"){let O=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,{buildWorkspaceGraphTokenEfficiencyReport:B}=await import('./workspace-graph-token-efficiency-WF6TGSK7.js'),H=await B({workspacePath:d,graph:oe,query:L,limit:G,...O?{projectId:O}:{}});n.json?console.log(JSON.stringify(H,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${L}`)),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:te}=await import('./workspace-knowledge-graph-query-BROIV27M.js'),z=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,ee=n.kind?String(n.kind).trim():void 0;if(ee){let{WORKSPACE_KNOWLEDGE_ENTITY_KINDS:O}=await import('./workspace-knowledge-graph-contract-FVX5T7SU.js');O.includes(ee)||(console.log(s.red(`\u274C Unknown graph entity kind: ${ee}`)),console.log(s.gray(` Supported: ${O.join(", ")}`)),process.exit(1));}let Y=te(oe,{query:L,limit:G,...ee?{kind:ee}:{},...z?{projectId:z}:{},projection:"agent"});if(n.json)console.log(JSON.stringify(Y,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${L}`)),console.log(s.gray(` ${Y.entities.length}/${Y.totalMatches} match(es)${Y.truncated?" (bounded)":""}`));for(let O of Y.entities)console.log(s.gray(` \u2022 ${O.kind}: ${O.label} [${O.id}]`));}return}if(x==="evidence"){let L=(r||"").trim();L||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let G=await q$1(),{queryKnowledgeEvidence:oe}=await import('./workspace-knowledge-graph-query-BROIV27M.js'),te=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,z=oe(G,L,te);if(n.json)console.log(JSON.stringify(z,null,2));else if(z.found){console.log(s.green(`\u2714 Graph evidence: ${L}`));for(let ee of z.proofs)console.log(s.gray(` \u2022 ${ee.artifact}${ee.pointer?`#${ee.pointer}`:""} [${ee.provider}/${ee.trust}/${ee.confidence}]`));}else {console.log(s.red(z.candidates.length>0?`\u274C Graph query is ambiguous: ${L}`:`\u274C Graph entity or relation not found: ${L}`));for(let ee of z.candidates.slice(0,10))console.log(s.gray(` \u2022 ${ee}`));}z.found||process.exit(1);return}if(x==="path"){let L=(r||"").trim(),G=(o||"").trim();(!L||!G)&&(console.log(s.red("\u274C workspace graph path requires <from> and <to>.")),console.log(s.gray(" npx workspai workspace graph path <from> <to> --json")),process.exit(1));let oe=await q$1(),{queryKnowledgePath:te}=await import('./workspace-knowledge-graph-query-BROIV27M.js'),z=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,ee=te(oe,L,G,z);if(n.json)console.log(JSON.stringify(ee,null,2));else if(ee.found){console.log(s.green(`\u2714 Graph proof path: ${L} \u2192 ${G}`));for(let Y of ee.hops)console.log(s.gray(` \u2022 ${Y.from} ${Y.direction==="forward"?"\u2192":"\u2190"} ${Y.to} [${Y.kind}]`));console.log(s.gray(` Proofs: ${ee.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${L} and ${G}.`));ee.found||process.exit(1);return}if(x==="overlay"){let L=(n.from||r||"").trim();L||(console.log(s.red("\u274C workspace graph overlay requires --from <graph.json>.")),console.log(s.gray(" npx workspai workspace graph overlay --from <graph.json> --json")),process.exit(1));let G=b.resolve(d,L),oe;try{oe=JSON.parse(await M__default.readFile(G,"utf8"));}catch(De){console.log(s.red(`\u274C Could not read the base knowledge graph: ${De instanceof Error?De.message:String(De)}`)),process.exit(1);}let te=oe&&typeof oe=="object"?oe:{},z=te.graph,ee=z&&typeof z=="object"?z:{},Y=te.schemaVersion===q.knowledgeGraph?te:te.knowledgeGraph??ee.knowledgeGraph;(!Y||typeof Y!="object"||Y.schemaVersion!==q.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${q.knowledgeGraph} document.`)),process.exit(1));let O=await q$1(),{buildWorkspaceKnowledgeGraphChangeOverlay:B}=await import('./workspace-knowledge-graph-change-overlay-FIIAFLO6.js'),H=B(Y,O);if(n.json){console.log(JSON.stringify(H,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${L}`)),console.log(s.gray(` Risk: ${H.summary.risk}`)),console.log(s.gray(` Entities: +${H.summary.entityAdds} -${H.summary.entityRemovals} ~${H.summary.entityChanges}`)),console.log(s.gray(` Relations: +${H.summary.relationAdds} -${H.summary.relationRemovals} ~${H.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${H.summary.proofAdds} -${H.summary.proofRemovals} ~${H.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${H.summary.impactedEntities} entities \xB7 ${H.summary.changedArtifacts} proof artifacts`));return}let J=k(D),{writeWorkspaceModel:ae}=await import('./workspace-model-POCPMNRT.js');await ae(V,d,{refreshKnowledgeGraph:C});let pe=await M__default.readJson(b.join(d,p.knowledgeGraph)),se={...J,knowledgeGraph:pe},qe=l();if(qe){let L=b.resolve(d,qe);await M__default.outputFile(L,`${JSON.stringify(se,null,2)}
|
|
425
|
-
`,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace graph emit",{format:"json",nodeCount:D.stats.nodeCount,edgeCount:D.stats.edgeCount,entityCount:pe.entities.length,relationCount:pe.relations.length,proofCount:pe.proofs.length},L),null,2)):(console.log(s.green("\u2714 Workspace graph artifact exported as JSON")),console.log(s.gray(` Written: ${L}`)));return}if(n.json){console.log(JSON.stringify(se,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${J.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${J.graph.stats.edgeCount} (inferred ${J.graph.stats.inferredEdges}, contract ${J.graph.stats.contractEdges}, manual ${J.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${J.integrity.ok?"ok":"issues"} (cycles ${J.integrity.stats.cycleCount}, dangling ${J.integrity.stats.danglingCount}, orphans ${J.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${J.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${pe.quality.entityCount} entities \xB7 ${pe.quality.relationCount} relations \xB7 ${pe.quality.proofCount} proofs \xB7 ${pe.providers.length} providers`));let Ye=(pe.source.inputs?.scopes??[]).filter(L=>L.truncated),Ee=pe.quality.completeness;if(Ye.length>0?console.log(s.yellow(` Inventory: emergency-bounded \u2014 ${Ye.map(L=>`${L.kind}:${L.id} indexed ${L.fileCount}/${L.eligibleFileCountExact===false?"at-least-":""}${L.eligibleFileCount??L.fileCount} eligible files`).join(", ")}`)):console.log(s.gray(` Inventory: complete \u2014 ${Ee?.inventory.indexedFiles??(pe.source.inputs?.scopes??[]).reduce((L,G)=>L+G.fileCount,0)} eligible files indexed across ${Ee?.inventory.scopeCount??(pe.source.inputs?.scopes??[]).length} scope(s)`)),Ee){let L=`${Ee.providers.complete} complete \xB7 ${Ee.providers.bounded} adaptive-bounded \xB7 ${Ee.providers.notApplicable} not-applicable \xB7 ${Ee.providers.failed} failed`;console.log(Ee.status==="complete"?s.gray(` Provider coverage: ${L}`):s.yellow(` Provider coverage: ${L}`));}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 d=a("watch"),{runWorkspaceWatch:g}=await import('./workspace-watch-
|
|
426
|
-
`,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace contract graph",{projectCount:C.graph.summary.projectCount,relationshipEdges:C.graph.summary.relationshipEdges,entityCount:C.graph.summary.entityCount,knowledgeRelations:C.graph.summary.knowledgeRelations,proofCount:C.graph.summary.proofCount},_),null,2)):(console.log(s.green("\u2714 Workspace contract graph exported as JSON")),console.log(s.gray(` Written: ${_}`)));return}if(n.json){console.log(JSON.stringify(C,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${C.contractPath}`)),console.log(s.gray(` Workspace: ${C.graph.workspace.name}`)),console.log(s.gray(` Projects: ${C.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${C.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${C.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${C.graph.summary.relationshipEdges} (${C.graph.summary.inferredEdges} inferred, ${C.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${C.graph.summary.connectedProjects}/${C.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(C.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(C.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${C.graph.summary.orphanProjects} \xB7 Hotspots: ${C.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${C.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${C.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${C.graph.summary.entityCount} entities \xB7 ${C.graph.summary.knowledgeRelations} relations \xB7 ${C.graph.summary.proofCount} proofs \xB7 ${C.graph.summary.providerCount} providers \xB7 ${C.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${C.graph.summary.portCount}`));for(let _ of C.graph.nodes){let N=_.ports.map(D=>`${D.name}:${D.port}`).join(", ")||"none",V=_.operationalProfile?` risk=${_.operationalProfile.weight}/${_.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${_.id} (${_.runtime||"unknown"}${_.framework?`/${_.framework}`:""}) ports=${N} manifests=${_.files.manifests.length}${V}`));}for(let _ of C.graph.edges){let N=_.type==="event"?`event:${_.label}`:_.label;console.log(s.gray(` ${_.from} -> ${_.to} [${N}]`));}if(C.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let _ of C.graph.dependencyGraph.edges)console.log(s.gray(` ${_.from} -> ${_.to} [${_.kind}/${_.source}/${_.confidence}] evidence=${_.evidence.length}`));}for(let _ of C.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${_.severity}: ${_.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${x}`)),console.log(s.white(` npx workspai workspace contract init|inspect|sync|verify|graph [--output ${I}]`)),process.exit(1);}catch(C){n.json&&(console.log(JSON.stringify({command:`workspace contract ${x}`,result:"error",workspacePath:d,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${x}.failed`,message:C.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${x} failed: ${C.message}`)),process.exit(1);}}else if(t==="share"){let d=a("share"),g=l()||e,{createWorkspaceShareBundle:w}=await import('./workspace-A33YMF2N.js'),k=await w(d,{outputPath:g,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:d,bundlePath:k,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${k}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let d=a("export");try{let{exportWorkspaceArchive:g}=await import('./workspace-archive-3AURTMYA.js'),w=n.archiveCompression?.trim().toLowerCase()??"store";if(w!=="store"&&w!=="deflate")throw new Error("--archive-compression must be store or deflate.");let k=await g({workspacePath:d,outputPath:l()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:w});if(n.json){console.log(JSON.stringify(k,null,2));return}let h=(k.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${k.archivePath}`)),console.log(s.gray(` Files: ${k.manifest.files.length}`)),console.log(s.gray(` Size: ${h} MB`)),k.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${g.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let d=r;d||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:g,inspectWorkspaceArchive:w,verifyWorkspaceArchive:k}=await import('./workspace-archive-3AURTMYA.js');try{if(e==="inspect"){let v=await w({archivePathOrUrl:d,safety:P()});if(n.json){console.log(JSON.stringify(v,null,2));return}let I=(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: ${I} MB`));return}if(e==="doctor"){let v=await g({archivePathOrUrl:d,strict:n.strict===true||i("--strict"),safety:P()});if(n.json)console.log(JSON.stringify(v,null,2));else {let I=v.status==="passed"?s.green:v.status==="warning"?s.yellow:s.red;console.log(I(`\u2714 Workspace archive doctor ${v.status}: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.workspaceName}`)),console.log(s.gray(` Files: ${v.fileCount}`));for(let x of v.checks){let j=x.status==="passed"?"\u2714":x.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${j} ${x.id}: ${x.message}`));}for(let x of v.recommendedActions)console.log(s.gray(` Next: ${x}`));}(v.status==="failed"||v.status==="warning"&&n.strict)&&process.exit(1);return}let h=await k({archivePathOrUrl:d,requireChecksums:n.strict===true||i("--strict"),safety:P()});if(n.json)console.log(JSON.stringify(h,null,2));else if(h.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.verifiedFiles}/${h.fileCount}`));else {let v=h.status==="failed"?s.red:s.yellow;console.log(v(`\u274C Workspace archive verification ${h.status}: ${h.archivePath}`)),h.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${h.missingArchiveEntries.join(", ")}`)),h.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${h.extraArchiveEntries.join(", ")}`)),h.mismatches.length&&console.log(s.gray(` Mismatches: ${h.mismatches.map(I=>I.path).join(", ")}`)),h.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${h.missingChecksumFiles.join(", ")}`));}(h.status==="failed"||h.status==="warning"&&n.strict)&&process.exit(1);}catch(h){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:d,error:{code:`workspace.archive.${e}.failed`,message:h.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${h.message}`)),process.exit(1);}}else if(t==="connect"){let d=b.resolve(e||process.cwd());try{let g=await Ns({workspacePath:d,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(g,null,2));return}console.log(s.green(g.status==="preview"?`\u2714 Workspace connection preview: ${d}`:`\u2714 Workspace connected: ${d}`));for(let w of g.warnings)console.log(s.yellow(` \u26A0 ${w}`));}catch(g){let w=g instanceof Error?g.message:String(g);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:w}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${w}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let d=e;d||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let g=await $s({archivePathOrUrl:d,outputPath:l(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:P()});if(n.json){console.log(JSON.stringify(g,null,2));return}console.log(s.green(g.status==="preview"?`\u2714 Workspace import preview: ${g.workspacePath}`:`\u2714 Workspace imported and registered: ${g.workspacePath}`));for(let w of g.warnings)console.log(s.yellow(` \u26A0 ${w}`));}else {let{hydrateWorkspaceArchive:g}=await import('./workspace-archive-3AURTMYA.js'),w=await g({archivePathOrUrl:d,outputPath:l(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:P()});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(w.dryRun?`\u2714 Workspace archive hydrate preview: ${w.outputPath}`:`\u2714 Workspace archive hydrated: ${w.outputPath}`)),console.log(s.gray(` Files: ${w.files.length}`)),w.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${w.manifest.workspaceName}`));}}catch(g){let w=g instanceof Error?g.message:String(g);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:w,context:{archivePathOrUrl:d,...l()?{outputPath:l()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:d,...l()?{outputPath:l()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:w}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${w}`)),process.exit(1);}}else if(t==="run"){let d=a(`run ${e||""}`.trim()),g=new Set(["init","test","build","start"]),w=e?.trim()??"";w||(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)),g.has(w)||(!/^[a-z][a-z0-9_-]*$/i.test(w)||w==="dev"||w==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${w}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),w==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let k=Js({raw:n.maxWorkers,operation:`workspace run ${w}`,json:n.json===true||i("--json")});if(w==="init"&&n.json!==true){let I=await Zs(d);I!==0&&process.exit(I);}let{runWorkspaceStage:h}=await import('./workspace-run-5YQR7GEZ.js'),v=await h({workspacePath:d,stage:w,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:k,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true,planOnly:n.plan===true,runtime:n.runtime});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 d=a(t),{parseWorkspaceExplainTarget:g}=await import('./workspace-explain-contract-KV7RTEJU.js'),{buildWorkspaceExplain:w,writeWorkspaceExplainReport:k}=await import('./workspace-explain-NXYRAQFI.js'),h=(e??r??"").trim();!h&&n.scope&&(h=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),h||(h="release-blocked");let v=g(h);v||(console.log(s.red(`\u274C Invalid explain target: ${h}`)),process.exit(1));let I=await w({workspacePath:d,target:v}),x=n.write===true||i("--write"),j;if(x&&(j=await k(I,d,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$6(`workspace ${t}`,I,j),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${I.summary}`));for(let R of I.sections)console.log(s.bold(`
|
|
425
|
+
`,"utf8"),n.json?console.log(JSON.stringify(b$6(`workspace graph ${x}`,{format:x,entityCount:L.entities.length,relationCount:L.relations.length,proofCount:L.proofs.length},Y),null,2)):(console.log(s.green(`\u2714 Workspace knowledge graph exported as ${x}`)),console.log(s.gray(` Written: ${Y}`)));return}console.log(z);return}if(x==="explain"){let L=(n.scope?.replace(/^project:/,"")||r||"").trim();L||(n.json&&(console.log(JSON.stringify({command:"workspace graph explain",result:"error",workspacePath:d,timestamp:new Date().toISOString(),error:{code:"workspace.graph.explain.missing_project",message:"workspace graph explain requires a project."},usage:["npx workspai workspace graph explain <project> --json","npx workspai workspace graph explain --scope project:<name> --json"]},null,2)),process.exit(1)),console.log(s.red("\u274C workspace graph explain requires a project.")),console.log(s.gray(" npx workspai workspace graph explain <project> --json")),console.log(s.gray(" npx workspai workspace graph explain --scope project:<name>")),process.exit(1));let G=I(D,L);if(n.json){console.log(JSON.stringify(G,null,2)),G.found||process.exit(1);return}G.found||(console.log(s.red(`\u274C Project not found in dependency graph: ${L}`)),process.exit(1)),console.log(s.green(`\u2714 Graph explain: ${G.project}`)),G.centrality&&console.log(s.gray(` Centrality: fanIn ${G.centrality.fanIn}, fanOut ${G.centrality.fanOut}, reach ${G.centrality.reach}, betweenness ${G.centrality.betweenness}${G.centrality.isHotspot?" (hotspot)":""}`)),console.log(s.gray(` Direct dependents: ${G.directDependents.join(", ")||"none"}`)),console.log(s.gray(` Direct dependencies: ${G.directDependencies.join(", ")||"none"}`)),console.log(s.gray(` Blast radius (transitive dependents): ${G.transitiveDependents.length}`));for(let oe of G.transitiveDependents.slice(0,10))console.log(s.gray(` \u2022 ${oe.id} (d${oe.distance}, via ${oe.via??"\u2014"})`));return}if(x==="entities"){let L=await q$1(),{queryKnowledgeEntities:G}=await import('./workspace-knowledge-graph-query-BROIV27M.js'),oe=(r||n.kind||"").trim()||void 0;if(oe){let{WORKSPACE_KNOWLEDGE_ENTITY_KINDS:B}=await import('./workspace-knowledge-graph-contract-FVX5T7SU.js');B.includes(oe)||(console.log(s.red(`\u274C Unknown graph entity kind: ${oe}`)),console.log(s.gray(` Supported: ${B.join(", ")}`)),process.exit(1));}let te=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,z=G(L,oe,te),ee=n.limit??c("--limit"),Y=ee===void 0?void 0:Number.parseInt(ee,10);Y!==void 0&&(!Number.isFinite(Y)||Y<1||Y>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let O=Y===void 0?z:z.slice(0,Y);if(n.json){console.log(JSON.stringify({schemaVersion:L.schemaVersion,generatedAt:L.generatedAt,kind:oe??null,...te?{projectId:te}:{},count:O.length,totalMatches:z.length,truncated:O.length<z.length,entities:O},null,2));return}console.log(s.green(`\u2714 Workspace graph entities${oe?`: ${oe}`:""}`)),console.log(s.gray(` Count: ${O.length}/${z.length}${O.length<z.length?" (bounded)":""}`));for(let B of O)console.log(s.gray(` \u2022 ${B.kind}: ${B.label} [${B.id}]`));return}if(x==="benchmark-suite"){let L=(r||"agent-core.v1").trim(),{WORKSPACE_INTELLIGENCE_BENCHMARK_REPORT_PATH:G,WORKSPACE_INTELLIGENCE_BENCHMARK_SUITES:oe,buildWorkspaceIntelligenceBenchmark:te,writeWorkspaceIntelligenceBenchmark:z}=await import('./workspace-intelligence-benchmark-V6AEVDMB.js');L in oe||(console.log(s.red(`\u274C Unknown benchmark suite: ${L}`)),console.log(s.gray(` Supported: ${Object.keys(oe).join(", ")}`)),process.exit(2));let ee=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(ee)||ee<1||ee>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let Y=await q$1(),O=await te({workspacePath:d,graph:Y,suite:L,limit:ee,...n.from?{baselineEvaluationPath:n.from}:{}}),H=n.write===true||i("--write")||!!l()?await z(d,O,l()??G):void 0;if(n.json){console.log(JSON.stringify(b$6("workspace graph benchmark-suite",O,H),null,2));return}console.log(s.green(`\u2714 Workspace Intelligence benchmark: ${O.suite.title}`)),console.log(s.gray(` Scenarios: ${O.retrievalSummary.matchedScenarioCount}/${O.retrievalSummary.scenarioCount} matched \xB7 ${O.retrievalSummary.status}`)),console.log(s.gray(` Median estimated retrieval: ${O.retrievalSummary.medianRetrievalEstimatedTokens} tokens \xB7 p95 ${O.retrievalSummary.p95RetrievalEstimatedTokens}`)),console.log(s.gray(` Median estimated payload reduction: ${O.retrievalSummary.medianEstimatedReductionPercent}%`)),console.log(s.gray(` Model evaluation: ${O.evaluation.availability} (${O.evaluation.provenance})`)),console.log(s.yellow(` ${O.methodology.claimBoundary}`)),H&&console.log(s.gray(` Written: ${H}`));return}if(x==="search"||x==="benchmark"){let L=(r||"").trim();L||(console.log(s.red(`\u274C workspace graph ${x} requires a search query.`)),console.log(s.gray(` npx workspai workspace graph ${x} "authentication endpoint" --json`)),process.exit(1));let G=Number.parseInt(n.limit??c("--limit")??"12",10);(!Number.isFinite(G)||G<1||G>100)&&(console.log(s.red("\u274C --limit must be an integer between 1 and 100.")),process.exit(1));let oe=await q$1();if(x==="benchmark"){let O=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,{buildWorkspaceGraphTokenEfficiencyReport:B}=await import('./workspace-graph-token-efficiency-WF6TGSK7.js'),H=await B({workspacePath:d,graph:oe,query:L,limit:G,...O?{projectId:O}:{}});n.json?console.log(JSON.stringify(H,null,2)):(console.log(s.green(`\u2714 Graph retrieval benchmark: ${L}`)),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:te}=await import('./workspace-knowledge-graph-query-BROIV27M.js'),z=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,ee=n.kind?String(n.kind).trim():void 0;if(ee){let{WORKSPACE_KNOWLEDGE_ENTITY_KINDS:O}=await import('./workspace-knowledge-graph-contract-FVX5T7SU.js');O.includes(ee)||(console.log(s.red(`\u274C Unknown graph entity kind: ${ee}`)),console.log(s.gray(` Supported: ${O.join(", ")}`)),process.exit(1));}let Y=te(oe,{query:L,limit:G,...ee?{kind:ee}:{},...z?{projectId:z}:{},projection:"agent"});if(n.json)console.log(JSON.stringify(Y,null,2));else {console.log(s.green(`\u2714 Workspace graph search: ${L}`)),console.log(s.gray(` ${Y.entities.length}/${Y.totalMatches} match(es)${Y.truncated?" (bounded)":""}`));for(let O of Y.entities)console.log(s.gray(` \u2022 ${O.kind}: ${O.label} [${O.id}]`));}return}if(x==="evidence"){let L=(r||"").trim();L||(console.log(s.red("\u274C workspace graph evidence requires an entity or relation id.")),process.exit(1));let G=await q$1(),{queryKnowledgeEvidence:oe}=await import('./workspace-knowledge-graph-query-BROIV27M.js'),te=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,z=oe(G,L,te);if(n.json)console.log(JSON.stringify(z,null,2));else if(z.found){console.log(s.green(`\u2714 Graph evidence: ${L}`));for(let ee of z.proofs)console.log(s.gray(` \u2022 ${ee.artifact}${ee.pointer?`#${ee.pointer}`:""} [${ee.provider}/${ee.trust}/${ee.confidence}]`));}else {console.log(s.red(z.candidates.length>0?`\u274C Graph query is ambiguous: ${L}`:`\u274C Graph entity or relation not found: ${L}`));for(let ee of z.candidates.slice(0,10))console.log(s.gray(` \u2022 ${ee}`));}z.found||process.exit(1);return}if(x==="path"){let L=(r||"").trim(),G=(o||"").trim();(!L||!G)&&(console.log(s.red("\u274C workspace graph path requires <from> and <to>.")),console.log(s.gray(" npx workspai workspace graph path <from> <to> --json")),process.exit(1));let oe=await q$1(),{queryKnowledgePath:te}=await import('./workspace-knowledge-graph-query-BROIV27M.js'),z=n.scope?.startsWith("project:")?n.scope.slice(8).trim():void 0,ee=te(oe,L,G,z);if(n.json)console.log(JSON.stringify(ee,null,2));else if(ee.found){console.log(s.green(`\u2714 Graph proof path: ${L} \u2192 ${G}`));for(let Y of ee.hops)console.log(s.gray(` \u2022 ${Y.from} ${Y.direction==="forward"?"\u2192":"\u2190"} ${Y.to} [${Y.kind}]`));console.log(s.gray(` Proofs: ${ee.proofs.length}`));}else console.log(s.red(`\u274C No graph path found between ${L} and ${G}.`));ee.found||process.exit(1);return}if(x==="overlay"){let L=(n.from||r||"").trim();L||(console.log(s.red("\u274C workspace graph overlay requires --from <graph.json>.")),console.log(s.gray(" npx workspai workspace graph overlay --from <graph.json> --json")),process.exit(1));let G=b.resolve(d,L),oe;try{oe=JSON.parse(await M__default.readFile(G,"utf8"));}catch(De){console.log(s.red(`\u274C Could not read the base knowledge graph: ${De instanceof Error?De.message:String(De)}`)),process.exit(1);}let te=oe&&typeof oe=="object"?oe:{},z=te.graph,ee=z&&typeof z=="object"?z:{},Y=te.schemaVersion===q.knowledgeGraph?te:te.knowledgeGraph??ee.knowledgeGraph;(!Y||typeof Y!="object"||Y.schemaVersion!==q.knowledgeGraph)&&(console.log(s.red(`\u274C Base file does not contain a ${q.knowledgeGraph} document.`)),process.exit(1));let O=await q$1(),{buildWorkspaceKnowledgeGraphChangeOverlay:B}=await import('./workspace-knowledge-graph-change-overlay-FIIAFLO6.js'),H=B(Y,O);if(n.json){console.log(JSON.stringify(H,null,2));return}console.log(s.green("\u2714 Workspace graph change overlay")),console.log(s.gray(` Base: ${L}`)),console.log(s.gray(` Risk: ${H.summary.risk}`)),console.log(s.gray(` Entities: +${H.summary.entityAdds} -${H.summary.entityRemovals} ~${H.summary.entityChanges}`)),console.log(s.gray(` Relations: +${H.summary.relationAdds} -${H.summary.relationRemovals} ~${H.summary.relationChanges}`)),console.log(s.gray(` Proofs: +${H.summary.proofAdds} -${H.summary.proofRemovals} ~${H.summary.proofChanges}`)),console.log(s.gray(` Impacted: ${H.summary.impactedEntities} entities \xB7 ${H.summary.changedArtifacts} proof artifacts`));return}let J=k(D),{writeWorkspaceModel:ae}=await import('./workspace-model-LBICKRVI.js');await ae(V,d,{refreshKnowledgeGraph:C});let pe=await M__default.readJson(b.join(d,p.knowledgeGraph)),se={...J,knowledgeGraph:pe},qe=l();if(qe){let L=b.resolve(d,qe);await M__default.outputFile(L,`${JSON.stringify(se,null,2)}
|
|
426
|
+
`,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace graph emit",{format:"json",nodeCount:D.stats.nodeCount,edgeCount:D.stats.edgeCount,entityCount:pe.entities.length,relationCount:pe.relations.length,proofCount:pe.proofs.length},L),null,2)):(console.log(s.green("\u2714 Workspace graph artifact exported as JSON")),console.log(s.gray(` Written: ${L}`)));return}if(n.json){console.log(JSON.stringify(se,null,2));return}console.log(s.green("\u2714 Workspace dependency graph")),console.log(s.gray(` Nodes: ${J.graph.stats.nodeCount}`)),console.log(s.gray(` Edges: ${J.graph.stats.edgeCount} (inferred ${J.graph.stats.inferredEdges}, contract ${J.graph.stats.contractEdges}, manual ${J.graph.stats.manualEdges})`)),console.log(s.gray(` Integrity: ${J.integrity.ok?"ok":"issues"} (cycles ${J.integrity.stats.cycleCount}, dangling ${J.integrity.stats.danglingCount}, orphans ${J.integrity.stats.orphanCount})`)),console.log(s.gray(` Hotspots: ${J.hotspots.join(", ")||"none"}`)),console.log(s.gray(` Knowledge: ${pe.quality.entityCount} entities \xB7 ${pe.quality.relationCount} relations \xB7 ${pe.quality.proofCount} proofs \xB7 ${pe.providers.length} providers`));let Ye=(pe.source.inputs?.scopes??[]).filter(L=>L.truncated),Ee=pe.quality.completeness;if(Ye.length>0?console.log(s.yellow(` Inventory: emergency-bounded \u2014 ${Ye.map(L=>`${L.kind}:${L.id} indexed ${L.fileCount}/${L.eligibleFileCountExact===false?"at-least-":""}${L.eligibleFileCount??L.fileCount} eligible files`).join(", ")}`)):console.log(s.gray(` Inventory: complete \u2014 ${Ee?.inventory.indexedFiles??(pe.source.inputs?.scopes??[]).reduce((L,G)=>L+G.fileCount,0)} eligible files indexed across ${Ee?.inventory.scopeCount??(pe.source.inputs?.scopes??[]).length} scope(s)`)),Ee){let L=`${Ee.providers.complete} complete \xB7 ${Ee.providers.bounded} adaptive-bounded \xB7 ${Ee.providers.notApplicable} not-applicable \xB7 ${Ee.providers.failed} failed`;console.log(Ee.status==="complete"?s.gray(` Provider coverage: ${L}`):s.yellow(` Provider coverage: ${L}`));}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 d=a("watch"),{runWorkspaceWatch:g}=await import('./workspace-watch-BKIZQ2SM.js'),w=n.once===true||i("--once"),k=n.graphStream===true||i("--graph-stream"),h=n.json===true||k,v=k?new(await import('./workspace-graph-stream-26ME2JJS.js')).WorkspaceGraphStreamPublisher({workspacePath:d}):null,I=new AbortController,x=()=>I.abort();process.once("SIGINT",x),process.once("SIGTERM",x),h||console.log(s.green("\u2714 Workspace watch (model + graph kept in memory)")),await g({workspacePath:d,once:w,signal:I.signal,buildOptions:{workspacePath:d,observableScanDepth:p$1()},onProgress:j=>{h||console.error(s.gray(` ${j}`));},onModel:v?async j=>{let R=(await import('./workspace-model-LBICKRVI.js')).workspaceModelProjectTopology(j);if(!R)return;let{buildWorkspaceKnowledgeGraph:C}=await import('./workspace-knowledge-graph-4RSZTEFJ.js'),{readWorkspaceContract:_}=await import('./workspace-contract-N2BJCAJ7.js'),N=null;try{N=(await _({workspacePath:d})).contract;}catch{}let V=await C({...u(),workspacePath:d,workspace:{name:j.workspace.name,...j.workspace.profile?{profile:j.workspace.profile}:{}},projects:j.projects.map(D=>({id:D.name,path:D.path,...D.absolutePath?{absolutePath:D.absolutePath}:{},runtime:D.runtime,runtimeCandidates:D.runtimeCandidates,framework:D.framework,...D.kit?{kit:D.kit}:{}})),projectTopology:R,contract:N,now:new Date(j.generatedAt),source:{kind:"workspace-model",artifact:p.model,hashAlgorithm:"sha256",hash:(await import('./workspace-model-hash-ZXYPIGCW.js')).hashWorkspaceModel(j)}});console.log(JSON.stringify(v.publish(j,V)));}:void 0,emit:j=>{if(k)return;if(h){console.log(JSON.stringify(j));return}if(j.kind==="ready"){console.log(s.gray(` Ready: ${j.graph.nodeCount} nodes, ${j.graph.edgeCount} edges (hash ${j.modelHash.slice(0,12)})`));return}if(j.kind==="error"){console.error(s.red(` \u2717 Rebuild failed: ${j.error??"unknown error"}`));return}if(j.kind==="unchanged"){console.log(s.gray(` No structural change (${j.mode}, ${j.durationMs}ms)`));return}let R=[];j.changedProjects.length>0&&R.push(`changed: ${j.changedProjects.join(", ")}`),j.addedProjects.length>0&&R.push(`added: ${j.addedProjects.join(", ")}`),j.removedProjects.length>0&&R.push(`removed: ${j.removedProjects.join(", ")}`),j.graph.edgesAdded.length>0&&R.push(`+${j.graph.edgesAdded.length} edges`),j.graph.edgesRemoved.length>0&&R.push(`-${j.graph.edgesRemoved.length} edges`),console.log(s.cyan(` \u21BB Changed (${j.mode}, ${j.durationMs}ms): ${R.join("; ")||"structure updated"}`));}}),process.removeListener("SIGINT",x),process.removeListener("SIGTERM",x),!h&&!w&&console.log(s.gray(" Watch stopped."));return}else if(t==="sync"){let d=a("sync"),{syncWorkspaceProjects:g}=await import('./workspace-AXU6ODER.js');n.json||console.log(s.cyan(`\u{1F4C2} Scanning workspace: ${b.basename(d)}`));let w=await g(d,n.json===true);await Mr(d,{silent:n.json===true});let{syncWorkspaceProjectLenses:k}=await import('./project-intelligence-lens-OQTZ4K7L.js'),h=await k({workspacePath:d,mode:n.projectGrounding??"managed"}),{readWorkspaceRegistrySummary:v}=await import('./workspace-registry-summary-3PXZENLC.js'),I=await v(d);n.json&&console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-sync-v1",workspacePath:d,registry:w,contractSynced:true,projectLenses:{synced:h.projects.length,skipped:h.skipped},registrySummary:I},null,2));}else if(t==="registry"){let d=a("registry"),g=e||"status";g!=="status"&&(console.log(s.red(`\u274C Unknown workspace registry action: ${g}`)),console.log(s.gray(" npx workspai workspace registry status [--refresh] [--json]")),process.exit(1));let{publishWorkspaceRegistrySummary:w,resolveWorkspaceRegisteredProjects:k}=await import('./workspace-registry-summary-3PXZENLC.js'),h=await w(d);if(n.json){console.log(JSON.stringify(h,null,2));return}let v=await k(d);console.log(s.cyan("Workspace registry")),console.log(s.gray(` Authority: ${h.authority}`)),console.log(s.gray(` Projects: ${h.projectCount}`)),console.log(s.gray(` Summary: ${h.registrySummaryPath}`)),v.summary.projectCount===0&&console.log(s.yellow(" No registered projects \u2014 run workspace sync after adding projects."));}else if(t==="foundation"){let d=a("foundation"),g=e||"ensure";g!=="ensure"&&(console.log(s.red(`\u274C Unknown workspace foundation action: ${g}`)),console.log(s.gray(" npx workspai workspace foundation ensure [--force] [--json]")),process.exit(1));let{ensureWorkspaceFoundation:w}=await import('./workspace-foundation-GYL3D7TW.js'),k=await w(d,{force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(k,null,2));return}k.created.length>0?console.log(s.green(`\u2714 Workspace foundation ensured: ${k.created.join(", ")}`)):console.log(s.gray("Workspace foundation files are already up to date."));}else if(t==="policy"){let d=a("policy"),g=await Th(d,e,r,o,n.json===true||i("--json"));g!==0&&process.exit(g);}else if(t==="contract"){let d=a("contract"),{buildWorkspaceContractGraph:g,readWorkspaceContract:w,syncWorkspaceContract:k,verifyWorkspaceContract:h,writeWorkspaceContract:v,WORKSPACE_CONTRACT_PATH:I}=await import('./workspace-contract-N2BJCAJ7.js'),x=e||"inspect",j=l(),R=x==="graph"||x==="sync"?void 0:j;try{if(x==="init"){let C=await v({workspacePath:d,outputPath:R,force:n.force===true||i("--force")});if(n.json){console.log(JSON.stringify(C,null,2));return}console.log(s.green(`\u2714 Workspace contract initialized: ${C.contractPath}`)),console.log(s.gray(` Projects: ${C.contract.projects.length}`));return}if(x==="inspect"){let C=await w({workspacePath:d,contractPath:R});if(n.json){console.log(JSON.stringify(C,null,2));return}console.log(s.green(`\u2714 Workspace contract: ${C.contractPath}`)),console.log(s.gray(` Workspace: ${C.contract.workspace.name}`)),console.log(s.gray(` Projects: ${C.contract.projects.length}`)),console.log(s.gray(` Schema: v${C.contract.schemaVersion}`));return}if(x==="sync"){let C=await k({workspacePath:d,strict:n.strict===true||i("--strict")});if(n.json){console.log(JSON.stringify(C,null,2));return}console.log(s.green(`\u2714 Workspace contract synchronized: ${C.contractPath}`)),console.log(s.gray(` Projects: ${C.contract.projects.length}`)),console.log(s.gray(` Added: ${C.addedProjects.join(", ")||"none"}`)),console.log(s.gray(` Updated: ${C.updatedProjects.join(", ")||"none"}`));return}if(x==="verify"){let C=await h({workspacePath:d,contractPath:R,strict:n.strict===true||i("--strict")}),{writeWorkspaceContractVerifyEvidence:_}=await import('./workspace-contract-N2BJCAJ7.js'),N=await _({workspacePath:d,result:C});if(n.json)console.log(JSON.stringify({...C,evidencePath:N},null,2));else {let V=C.status==="passed"?s.green:s.red;console.log(V(`\u2714 Workspace contract verification ${C.status}: ${C.contractPath}`)),console.log(s.gray(` Projects: ${C.projectCount}`));for(let D of C.checks){let q=D.status==="passed"?"\u2714":"\u2718";console.log(s.gray(` ${q} ${D.id}: ${D.message}`));}for(let D of C.violations)console.log(s.gray(` Violation: ${D}`));}(C.status==="failed"||C.status!=="passed"&&n.strict)&&process.exit(1);return}if(x==="graph"){let C=await g({workspacePath:d,contractPath:R});if(j){let _=b.resolve(d,j);await M__default.outputFile(_,`${JSON.stringify(C,null,2)}
|
|
427
|
+
`,"utf8"),n.json?console.log(JSON.stringify(b$6("workspace contract graph",{projectCount:C.graph.summary.projectCount,relationshipEdges:C.graph.summary.relationshipEdges,entityCount:C.graph.summary.entityCount,knowledgeRelations:C.graph.summary.knowledgeRelations,proofCount:C.graph.summary.proofCount},_),null,2)):(console.log(s.green("\u2714 Workspace contract graph exported as JSON")),console.log(s.gray(` Written: ${_}`)));return}if(n.json){console.log(JSON.stringify(C,null,2));return}console.log(s.green(`\u2714 Workspace contract graph: ${C.contractPath}`)),console.log(s.gray(` Workspace: ${C.graph.workspace.name}`)),console.log(s.gray(` Projects: ${C.graph.summary.projectCount}`)),console.log(s.gray(` Dependencies: ${C.graph.summary.dependencyEdges}`)),console.log(s.gray(` Event links: ${C.graph.summary.eventEdges}`)),console.log(s.gray(` Evidence-backed relationships: ${C.graph.summary.relationshipEdges} (${C.graph.summary.inferredEdges} inferred, ${C.graph.summary.authoritativeEdges} authoritative)`)),console.log(s.gray(` Connected projects: ${C.graph.summary.connectedProjects}/${C.graph.summary.projectCount} \xB7 Edge coverage: ${Math.round(C.graph.summary.edgeCoverageRatio*100)}% \xB7 Evidence coverage: ${Math.round(C.graph.summary.evidenceCoverageRatio*100)}%`)),console.log(s.gray(` Orphans: ${C.graph.summary.orphanProjects} \xB7 Hotspots: ${C.graph.summary.hotspotProjects} \xB7 Low-confidence edges: ${C.graph.summary.lowConfidenceEdges} \xB7 Cycles: ${C.graph.summary.hasCycle?"yes":"no"}`)),console.log(s.gray(` Knowledge: ${C.graph.summary.entityCount} entities \xB7 ${C.graph.summary.knowledgeRelations} relations \xB7 ${C.graph.summary.proofCount} proofs \xB7 ${C.graph.summary.providerCount} providers \xB7 ${C.graph.summary.knowledgeUnknowns} unknown(s)`)),console.log(s.gray(` Ports: ${C.graph.summary.portCount}`));for(let _ of C.graph.nodes){let N=_.ports.map(D=>`${D.name}:${D.port}`).join(", ")||"none",V=_.operationalProfile?` risk=${_.operationalProfile.weight}/${_.operationalProfile.verificationPriority}`:"";console.log(s.gray(` \u2022 ${_.id} (${_.runtime||"unknown"}${_.framework?`/${_.framework}`:""}) ports=${N} manifests=${_.files.manifests.length}${V}`));}for(let _ of C.graph.edges){let N=_.type==="event"?`event:${_.label}`:_.label;console.log(s.gray(` ${_.from} -> ${_.to} [${N}]`));}if(C.graph.dependencyGraph.edges.length>0){console.log(s.gray(" Evidence-backed dependency direction (consumer -> dependency):"));for(let _ of C.graph.dependencyGraph.edges)console.log(s.gray(` ${_.from} -> ${_.to} [${_.kind}/${_.source}/${_.confidence}] evidence=${_.evidence.length}`));}for(let _ of C.graph.dependencyGraph.diagnostics||[])console.log(s.gray(` ${_.severity}: ${_.message}`));return}console.log(s.red(`\u274C Unknown workspace contract action: ${x}`)),console.log(s.white(` npx workspai workspace contract init|inspect|sync|verify|graph [--output ${I}]`)),process.exit(1);}catch(C){n.json&&(console.log(JSON.stringify({command:`workspace contract ${x}`,result:"error",workspacePath:d,timestamp:new Date().toISOString(),error:{code:`workspace.contract.${x}.failed`,message:C.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace contract ${x} failed: ${C.message}`)),process.exit(1);}}else if(t==="share"){let d=a("share"),g=l()||e,{createWorkspaceShareBundle:w}=await import('./workspace-AXU6ODER.js'),k=await w(d,{outputPath:g,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:d,bundlePath:k,options:{includePaths:n.includePaths===true,includeDoctorEvidence:n.doctor!==false,includeBlueprint:n.blueprint!==false}},null,2));return}console.log(s.green(`\u2714 Workspace share bundle exported: ${k}`)),console.log(s.gray("Share this JSON with your team for reproducible workspace/project diagnostics."));}else if(t==="export"){let d=a("export");try{let{exportWorkspaceArchive:g}=await import('./workspace-archive-3AURTMYA.js'),w=n.archiveCompression?.trim().toLowerCase()??"store";if(w!=="store"&&w!=="deflate")throw new Error("--archive-compression must be store or deflate.");let k=await g({workspacePath:d,outputPath:l()||e,includeEnv:n.includeEnv===true||i("--include-env"),compression:w});if(n.json){console.log(JSON.stringify(k,null,2));return}let h=(k.bytesWritten/(1024*1024)).toFixed(2);console.log(s.green(`\u2714 Workspace archive exported: ${k.archivePath}`)),console.log(s.gray(` Files: ${k.manifest.files.length}`)),console.log(s.gray(` Size: ${h} MB`)),k.manifest.security.envFilesIncluded||console.log(s.gray(" Secrets: excluded (.env, private keys, logs, dependency caches)"));}catch(g){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:"export",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.archive.export.failed",message:g.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive export failed: ${g.message}`)),process.exit(1);}}else if(t==="archive"&&(e==="inspect"||e==="verify"||e==="doctor")){let d=r;d||(n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),error:{code:`workspace.archive.${e}.input-required`,message:`workspace archive ${e} requires an archive path or URL.`}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace archive ${e} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace archive ${e} team.workspai-archive.zip`)),process.exit(1));let{doctorWorkspaceArchive:g,inspectWorkspaceArchive:w,verifyWorkspaceArchive:k}=await import('./workspace-archive-3AURTMYA.js');try{if(e==="inspect"){let v=await w({archivePathOrUrl:d,safety:P()});if(n.json){console.log(JSON.stringify(v,null,2));return}let I=(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: ${I} MB`));return}if(e==="doctor"){let v=await g({archivePathOrUrl:d,strict:n.strict===true||i("--strict"),safety:P()});if(n.json)console.log(JSON.stringify(v,null,2));else {let I=v.status==="passed"?s.green:v.status==="warning"?s.yellow:s.red;console.log(I(`\u2714 Workspace archive doctor ${v.status}: ${v.archivePath}`)),console.log(s.gray(` Workspace: ${v.workspaceName}`)),console.log(s.gray(` Files: ${v.fileCount}`));for(let x of v.checks){let j=x.status==="passed"?"\u2714":x.status==="warning"?"\u26A0":"\u2718";console.log(s.gray(` ${j} ${x.id}: ${x.message}`));}for(let x of v.recommendedActions)console.log(s.gray(` Next: ${x}`));}(v.status==="failed"||v.status==="warning"&&n.strict)&&process.exit(1);return}let h=await k({archivePathOrUrl:d,requireChecksums:n.strict===true||i("--strict"),safety:P()});if(n.json)console.log(JSON.stringify(h,null,2));else if(h.status==="passed")console.log(s.green(`\u2714 Workspace archive verified: ${h.archivePath}`)),console.log(s.gray(` Files: ${h.verifiedFiles}/${h.fileCount}`));else {let v=h.status==="failed"?s.red:s.yellow;console.log(v(`\u274C Workspace archive verification ${h.status}: ${h.archivePath}`)),h.missingArchiveEntries.length&&console.log(s.gray(` Missing entries: ${h.missingArchiveEntries.join(", ")}`)),h.extraArchiveEntries.length&&console.log(s.gray(` Unexpected entries: ${h.extraArchiveEntries.join(", ")}`)),h.mismatches.length&&console.log(s.gray(` Mismatches: ${h.mismatches.map(I=>I.path).join(", ")}`)),h.missingChecksumFiles.length&&console.log(s.gray(` Missing checksums: ${h.missingChecksumFiles.join(", ")}`));}(h.status==="failed"||h.status==="warning"&&n.strict)&&process.exit(1);}catch(h){n.json&&(console.log(JSON.stringify({schemaVersion:c$3,operation:e,status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:d,error:{code:`workspace.archive.${e}.failed`,message:h.message}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace archive ${e} failed: ${h.message}`)),process.exit(1);}}else if(t==="connect"){let d=b.resolve(e||process.cwd());try{let g=await Ts({workspacePath:d,dryRun:n.dryRun===true||i("--dry-run"),projectGrounding:n.projectGrounding});if(n.json){console.log(JSON.stringify(g,null,2));return}console.log(s.green(g.status==="preview"?`\u2714 Workspace connection preview: ${d}`:`\u2714 Workspace connected: ${d}`));for(let w of g.warnings)console.log(s.yellow(` \u26A0 ${w}`));}catch(g){let w=g instanceof Error?g.message:String(g);n.json?console.log(JSON.stringify(c$1({operation:"workspace connect",code:"workspace.connect.failed",message:w}),null,2)):console.log(s.red(`\u274C Workspace connect failed: ${w}`)),process.exit(1);}}else if(t==="hydrate"||t==="import"){let d=e;d||(n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.input-required",message:"workspace import requires an archive path or URL."}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),error:{code:"workspace.hydrate.input-required",message:"workspace hydrate requires an archive path or URL."}},null,2)),process.exit(1)),console.log(s.red(`\u274C workspace ${t} requires an archive path or URL.`)),console.log(s.white(` npx workspai workspace ${t} team.workspai-archive.zip --output ./team`)),process.exit(1));try{if(t==="import"){let g=await Ms({archivePathOrUrl:d,outputPath:l(),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),projectGrounding:n.projectGrounding,safety:P()});if(n.json){console.log(JSON.stringify(g,null,2));return}console.log(s.green(g.status==="preview"?`\u2714 Workspace import preview: ${g.workspacePath}`:`\u2714 Workspace imported and registered: ${g.workspacePath}`));for(let w of g.warnings)console.log(s.yellow(` \u26A0 ${w}`));}else {let{hydrateWorkspaceArchive:g}=await import('./workspace-archive-3AURTMYA.js'),w=await g({archivePathOrUrl:d,outputPath:l(),force:n.force===true||i("--force"),dryRun:n.dryRun===true||i("--dry-run"),strict:n.strict===true||i("--strict"),safety:P()});if(n.json){console.log(JSON.stringify(w,null,2));return}console.log(s.green(w.dryRun?`\u2714 Workspace archive hydrate preview: ${w.outputPath}`:`\u2714 Workspace archive hydrated: ${w.outputPath}`)),console.log(s.gray(` Files: ${w.files.length}`)),w.manifest?.workspaceName&&console.log(s.gray(` Workspace: ${w.manifest.workspaceName}`));}}catch(g){let w=g instanceof Error?g.message:String(g);n.json&&(t==="import"&&(console.log(JSON.stringify(c$1({operation:"workspace import",code:"workspace.import.failed",message:w,context:{archivePathOrUrl:d,...l()?{outputPath:l()}:{}}}),null,2)),process.exit(1)),console.log(JSON.stringify({schemaVersion:c$3,operation:"hydrate",status:"error",timestamp:new Date().toISOString(),archivePathOrUrl:d,...l()?{outputPath:l()}:{},dryRun:n.dryRun===true||i("--dry-run"),error:{code:`workspace.${t}.failed`,message:w}},null,2)),process.exit(1)),console.log(s.red(`\u274C Workspace ${t} failed: ${w}`)),process.exit(1);}}else if(t==="run"){let d=a(`run ${e||""}`.trim()),g=new Set(["init","test","build","start"]),w=e?.trim()??"";w||(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)),g.has(w)||(!/^[a-z][a-z0-9_-]*$/i.test(w)||w==="dev"||w==="stop")&&(console.log(s.red(`Unknown workspace run stage: ${w}`)),console.log(s.gray("Available stages: init | test | build | start | <custom-from-context>")),w==="dev"&&console.log(s.gray(" Note: dev is excluded \u2014 it is a local-only primitive, not a CI stage")),process.exit(2));let k=Us({raw:n.maxWorkers,operation:`workspace run ${w}`,json:n.json===true||i("--json")});if(w==="init"&&n.json!==true){let I=await ti(d);I!==0&&process.exit(I);}let{runWorkspaceStage:h}=await import('./workspace-run-VDQ6BYLS.js'),v=await h({workspacePath:d,stage:w,scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:k,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates,reusePassed:n.reusePassed===true,planOnly:n.plan===true,runtime:n.runtime});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 d=a(t),{parseWorkspaceExplainTarget:g}=await import('./workspace-explain-contract-KV7RTEJU.js'),{buildWorkspaceExplain:w,writeWorkspaceExplainReport:k}=await import('./workspace-explain-5WKK6ENK.js'),h=(e??r??"").trim();!h&&n.scope&&(h=n.scope.startsWith("project:")?n.scope:`project:${n.scope}`),h||(h="release-blocked");let v=g(h);v||(console.log(s.red(`\u274C Invalid explain target: ${h}`)),process.exit(1));let I=await w({workspacePath:d,target:v}),x=n.write===true||i("--write"),j;if(x&&(j=await k(I,d,t==="why"?"why":"explain")),n.json){console.log(JSON.stringify(b$6(`workspace ${t}`,I,j),null,2));return}console.log(s.green(`\u2714 Workspace ${t==="why"?"why":"explain"}: ${I.summary}`));for(let R of I.sections)console.log(s.bold(`
|
|
427
428
|
${R.title}`)),console.log(R.body);j&&console.log(s.gray(`
|
|
428
|
-
Written: ${j}`));}else if(t==="trace"){let d=a("trace"),g=n.from||e;g||(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:w}=await import('./workspace-explain-contract-KV7RTEJU.js'),{buildWorkspaceExplain:k,writeWorkspaceExplainReport:h}=await import('./workspace-explain-
|
|
429
|
+
Written: ${j}`));}else if(t==="trace"){let d=a("trace"),g=n.from||e;g||(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:w}=await import('./workspace-explain-contract-KV7RTEJU.js'),{buildWorkspaceExplain:k,writeWorkspaceExplainReport:h}=await import('./workspace-explain-5WKK6ENK.js'),v=w(g);(!v||v.kind!=="trace")&&(console.log(s.red(`\u274C Invalid trace ref: ${g}`)),console.log(s.gray(" Use a diff artifact path or trace:<path>, e.g. trace:.workspai/reports/workspace-model-diff-last-run.json")),process.exit(1));let I=await k({workspacePath:d,target:v}),x=n.write===true||i("--write"),j;if(x&&(j=await h(I,d,"trace")),n.json){console.log(JSON.stringify(b$6("workspace trace",I,j),null,2));return}console.log(s.green(`\u2714 Workspace trace: ${I.summary}`));for(let R of I.sections)console.log(s.bold(`
|
|
429
430
|
${R.title}`)),console.log(R.body);j&&console.log(s.gray(`
|
|
430
431
|
Written: ${j}`));}else if(t==="eval"){let d=a("eval"),g=(e||"status").toLowerCase(),{WORKSPACE_EVALUATION_LAST_RUN_PATH:w,WORKSPACE_EVALUATION_LIVE_PATH:k,appendWorkspaceEvaluationEvent:h,compareWorkspaceEvaluations:v,createWorkspaceEvaluation:I,finalizeWorkspaceEvaluation:x,readWorkspaceEvaluation:j,writeWorkspaceEvaluation:R}=await import('./workspace-intelligence-evaluation-4AB4BBRP.js');if(g==="init"){let C=(r||"").trim(),_=(o||"workspace-intelligence").trim(),N=["full-corpus","grep","vector","graph","workspace-intelligence","custom"];(!C||!N.includes(_))&&(console.log(s.red("\u274C workspace eval init requires <task> and an optional valid strategy.")),console.log(s.gray(` Strategies: ${N.join(" | ")}
|
|
431
|
-
npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:V}=await import('./workspace-marker-7U3NYRPJ.js'),D=await V(d),q=I({workspacePath:d,workspaceName:D?.name,taskId:C,strategy:_}),J=await R(d,q);if(n.json){console.log(JSON.stringify(b$6("workspace eval init",q,J),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${C}`)),console.log(s.gray(` Run: ${q.runId}`)),console.log(s.gray(` Strategy: ${q.configuration.strategy}`)),console.log(s.gray(` Live: ${J}`));return}if(g==="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:C,readStdinAll:_}=await import('./workspace-feedback-FF34CSJE.js'),N=C(await _());N||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let V=await h({workspacePath:d,payload:N});console.log(JSON.stringify(V,null,2));}catch(V){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:V instanceof Error?V.message:String(V),context:{workspacePath:d}}),null,2)),process.exit(1);}return}if(g==="report"){let C=await x({workspacePath:d}),_=l(),N=C.outputPath;if(_){let V=b.resolve(d,_);b.resolve(C.outputPath)!==V&&await M__default.copy(C.outputPath,V,{overwrite:true}),N=V;}if(n.json){console.log(JSON.stringify(b$6("workspace eval report",C.report,N),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${C.report.runId}`)),console.log(s.gray(` Tokens: ${C.report.summary.tokens.observedTotal} \xB7 model calls ${C.report.summary.modelCalls} \xB7 tool calls ${C.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${C.report.summary.outcome.status}${C.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${N}`));return}if(g==="compare"){let C=(n.from||r||"").trim();C||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let _=await j(d,w),N=await j(d,C),V=v(_,N);if(n.json){console.log(JSON.stringify(V,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${V.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${V.delta.tokens}`)),console.log(s.gray(` Reduction: ${V.delta.reductionPercent===null?"unavailable":`${V.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${V.comparableOutcome?"yes":"no"}`));return}if(g==="status"){let C;try{C=await j(d,k);}catch{C=await j(d,w);}if(n.json){console.log(JSON.stringify(C,null,2));return}console.log(s.green(`\u2714 Evaluation ${C.status}: ${C.configuration.taskId}`)),console.log(s.gray(` Run: ${C.runId}`)),console.log(s.gray(` Events: ${C.events.length}`)),console.log(s.gray(` Tokens: ${C.summary.tokens.observedTotal} (${C.summary.tokenSources.providerReported} provider-reported calls, ${C.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${g}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let d=a("feedback"),g=(e||"record").toLowerCase();g!=="record"&&(console.log(s.red(`Unknown feedback action: ${g}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!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:w,parseFeedbackStdinPayload:k,readStdinAll:h}=await import('./workspace-feedback-FF34CSJE.js'),v=await h(),I=k(v);I||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let x=await w({workspacePath:d,payload:I});n.json?console.log(JSON.stringify(x,null,2)):x.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${x.historyPath}`))):console.log(s.red(`\u274C ${x.error??"Failed to record feedback"}`)),x.ok||process.exit(1);}else if(t==="goal"){let d=a("goal"),g=(e||"status").toLowerCase(),w=r?.trim(),{planVerifiedGoal:k,readVerifiedGoal:h,verifyVerifiedGoal:v,VERIFIED_GOAL_SCHEMA_VERSION:I}=await import('./verified-goal-
|
|
432
|
+
npx workspai workspace eval init repair-readiness workspace-intelligence --json`)),process.exit(1));let{readWorkspaceMarker:V}=await import('./workspace-marker-7U3NYRPJ.js'),D=await V(d),q=I({workspacePath:d,workspaceName:D?.name,taskId:C,strategy:_}),J=await R(d,q);if(n.json){console.log(JSON.stringify(b$6("workspace eval init",q,J),null,2));return}console.log(s.green(`\u2714 Evaluation started: ${C}`)),console.log(s.gray(` Run: ${q.runId}`)),console.log(s.gray(` Strategy: ${q.configuration.strategy}`)),console.log(s.gray(` Live: ${J}`));return}if(g==="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:C,readStdinAll:_}=await import('./workspace-feedback-FF34CSJE.js'),N=C(await _());N||(console.log(s.red("\u274C Invalid or empty evaluation event JSON on stdin.")),process.exit(1));try{let V=await h({workspacePath:d,payload:N});console.log(JSON.stringify(V,null,2));}catch(V){console.log(JSON.stringify(c$1({operation:"workspace eval record",code:"workspace.eval.event_invalid",message:V instanceof Error?V.message:String(V),context:{workspacePath:d}}),null,2)),process.exit(1);}return}if(g==="report"){let C=await x({workspacePath:d}),_=l(),N=C.outputPath;if(_){let V=b.resolve(d,_);b.resolve(C.outputPath)!==V&&await M__default.copy(C.outputPath,V,{overwrite:true}),N=V;}if(n.json){console.log(JSON.stringify(b$6("workspace eval report",C.report,N),null,2));return}console.log(s.green(`\u2714 Evaluation finalized: ${C.report.runId}`)),console.log(s.gray(` Tokens: ${C.report.summary.tokens.observedTotal} \xB7 model calls ${C.report.summary.modelCalls} \xB7 tool calls ${C.report.summary.toolCalls}`)),console.log(s.gray(` Outcome: ${C.report.summary.outcome.status}${C.report.summary.outcome.verified?" (verified)":" (unverified)"}`)),console.log(s.gray(` Written: ${N}`));return}if(g==="compare"){let C=(n.from||r||"").trim();C||(console.log(s.red("\u274C workspace eval compare requires --from <baseline-report>.")),process.exit(1));let _=await j(d,w),N=await j(d,C),V=v(_,N);if(n.json){console.log(JSON.stringify(V,null,2));return}console.log(s.green("\u2714 Workspace Intelligence evaluation comparison")),console.log(s.gray(` Task aligned: ${V.taskAligned?"yes":"no"}`)),console.log(s.gray(` Token delta: ${V.delta.tokens}`)),console.log(s.gray(` Reduction: ${V.delta.reductionPercent===null?"unavailable":`${V.delta.reductionPercent}%`}`)),console.log(s.gray(` Comparable verified outcome: ${V.comparableOutcome?"yes":"no"}`));return}if(g==="status"){let C;try{C=await j(d,k);}catch{C=await j(d,w);}if(n.json){console.log(JSON.stringify(C,null,2));return}console.log(s.green(`\u2714 Evaluation ${C.status}: ${C.configuration.taskId}`)),console.log(s.gray(` Run: ${C.runId}`)),console.log(s.gray(` Events: ${C.events.length}`)),console.log(s.gray(` Tokens: ${C.summary.tokens.observedTotal} (${C.summary.tokenSources.providerReported} provider-reported calls, ${C.summary.tokenSources.estimated} estimated calls)`));return}console.log(s.red(`Unknown eval action: ${g}`)),console.log(s.gray("Available: init | record | status | report | compare")),process.exit(1);}else if(t==="feedback"){let d=a("feedback"),g=(e||"record").toLowerCase();g!=="record"&&(console.log(s.red(`Unknown feedback action: ${g}`)),console.log(s.gray("Available: record")),process.exit(1)),!n.json&&!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:w,parseFeedbackStdinPayload:k,readStdinAll:h}=await import('./workspace-feedback-FF34CSJE.js'),v=await h(),I=k(v);I||(console.log(s.red("\u274C Invalid or empty feedback JSON on stdin")),process.exit(1));let x=await w({workspacePath:d,payload:I});n.json?console.log(JSON.stringify(x,null,2)):x.ok?(console.log(s.green("\u2714 Workspace feedback recorded")),console.log(s.gray(` History: ${x.historyPath}`))):console.log(s.red(`\u274C ${x.error??"Failed to record feedback"}`)),x.ok||process.exit(1);}else if(t==="goal"){let d=a("goal"),g=(e||"status").toLowerCase(),w=r?.trim(),{planVerifiedGoal:k,readVerifiedGoal:h,verifyVerifiedGoal:v,VERIFIED_GOAL_SCHEMA_VERSION:I}=await import('./verified-goal-VB7IOTNO.js'),x=j=>{if(n.json){console.log(JSON.stringify(j,null,2));return}let R=j.goal;console.log(j.status.state==="verified"?s.green("\u2714 Verified goal satisfied"):s.cyan(j.resumed?"\u21BB Verified goal resumed":"\u25C6 Verified goal ready")),R&&console.log(s.bold(` ${R.summary}`)),console.log(s.gray(` Goal: ${j.status.goalId}`)),console.log(s.gray(` Progress: ${j.status.progress.message}`)),console.log(s.gray(` State: ${j.status.state}`)),j.status.blockingReasons.length>0&&console.log(s.gray(` Remaining: ${j.status.blockingReasons[0]}`)),j.status.nextActions.length>0&&console.log(s.gray(` Next: ${j.status.nextActions[0]}`)),console.log(s.gray(` Status: ${j.status.artifactPath}`));};if(g==="plan"){if(!w||!["release-readiness","dependency-security","test-coverage"].includes(w)){let V="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:V}),null,2)):console.log(s.red(`\u274C ${V}`)),process.exit(1);}let R=Number(n.target??80);if(!Number.isFinite(R)||R<0||R>100)throw new Error("--target must be a number from 0 to 100.");let C=["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"],_=n.runtime;if(w==="test-coverage"&&_!==void 0&&!C.includes(_))throw new Error(`--runtime must be one of: ${C.join(", ")}.`);let N=await k({workspacePath:d,kind:w,scope:n.scope,target:R,runtime:w==="test-coverage"?_:void 0,allowBreakingChanges:n.allowBreaking===true,allowForce:n.allowForce===true,requireBuild:n.build!==false,requireTests:n.tests!==false});x(N);}else if(g==="status"){if(!w)throw new Error("workspace goal status requires a goal id.");let j=await h(d,w);x({...j,resumed:j.status.state!=="verified"});}else if(g==="verify"){if(!w)throw new Error("workspace goal verify requires a goal id.");let j=await h(d,w),R=await v({workspacePath:d,goalId:w,run:n.run!==false,runIntelligence:n.reuseIntelligence!==true});x({goal:j.goal,status:R}),R.state!=="verified"&&process.exit(2);}else {let j=`Unknown workspace goal action: ${g}`;n.json?console.log(JSON.stringify(c$1({operation:"workspace goal",code:"workspace.goal.action.invalid",message:j,context:{schemaVersion:I,availableActions:["plan","status","verify"]}}),null,2)):console.log(s.red(`\u274C ${j}`)),process.exit(1);}}else if(t==="mcp"){let d=a("mcp"),g=(e||"serve").toLowerCase();g!=="serve"&&(n.json&&(console.log(JSON.stringify({command:"workspace mcp",action:g,result:"error",workspacePath:d,timestamp:new Date().toISOString(),error:{code:"workspace.mcp.unknown_action",message:`Unknown mcp action: ${g}`},availableActions:["serve"]},null,2)),process.exit(1)),console.log(s.red(`Unknown mcp action: ${g}`)),console.log(s.gray("Available: serve")),process.exit(1));let{runWorkspaceMcpServe:w}=await import('./workspace-mcp-serve-BSA6Q4EB.js');n.json||console.error(s.gray("\u2139 Workspai MCP server (read-mostly) listening on stdio JSON-RPC\u2026")),await w({workspacePath:d});}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:
|
|
432
433
|
npx workspai init | npx workspai workspace init | npx workspai workspace run init
|
|
433
|
-
`)));let d=a("init"),g=
|
|
434
|
-
`)),console.log(s.cyan(` ${
|
|
435
|
-
`)),Dh==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${
|
|
434
|
+
`)));let d=a("init"),g=Us({raw:n.maxWorkers,operation:"workspace init",json:n.json===true||i("--json")});if(n.json!==true){let h=await ti(d);h!==0&&process.exit(h);}let{runWorkspaceStage:w}=await import('./workspace-run-VDQ6BYLS.js'),k=await w({workspacePath:d,stage:"init",scope:n.scope,affected:n.affected===true,blastRadius:n.blastRadius===true,since:n.since,parallel:n.parallel===true,maxWorkers:g,continueOnError:n.continueOnError===true,strict:n.strict===true,json:n.json===true,enforceGates:n.gates});n.json&&console.log(JSON.stringify(k,null,2)),k.summary.exitCode!==0&&process.exit(k.summary.exitCode);}else (n.json===true||i("--json"))&&(console.log(JSON.stringify(c$1({operation:`workspace ${t}`,code:"workspace.action.unknown",message:`Unknown workspace action: ${t}`,context:{availableActions:yo}}),null,2)),process.exit(1)),console.log(s.red(`Unknown workspace action: ${t}`)),console.log(s.gray(`Available: ${yo.join(", ")}`)),process.exit(1);});function jo(t){let e="\u2500".repeat(46);console.log(""),console.log(s.gray(e)),console.log(s.bold(t)),console.log(s.gray(e));}function Fu(){let t=n=>n.replace(/\bnpx (?:rapidkit|workspai)\b/g,Ks),e=(n,a)=>{let i=t(n);if(i.length>65){console.log(s.cyan(` ${i}`)),console.log(s.gray(` ${a}`));return}console.log(s.cyan(` ${i.padEnd(67)} `)+s.gray(a));},r=(n,a)=>{console.log(s.white(` ${n}`));for(let i=0;i<a.length;i+=8)console.log(s.gray(` ${a.slice(i,i+8).join(" \xB7 ")}`));};console.log(s.white(`Usage:
|
|
435
|
+
`)),console.log(s.cyan(` ${Ks} <command> [options]
|
|
436
|
+
`)),Dh==="rapidkit"&&console.log(s.gray(` You are using the legacy rapidkit alias. New docs use ${Ks}.
|
|
436
437
|
`)),console.log(s.bold(`Open-Source Workspace Intelligence for Software Systems
|
|
437
438
|
`)),console.log(s.white("Connect projects, contracts, evidence, and checks so developers, CI, IDEs, and AI agents share one current view of the system.")),console.log(s.dim(`One workspace. One truth. Humans and AI aligned.
|
|
438
439
|
`)),jo("Workspace Lifecycle"),console.log(""),e("npx workspai create workspace my-workspace --profile minimal --yes","Start a new canonical workspace"),e("npx workspai create project","Choose an official frontend or backend kit interactively"),e("npx workspai create project nextjs web --yes","Scaffold an official kit and register the project"),e("npx workspai adopt .","Link the current project without moving its source"),e("npx workspai import <path|git-url>","Copy or clone software into a workspace"),e("npx workspai workspace intelligence run --for-agent generic --strict --json","Build or refresh the complete canonical evidence chain"),e("npx workspai agent bootstrap --for-agent <host> --strict --json","Prove agent entry before broad source discovery"),jo("Golden Path \xB7 Understand \u2192 Impact \u2192 Act \u2192 Verify"),console.log(""),e('npx workspai goal "<outcome>" --for-agent generic',"Auto-bind a project or choose a bounded multi-project scope"),e('npx workspai goal "<coverage outcome>" --scope projects:a,b --runtime node',"Bind automation explicitly to canonical projects and runtime"),e('npx workspai workspace graph search "<question>" --scope project:<name> --json',"Retrieve focused, proof-backed evidence"),e("npx workspai workspace diff --from git:HEAD~1 --json","Model what changed"),e("npx workspai workspace impact --from .workspai/reports/workspace-model-diff-last-run.json --json","Bound the affected system before action"),e("npx workspai workspace repair --help","Plan, approve, execute, verify, or roll back"),e("npx workspai workspace verify --strict --json","Prove canonical workspace evidence"),jo("Workspace Intelligence \xB7 What the loop builds"),console.log(s.gray(`
|
|
@@ -443,22 +444,22 @@ Written: ${j}`));}else if(t==="eval"){let d=a("eval"),g=(e||"status").toLowerCas
|
|
|
443
444
|
Flags clarification:`)),console.log(s.gray(" --skip-install npm fast-path for lock/dependency steps")),console.log(s.gray(` --skip-essentials core flag for skipping essential module installation
|
|
444
445
|
`)),Lh?(console.log(s.bold("Legacy (shown because RAPIDKIT_SHOW_LEGACY=1):")),console.log(s.gray(" npx workspai my-project --template fastapi")),console.log(s.gray(" npx workspai my-project --template nestjs")),console.log(s.gray(" npx workspai my-project --template springboot")),console.log(s.gray(" npx workspai my-project --template gofiber")),console.log(s.gray(" npx workspai my-project --template gogin")),console.log(s.gray(" npx workspai my-project --template dotnet")),console.log(s.gray(` --skip-install Fast-path lock/deps (legacy template mode) \u2014 not same as --skip-essentials
|
|
445
446
|
`))):console.log(s.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
|
|
446
|
-
`));}var Au="__rapidkit_signal_handlers_registered__",Ru=globalThis;Ru[Au]||(Ru[Au]=true,process.on("SIGINT",async()=>{if(!
|
|
447
|
+
`));}var Au="__rapidkit_signal_handlers_registered__",Ru=globalThis;Ru[Au]||(Ru[Au]=true,process.on("SIGINT",async()=>{if(!Xn){if(Xn=true,console.log(s.yellow(`
|
|
447
448
|
|
|
448
|
-
\u26A0\uFE0F Interrupted by user`)),Jt&&await M__default.pathExists(Jt)){console.log(s.gray("Cleaning up partial installation..."));try{await M__default.remove(Jt),console.log(s.green("\u2713 Cleanup complete"));}catch(t){e.debug("Cleanup failed:",t);}}b$7(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!
|
|
449
|
+
\u26A0\uFE0F Interrupted by user`)),Jt&&await M__default.pathExists(Jt)){console.log(s.gray("Cleaning up partial installation..."));try{await M__default.remove(Jt),console.log(s.green("\u2713 Cleanup complete"));}catch(t){e.debug("Cleanup failed:",t);}}b$7(130,"Interrupted by user"),process.exit(130);}}),process.on("SIGTERM",async()=>{if(!Xn){if(Xn=true,e.debug("Received SIGTERM"),Jt&&await M__default.pathExists(Jt))try{await M__default.remove(Jt);}catch(t){e.debug("Cleanup failed:",t);}b$7(143,"Terminated"),process.exit(143);}}));var Vh=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Jh=(()=>{let t=process.argv[1];if(!t)return false;let e=t.replace(/\\/g,"/"),r=e.endsWith("/dist/index.js")||e.endsWith("/src/index.ts");try{return $.realpathSync(t)===$.realpathSync(fileURLToPath(import.meta.url))||r}catch{return b.resolve(t)===b.resolve(fileURLToPath(import.meta.url))||r}})(),Kh=!Vh||Jh;function Uh(){for(let t of [process.stdout,process.stderr])t._handle?.setBlocking?.(true);}function Bh(){for(let t of [process.stdout,process.stderr]){if(t.isTTY)continue;let e=t;if(e.__rapidkitSyncWriteInstalled)continue;let r=t.fd;if(typeof r!="number")continue;let o=t.write.bind(t);e.write=((n,a,i)=>{let c=typeof a=="string"?a:"utf8",l=typeof a=="function"?a:typeof i=="function"?i:void 0;try{let p=typeof n=="string"?Buffer.from(n,c):n instanceof Uint8Array?Buffer.from(n):Buffer.from(String(n),c);return $.writeSync(r,p),l?.(),true}catch{return o(n,c,l)}}),e.__rapidkitSyncWriteInstalled=true;}}async function Ke(t){b$7(t),await new Promise(e=>setImmediate(e)),await new Promise(e=>setTimeout(e,25)),await Promise.all([process.stdout,process.stderr].map(e=>new Promise(r=>{e.write("",()=>r());}))),process.exit(t);}async function Qn(t,e=0){return $.writeSync(process.stdout.fd??1,t),Ke(e)}async function Hh(){Uh(),Bh(),d$7(),c$6(process.argv),a$6({argv:process.argv,cwd:process.cwd(),rapidkitVersion:h(),activityBlueprint:Cd(process.argv.slice(2))});let t=process.argv.slice(2),e=t[0],r=process.cwd(),o=et(r),n=u$1(r,"project.json").some(u=>$.existsSync(u)),a$1=fh(),i=vu(t),c=a$1&&Co(t),l$1=e==="init"&&o&&!n,p=t.length===0||t.length===1&&(e==="--help"||e==="-h"||e==="help"),m=e==="version"&&t.slice(1).every(u=>u==="--json"||u==="--no-color");t$2(e)&&t.slice(1,t.indexOf("--")<0?void 0:t.indexOf("--")).some(u=>u==="--help"||u==="-h")&&await Qn(`Workspai ${e}
|
|
449
450
|
|
|
450
451
|
Usage: workspai ${e}
|
|
451
452
|
|
|
452
453
|
Run the project's ${e} command through its runtime adapter.
|
|
453
454
|
Run workspai project commands --json to inspect project capabilities.
|
|
454
455
|
Run workspai workspace run --help for fleet execution and planning.
|
|
455
|
-
`),Id(t)&&await
|
|
456
|
-
`),p&&(a("npm cli"),Fu(),await Ke(0)),(m||t.some(u=>u==="--version"||u==="-V"||u==="-v"))&&!t.some(u=>u==="--help"||u==="-h"||u==="help")&&(t.includes("--json")?await
|
|
457
|
-
`):await
|
|
458
|
-
`)),
|
|
456
|
+
`),Id(t)&&await Qn(`${Od(t[1])}
|
|
457
|
+
`),p&&(a("npm cli"),Fu(),await Ke(0)),(m||t.some(u=>u==="--version"||u==="-V"||u==="-v"))&&!t.some(u=>u==="--help"||u==="-h"||u==="help")&&(t.includes("--json")?await Qn(`${JSON.stringify(hh(),null,2)}
|
|
458
|
+
`):await Qn(`${h()}
|
|
459
|
+
`)),Ys(t)&&await Ke(0),c&&e===Dn?(async()=>{await Ke(await qs(t));})().catch(u=>{process.stderr.write(`Workspai CLI failed to run create: ${u?.message??u}
|
|
459
460
|
`),process.exit(1);}):c&&Pu(e)?(async()=>{await Ke(await bu(e,t));})().catch(u=>{process.stderr.write(`Workspai CLI failed to run ${e}: ${u?.message??u}
|
|
460
461
|
`),process.exit(1);}):i||c?he.parseAsync().then(()=>{let u=Number(process.exitCode??0);return Ke(Number.isInteger(u)?u:1)}).catch(u=>{let f=$r()&&u instanceof Error&&u.stack?u.stack:u?.message??u;process.stderr.write(`Workspai CLI failed: ${f}
|
|
461
|
-
`),process.exit(1);}):l$1?
|
|
462
|
+
`),process.exit(1);}):l$1?oi(t).then(u=>Ke(u)).catch(u=>{process.stderr.write(`Workspai CLI failed to run workspace init: ${u?.message??u}
|
|
462
463
|
`),process.exit(1);}):Wh().then(async u=>{if(!u){let f=process.argv.slice(2);if($r()&&process.stderr.write(`[workspai-cli] argv=${JSON.stringify(f)}
|
|
463
|
-
`),vu(f)){await he.parseAsync();return}if(
|
|
464
|
-
`),P){let y=await e$2(f,{cwd:process.cwd()});await Ke(y);}await he.parseAsync();}});}Kh&&await Hh();export{
|
|
464
|
+
`),vu(f)){await he.parseAsync();return}if(Ys(f)&&await Ke(0),f[0]===Dn){let y=await qs(f);await Ke(y);}if(f[0]==="init"){let y=await oi(f);await Ke(y);}if(Pu(f[0])){let y=await bu(f[0],f);await Ke(y);}if(t$2(f[0])){if(Xs(f))return;let y=f[0],E=j$2(process.cwd()),A=await rr(process.cwd()),S=xe(process.cwd()),d=false;if(S){let h=t$1(S,"policies.yml").find(v=>$.existsSync(v));if(h&&await M__default.pathExists(h))try{let v=await $.promises.readFile(h,"utf-8");if(d=((v.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??v.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict",d){let j=t$1(S,"toolchain.lock").find(_=>$.existsSync(_)),R=[];if(!j||!await M__default.pathExists(j))R.push("toolchain.lock is missing \u2014 run `workspai bootstrap` first (strict mode requires a reproducible toolchain).");else try{let N=JSON.parse(await $.promises.readFile(j,"utf-8")).runtime??{};k$2(E,process.cwd())&&!N.go?.version&&R.push("Go runtime version is not pinned in toolchain.lock \u2014 run `workspai setup go` first."),l(E,process.cwd())&&!N.node?.version&&R.push("Node runtime version is not pinned in toolchain.lock \u2014 run `workspai setup node` first."),m$1(E,process.cwd())&&!N.java?.version&&R.push("Java runtime version is not pinned in toolchain.lock \u2014 run `workspai setup java` first."),n$1(E,process.cwd())&&!N.dotnet?.version&&R.push(".NET runtime version is not pinned in toolchain.lock \u2014 run `workspai setup dotnet` first."),o$1(E,process.cwd())&&!N.python?.version&&R.push("Python runtime version is not pinned in toolchain.lock \u2014 run `workspai setup python` first.");}catch{R.push("toolchain.lock is invalid JSON \u2014 regenerate it with `workspai bootstrap` before running commands in strict mode.");}let C=t$1(S,"workspace.json").find(_=>$.existsSync(_));if(C&&await M__default.pathExists(C))try{let N=JSON.parse(await $.promises.readFile(C,"utf-8")).profile??"",V=m$2(process.cwd(),E),D=W({profile:N,runtime:V.runtime,subjectLabel:b.basename(process.cwd()),mode:"strict"});D.ok||R.push(`${D.message} Update the workspace profile or use a polyglot workspace.`);}catch{}if(R.length>0){console.log(s.red(`\u274C Strict policy violations block \`${y}\`:`));for(let _ of R)console.log(s.red(` \u2022 ${_}`));console.log(s.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .workspai/policies.yml")),await Ke(1);}}}catch{}}let g=await a$7({startPath:process.cwd(),action:y,writeReport:true}),w=d||process.env.RAPIDKIT_LIFECYCLE_ENFORCE_READINESS==="1"||process.env.RAPIDKIT_ENFORCE_READINESS==="1";if(g.blocking&&w){console.log(s.red(`\u274C Release readiness blocks \`${y}\`:`));for(let h of g.blockingReasons)console.log(s.red(` \u2022 ${h}`));g.evidencePath&&console.log(s.gray(`\u2139\uFE0F Readiness evidence: ${g.evidencePath}`)),await Ke(1);}g.overallStatus!=="pass"&&!w&&(console.log(s.yellow(`\u26A0\uFE0F Release readiness is ${g.overallStatus}. Command continues in warn mode.`)),g.evidencePath&&console.log(s.gray(` Evidence: ${g.evidencePath} (set RAPIDKIT_LIFECYCLE_ENFORCE_READINESS=1 to block)`)));let k=await Mu(process.cwd(),async()=>{if(k$2(E,process.cwd())||A==="go"){let h=Ze("go",{runCommandInCwd:Ie,runCoreRapidkit:e$2});if(y==="lint")return ce(await h.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(y==="format")return ce(await h.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let v=y==="dev"?await h.runDev(process.cwd()):y==="test"?await h.runTest(process.cwd()):y==="build"?await h.runBuild(process.cwd()):await h.runStart(process.cwd());return v.message&&console.log(s.red(`\u274C ${v.message}`)),v.exitCode}if(m$1(E,process.cwd())||A==="java")return y==="dev"?await Rt("dev",process.cwd()):y==="test"?await Rt("test",process.cwd()):y==="build"?await Rt("build",process.cwd()):y==="lint"?await Rt("lint",process.cwd()):y==="format"?await Rt("format",process.cwd()):await Rt("start",process.cwd());if(n$1(E,process.cwd())||A==="dotnet"){let h=Ze("dotnet",{runCommandInCwd:Ie,runCoreRapidkit:e$2});if(y==="lint")return ce(await h.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(y==="format")return ce(await h.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let v=y==="dev"?await h.runDev(process.cwd()):y==="test"?await h.runTest(process.cwd()):y==="build"?await h.runBuild(process.cwd()):await h.runStart(process.cwd());return v.message&&console.log(s.red(`\u274C ${v.message}`)),v.exitCode}if(l(E,process.cwd())||A==="node")return y==="dev"?await tr("dev",process.cwd()):y==="test"?await tr("test",process.cwd()):y==="build"?await tr("build",process.cwd()):y==="lint"?await tr("lint",process.cwd()):y==="format"?await tr("format",process.cwd()):await tr("start",process.cwd());if(o$1(E,process.cwd())||A==="python"){if(y==="lint"||y==="format")return await e$2([y],{cwd:process.cwd()});let h=Ze("python",{runCommandInCwd:Ie,runCoreRapidkit:e$2});return ce(y==="dev"?await h.runDev(process.cwd()):y==="test"?await h.runTest(process.cwd()):y==="build"?await h.runBuild(process.cwd()):await h.runStart(process.cwd()))}if(A==="rust"||A==="php"){let h=Ze(A,{runCommandInCwd:Ie,runCoreRapidkit:e$2});if(y==="lint")return ce(await h.runLint?.(process.cwd())??{exitCode:1,message:"Lint is not supported."});if(y==="format")return ce(await h.runFormat?.(process.cwd())??{exitCode:1,message:"Format is not supported."});let v=y==="dev"?await h.runDev(process.cwd()):y==="test"?await h.runTest(process.cwd()):y==="build"?await h.runBuild(process.cwd()):await h.runStart(process.cwd());return ce(v)}return -1});if(!k.ok){await Ke(k.code);return}if(k.ok&&k.value>=0){await Ke(k.value);return}if(k.ok&&k.value===-1){console.error(s.red(`\u274C Workspai cannot run \`${y}\` for this project runtime.`)),console.error(s.gray("Run `workspai project commands` to inspect supported commands.")),await Ke(1);return}}if(Xs(f))return;let P=await Fh(f);if($r()&&process.stderr.write(`[workspai-cli] shouldForwardToCore=${P}
|
|
465
|
+
`),P){let y=await e$2(f,{cwd:process.cwd()});await Ke(y);}await he.parseAsync();}});}Kh&&await Hh();export{As as COMMAND_CAPABILITIES_SCHEMA_VERSION,Kf as NPM_ONLY_SCOPED_COMMANDS,Uf as NPM_ONLY_TOP_LEVEL_COMMANDS,Ld as VERSION_CONTRACT_SCHEMA_VERSION,dh as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,Hh as bootstrapCli,Ds as bridgeFailureCode,Bs as buildDelegationEnvForInit,Su as checkStrictPolicyPreflightForDelegation,Yf as commandAvailable,xu as createProjectVenv,Qf as createWorkspaceVenv,bh as defaultWorkspacePolicyYaml,yh as detectWindowsDoctorWorkspaceShadow,eh as ensurePythonProjectUsesLocalVenv,Zf as ensureWorkspaceVenvHasPip,Ou as findContextFileUp,kh as findLegacyWorkspaceUp,Qs as findWorkspaceMarkerUp,xe as findWorkspaceUp,_u as getGlobalCommandCapabilities,Vn as getPublishedContractCatalog,vo as getPublishedContractVersions,hh as getVersionContract,Wu as handleAdoptCommand,_h as handleBootstrapCommand,$h as handleCacheCommand,qs as handleCreateOrFallback,Vs as handleGoInit,ei as handleImportCommand,oi as handleInitCommand,Rt as handleJavaCommand,Mh as handleMirrorCommand,tr as handleNodeCommand,Oh as handleSetupCommand,et as hasWorkspaceRootMarkers,ii as hostPythonCandidates,rr as inferRuntimeByFiles,th as installPythonDependenciesWithPipFallback,ti as installWorkspaceDependencies,fh as isNpmExecInvocation,Co as isNpmOnlyInvocation,Pu as isNpmOnlyManualHandlerCommand,gh as isNpmOnlyParseDirectCommand,vu as isNpmOnlyParseDirectInvocation,zs as isNpmOnlyScopedCommand,mh as isNpmOnlyTopLevelCommand,Hf as normalizeFallbackTemplate,Nh as parseCacheConfig,qf as parseMaxWorkersOption,Sh as parseNodeEvalScript,Ch as parsePolicyBooleanLiteral,Fu as printHelp,he as program,Re as readFlagValue,Ph as replaceOrInsertRulePolicyLine,Cu as replaceOrInsertTopLevelPolicyLine,Bf as resolveInvokedCliName,Ie as runCommandInCwd,Yn as runCreateFallback,Fh as shouldForwardToCore,rh as validateNpmKitFlags};
|