workspai 0.52.3 → 0.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/contracts/artifact-remediation-plan.v1.json +23 -3
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +36 -0
- package/contracts/doctor-project-evidence.v1.json +21 -2
- package/contracts/doctor-remediation-plan.v1.json +22 -3
- package/contracts/doctor-workspace-evidence.v1.json +21 -2
- package/contracts/extension-cli-compatibility.v1.json +24 -2
- package/contracts/published-contract-catalog.v1.json +113 -2
- package/contracts/runtime-command-surface.v1.json +216 -5
- package/contracts/studio-card-repair-capabilities.v1.json +378 -0
- package/contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json +52 -13
- package/contracts/workspace-intelligence/workspace-repair-proposal.v1.json +78 -0
- package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +299 -0
- package/contracts/workspace-intelligence-chain.v1.json +6 -0
- package/contracts/workspace-repair-capabilities.v1.json +364 -0
- package/dist/analyze-AAZEJ4FC.js +1 -0
- package/dist/artifact-remediation-plan-A2PRCUNA.js +1 -0
- package/dist/autopilot-release-63XHNGR6.js +1 -0
- package/dist/{chunk-OTDGTAZJ.js → chunk-2FJW6GSW.js} +1 -1
- package/dist/chunk-3DONU3DU.js +1 -0
- package/dist/chunk-3LVJBH7V.js +5 -0
- package/dist/chunk-44VJHNZB.js +1 -0
- package/dist/chunk-4HTSZGEU.js +88 -0
- package/dist/chunk-5XDPQ3CB.js +1 -0
- package/dist/chunk-7AR5PDLD.js +1 -0
- package/dist/chunk-7KKP7RNB.js +3 -0
- package/dist/chunk-AMB42V2F.js +1 -0
- package/dist/chunk-BPACED27.js +8 -0
- package/dist/chunk-BYVTHIC3.js +2 -0
- package/dist/{chunk-6PBSAAS5.js → chunk-EBKYSDCX.js} +1 -1
- package/dist/chunk-FQLB4BIC.js +7 -0
- package/dist/{chunk-ICLYL3N5.js → chunk-FZCYTRBQ.js} +1 -1
- package/dist/{chunk-ZVOEPWQM.js → chunk-GDU7VP6G.js} +1 -1
- package/dist/chunk-H7P7SSUW.js +75 -0
- package/dist/{chunk-MZFSINY7.js → chunk-HRN5J6PW.js} +12 -12
- package/dist/chunk-HY3RMPW5.js +10 -0
- package/dist/chunk-I5CGTCP5.js +1 -0
- package/dist/chunk-IQQWQ3II.js +3 -0
- package/dist/chunk-KFKZOPZC.js +1 -0
- package/dist/{chunk-HPWLSLMC.js → chunk-KVUYAYTY.js} +1 -1
- package/dist/chunk-MQ73VS4E.js +2 -0
- package/dist/{chunk-2OIBHUVH.js → chunk-MRFN5ZQP.js} +1 -1
- package/dist/{chunk-4UVGTFOX.js → chunk-NYHVCFBT.js} +1 -1
- package/dist/{chunk-IO54DFWR.js → chunk-OLX6LX77.js} +1 -1
- package/dist/chunk-OUBBBC7T.js +36 -0
- package/dist/{chunk-WJY7ZXVJ.js → chunk-P7K5RHJC.js} +1 -1
- package/dist/chunk-QZ7PNMVP.js +1 -0
- package/dist/chunk-RA24WQLF.js +1 -0
- package/dist/{chunk-3PTIIBRY.js → chunk-RMXXK64P.js} +1 -1
- package/dist/{chunk-PTTZPDLX.js → chunk-S7Z4DP3P.js} +1 -1
- package/dist/chunk-SJLUE6AY.js +1 -0
- package/dist/chunk-UFOCUHG3.js +1 -0
- package/dist/chunk-WD2XDMGB.js +1 -0
- package/dist/chunk-WIO6L24E.js +2 -0
- package/dist/{chunk-QURMI7ID.js → chunk-WZA5ISAQ.js} +1 -1
- package/dist/chunk-XVRJVKOX.js +1 -0
- package/dist/chunk-ZLYEYHMH.js +1 -0
- package/dist/{create-ESK3CQPK.js → create-R6A7EHQZ.js} +1 -1
- package/dist/{doctor-MYRJ5BFF.js → doctor-HJ3O7SAO.js} +1 -1
- package/dist/index.d.ts +92 -23
- package/dist/index.js +246 -244
- package/dist/pipeline-TDQK5QYQ.js +5 -0
- package/dist/{project-intelligence-lens-Q4SZDI2N.js → project-intelligence-lens-ZOAWXYC5.js} +1 -1
- package/dist/project-test-coverage-44ZPCOPV.js +1 -0
- package/dist/{verified-goal-PSQF2TF2.js → verified-goal-S2PEBJUV.js} +1 -1
- package/dist/{workspace-LSOZM2CG.js → workspace-B53XH35L.js} +1 -1
- package/dist/{workspace-agent-sync-RZBQXCNJ.js → workspace-agent-sync-446AXPHJ.js} +1 -1
- package/dist/{workspace-archive-ZOWQXWJ6.js → workspace-archive-VHUPOBAV.js} +1 -1
- package/dist/{workspace-context-IYJKO5BN.js → workspace-context-XSECHC7O.js} +1 -1
- package/dist/{workspace-contract-AZFISDLS.js → workspace-contract-AYFTZIKM.js} +1 -1
- package/dist/workspace-explain-SZI2WAAD.js +1 -0
- package/dist/workspace-explain-contract-N2XQHAPM.js +1 -0
- package/dist/{workspace-feedback-LIHEWTNV.js → workspace-feedback-WXE7NVMV.js} +1 -1
- package/dist/{workspace-foundation-H5UTAUXQ.js → workspace-foundation-FFNCK5ZD.js} +1 -1
- package/dist/{workspace-graph-stream-KUDOZE73.js → workspace-graph-stream-AJPS45FD.js} +1 -1
- package/dist/{workspace-history-HULG5EFN.js → workspace-history-YY7YRDOH.js} +1 -1
- package/dist/{workspace-intelligence-A4UE4DZK.js → workspace-intelligence-FWRB47EJ.js} +1 -1
- package/dist/{workspace-intelligence-evaluation-AOLGHYHC.js → workspace-intelligence-evaluation-UP2K3L35.js} +1 -1
- package/dist/{workspace-intelligence-runner-5VAAMKMK.js → workspace-intelligence-runner-EQFLRVRL.js} +1 -1
- package/dist/workspace-intelligence-runtime-registry-MRSF7RTT.js +1 -0
- package/dist/{workspace-knowledge-graph-LEM6X5CM.js → workspace-knowledge-graph-BMMM2FUE.js} +1 -1
- package/dist/{workspace-mcp-serve-N2QPR7VJ.js → workspace-mcp-serve-COA4FMCA.js} +1 -1
- package/dist/{workspace-model-FJXX3NET.js → workspace-model-MNJOGBPP.js} +1 -1
- package/dist/{workspace-onboarding-IKFISWWY.js → workspace-onboarding-2B7CYZ5H.js} +1 -1
- package/dist/{workspace-readme-E2M35RJH.js → workspace-readme-4S6PJ74A.js} +1 -1
- package/dist/{workspace-registry-summary-HOQ3OBNT.js → workspace-registry-summary-GPJEL7K7.js} +1 -1
- package/dist/workspace-repair-engine-OZXOXVVV.js +3 -0
- package/dist/workspace-run-VPXRRHDK.js +1 -0
- package/dist/{workspace-verify-32AWCJQG.js → workspace-verify-C6HWHRLJ.js} +1 -1
- package/dist/{workspace-watch-4WVNB26E.js → workspace-watch-DLPHLF5R.js} +1 -1
- package/docs/README.md +2 -0
- package/docs/commands-reference.md +10 -8
- package/docs/contracts/ARTIFACT_CATALOG.md +27 -22
- package/docs/contracts/README.md +3 -0
- package/docs/contracts/RUNTIME_ACCEPTANCE_MATRIX.md +20 -11
- package/docs/doctor-command.md +16 -4
- package/docs/workspace-intelligence-runner.md +2 -1
- package/docs/workspace-knowledge-graph.md +6 -1
- package/docs/workspace-operations.md +3 -1
- package/docs/workspace-repair-engine.md +122 -0
- package/docs/workspace-run.md +17 -14
- package/package.json +3 -2
- package/scripts/enterprise-package-smoke.mjs +9 -6
- package/dist/analyze-J7VNZMDH.js +0 -1
- package/dist/artifact-remediation-plan-IDCJGULX.js +0 -3
- package/dist/autopilot-release-XRNPBYC6.js +0 -1
- package/dist/chunk-23JDMHSD.js +0 -86
- package/dist/chunk-2E6WGUN6.js +0 -1
- package/dist/chunk-2ZRMYFJG.js +0 -1
- package/dist/chunk-3D3PFPP5.js +0 -1
- package/dist/chunk-4D7DIGAB.js +0 -1
- package/dist/chunk-5XJRCP3D.js +0 -36
- package/dist/chunk-62K2H72S.js +0 -1
- package/dist/chunk-7MQZQ4UU.js +0 -1
- package/dist/chunk-AL237TSJ.js +0 -7
- package/dist/chunk-B4CPDK6J.js +0 -2
- package/dist/chunk-CZC5P2MF.js +0 -1
- package/dist/chunk-DZ4VKAXB.js +0 -75
- package/dist/chunk-FUPHQOJB.js +0 -1
- package/dist/chunk-GHB6QMQH.js +0 -1
- package/dist/chunk-LOCPNNSK.js +0 -1
- package/dist/chunk-LPCL4U4L.js +0 -1
- package/dist/chunk-MBRU3VWJ.js +0 -2
- package/dist/chunk-NHVHRBBV.js +0 -4
- package/dist/chunk-OXNV7OJM.js +0 -8
- package/dist/chunk-P4OSLAVD.js +0 -3
- package/dist/chunk-Q6CUJ3WF.js +0 -10
- package/dist/chunk-ULR66OJR.js +0 -2
- package/dist/chunk-XHRHNVCZ.js +0 -1
- package/dist/chunk-ZTKIBREF.js +0 -1
- package/dist/pipeline-P6DFMDL4.js +0 -5
- package/dist/project-test-coverage-A677ZLW3.js +0 -1
- package/dist/workspace-explain-26UGV7L4.js +0 -1
- package/dist/workspace-explain-contract-GIWPCCEF.js +0 -1
- package/dist/workspace-intelligence-runtime-registry-YOQ5GFFJ.js +0 -1
- package/dist/workspace-run-HRKCACGR.js +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {c as c$1}from'./chunk-
|
|
2
|
-
`);}async function
|
|
3
|
-
`),await
|
|
1
|
+
import {c as c$1}from'./chunk-QZ7PNMVP.js';import {a}from'./chunk-A5FBGRJA.js';import {a as a$2}from'./chunk-27UR373Z.js';import {b as b$1}from'./chunk-BYVTHIC3.js';import {e,d}from'./chunk-44VJHNZB.js';import {i}from'./chunk-VRW6KXNK.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {t,s}from'./chunk-MOSXTVPU.js';import {q as q$1,r,s as s$1}from'./chunk-RJIYCDVC.js';import {promises}from'fs';import {randomUUID}from'crypto';import p from'path';import c from'chalk';import ne from'fs-extra';import P from'ora';import {execa}from'execa';async function ce(e){try{let r=await execa("git",["rev-parse","--show-toplevel"],{cwd:e,env:a$1()});return r.stdout.trim()?p.resolve(e,r.stdout.trim()):null}catch{return null}}async function Z(e,r,t){if(await ce(e)){r.warn("Git initialization skipped because target is already inside a git worktree");return}r.start("Initializing git repository...");try{await execa("git",["init"],{cwd:e,env:a$1()}),await execa("git",["add","."],{cwd:e,env:a$1()}),await execa("git",["-c","user.name=Workspai","-c","user.email=workspai@localhost","commit","-m",t],{cwd:e,env:a$1()}),r.succeed("Git repository initialized");}catch{r.warn("Could not initialize git repository");}}function B(e){let r=a(e.path),t=Array.isArray(e.projects)?e.projects:[],o=[],a$1=new Set;for(let s of t){if(!s||typeof s.name!="string"||typeof s.path!="string")continue;let i=a(s.path);a$1.has(i)||(a$1.add(i),o.push({name:s.name,path:i}));}return {name:e.name,path:r,mode:e.mode,projects:o}}function b(e){let r=[],t=new Set;for(let o of e.workspaces||[]){if(!o||typeof o.name!="string"||typeof o.path!="string")continue;let a=B(o);t.has(a.path)||(t.add(a.path),r.push(a));}return {workspaces:r}}async function pe(e){let r;try{r=await promises.readFile(e,"utf8");}catch(t){if(t.code==="ENOENT")return {workspaces:[]};throw t}try{let t=JSON.parse(r);if(!t||!Array.isArray(t.workspaces))throw new Error("missing workspaces array");return b(t)}catch(t){throw new Error(`Workspace registry is invalid: ${e}`,{cause:t})}}async function le(e){let r;try{r=await promises.readFile(e,"utf8");}catch(o){if(o.code==="ENOENT")return {workspaces:[]};throw o}let t;try{t=JSON.parse(r);}catch(o){throw new Error(`Workspace registry is invalid: ${e}`,{cause:o})}if(!t||typeof t!="object"||!Array.isArray(t.workspaces))throw new Error(`Workspace registry is invalid: ${e}`);for(let o of t.workspaces)if(!o||typeof o.name!="string"||typeof o.path!="string"||o.mode!==void 0&&typeof o.mode!="string"||o.projects!==void 0&&!Array.isArray(o.projects)||Array.isArray(o.projects)&&o.projects.some(a=>!a||typeof a.name!="string"||typeof a.path!="string"))throw new Error(`Workspace registry contains an invalid entry: ${e}`);return b(t)}async function F(){let e={workspaces:[]},r=new Set;for(let t of s$1()){let o=await pe(t);for(let a of o.workspaces)r.has(a.path)||(r.add(a.path),e.workspaces.push(a));}return e}async function ee(e=s$1()){let r={workspaces:[]},t=new Set;for(let o of e){let a=await le(o);for(let s of a.workspaces)t.has(s.path)||(t.add(s.path),r.workspaces.push(s));}return r}function de(e){let r=e?.code;return process.platform==="win32"&&(r==="EPERM"||r==="EINVAL"||r==="ENOSYS")}async function te(e){try{await e.sync();}catch(r){if(!de(r))throw r}}async function q(e,r){let t=p.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${p.basename(e)}.`,a=Date.now();for(let i of await promises.readdir(t)){if(!i.startsWith(o)||!i.endsWith(".tmp"))continue;let n=p.join(t,i),d=await promises.stat(n).catch(()=>null);d&&a-d.mtimeMs>3e4&&await promises.rm(n,{force:true}).catch(()=>{});}let s=await promises.readFile(e,"utf8").catch(()=>null);if(s!==null){let i=false;try{let n=JSON.parse(s);i=Array.isArray(n.workspaces);}catch{i=false;}if(!i){let n=`${e}.corrupt-${Date.now()}`;await promises.copyFile(e,n);}}await re(e,`${JSON.stringify(b(r),null,2)}
|
|
2
|
+
`);}async function re(e,r){let t=p.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${e}.${process.pid}.${randomUUID()}.tmp`;try{await promises.writeFile(o,r);let a=await promises.open(o,"r");try{await te(a);}finally{await a.close();}try{await promises.rename(o,e);}catch(s){let i=s.code;if(i!=="EEXIST"&&i!=="EPERM")throw s;await ne.move(o,e,{overwrite:true});}}finally{await promises.rm(o,{force:true}).catch(()=>{});}}async function K(e){try{return {exists:true,content:await promises.readFile(e)}}catch(r){if(r.code==="ENOENT")return {exists:false};throw r}}async function X(e,r){if(!r.exists){await promises.rm(e,{force:true});return}await re(e,r.content);}async function me(e,r){let t=p.join(e,"workspaces.json.lock"),o=randomUUID();await promises.mkdir(e,{recursive:true});let a=Date.now(),s;for(;!s;)try{s=await promises.open(t,"wx"),await s.writeFile(`${JSON.stringify({pid:process.pid,lockId:o,createdAt:new Date().toISOString()})}
|
|
3
|
+
`),await te(s);}catch(i){if(i.code!=="EEXIST")throw i;let n=await promises.stat(t).catch(()=>null);if(n&&Date.now()-n.mtimeMs>3e4){let d=await promises.readFile(t,"utf8").then(m=>JSON.parse(m)).catch(()=>null),u=Number(d?.pid),w=false;if(Number.isInteger(u)&&u>0)try{process.kill(u,0),w=true;}catch(m){w=m.code==="EPERM";}if(!w){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>1e4)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(d=>setTimeout(d,25));}try{return await r()}finally{await s.close().catch(()=>{}),await promises.readFile(t,"utf8").then(n=>JSON.parse(n).lockId===o).catch(()=>false)&&await promises.rm(t,{force:true}).catch(()=>{});}}async function _(e){let r$1=q$1(),t=p.join(r$1,"workspaces.json"),o=p.join(r(),"workspaces.json"),a=[...new Set(s$1())];return me(r$1,async()=>{let[s,i]=await Promise.all([K(t),K(o)]),n=await ee(a);await e(n);let d=b(n);try{await q(t,d),await q(o,d);}catch(u){let m=(await Promise.allSettled([X(t,s),X(o,i)])).filter(g=>g.status==="rejected").map(g=>g.reason);throw m.length>0?new AggregateError([u,...m],"Workspace registry transaction failed and could not be fully restored"):u}return d})}async function oe(e,r){let t=a(e);await _(o=>{let a=o.workspaces.find(s=>s.path===t);if(a){a.name=r,a.mode=a.mode||"full",a.projects=Array.isArray(a.projects)?a.projects:[];return}o.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function Je(e){let r=a(e),o=(await ee()).workspaces.find(a=>a.path===r);return o?{...o,projects:o.projects.map(a=>({...a}))}:null}async function ze(e,r){let t=a(e);await _(o=>{let a=o.workspaces.findIndex(i=>i.path===t);if(!r){a>=0&&o.workspaces.splice(a,1);return}let s=B(r);a>=0?o.workspaces[a]=s:o.workspaces.push(s);});}async function Ue(e){let r=a(e);await _(t=>{t.workspaces=t.workspaces.filter(o=>o.path!==r);});}async function ge(e,r){try{await oe(e,r);}catch{console.warn(c.gray("Note: Could not register workspace in shared registry"));}}async function Ge(e,r=false){let t$1=a(e),o={workspacePath:t$1,workspaceFound:false,added:[],skipped:0};try{let a$1=await F(),s=a$1.workspaces.find(g=>g.path===t$1);if(!s){if(await ge(t$1,p.basename(p.resolve(e))),a$1=await F(),s=a$1.workspaces.find(g=>g.path===t$1),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),o;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,n=0,d=[],u=[],w=[e],m=new Set;for(;w.length>0;){let g=w.shift();if(!g||m.has(g))continue;m.add(g);let y=await promises.readdir(g,{withFileTypes:true});for(let h of y){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let j=p.join(g,h.name),f=a(j);try{let k=false;for(let $ of [...t(f,"context.json"),...t(f,"project.json")])try{await promises.access($),k=true;break}catch{}if(k){let $=p.basename(f),S=s.projects.some(C=>C.path===f);u.push({name:$,path:f}),S?n++:(s.projects.push({name:$,path:f}),i++,d.push(f),r||console.log(`\u2714 Added: ${p.relative(e,f)}`));continue}}catch{}w.push(j);}}return await _(g=>{let y=g.workspaces.find(f=>f.path===t$1);if(!y)return;let h=`${t$1}${p.sep}`,j=(y.projects||[]).filter(f=>f.path!==t$1&&!f.path.startsWith(h));y.projects=B({...y,projects:[...j,...u]}).projects;}),i>0?r||console.log(`
|
|
4
4
|
\u2705 Synced ${i} project(s) to registry`):r||console.log(`
|
|
5
|
-
\u2705 All projects already registered (${n} found)`),{workspacePath:t$1,workspaceFound:true,added:d,skipped:n}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function
|
|
5
|
+
\u2705 All projects already registered (${n} found)`),{workspacePath:t$1,workspaceFound:true,added:d,skipped:n}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function ue(e,r,t){let o=a(e),a$1=a(t);await _(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let n=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};n>=0?i.projects[n]=d:i.projects.push(d);});}async function Me(e,r,t){try{await ue(e,r,t);}catch{}}async function Ve(e,r){let t=P("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(p.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:i(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(p.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-R6A7EHQZ.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=ke();await promises.writeFile(p.join(e,"rapidkit"),s),await promises.chmod(p.join(e,"rapidkit"),493);let i$1=we();await promises.writeFile(p.join(e,"rapidkit.cmd"),i$1);let n=fe(r.name);await promises.writeFile(p.join(e,"README.md"),n),await promises.writeFile(p.join(e,".gitignore"),`# Workspai workspace
|
|
6
6
|
.env
|
|
7
7
|
.env.*
|
|
8
8
|
!.env.example
|
|
@@ -17,7 +17,7 @@ Thumbs.db
|
|
|
17
17
|
|
|
18
18
|
# Logs
|
|
19
19
|
*.log
|
|
20
|
-
`),await
|
|
20
|
+
`),await he(e),t.succeed("Workspace created!"),r.skipGit||await Z(e,P(),"Initial commit: Workspai workspace"),await oe(e,r.name);let{publishWorkspaceRegistrySummary:u}=await import('./workspace-registry-summary-GPJEL7K7.js');await u(e),console.log(`
|
|
21
21
|
${c.green("\u2728 Workspai workspace created successfully!")}
|
|
22
22
|
|
|
23
23
|
${c.bold("\u{1F4C2} Workspace structure:")}
|
|
@@ -54,7 +54,7 @@ ${c.bold("\u{1F4DA} Commands:")}
|
|
|
54
54
|
|
|
55
55
|
${c.gray("Alternative: npx workspai dev, make dev")}
|
|
56
56
|
${c.gray("\u{1F4A1} Tip: Install globally (npm i -g workspai) to use without npx")}
|
|
57
|
-
`);}catch(o){throw t.fail("Failed to create workspace"),o}}function
|
|
57
|
+
`);}catch(o){throw t.fail("Failed to create workspace"),o}}function ke(){return `#!/usr/bin/env bash
|
|
58
58
|
#
|
|
59
59
|
# Workspai CLI - local workspace commands
|
|
60
60
|
# This script provides legacy ./rapidkit commands within the workspace
|
|
@@ -440,7 +440,7 @@ main() {
|
|
|
440
440
|
}
|
|
441
441
|
|
|
442
442
|
main "$@"
|
|
443
|
-
`}function
|
|
443
|
+
`}function we(){return `@echo off
|
|
444
444
|
setlocal enabledelayedexpansion
|
|
445
445
|
|
|
446
446
|
set "SCRIPT_DIR=%~dp0"
|
|
@@ -460,7 +460,7 @@ if %ERRORLEVEL%==0 (
|
|
|
460
460
|
echo [Workspai] No sh/bash found. Falling back to npx workspai.
|
|
461
461
|
npx workspai %*
|
|
462
462
|
exit /b %ERRORLEVEL%
|
|
463
|
-
`}function
|
|
463
|
+
`}function fe(e){return `# ${e}
|
|
464
464
|
|
|
465
465
|
Workspai workspace for building API projects.
|
|
466
466
|
|
|
@@ -517,7 +517,7 @@ instructions start at \`AGENTS.md\`.
|
|
|
517
517
|
|
|
518
518
|
- [Workspai Documentation](https://workspai.dev)
|
|
519
519
|
- [GitHub Repository](https://github.com/chistiq/workspai)
|
|
520
|
-
`}async function
|
|
520
|
+
`}async function he(e){let{fileURLToPath:r}=await import('url'),t=r(import.meta.url),o=p.dirname(t),a=p.resolve(o,".."),s=p.join(a,"templates","kits"),i=p.join(e,".workspai","templates"),{default:n}=await import('fs-extra');await n.copy(s,i);let d=p.join(a,"templates","generator.js"),u=p.join(e,".workspai","generator.js");await n.copy(d,u);}async function Ye(e,r){let t=r.template==="fastapi",o=t?"FastAPI":"NestJS",a=P(`Creating ${o} project...`).start();try{let{fileURLToPath:s}=await import('url'),i$1=s(import.meta.url),n=p.dirname(i$1),d=p.resolve(n,".."),u=t?"fastapi-standard":"nestjs-standard",w=p.join(d,"templates","kits",u);await promises.mkdir(e,{recursive:true});let m={project_name:t?r.name.replace(/-/g,"_").toLowerCase():r.name.replace(/_/g,"-").toLowerCase(),author:r.author,description:r.description||`${o} application generated with Workspai`,app_version:"0.1.0",license:"MIT",package_manager:r.package_manager||"npm",created_at:new Date().toISOString(),rapidkit_version:i()};await ae(w,e,m);let g=t?`# Python
|
|
521
521
|
__pycache__/
|
|
522
522
|
*.py[cod]
|
|
523
523
|
*$py.class
|
|
@@ -585,7 +585,7 @@ Thumbs.db
|
|
|
585
585
|
|
|
586
586
|
# Coverage
|
|
587
587
|
coverage/
|
|
588
|
-
`;if(await promises.writeFile(p.join(e,".gitignore"),g),a.succeed(`${o} project created!`),r.skipGit||await
|
|
588
|
+
`;if(await promises.writeFile(p.join(e,".gitignore"),g),a.succeed(`${o} project created!`),r.skipGit||await Z(e,P(),`Initial commit: ${o} project via Workspai`),!r.skipInstall&&!t){let h=r.package_manager||"npm",j=P(`Installing dependencies with ${h}...`).start();try{await execa(h,["install"],{cwd:e}),j.succeed("Dependencies installed");}catch{j.warn(`Could not install dependencies. Run '${h} install' manually.`);}}let y=p.basename(e);console.log(t?`
|
|
589
589
|
${c.green("\u2728 FastAPI project created successfully!")}
|
|
590
590
|
|
|
591
591
|
${c.bold("\u{1F4C2} Project structure:")}
|
|
@@ -651,7 +651,7 @@ ${c.bold("\u{1F310} API endpoints:")}
|
|
|
651
651
|
http://localhost:8000/examples/notes # Example API
|
|
652
652
|
|
|
653
653
|
${c.gray("\u{1F4A1} Tip: Install globally (npm i -g workspai) to use without npx")}
|
|
654
|
-
`);}catch(s){throw a.fail(`Failed to create ${o} project`),s}}async function
|
|
654
|
+
`);}catch(s){throw a.fail(`Failed to create ${o} project`),s}}async function ae(e,r,t){let o=await promises.readdir(e,{withFileTypes:true});for(let a of o){let s=p.join(e,a.name),i=a.name.replace(/\.j2$/,""),n=p.join(r,i);if(a.isDirectory())await promises.mkdir(n,{recursive:true}),await ae(s,n,t);else {let d=await promises.readFile(s,"utf-8");a.name.endsWith(".j2")&&(d=ye(d,t)),await promises.writeFile(n,d),(i==="rapidkit"||i==="activate"||i.endsWith(".py")&&(n.includes(".workspai")||n.includes(".rapidkit")))&&await promises.chmod(n,493);}}}function ye(e,r){let t=e;for(let[o,a]of Object.entries(r)){let s=new RegExp(`\\{\\{\\s*${o}\\s*\\}\\}`,"g");t=t.replace(s,String(a));let i=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\}\\}`,"g");t=t.replace(i,(u,w,m)=>String(a).replace(new RegExp(w,"g"),m));let n=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(n,String(a).toLowerCase());let d=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(d,(u,w,m)=>String(a).replace(new RegExp(w,"g"),m).toLowerCase());}return t}async function He(e={}){let r=q$1(),t=p.join(r,"workspaces.json"),o=await F();if(o.workspaces.length===0){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:false}},null,2));return}console.log(c.yellow(`
|
|
655
655
|
\u26A0\uFE0F No workspaces registered yet.
|
|
656
656
|
`)),console.log(c.gray(`Create a workspace with: npx workspai <workspace-name>
|
|
657
657
|
`));return}try{let a=o;if(!a||typeof a!="object"||!Array.isArray(a.workspaces)){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:true,registryValid:false},error:{code:"workspace.registry.invalid",message:"Workspace registry is invalid."}},null,2));return}console.log(c.yellow(`
|
|
@@ -663,4 +663,4 @@ ${c.gray("\u{1F4A1} Tip: Install globally (npm i -g workspai) to use without npx
|
|
|
663
663
|
\u{1F4E6} Registered Workspai Workspaces:
|
|
664
664
|
`));for(let m of d.workspaces)console.log(c.cyan(` ${m.name}`)),console.log(c.gray(` Path: ${m.path}`)),console.log(c.gray(` Projects: ${m.projects?.length||0}`)),console.log();n>0&&console.log(c.gray(`Cleaned ${n} stale workspace entr${n===1?"y":"ies"}.`)),console.log(c.gray(`Total: ${d.workspaces.length} workspace(s)
|
|
665
665
|
`));}catch(a){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:true,registryValid:false},error:{code:"workspace.registry.read_failed",message:a.message}},null,2));return}console.error(c.red(`
|
|
666
|
-
\u274C Failed to read workspace registry`)),console.error(c.gray(String(a)));}}async function
|
|
666
|
+
\u274C Failed to read workspace registry`)),console.error(c.gray(String(a)));}}async function $e(e){try{let r=await promises.readFile(e,"utf8");return JSON.parse(r)}catch{return null}}async function L(e){for(let r of e){let t=await $e(r);if(t!==null)return t}return null}function je(e){return c$1(e)}async function ve(e){return a$2(e,{skipDirs:new Set(["node_modules","dist","build","target","coverage","htmlcov"]),includeHiddenDirs:false,descendIntoMatchedProjects:true})}async function O(e){try{return (await promises.readdir(e,{withFileTypes:true})).filter(t=>t.isFile()&&t.name.toLowerCase().endsWith(".json")).map(t=>t.name).sort((t,o)=>t.localeCompare(o))}catch{return []}}async function qe(e$1,r){let t$1=r?.includePaths===true,o=r?.includeDoctorEvidence!==false,a=r?.includeBlueprint!==false,s$1=p.resolve(e$1),i=await L(s(s$1,"workspace.json")),n=typeof i?.workspace_name=="string"&&i.workspace_name.trim()||p.basename(s$1),d$1=typeof i?.profile=="string"?i.profile:void 0,u=typeof i?.rapidkit_version=="string"?i.rapidkit_version:void 0,w=await ve(s$1),m=[];for(let k of w){let $=await L(t(k,"project.json")),S=p.relative(s$1,k)||".",C=p.dirname(t(k,p.join("reports","placeholder"))[0]),J=p.dirname(t(k,p.join("reports","placeholder"))[1]),N={name:p.basename(k),relative_path:S,runtime:typeof $?.runtime=="string"?$.runtime:void 0,kit_name:typeof $?.kit_name=="string"?$.kit_name:void 0,modules:Array.isArray($?.modules)?$.modules.filter(x=>typeof x=="string"):void 0};if(t$1&&(N.absolute_path=k),o){let x=await L([p.join(C,"doctor-last-run.json"),p.join(J,"doctor-last-run.json")]);je(x)&&(N.doctor_report=x);}let z=[...await O(C),...await O(J)].filter((x,se,ie)=>ie.indexOf(x)===se);z.length>0&&(N.reports=z),m.push(N);}let g=s(s$1,"reports"),y=[...await O(g[0]),...await O(g[1])].filter((k,$,S)=>S.indexOf(k)===$),h=await L(s(s$1,"workspace.contract.json")),j={schema_version:d.workspaceShareBundle.schemaVersion,generated_at:new Date().toISOString(),generated_by:"workspai",workspace:{name:n,relative_root:".",profile:d$1,rapidkit_version:u,...t$1?{absolute_root:s$1}:{}},summary:{project_count:m.length,doctor_evidence_included:o,contract_included:!!h},reports:{workspace:y},projects:m,...h?{contract:h}:{}};a&&(j.blueprint={schema_version:"rapidkit.workspace-blueprint.v1",purpose:"portable-reproducibility",workspace:{name:n,profile:d$1},projects:m.map(k=>({name:k.name,relative_path:k.relative_path,runtime:k.runtime,kit_name:k.kit_name,modules:k.modules??[],recreate_commands:[...k.kit_name?[`npx workspai create project ${k.kit_name} ${k.name} --yes --skip-install`]:[],`cd ${k.relative_path}`,"npx workspai init","npx workspai test"]})),recommended_commands:["npx workspai workspace contract verify --strict","npx workspai doctor workspace","npx workspai workspace run init --json","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"]});let f=r?.outputPath?p.resolve(r.outputPath):p.join(g[0],"share-bundle.json");return r?.outputPath||b$1(e.workspaceShareBundle,j),await promises.mkdir(p.dirname(f),{recursive:true}),await promises.writeFile(f,JSON.stringify(j,null,2),"utf8"),f}export{B as a,oe as b,Je as c,ze as d,Ue as e,ge as f,Ge as g,ue as h,Me as i,Ve as j,Ye as k,He as l,qe as m};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import {a}from'./chunk-GR6442P7.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e}from'./chunk-44VJHNZB.js';import {j,s,p as p$1,v}from'./chunk-MOSXTVPU.js';import z from'crypto';import Y from'os';import l from'path';import {once}from'events';import {createWriteStream,createReadStream}from'fs';import*as Q from'readline';import {Transform,Readable}from'stream';import {pipeline}from'stream/promises';import {lookup}from'dns/promises';import T from'net';import p from'fs-extra';import*as ee from'yauzl';import*as te from'yazl';var qe="workspai-workspace-archive-capabilities-v1",q="workspai-workspace-archive-manifest-v1",k="workspai-workspace-archive-operation-result-v1";var K="contracts/workspace-archive-manifest.v1.json",Z="contracts/workspace-archive-operation-result.v1.json",Ke={archiveCompression:{signature:"--archive-compression <mode>",description:"Archive compression: store (default) or deflate",appliesTo:["export"]},maxDownloadSize:{signature:"--max-download-size <size>",description:"Maximum remote archive download size (secure default: 5gb)",appliesTo:["inspect","verify","doctor","hydrate","import"]},maxExpandedSize:{signature:"--max-expanded-size <size>",description:"Maximum expanded archive payload size (secure default: 20gb)",appliesTo:["inspect","verify","doctor","hydrate","import"]},downloadTimeoutMs:{signature:"--download-timeout-ms <ms>",description:"Remote archive download timeout in milliseconds; 0 disables it",appliesTo:["inspect","verify","doctor","hydrate","import"]},allowPrivateNetwork:{signature:"--allow-private-network",description:"Allow archive downloads from loopback/private networks (unsafe for untrusted input)",appliesTo:["inspect","verify","doctor","hydrate","import"]}};var A=".workspai/archive-manifest.json",R=".rapidkit/archive-manifest.json",de="workspai.workspace.archive",ye=300*1e3,ve=5*1024*1024*1024,we=20*1024*1024*1024,J=2e5,ge=5*1024*1024*1024,ke=1e3,M=5,Ee=64*1024*1024;function Ae(r){let t=r.toLowerCase().split("%")[0];if(T.isIPv4(t)){let e=t.split(".").map(Number);return e[0]===0||e[0]===10||e[0]===127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&e[1]===168||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]>=224}return T.isIPv6(t)?t==="::"||t==="::1"||t.startsWith("fc")||t.startsWith("fd")||/^fe[89ab]/.test(t)||t.startsWith("ff")||t.startsWith("::ffff:127.")||t.startsWith("::ffff:10.")||t.startsWith("::ffff:192.168."):true}async function X(r,t){let e=new URL(r);if(e.protocol!=="https:"&&e.protocol!=="http:")throw new Error(`Workspace archive URL protocol is not supported: ${e.protocol}`);if(e.protocol!=="https:"&&!t)throw new Error("Remote workspace archives require HTTPS unless private-network access is explicitly enabled.");if(e.username||e.password)throw new Error("Workspace archive URL must not contain embedded credentials.");if(t)return e;let i=e.hostname.replace(/^\[|\]$/g,"").toLowerCase();if(i==="localhost"||i.endsWith(".localhost"))throw new Error("Workspace archive URL resolves to a private or local network address.");let a=T.isIP(i)?[{address:i}]:await lookup(i,{all:true,verbatim:true});if(a.length===0||a.some(({address:s})=>Ae(s)))throw new Error("Workspace archive URL resolves to a private or local network address.");return e}async function Pe(r,t,e){let i=await X(r,e);for(let a=0;a<=M;a+=1){let s=await fetch(i,{signal:t,redirect:"manual",credentials:"omit"});if(![301,302,303,307,308].includes(s.status))return s;let n=s.headers.get("location");if(await s.body?.cancel(),!n)throw new Error("Workspace archive redirect is missing a Location header.");if(a===M)throw new Error(`Workspace archive download exceeded ${M} redirects.`);i=await X(new URL(n,i).href,e);}throw new Error("Workspace archive redirect policy failed.")}var We=new Set(["__pycache__",".venv","venv","node_modules",".git","dist","build","target",".pytest_cache",".mypy_cache",".ruff_cache","htmlcov",".next",".turbo",".cache"]),be=new Set([".DS_Store","Thumbs.db",".coverage","npm-debug.log","yarn-error.log","pnpm-debug.log","workspace-link.local.json","imported-projects.json","workspace-registry.v1.json"]),Se=[/^\.env$/i,/^\.env\.(?!example$|sample$|template$).+/i,/^.*\.pem$/i,/^.*\.key$/i,/^id_rsa$/i,/^id_ed25519$/i];function _(r){return r.replace(/\\/g,"/")}function re(r){return r.trim().replace(/\.workspai-archive\.zip$/i,"").replace(/\.rapidkit-archive\.zip$/i,"").replace(/\.zip$/i,"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)||"imported-workspace"}function ie(r){let t=_(r).trim();if(!t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0"))return false;let e=t.split("/").filter(Boolean);return e.length>0&&!e.some(i=>i===".."||i===".")}function ae(r){if(!ie(r))throw new Error(`Archive contains an unsafe path: ${r}`)}function Re(r,t){let e=l.relative(t,r);return e===""||!!e&&!e.startsWith("..")&&!l.isAbsolute(e)}function _e(r,t){let e$1=_(r),i=e$1.split("/").filter(Boolean);if(i.some((n,o)=>(n===".workspai"||n===".rapidkit")&&["cache","reports"].includes(i[o+1]||""))||i.some(n=>We.has(n)||a(n)))return true;let s=i[i.length-1]||"";return e$1===e.workspaceContract||e$1===".rapidkit/workspace.contract.json"||be.has(s)||/\.(?:workspai|rapidkit)-archive\.zip$/i.test(s)||!t?.includeEnv&&Se.some(n=>n.test(s))?true:s.endsWith(".pyc")||s.endsWith(".log")}async function Ce(r){for(let t of [l.join(r,".workspai","workspace.contract.json"),l.join(r,".rapidkit","workspace.contract.json")])if(await p.pathExists(t))try{return await p.readJson(t)}catch(e){throw new Error(`Workspace contract could not be inspected safely for archive portability: ${t}: ${e instanceof Error?e.message:String(e)}`)}return null}function xe(r){return (r?.projects??[]).filter(t=>typeof t.externalPath=="string"||typeof t.relativePath=="string"&&t.relativePath.startsWith("external/")).map(t=>({name:t.slug||t.relativePath||"external-project",relationship:["adopted","linked","imported","managed","restored"].includes(String(t.relationship))?t.relationship:"adopted",included:false,requiredAction:"relink"})).sort((t,e)=>t.name.localeCompare(e.name))}function Oe(r){if(r)return {...r,workspace:{...r.workspace},projects:r.projects.filter(t=>typeof t.externalPath!="string"&&!t.relativePath.startsWith("external/")).map(({externalPath:t,...e})=>({...e,modules:[...e.modules],ports:e.ports.map(i=>({...i})),contracts:{owns:[...e.contracts.owns],apis:e.contracts.apis.map(i=>({...i})),publishes:[...e.contracts.publishes],consumes:[...e.contracts.consumes],dependsOn:[...e.contracts.dependsOn],env:[...e.contracts.env]}}))}}async function*se(r,t,e){let i=(await p.readdir(t,{withFileTypes:true})).sort((a,s)=>a.name.localeCompare(s.name));for(let a of i){let s=l.join(t,a.name),n=_(l.relative(r,s));if(!(!n||_e(n,e))){if(a.isDirectory()){yield*se(r,s,e);continue}a.isFile()&&(yield {relativePath:n,fullPath:s});}}}async function ze(r){for(let t of s(r,"workspace.json"))try{let e=await p.readJson(t);if(typeof e.workspace_name=="string"&&e.workspace_name.trim())return e.workspace_name.trim();if(typeof e.name=="string"&&e.name.trim())return e.name.trim()}catch{}return l.basename(l.resolve(r))}async function Ne(r){let t=await p.stat(r.fullPath),e=z.createHash("sha256"),i=0;for await(let s of createReadStream(r.fullPath)){let n=Buffer.isBuffer(s)?s:Buffer.from(s);i+=n.length,e.update(n);}let a=await p.stat(r.fullPath);if(t.size!==a.size||t.mtimeMs!==a.mtimeMs||i!==a.size)throw new Error(`Workspace file changed while preparing archive: ${r.relativePath}`);return {...r,size:i,mtimeMs:a.mtimeMs,sha256:e.digest("hex")}}async function E(r,t){r.write(t)||await once(r,"drain");}async function ne(r){await new Promise((t,e)=>{r.once("error",e),r.end(t);});}async function*O(r){let t=Q.createInterface({input:createReadStream(r),crlfDelay:1/0});for await(let e of t){let i=e.trim();i&&(yield JSON.parse(i));}}async function Me(r){let t=createWriteStream(r.manifestPath,{flags:"wx"});try{await E(t,`{
|
|
2
|
+
`);for(let[i,a]of Object.entries(r.manifestBase))await E(t,` ${JSON.stringify(i)}: ${JSON.stringify(a,null,2)},
|
|
3
|
+
`);await E(t,` "files": [
|
|
4
|
+
`);let e=true;for await(let i of O(r.spoolPath)){let{mtimeMs:a,...s}=i;await E(t,`${e?"":`,
|
|
5
|
+
`} ${JSON.stringify(s)}`),e=false;}await E(t,`
|
|
6
|
+
]
|
|
7
|
+
}
|
|
8
|
+
`),await ne(t);}catch(e){throw t.destroy(),await p.remove(r.manifestPath).catch(()=>{}),e}}async function Te(r,t){let e=[];for await(let i of O(t)){let{mtimeMs:a,...s}=i;e.push(s);}return {...r,files:e}}async function Ie(r,t){try{await p.rename(r,t);}catch(e){let i=e.code;if(i!=="EEXIST"&&i!=="EPERM")throw e;await p.move(r,t,{overwrite:true});}}async function ht(r){let t=l.resolve(r.workspacePath);if(!j(t))throw new Error("Workspace export requires a Workspai workspace root with .workspai-workspace or a legacy .rapidkit-workspace marker.");let e=await ze(t),i=await Ce(t),a=xe(i),s=Oe(i),n=l.resolve(r.outputPath||`${re(e)}.workspai-archive.zip`),o={schemaVersion:q,version:1,kind:de,workspaceName:e,exportedAt:(r.now??new Date).toISOString(),exportedBy:"workspai",archiveFormat:r.compression==="deflate"?"zip-deflate":"zip-store",containerFormat:"zip64",compression:r.compression==="deflate"?"deflate":"store",streaming:true,security:{envFilesIncluded:r.includeEnv===true,excludedByDefault:[".git","node_modules",".venv",".workspai/cache",".workspai/reports",".rapidkit/cache",".rapidkit/reports","dist","build","target",".env","*.pem","*.key","*.log"]},...a.length>0?{externalProjects:a}:{},...s?{portableContract:s}:{}},m=l.resolve(n);await p.ensureDir(l.dirname(n));let h=`${n}.${process.pid}.${z.randomUUID()}.tmp`,u=await p.mkdtemp(l.join(Y.tmpdir(),"workspai-archive-export-")),y=l.join(u,"manifest-files.jsonl"),c=l.join(u,"archive-manifest.json"),f=new te.ZipFile,w=r.now??new Date,v=r.compression==="deflate";try{let P=createWriteStream(y,{flags:"wx"});try{for await(let d of se(t,t,{includeEnv:r.includeEnv===true})){if(l.resolve(d.fullPath)===m)continue;let g=await Ne(d),x={path:g.relativePath,size:g.size,sha256:g.sha256,mtimeMs:g.mtimeMs};await E(P,`${JSON.stringify(x)}
|
|
9
|
+
`);}await ne(P);}catch(d){throw P.destroy(),d}await Me({manifestBase:o,spoolPath:y,manifestPath:c});for await(let d of O(y)){let g=l.join(t,...d.path.split("/"));f.addFile(g,d.path,{compress:v,forceZip64Format:d.size>=4294967295,mtime:w});}f.addFile(c,A,{compress:v,mtime:w}),f.end({forceZip64Format:true,comment:""}),await pipeline(f.outputStream,createWriteStream(h,{flags:"wx"}));for await(let d of O(y)){let g=l.join(t,...d.path.split("/")),x=await p.stat(g);if(x.size!==d.size||x.mtimeMs!==d.mtimeMs)throw new Error(`Workspace file changed while writing archive: ${d.path}`)}let W=await p.stat(h);await Ie(h,n);let b=await Te(o,y);return C({schemaVersion:k,operation:"export",status:"passed",archivePath:n,manifest:b,bytesWritten:W.size})}finally{await p.remove(u).catch(()=>{}),await p.remove(h).catch(()=>{});}}async function oe(r,t={}){if(/^https?:\/\//i.test(r)){let e=await p.mkdtemp(l.join(Y.tmpdir(),"workspai-workspace-archive-")),i=l.join(e,"workspace.workspai-archive.zip"),a=new AbortController,s=t.downloadTimeoutMs??ye,n=s>0?setTimeout(()=>a.abort(new Error("Download timed out")),s):null;try{let o=await Pe(r,a.signal,t.allowPrivateNetwork===true);if(!o.ok)throw new Error(`Failed to download workspace archive: HTTP ${o.status}`);if(!o.body)throw new Error("Failed to download workspace archive: response body is empty.");let m=t.maxDownloadBytes??ve,h=Number(o.headers.get("content-length"));if(Number.isFinite(h)&&h>m)throw new Error(`Workspace archive download exceeds configured limit (${h} > ${m} bytes).`);let u=0,y=new Transform({transform(f,w,v){if(u+=f.length,u>m){v(new Error(`Workspace archive download exceeds configured limit (${m} bytes).`));return}v(null,f);}}),c=Readable.fromWeb(o.body);return await pipeline(c,y,createWriteStream(i,{flags:"wx"})),{archivePath:i,cleanup:e}}catch(o){throw await p.remove(e).catch(()=>{}),a.signal.aborted?new Error(`Workspace archive download timed out after ${s}ms.`,{cause:o}):o}finally{n&&clearTimeout(n);}}return {archivePath:l.resolve(r)}}function $e(r){return new Promise((t,e)=>{ee.open(r,{autoClose:false,lazyEntries:true,decodeStrings:true,validateEntrySizes:true,strictFileNames:true},(i,a)=>{i||!a?e(i??new Error("Failed to open workspace archive.")):t(a);});})}function Fe(r){return new Promise((t,e)=>{let i=[],a=s=>e(s);r.once("error",a),r.on("entry",s=>{try{if(ae(s.fileName),s.isEncrypted())throw new Error(`Encrypted workspace archive entries are not supported: ${s.fileName}`);s.fileName.endsWith("/")||i.push({name:s.fileName,size:s.uncompressedSize,compressedSize:s.compressedSize,crc32:s.crc32,entry:s}),r.readEntry();}catch(n){e(n);}}),r.once("end",()=>{r.removeListener("error",a),t(i);}),r.readEntry();})}function $(r,t){return new Promise((e,i)=>{r.openReadStream(t,(a,s)=>{a||!s?i(a??new Error(`Failed to read ${t.fileName}.`)):e(s);});})}async function Le(r,t,e=Ee){if(t.size>e)throw new Error(`Workspace archive manifest exceeds ${e} bytes.`);let i=[],a=0,s=await $(r,t.entry);for await(let n of s){let o=Buffer.isBuffer(n)?n:Buffer.from(n);if(a+=o.length,a>e)throw s.destroy(),new Error(`Workspace archive manifest exceeds ${e} bytes.`);i.push(o);}return Buffer.concat(i,a)}function Ve(r){let t=JSON.parse(r.toString("utf-8"));a$1(t,K,"Workspace archive manifest");let e=new Set;for(let i of t.files){if(!ie(i.path)||_(i.path)!==i.path)throw new Error(`Workspace archive manifest contains an unsafe path: ${i.path}`);if(i.path===A||i.path===R)throw new Error(`Workspace archive manifest cannot inventory itself: ${i.path}`);if(e.has(i.path))throw new Error(`Workspace archive manifest contains duplicate path: ${i.path}`);e.add(i.path);}return t}function C(r){return a$1(r,Z,"Workspace archive operation result"),r}function Be(r){return v(_(r))}function De(r){let t=new Map;for(let e of r){if(e.name===A||e.name===R)continue;let i=Be(e.name),a=t.get(i);if(!a){t.set(i,{...e,sourceName:e.name,targetName:i});continue}let s=e.name===i,n=a.sourceName===a.targetName;if(s&&!n){t.set(i,{...e,sourceName:e.name,targetName:i});continue}if(!(a.size===e.size&&a.crc32===e.crc32)&&!n)throw new Error(`Workspace archive contains conflicting entries for ${i}: ${a.sourceName}, ${e.name}`)}return [...t.values()].sort((e,i)=>e.targetName.localeCompare(i.targetName))}async function F(r,t={}){let e=await oe(r,t),i;try{i=await $e(e.archivePath);let a=await Fe(i);if(a.length>J)throw new Error(`Workspace archive contains too many entries (${a.length} > ${J}).`);for(let h of a){if(h.size>ge)throw new Error(`Workspace archive entry is too large: ${h.name}`);if(h.size/Math.max(1,h.compressedSize)>ke)throw new Error(`Workspace archive entry has an unsafe compression ratio: ${h.name}`)}let s=a.reduce((h,u)=>h+u.size,0),n=t.maxExpandedBytes??we;if(s>n)throw new Error(`Workspace archive payload exceeds configured limit (${s} > ${n} bytes).`);let o=a.find(h=>h.name===A||h.name===R);if(!o)throw new Error(`Workspace archive is missing ${p$1("","archive-manifest.json").replace(/^\//,"")}.`);let m=Ve(await Le(i,o));return {archivePath:e.archivePath,entries:a,manifest:m,zipFile:i,cleanup:e.cleanup}}catch(a){throw i?.close(),e.cleanup&&await p.remove(e.cleanup).catch(()=>{}),a}}async function L(r){r.zipFile?.close(),r.cleanup&&await p.remove(r.cleanup).catch(()=>{});}async function je(r){let t=await F(r.archivePathOrUrl,r.safety);try{let e=new Map(t.entries.filter(a=>a.name!==A&&a.name!==R).map(a=>[a.name,a])),i=t.manifest.files.map(a=>({path:a.path,size:e.get(a.path)?.size??a.size,hasChecksum:typeof a.sha256=="string"&&a.sha256.length>0}));return C({schemaVersion:k,operation:"inspect",status:"passed",archivePath:t.archivePath,manifest:t.manifest,fileCount:i.length,totalBytes:i.reduce((a,s)=>a+s.size,0),entries:i})}finally{await L(t);}}async function ce(r){let t=await F(r.archivePathOrUrl,r.safety);try{let e=new Map(t.entries.filter(c=>c.name!==A&&c.name!==R).map(c=>[c.name,c])),i=new Set(t.manifest.files.map(c=>c.path)),a=[...e.keys()].filter(c=>!i.has(c)).sort(),s=[],n=[],o=[],m=0;for(let c of t.manifest.files){ae(c.path);let f=e.get(c.path);if(!f){s.push(c.path);continue}let w=z.createHash("sha256"),v=0,P=await $(t.zipFile,f.entry);for await(let b of P){let d=Buffer.isBuffer(b)?b:Buffer.from(b);v+=d.length,w.update(d);}let W={size:v,sha256:w.digest("hex")};if(v!==f.size||v!==c.size){o.push({path:c.path,expected:{size:c.size,sha256:c.sha256},actual:W});continue}if(!c.sha256){n.push(c.path);continue}if(W.sha256!==c.sha256){o.push({path:c.path,expected:{size:c.size,sha256:c.sha256},actual:W});continue}m+=1;}let h=r.requireChecksums===true&&n.length>0,u=s.length>0||o.length>0||h||a.length>0,y=n.length>0;return C({schemaVersion:k,operation:"verify",archivePath:t.archivePath,manifest:t.manifest,status:u?"failed":y?"warning":"passed",fileCount:t.manifest.files.length,totalBytes:t.manifest.files.reduce((c,f)=>c+f.size,0),verifiedFiles:m,missingChecksumFiles:n,missingArchiveEntries:s,extraArchiveEntries:a,mismatches:o})}finally{await L(t);}}async function mt(r){let t=await oe(r.archivePathOrUrl,r.safety);try{return await He({archivePath:t.archivePath,strict:r.strict})}finally{t.cleanup&&await p.remove(t.cleanup).catch(()=>{});}}async function He(r){let t=await je({archivePathOrUrl:r.archivePath}),e=await ce({archivePathOrUrl:r.archivePath,requireChecksums:r.strict===true}),i=[],a=[];i.push({id:"manifest-present",status:"passed",message:`Archive manifest found for workspace "${t.manifest.workspaceName}".`}),i.push({id:"integrity",status:e.status,message:e.status==="passed"?`Verified ${e.verifiedFiles}/${e.fileCount} files.`:"Archive integrity verification did not fully pass."});let s=t.manifest.security?.envFilesIncluded===true;i.push({id:"secrets-policy",status:s?"warning":"passed",message:s?"Archive manifest says environment/private files were intentionally included.":"Archive manifest excludes environment/private files by default."}),s&&a.push("Share this archive only through trusted internal channels."),e.missingChecksumFiles.length>0&&a.push("Re-export the archive with the latest RapidKit/Workspai tooling."),e.mismatches.length>0&&a.push("Reject this archive and request a fresh export from the owner."),(e.extraArchiveEntries.length>0||e.missingArchiveEntries.length>0)&&a.push("Regenerate the archive so ZIP entries and manifest entries match."),r.strict===true&&e.status!=="passed"&&a.push("Do not hydrate this archive in strict or production workflows.");let n=i.some(m=>m.status==="failed"),o=i.some(m=>m.status==="warning");return C({schemaVersion:k,operation:"doctor",archivePath:t.archivePath,status:n?"failed":o?"warning":"passed",workspaceName:t.manifest.workspaceName,fileCount:t.fileCount,totalBytes:t.totalBytes,checks:i,recommendedActions:a})}async function Ue(r,t){let e=await p.lstat(r).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!e)return false;if(e.isSymbolicLink())throw new Error(`Output directory must not be a symbolic link: ${r}`);if(!e.isDirectory())throw new Error(`Output path is not a directory: ${r}`);if((await p.readdir(r)).length>0&&!t)throw new Error(`Output directory is not empty: ${r}. Use --force to overwrite.`);return true}async function ft(r){let t=await F(r.archivePathOrUrl,r.safety);try{let e=await ce({archivePathOrUrl:t.archivePath,requireChecksums:r.strict===true});if(e.status==="failed"){let o=[e.missingArchiveEntries.length?`missing entries: ${e.missingArchiveEntries.join(", ")}`:"",e.extraArchiveEntries.length?`unexpected entries: ${e.extraArchiveEntries.join(", ")}`:"",e.mismatches.length?`checksum/size mismatches: ${e.mismatches.map(m=>m.path).join(", ")}`:"",e.missingChecksumFiles.length&&r.strict===true?`missing checksums: ${e.missingChecksumFiles.join(", ")}`:""].filter(Boolean).join("; ");throw new Error(`Workspace archive verification failed${o?` (${o})`:""}.`)}if(e.status==="warning"&&r.strict===true)throw new Error(`Workspace archive verification requires checksums for every file: ${e.missingChecksumFiles.join(", ")}`);let i=De(t.entries),a=t.manifest,s=l.resolve(r.outputPath||re(a.workspaceName||"imported-workspace")),n=await Ue(s,r.force===true);if(!r.dryRun){let o=l.dirname(s),m=`${process.pid}-${z.randomUUID()}`,h=l.join(o,`.${l.basename(s)}.hydrate-${m}.tmp`),u=l.join(o,`.${l.basename(s)}.hydrate-${m}.backup`),y=false,c=false;await p.ensureDir(o);try{await p.ensureDir(h);for(let f of i){let w=l.resolve(h,f.targetName);if(!Re(w,h))throw new Error(`Archive entry escapes output directory: ${f.targetName}`);await p.ensureDir(l.dirname(w));let v=await $(t.zipFile,f.entry);await pipeline(v,createWriteStream(w,{flags:"wx"}));}n&&(await p.rename(s,u),y=true),await p.rename(h,s),c=true,y&&await p.remove(u).catch(()=>{});}catch(f){throw y&&!await p.pathExists(s)&&await p.rename(u,s).catch(()=>{}),f}finally{await p.remove(h).catch(()=>{}),c&&await p.remove(u).catch(()=>{});}}return C({schemaVersion:k,operation:"hydrate",status:"passed",archivePath:t.archivePath,outputPath:s,dryRun:r.dryRun===true,manifest:a,files:i.map(o=>({path:o.targetName,size:o.size}))})}finally{await L(t);}}
|
|
10
|
+
export{qe as a,q as b,k as c,Ke as d,A as e,de as f,Ae as g,X as h,re as i,ie as j,_e as k,ht as l,je as m,ce as n,mt as o,ft as p};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b,a,c as c$1}from'./chunk-44VJHNZB.js';var c=b.repairTransaction,l=a.repairTransaction,d=c$1.repairTransaction;var g="workspai.workspace-repair-proposal.v1",m="contracts/workspace-intelligence/workspace-repair-proposal.v1.json";var o="workspai.workspace-repair-capabilities.v1",s=[{id:"node",ecosystem:"JavaScript / TypeScript",manifests:["package.json"],lockfiles:["package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"],packageManagers:["npm","pnpm","yarn","bun"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["selected package manager"]},{id:"python",ecosystem:"Python",manifests:["pyproject.toml","requirements.txt"],lockfiles:["uv.lock","poetry.lock","requirements.txt"],packageManagers:["uv","poetry","pip"],support:"conditional",stages:{reconcile:"conditional",audit:"conditional",test:"conditional",build:"declared"},requiredToolFamilies:["isolated Python","selected environment manager","pip-audit or governed Doctor audit"],limitation:"A bounded isolated environment and an installed audit surface are required."},{id:"go",ecosystem:"Go",manifests:["go.mod"],lockfiles:["go.sum"],packageManagers:["go modules"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["go","govulncheck"],limitation:"govulncheck must be installed; the engine never fetches an unreviewed tool."},{id:"rust",ecosystem:"Rust",manifests:["Cargo.toml"],lockfiles:["Cargo.lock"],packageManagers:["cargo"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["cargo","cargo-audit"],limitation:"The cargo-audit subcommand must already be installed."},{id:"php-composer",ecosystem:"PHP",manifests:["composer.json"],lockfiles:["composer.lock"],packageManagers:["composer"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["composer"]},{id:"ruby-bundler",ecosystem:"Ruby",manifests:["Gemfile"],lockfiles:["Gemfile.lock"],packageManagers:["bundler"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"declared",build:"declared"},requiredToolFamilies:["bundle","bundle-audit"],limitation:"bundle-audit and the declared Rake tasks must already exist."},{id:"elixir-mix",ecosystem:"Elixir",manifests:["mix.exs"],lockfiles:["mix.lock"],packageManagers:["mix"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["mix","Hex audit task"],limitation:"The project must expose the Hex audit task used by its dependency policy."},{id:"deno",ecosystem:"Deno",manifests:["deno.json","deno.jsonc"],lockfiles:["deno.lock"],packageManagers:["deno"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["deno"]},{id:"dotnet",ecosystem:".NET",manifests:["*.sln","*.csproj","*.fsproj","*.vbproj"],lockfiles:["Directory.Packages.props","packages.lock.json"],packageManagers:["NuGet / dotnet"],support:"full",stages:{reconcile:"native",audit:"native",test:"native",build:"native"},requiredToolFamilies:["dotnet"]},{id:"jvm-maven",ecosystem:"JVM / Maven",manifests:["pom.xml"],lockfiles:[],packageManagers:["Maven Wrapper","Maven"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["mvnw or mvn","governed Doctor audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."},{id:"jvm-gradle",ecosystem:"JVM / Gradle",manifests:["build.gradle.kts","build.gradle"],lockfiles:["gradle.lockfile","gradle/libs.versions.toml"],packageManagers:["Gradle Wrapper","Gradle"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["gradlew or gradle","governed Doctor audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."},{id:"clojure",ecosystem:"Clojure",manifests:["deps.edn","project.clj"],lockfiles:[],packageManagers:["Clojure CLI","Leiningen"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"conditional",build:"conditional"},requiredToolFamilies:["clojure or lein","governed project audit"],limitation:"Tests and builds run only when the selected Clojure project surface declares a deterministic entrypoint."},{id:"scala-sbt",ecosystem:"Scala / sbt",manifests:["build.sbt"],lockfiles:[],packageManagers:["sbt"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["sbt","governed project audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."}];function R(){return {schemaVersion:o,owner:"Workspai CLI",workflow:["plan","preconditions","approval","checkpoint","execute","reconcile","audit","test","build","canonical-verify","close-or-rollback-or-decision"],invariants:{multiAdapterProjects:true,missingTools:"decision-required",unsupportedEcosystems:"decision-required",silentFallbackToModelExecution:false,approvalBoundToPlanHash:true,canonicalVerificationRequired:true,rollbackConflictDetection:true},adapters:s}}export{c as a,l as b,d as c,g as d,m as e,o as f,s as g,R as h};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a as a$2}from'./chunk-UFOCUHG3.js';import {a as a$1}from'./chunk-5XDPQ3CB.js';import {a,e,b}from'./chunk-WIO6L24E.js';import {e as e$1,d}from'./chunk-44VJHNZB.js';import w from'path';import {existsSync}from'fs';import F from'fs-extra';var L=[{artifactKind:"bootstrap-compliance",cardId:"bootstrap",fileNames:["bootstrap-compliance.latest.json"]},{artifactKind:"doctor-workspace",cardId:"doctor",fileNames:["doctor-remediation-plan-last-run.json","doctor-last-run.json"]},{artifactKind:"analyze",cardId:"analyze",fileNames:["analyze-last-run.json"]},{artifactKind:"readiness",cardId:"readiness",fileNames:["release-readiness-last-run.json"]},{artifactKind:"pipeline",cardId:"pipeline",fileNames:["pipeline-last-run.json"]},{artifactKind:"workspace-run",cardId:"workspaceRun",fileNames:["workspace-run-last.json"]},{artifactKind:"workspace-verify",cardId:"workspaceVerify",fileNames:["workspace-verify-last-run.json"]}];function u(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function k(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function v(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))]}function x(e,t,o){return o?t:w.relative(e,t).split(w.sep).join("/")}function q(e){let t=e?.trim()||"npx workspai bootstrap";if(!/(?:^|\s)--ci(?:\s|$)/.test(t)&&/(?:^|\s)--json(?:\s|$)/.test(t))return t.replace(/(?:^|\s)--json(?:\s|$)/,n=>{let r=n.startsWith(" ")?" ":"",a=n.endsWith(" ")?" ":"";return `${r}--ci --json${a}`}).trim();let o=/(?:^|\s)--ci(?:\s|$)/.test(t)?t:`${t} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(o)?o:`${o} --json`}function W(e){return `${JSON.stringify({schemaVersion:d.compatibilityMatrix.schemaVersion,generatedAt:e,source:"workspai workspace remediation-plan",runtimes:{},notes:["Minimal enterprise baseline. Add runtime and toolchain entries as governance matures."]},null,2)}
|
|
2
|
+
`}function J(e){return `${JSON.stringify({schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:e,note:"Minimal enterprise baseline. Set enabled: true and add artifact entries to activate mirroring."},null,2)}
|
|
3
|
+
`}function U(e){let t=e.payload,o=k(t.blockers),n=k(t.blockingReasons),r=k(t.failures),a=k(t.reasons),d=k(t.policyViolations),s=u(t.summary),l=k(s?.blockers);if(e.artifactKind==="analyze"){let c=(Array.isArray(t.findings)?t.findings:[]).map(i=>u(i)).filter(i=>!!i).map(i=>String(i.message??i.title??i.id??"").trim()).filter(Boolean);return v([...o,...c,...n])}if(e.artifactKind==="workspace-run"){let g=u(t.stages),c=Object.entries(g??{}).flatMap(([i,p])=>{let b=u(p);return (Array.isArray(b?.projects)?b.projects:[]).map(f=>u(f)).filter(f=>!!f).filter(f=>f.status==="failed"||f.ok===false).map(f=>`${i}: ${String(f.project??f.name??"project")} failed`)});return v([...o,...c,...n])}return v([...o,...n,...r,...a,...d,...l])}function A(e){return {id:e.id,artifactKind:e.artifactKind,cardId:e.cardId,title:e.title,order:e.order,phase:e.phase,scope:e.scope??"workspace",...e.projectName?{projectName:e.projectName}:{},...e.projectPath?{projectPath:e.projectPath}:{},...e.sourceStepId?{sourceStepId:e.sourceStepId}:{},...e.dependsOn?{dependsOn:e.dependsOn}:{},...e.strategy?{strategy:structuredClone(e.strategy)}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},status:e.status??"ready",mode:e.mode,risk:e.risk,requiresApproval:true,blocker:e.blocker,summary:e.summary,...e.command?{command:e.command}:{},...e.invocation?{invocation:structuredClone(e.invocation)}:{},verifyCommand:e.verifyCommand,cwd:e.cwd??"workspace",files:e.files??[],...e.operation?{operation:e.operation}:{},rollback:e.rollback??(e.operation?{available:true,strategy:"idempotent"}:{available:false,strategy:"none"}),notes:e.notes??[]}}function H(e){return (Array.isArray(e.report.payload.steps)?e.report.payload.steps:[]).flatMap((o,n)=>{let r=u(o),a=typeof r?.id=="string"?r.id.trim():"",d=typeof r?.projectName=="string"?r.projectName.trim():"",s=typeof r?.projectPath=="string"?r.projectPath.trim():"",l=typeof r?.originalCommand=="string"?r.originalCommand.trim():"";if(!r||!a||!d||!s)return [];let g=u(r.studioStatus),c=g?.state==="ready"||g?.state==="review-required"||g?.state==="blocked"||g?.state==="guidance-only"?g.state:"guidance-only",i=r.risk==="safe"||r.risk==="guarded"||r.risk==="invasive"?r.risk:"guarded",p=u(r.preview),b=x(e.workspacePath,s,e.includeAbsolutePaths),h=_({capability:{...r,command:l},absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),f=B({capability:r,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),j=r.executableInCurrentEnvironment===true&&!!h,R=V({strategy:r.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),m=u(r.transaction),y=m?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(m):void 0;return y&&(y.projectPath=b),[A({id:`doctor.${a}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof p?.title=="string"&&p.title.trim()?p.title.trim():`Repair ${d}`,order:e.startOrder+n,phase:typeof r.phase=="string"?r.phase:"doctor-remediation",blocker:typeof p?.summary=="string"&&p.summary.trim()?p.summary.trim():`Doctor remediation is pending for ${d}.`,summary:typeof p?.summary=="string"&&p.summary.trim()?p.summary.trim():`Execute the CLI-authored Doctor step for ${d}.`,mode:j?"run-command":"manual-guidance",risk:i,status:c,...j&&h?{command:h}:{},...j&&f?{invocation:f}:{},verifyCommand:typeof r.verifyCommand=="string"&&r.verifyCommand.trim()?r.verifyCommand.trim():"npx workspai doctor project --json",files:k(r.files).map(P=>{let S=w.isAbsolute(P)?P:w.resolve(s,P);return x(e.workspacePath,S,e.includeAbsolutePaths)}),notes:[`Source Doctor step: ${a}`,...typeof g?.reason=="string"?[g.reason]:[]],scope:"project",projectName:d,projectPath:b,sourceStepId:a,dependsOn:k(r.dependsOn).map(P=>`doctor.${P}`),strategy:R,transaction:y,cwd:"project",...u(r.rollback)?.available===true?{rollback:{available:true,strategy:"manual"}}:{}})]})}function _(e){let t=typeof e.capability.command=="string"?e.capability.command.trim():"";if(e.includeAbsolutePaths&&t)return t;let o=Z({operation:e.capability.operation,absoluteProjectPath:e.absoluteProjectPath});if(o)return a$2(o);let n=u(e.capability.invocation),r=typeof n?.executable=="string"?n.executable.trim():"",a=k(n?.args);if(r)return [r,...a].map(s=>/^[a-zA-Z0-9_./:@=+-]+$/.test(s)?s:JSON.stringify(s)).join(" ");if(!t)return;let d=e.absoluteProjectPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.replace(new RegExp(`^cd\\s+["']?${d}["']?\\s*&&\\s*`,"i"),"").replaceAll(e.absoluteProjectPath,".")}function B(e){let t=u(e.capability.invocation),o=typeof t?.executable=="string"?t.executable.trim():"",n=k(t?.args);if(!(!o||n.length!==(Array.isArray(t?.args)?t.args.length:0)))return {cwd:e.includeAbsolutePaths?e.absoluteProjectPath:".",executable:o,args:n}}function Z(e){let t=u(e.operation);if(!t||typeof t.type!="string")return;let o=structuredClone(t);for(let n of ["path","sourcePath"]){let r=o[n];if(typeof r!="string")continue;let a=w.isAbsolute(r)?w.relative(e.absoluteProjectPath,r):r;if(!a||a===".."||a.startsWith(`..${w.sep}`)||w.isAbsolute(a))return;o[n]=a.split(w.sep).join("/");}return o}function V(e){if(!Array.isArray(e.strategy))return;let t=structuredClone(e.strategy);if(!e.includeAbsolutePaths)for(let o of t)o.invocation&&(o.invocation.cwd=".");return t}function G(e){let t=Array.isArray(e.report.payload.projects)?e.report.payload.projects:e.report.payload.project?[e.report.payload.project]:[],o=new Set,n=[];for(let r of t){let a=u(r);if(!a)continue;let d=typeof a.name=="string"?a.name.trim():"",s=typeof a.path=="string"?a.path.trim():"";if(!d||!s)continue;let l=Array.isArray(a.repairCapabilities)?a.repairCapabilities:Array.isArray(a.probes)?a.probes.map(c=>u(c)?.repairCapability).filter(c=>c!==void 0):[],g=new Map;for(let c of Array.isArray(a.probes)?a.probes:[]){let i=u(c),p=u(i?.repairCapability),b=typeof p?.id=="string"?p.id.trim():"";b&&g.set(b,i?.status==="fail"?"blocking":"advisory");}for(let c of l){let i=u(c),p=typeof i?.id=="string"?i.id.trim():"";if(!i||!p)continue;let b=`${d}:${p}`;if(o.has(b))continue;o.add(b);let h=i.risk==="safe"||i.risk==="guarded"||i.risk==="invasive"?i.risk:"guarded",f=_({capability:i,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),j=B({capability:i,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),R=i.status==="available"&&!!f,m=u(i.transaction),y=m?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(m):void 0,P=g.get(p)??(y?"blocking":"advisory");y&&(y.projectPath=x(e.workspacePath,s,e.includeAbsolutePaths));let S=V({strategy:i.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),O=k(i.files).map(I=>x(e.workspacePath,I,e.includeAbsolutePaths)),C=f?n.find(I=>I.projectName===d&&I.command===f&&I.cwd==="project"):void 0;if(C){C.files=v([...C.files,...O]),C.notes=v([...C.notes,`Also satisfies Doctor capability: ${p}`]);continue}n.push(A({id:`doctor.${d}.${p}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof i.title=="string"&&i.title.trim()?i.title.trim():`Repair ${d}`,order:e.startOrder+n.length,phase:y?"dependency-remediation":"doctor-remediation",blocker:typeof i.reason=="string"&&i.reason.trim()?i.reason.trim():`Doctor remediation is pending for ${d}.`,summary:typeof i.reason=="string"&&i.reason.trim()?i.reason.trim():`Execute the Doctor-authored repair capability for ${d}.`,mode:R?i.canEditFiles===true?"edit-file":"run-command":"manual-guidance",risk:h,status:R?"ready":i.status==="manual"?"guidance-only":"blocked",...f?{command:f}:{},...j?{invocation:j}:{},verifyCommand:typeof i.verifyCommand=="string"&&i.verifyCommand.trim()?i.verifyCommand.trim():"npx workspai doctor project --json",files:O,notes:[`Source Doctor capability: ${p}`,`Doctor finding status: ${P}`,...k(i.limitations)],scope:"project",projectName:d,projectPath:x(e.workspacePath,s,e.includeAbsolutePaths),sourceStepId:p,strategy:S,transaction:y,cwd:"project",...i.operation?{rollback:{available:true,strategy:"manual"}}:{}}));}}return n}function Q(e){let t=[],o=q("npx workspai bootstrap --json");for(let n of e.blockers)n.includes("profile.enterprise.ci")&&t.push(A({id:"bootstrap.enterprise-ci",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Run bootstrap in deterministic CI mode",order:10,phase:"bootstrap-preflight",blocker:n,summary:"Enterprise bootstrap compliance requires --ci for deterministic execution.",mode:"run-command",risk:"safe",command:o,verifyCommand:o})),n.includes("profile.enterprise.compatibility-matrix")&&t.push(A({id:"bootstrap.compatibility-matrix",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise compatibility matrix baseline",order:20,phase:"bootstrap-config",blocker:n,summary:"Create the missing compatibility matrix baseline without overwriting user data.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[e$1.compatibilityMatrix],operation:{type:"file-create",path:e$1.compatibilityMatrix,content:W(e.generatedAt),overwrite:false}})),n.includes("profile.enterprise.mirror-config")&&t.push(A({id:"bootstrap.mirror-config",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise mirror config baseline",order:30,phase:"bootstrap-config",blocker:n,summary:"Create the missing mirror configuration baseline without enabling mirroring.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[".workspai/mirror-config.json"],operation:{type:"file-create",path:".workspai/mirror-config.json",content:J(e.generatedAt),overwrite:false}}));return t}function X(e){let t=Array.isArray(e.report.payload.steps)?e.report.payload.steps:[],o=[],n=new Map;for(let r of t){let a=u(r),d=u(a?.command),s=typeof a?.id=="string"?a.id.trim():"",l=typeof a?.project=="string"?a.project.trim():"",g=typeof a?.status=="string"?a.status:"",c=typeof d?.display=="string"?d.display.trim():"",i=a?.required===true;if(!s.startsWith("project.")||!l||!i||g!=="fail"&&g!=="missing"||!/^npx\s+workspai\s+workspace\s+run\s+/i.test(c))continue;let p=s.split(".").at(-1)??"stage",b=`workspaceVerify.${s}`,h=n.get(l),f=/(?:^|\s)--no-gates(?:\s|$)/.test(c)?c:`${c} --no-gates`;o.push(A({id:b,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof a.label=="string"&&a.label.trim()?a.label.trim():`Run ${p} for ${l}`,order:e.startOrder+o.length,phase:"fleet-run",blocker:typeof a.message=="string"&&a.message.trim()?a.message.trim():`${p} evidence is not current for ${l}.`,summary:`Produce fresh ${p} evidence for ${l} without re-entering the blocked aggregate gates.`,mode:"run-command",risk:p==="start"?"guarded":"safe",status:"ready",command:f,verifyCommand:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",scope:"project",projectName:l,projectPath:l,sourceStepId:s,...h?{dependsOn:[h]}:{},cwd:"workspace",notes:[`Source Workspace Verify step: ${s}`,"Aggregate verification must run only after this project evidence producer completes."]})),n.set(l,b);}return o}function Y(e){let t=v(e.blockers.flatMap(n=>{let r=n.match(/(?:project runtimes?|workspace)\s*\(([^)]+)\)\s+(?:is|are) not pinned/i);return r?.[1]?r[1].split(",").map(a=>a.trim().toLowerCase()).filter(a=>/^(python|node|go|java|dotnet|rust|php)$/.test(a)):[]})),o=[];for(let n of t){let r=`readiness.toolchain.${n}.setup`,a=e.blockers.find(d=>d.toLowerCase().includes(`(${n})`))??`The ${n} runtime is not pinned in the canonical workspace toolchain.`;o.push(A({id:r,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Pin ${n} in the workspace toolchain`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:a,summary:`Detect and persist the current ${n} runtime in the canonical workspace toolchain lock.`,mode:"run-command",risk:"safe",command:`npx workspai setup ${n} --json`,verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Run from the workspace root so the canonical toolchain.lock is updated."]})),o.push(A({id:`readiness.toolchain.${n}.bootstrap`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Reconcile the ${n} workspace foundation`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:`The ${n} runtime pin must be reconciled with the workspace foundation.`,summary:"Refresh the workspace foundation after the runtime pin is written.",mode:"run-command",risk:"guarded",command:"npx workspai bootstrap --ci --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:[r]}));}return o}function ee(e){if(e.report.artifactKind==="readiness"&&/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(e.blocker))return A({id:`${e.report.cardId}.doctor-owner.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:"Resolve dependency vulnerability through Doctor",order:e.order,phase:"dependency-remediation",blocker:e.blocker,summary:"Release Readiness is the aggregate gate; use the project-scoped Doctor remediation capability that owns this dependency failure.",mode:"verify-before-fix",risk:"guarded",status:"review-required",command:"npx workspai doctor workspace --plan --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Read doctor-remediation-plan-last-run.json and execute the matching surface-security-hygiene capability before rerunning Readiness.","Do not treat a Readiness refresh as remediation for a source dependency vulnerability."]});let o={analyze:{title:"Refresh analyze evidence",phase:"analysis",command:"npx workspai analyze --strict --json",verify:"npx workspai analyze --strict --json"},readiness:{title:"Refresh release readiness",phase:"release-readiness",command:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",verify:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json"},pipeline:{title:"Rerun governance pipeline",phase:"governance-pipeline",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"},"workspace-run":{title:"Rerun failed workspace stage",phase:"fleet-run",command:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json",verify:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json"},"workspace-verify":{title:"Refresh workspace verify gate",phase:"verification",command:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",verify:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json"},"doctor-workspace":{title:"Use Doctor remediation plan",phase:"doctor-remediation",command:"npx workspai doctor workspace --plan --json",verify:"npx workspai doctor workspace --json"}}[e.report.artifactKind]??{title:"Refresh artifact evidence",phase:"evidence-refresh",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"};return A({id:`${e.report.cardId}.refresh.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:o.title,order:e.order,phase:o.phase,blocker:e.blocker,summary:"No deterministic file operation is available for this artifact yet; refresh the evidence and continue with the card-specific plan.",mode:e.report.artifactKind==="doctor-workspace"?"verify-before-fix":"run-command",risk:"guarded",status:e.report.artifactKind==="doctor-workspace"?"review-required":"ready",command:o.command,verifyCommand:o.verify,notes:e.report.artifactKind==="doctor-workspace"?["Read doctor-remediation-plan-last-run.json for ordered file-level steps."]:[]})}async function te(e){let t=[a(e,".workspai/reports"),b(e,".workspai/reports")],o=[],n=new Set;for(let r of L)for(let a of r.fileNames){let d=(await Promise.all(t.map(s=>w.join(s,a)))).find(s=>existsSync(s));if(!(!d||n.has(`${r.artifactKind}:${a}`))){n.add(`${r.artifactKind}:${a}`);try{let s=await F.readJSON(d),l=u(s);if(!l)continue;o.push({artifactKind:r.artifactKind,cardId:r.cardId,fileName:a,absolutePath:d,payload:l});break}catch{o.push({artifactKind:r.artifactKind,cardId:r.cardId,fileName:a,absolutePath:d,payload:{blockers:[`${r.artifactKind}: report exists but could not be parsed.`]}});break}}}return o}async function le(e){let t=w.resolve(e.workspacePath),o=e.includeAbsolutePaths===true,n=e.ciMode===true,r=new Date().toISOString(),a$2=a(t,".workspai/reports"),d=await te(t),s=[],l=1;for(let c of d){if(c.artifactKind==="doctor-workspace"){let m=Array.isArray(c.payload.steps)?H({report:c,workspacePath:t,includeAbsolutePaths:o,startOrder:l}):G({report:c,workspacePath:t,includeAbsolutePaths:o,startOrder:l});s.push(...m),l+=m.length;continue}let i=U(c);if(i.length===0)continue;if(c.artifactKind==="bootstrap-compliance"){s.push(...Q({blockers:i,generatedAt:r})),l=s.length+1;continue}if(c.artifactKind==="workspace-verify"){let m=X({report:c,startOrder:l,ciMode:n});if(m.length>0){s.push(...m),l+=m.length;continue}}if(c.artifactKind==="readiness"){let m=Y({report:c,blockers:i,startOrder:l,ciMode:n});if(m.length>0){s.push(...m),l+=m.length;continue}}let p=s.some(m=>m.transaction?.kind==="dependency-security"),b=c.artifactKind==="readiness"&&i.some(m=>/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(m));if(p&&b)continue;let h=i[0],f=ee({report:c,blocker:h,order:l,ciMode:n}),R={readiness:new Set(["bootstrap","doctor"]),pipeline:new Set(["bootstrap","doctor","analyze","readiness"]),workspaceVerify:new Set(["bootstrap","doctor","readiness","workspaceRun"])}[c.cardId];if(c.cardId==="pipeline"){let m=["doctor","analyze","readiness"].find(y=>h.toLowerCase().includes(y));m&&(R=new Set([m]));}if(R){let m=s.filter(y=>R.has(y.cardId)&&y.risk!=="invasive"&&y.status!=="blocked"&&y.status!=="guidance-only").map(y=>y.id);m.length>0&&(f.dependsOn=v([...f.dependsOn??[],...m]),f.notes.push("This aggregate gate must run after its contract-owned upstream remediation actions."));}i.length>1&&f.notes.push(...i.slice(1,8).map(m=>`Related blocker: ${m}`)),s.push(f),l+=1;}let g={safe:s.filter(c=>c.risk==="safe").length,guarded:s.filter(c=>c.risk==="guarded").length,invasive:s.filter(c=>c.risk==="invasive").length};return {schemaVersion:a$1,generatedAt:r,workspace:{name:w.basename(t),...o?{path:t}:{}},source:{command:"workspace remediation-plan",reportsDir:x(t,a$2,o),includeAbsolutePaths:o,ciMode:n},summary:{artifactsScanned:d.length,cardsCovered:v(s.map(c=>c.cardId)).length,totalActions:s.length,executableActions:s.filter(c=>c.status==="ready").length,risk:g},actions:s}}async function me(e$2,t){return e(t,e$1.artifactRemediationPlan,e$2)}export{le as a,me as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {d}from'./chunk-44VJHNZB.js';var i=d.doctorFixResult.schemaVersion,n="npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json";function a(t){return {schemaVersion:i,generatedAt:new Date().toISOString(),appliedFixes:t.appliedFixes,remainingBlockers:t.remainingBlockers,verifyRecommended:t.verifyRecommended??n}}var g="doctor-graph-diagnosis.v1";export{i as a,n as b,a as c,g as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {f as f$1,e}from'./chunk-T3GJ7YVG.js';import {a as a$1,b as b$2}from'./chunk-
|
|
1
|
+
import {f as f$1,e}from'./chunk-T3GJ7YVG.js';import {a as a$1,b as b$2}from'./chunk-MRFN5ZQP.js';import {a as a$2}from'./chunk-27UR373Z.js';import {h,j as j$1}from'./chunk-2PY65U6X.js';import {e as e$1}from'./chunk-WIO6L24E.js';import {a,b as b$1}from'./chunk-44VJHNZB.js';import {j,s,t}from'./chunk-MOSXTVPU.js';import b from'fs';import p from'path';import o from'chalk';var H=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function D(e){try{return await b.promises.access(e,b.constants.F_OK),true}catch{return false}}async function P(e){try{let n=JSON.parse(await b.promises.readFile(e,"utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function L(e){try{return await b.promises.readFile(e,"utf-8")}catch{return ""}}function K(e){return a$1(e)}async function B(e,n){return await N([...t(e,"project.json"),...t(e,"context.json")])?true:b$2(e)?false:p.resolve(e)===p.resolve(n)?h(e).length>0:h(e).length>0}async function U(e){let n=await a$2(e,{skipDirs:H,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:B});return n.length>0?n:b$2(e)?[]:h(e).length>0?[e]:[]}function V(e,n){return p.relative(e,n).replace(/\\/g,"/")||"."}async function A(e,n){for(let t of n)if(await D(p.join(e,t)))return true;return false}async function N(e){for(let n of e)if(await D(n))return true;return false}async function M(e){for(let n of e){let t=await P(n);if(t)return t}return null}async function q(e){return A(e,["health","health.ts","health.js","health.py","health.go","health.kt","health.rb","health.php","healthcheck","health-check","src/health.ts","src/health.js","src/health.py","src/health.go","src/health.kt","src/health.rb","src/health.php","src/healthcheck.ts","src/healthcheck.js","src/liveness.ts","src/readiness.ts","src/ping.ts"])}async function Q(e){if(await A(e,["tests","test","__tests__","src/__tests__","pytest.ini","vitest.config.ts","jest.config.ts"]))return true;let t=await P(p.join(e,"package.json")),r=t?.scripts&&typeof t.scripts=="object"?t.scripts:{};return typeof r.test=="string"&&r.test.trim().length>0}async function X(e){let n=await P(p.join(e,"package.json")),t=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return Object.keys(t).sort()}function f(e,n,t,r,s,a){return {id:e,severity:n,target:t,title:r,detail:s,remediation:a}}function Y(e){let n=e.reduce((t,r)=>r.severity==="fail"?t+28:r.severity==="warn"?t+12:t+3,0);return Math.max(0,100-n)}async function Z(e,n){let t$1=await M(t(n,"project.json")),r=j$1(n,t$1),s=h(n),a=r.runtime==="unknown"?s[0]||"unknown":r.runtime,i=V(e,n),l=i,u=await X(n),g=await N([...t(n,"project.json"),...t(n,"context.json")]),d=await Q(n),h$1=await A(n,["Dockerfile","dockerfile"]),k=await A(n,[".env.example","env.example","config/env.example"]),z=await A(n,[".github/workflows/ci.yml",".github/workflows/ci.yaml",".github/workflows/main.yml",".github/workflows/build.yml",".github/workflows/test.yml",".github/workflows/deploy.yml",".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml"]),C=await q(n),m=[];return r.key==="unknown"&&m.push(f("project.stack.unknown","fail",l,"Project stack is unknown","Workspai cannot confidently classify this backend project.","Add .workspai/project.json metadata or import the project with `workspai import`.")),g||m.push(f("project.marker.missing","warn",l,"Workspai marker is missing","The project can be detected by files, but it is not registered with Workspai metadata.","Run `workspai import <path>` from a workspace or create the project through Workspai.")),d||m.push(f("project.tests.missing","warn",l,"Test entrypoint is missing","No common test folder, config, or package test script was found.","Add a test command so `workspai workspace run test --affected` can gate changes.")),k||m.push(f("project.env.example.missing","info",l,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.")),z||m.push(f("project.ci.missing","warn",l,"Continuous integration is missing","No recognized CI/CD configuration file was detected for this project.","Add CI configuration so tests and checks run automatically for every change.")),C||m.push(f("project.health.missing","info",l,"Health or readiness probe is missing","The project has no obvious health or readiness endpoint to support automated deployment and runtime checks.","Add a simple health endpoint and document it for readiness gates and observability.")),h$1||m.push(f("project.container.missing","info",l,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.")),{name:p.basename(n),path:n,relativePath:i,runtime:a,framework:r.key,confidence:r.confidence,supportTier:r.supportTier,hasRapidKitMarker:g,hasTests:d,hasDockerfile:h$1,hasEnvExample:k,hasCiConfig:z,hasHealthEndpoint:C,scripts:u,findings:m,score:Y(m)}}function ee(e){return e.name.toLowerCase()}async function ne(e){let n=new Map(e.map(s=>[ee(s),s])),t=[];for(let s of e){let a=await P(p.join(s.path,"package.json")),i={...a?.dependencies??{},...a?.devDependencies??{},...a?.peerDependencies??{}};for(let u of Object.keys(i)){let g=u.replace(/^@[^/]+\//,"").toLowerCase(),d=n.get(g);d&&d.relativePath!==s.relativePath&&t.push({from:s.relativePath,to:d.relativePath,kind:"package"});}let l=await L(p.join(s.path,"pyproject.toml"));for(let u of e)u.relativePath!==s.relativePath&&l.includes(u.name)&&t.push({from:s.relativePath,to:u.relativePath,kind:"workspace-reference"});}let r=new Set;return t.filter(s=>{let a=`${s.from}\0${s.to}\0${s.kind}`;return r.has(a)?false:(r.add(a),true)})}function te(e,n){let t=new Map;for(let r of e)t.set(r.relativePath,{project:r.relativePath,directDependents:0,directDependencies:0});for(let r of n){let s=t.get(r.from),a=t.get(r.to);s&&(s.directDependencies+=1),a&&(a.directDependents+=1);}return Array.from(t.values()).sort((r,s)=>s.directDependents-r.directDependents||s.directDependencies-r.directDependencies)}async function re(e){let n=await M(s(e,"workspace.json"));return typeof n?.profile=="string"?n.profile:null}function se(e){return {fail:e.filter(n=>n.severity==="fail").length,warn:e.filter(n=>n.severity==="warn").length,info:e.filter(n=>n.severity==="info").length}}function oe(e){if(e.projectCount===0)return e.workspaceDetected?["Add your first project: npx workspai create project <name> --kit <kit>","Import an existing service: npx workspai import <path>"]:["Create a Workspai workspace: npx workspai create workspace my-workspace --profile polyglot","Import an existing service: npx workspai import ../service"];let n=[];return e.findings.some(t=>t.id==="workspace.marker.missing")&&n.push("Initialize workspace metadata with `workspai bootstrap --profile polyglot`."),e.findings.some(t=>t.id==="project.marker.missing")&&n.push("Register detected projects with `workspai import <path>` or recreate them via `workspai create project`."),e.findings.some(t=>t.id==="project.tests.missing")&&n.push("Add test entrypoints, then gate changes with `workspai workspace run test --affected --strict`."),e.findings.some(t=>t.id==="project.ci.missing")&&n.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(t=>t.id==="project.health.missing")&&n.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasGraph||n.push("Create `.workspai/workspace-dependency-graph.json` or use analyze output as the first graph seed."),n.push("Run `workspai autopilot release --mode audit --json` before release."),Array.from(new Set(n))}async function ke(e$2={}){let n=p.resolve(e$2.workspacePath||process.cwd());if(!await D(n))throw new Error(`Workspace path does not exist: ${n}`);let t=K(n)??n,r=j(t),s=await re(t),a$1=await U(t),i=await Promise.all(a$1.map(c=>Z(t,c))),l=await ne(i),u=te(i,l),g=[];r||g.push(f("workspace.marker.missing","warn",".","Workspace metadata is missing","The directory can be analyzed, but it is not a registered Workspai workspace.","Run `workspai create workspace` or `workspai bootstrap --profile polyglot` in a workspace root.")),i.length===0&&g.push(f("workspace.projects.missing","warn",".","No backend projects detected","Workspai did not find runtime markers or project metadata under this root.","Create a project with `workspai create project` or import one with `workspai import <path>`."));let d=[...g,...i.flatMap(c=>c.findings)],h=se(d),k={};for(let c of i)k[c.runtime]=(k[c.runtime]||0)+1;let z=i.length>0?Math.round(i.reduce((c,y)=>c+y.score,0)/i.length):0,C=g.reduce((c,y)=>c+(y.severity==="fail"?20:y.severity==="warn"?8:2),0),m=Math.max(0,z-C),O=i.length===0&&h.fail===0&&d.length>0&&d.every(c=>c.id==="workspace.projects.missing"&&c.severity==="warn"),J=h.fail>0||e$2.strict&&h.warn>0&&!O?"blocked":h.warn>0?"needs-attention":"ready",w={schemaVersion:b$1.analyze,generatedAt:new Date().toISOString(),workspacePath:t,workspaceDetected:r,profile:s,summary:{score:m,verdict:J,projectCount:i.length,runtimeCount:Object.keys(k).length,findings:h},runtimes:k,projects:i,dependencyGraph:{status:l.length>0?"generated":"empty",edges:l,topImpactedProjects:u.slice(0,5)},findings:d,nextActions:oe({findings:d,projectCount:i.length,hasGraph:l.length>0,workspaceDetected:r}),enterpriseControls:{jsonReady:true,ciGateCommand:"workspai analyze --json --strict",releaseGateCommand:"workspai autopilot release --mode enforce --json",evidencePath:a.analyze}};if(e$2.output&&(await b.promises.mkdir(p.dirname(p.resolve(e$2.output)),{recursive:true}),await b.promises.writeFile(p.resolve(e$2.output),`${JSON.stringify(w,null,2)}
|
|
2
2
|
`)),!e$2.output&&r){let c=f$1(w,{commandId:"workspaceAnalyze",exitCode:w.summary.verdict==="blocked"?2:w.summary.verdict==="needs-attention"?1:0,generatedAt:w.generatedAt,blockers:w.findings.filter(y=>y.severity==="fail").map(y=>y.title).slice(0,12),runId:e()});await e$1(t,a.analyze,c);}return w}function we(e){let n=e.summary.verdict==="ready"?o.green:e.summary.verdict==="needs-attention"?o.yellow:o.red;if(console.log(o.bold(`
|
|
3
3
|
Workspai Workspace Analysis
|
|
4
4
|
`)),console.log(o.cyan("Workspace:"),e.workspacePath),console.log(o.cyan("Profile:"),e.profile||"not configured"),console.log(o.cyan("Score:"),`${e.summary.score}/100`),console.log(o.cyan("Verdict:"),n(e.summary.verdict)),console.log(o.gray(`Projects: ${e.summary.projectCount}, runtimes: ${e.summary.runtimeCount}, findings: ${e.summary.findings.fail} fail / ${e.summary.findings.warn} warn / ${e.summary.findings.info} info`)),e.projects.length>0){console.log(o.bold(`
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {w}from'./chunk-6HJJHEL6.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2,d as d$1,c,e as e$2}from'./chunk-WIO6L24E.js';import {b as b$1}from'./chunk-BYVTHIC3.js';import {e,a,d,b}from'./chunk-44VJHNZB.js';import {l}from'./chunk-OCGZNSOE.js';import {e as e$1}from'./chunk-RO73VVHW.js';import {s,t,p}from'./chunk-MOSXTVPU.js';import*as g from'path';import g__default from'path';import h from'fs-extra';var he="unknown-run";function X(e){let t=e$1();return !t||t===he?e:{...e,runId:t}}async function ee(e,t){await h.ensureDir(g.dirname(e));let r=`${e}.${process.pid}.${Date.now()}.tmp`;try{await h.writeJSON(r,t,{spaces:2}),await h.move(r,e,{overwrite:true});}finally{await h.remove(r).catch(()=>{});}}function te(e){return p(e,"imported-projects.json")}async function I(e){let t=(await Promise.all(s(e,"imported-projects.json").map(async r=>await h.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!t)return [];try{let r=await h.readJSON(t);if(!r||typeof r!="object"||r.version!==1||!Array.isArray(r.projects))throw new Error("expected a version 1 registry with a projects array");let o=r.projects,a=o.filter(c=>{if(!c||typeof c!="object")return false;let i=c;return typeof i.name=="string"&&typeof i.path=="string"&&typeof i.stack=="string"&&typeof i.confidence=="string"&&typeof i.importedAt=="string"});if(a.length!==o.length)throw new Error("one or more project entries are invalid");return a}catch(r){throw new Error(`Imported-project registry is invalid: ${t}`,{cause:r})}}async function Te(e,t){if(t.length===0)return;let r=await I(e),o=new Map;for(let l of r)o.set(l.path,l);for(let l of t)o.set(l.path,l);let a=Array.from(o.values()).sort((l,u)=>l.name.localeCompare(u.name)).map(l=>({...l})),c={version:1,updatedAt:new Date().toISOString(),projects:a},i=te(e);await ee(i,c);}async function Ve(e,t){if(t.length===0)return;let r=await I(e),o=new Set(t.map(l=>g.resolve(l))),a=r.filter(l=>!o.has(g.resolve(l.path))),c={version:1,updatedAt:new Date().toISOString(),projects:a},i=te(e);await ee(i,c);}var Fe="workspace-dependency-graph.v1",re=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],oe=["inferred","contract","manual"];var E=e.workspaceContract,ke=a.contractVerify,R=d.workspaceContract.schemaVersion,we=b.contractVerify,N=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function ie(e){return e.replace(/\\/g,"/")}function H(e){let t=ie(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function ne(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function Pe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function ye(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(c=>{if(!c||typeof c!="object"||Array.isArray(c))return null;let i=c,l=Number(i.port);if(!Number.isInteger(l)||l<1||l>65535)return null;let u=i.protocol==="https"||i.protocol==="grpc"||i.protocol==="tcp"||i.protocol==="udp"?i.protocol:"http";return {name:typeof i.name=="string"&&i.name.trim()?i.name:"http",port:l,protocol:u}}).filter(c=>c!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,a=Number(e.port??o?.default_port);return Number.isInteger(a)&&a>=1&&a<=65535?[{name:"http",port:a,protocol:"http"}]:[]}async function D(e){for(let t of e)if(await h.pathExists(t))return t;return null}async function Ce(e){for(let t of s(e,"workspace.json"))try{let r=await h.readJson(t);return {name:typeof r.workspace_name=="string"&&r.workspace_name.trim()||typeof r.name=="string"&&r.name.trim()||g__default.basename(e),profile:typeof r.profile=="string"?r.profile:void 0}}catch{}return {name:g__default.basename(e)}}async function Ee(e){let t$1=[],r=[e],o=new Set,a=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let c=r.shift();if(!c||o.has(c))continue;o.add(c);let i=await D(t(c,"project.json")),l=await D(t(c,"context.json"));if(i||l){t$1.push(i??l??"");continue}let u;try{u=await h.readdir(c,{withFileTypes:true});}catch{continue}for(let d of u)!d.isDirectory()||a.has(d.name)||a$1(d.name)||r.push(g__default.join(c,d.name));}return t$1.sort()}function je(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function be(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function ae(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function M(e,t,r){let o=e!==void 0&&e.source===void 0,a=be(t.kit,t.runtime),c=e?.ports||[],i=t.ports||[],u=(c.length>0?c:i.length>0?i:a?[{name:"http",port:ae(a,r),protocol:"http"}]:[]).map(p=>({...p,port:ae(p.port,r)}));for(let p of u)r.add(p.port);let d={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&H(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:e?.runtime||t.runtime,framework:e?.framework||t.framework,kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:u,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},s=JSON.stringify(e||null)!==JSON.stringify(d);return {project:d,changed:s}}async function pe(e){let t$1=g__default.resolve(e.workspacePath),r=await Ce(t$1),o=await Ee(t$1),a=await I(t$1),c=[];for(let d of a){let s=g__default.resolve(d.path),p=await D(t(s,"project.json"))??await D(t(s,"context.json"));!p||o.some(k=>g__default.resolve(k)===g__default.resolve(p))||c.push({projectJsonPath:p,registryEntry:d});}let i=[],l=[...o.map(d=>({projectJsonPath:d})),...c];for(let{projectJsonPath:d,registryEntry:s}of l){let p=g__default.dirname(g__default.dirname(d)),k=ie(g__default.relative(t$1,p)),f=s!==void 0&&!H(k),P=ne(s?.name||g__default.basename(p),g__default.basename(p)),y=f?`external/${P}`:k||P,w=await h.readJson(d),x=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,n=typeof w.framework=="string"&&w.framework||je(x);i.push({slug:s?.name||y||g__default.basename(p),relativePath:y,source:s?.source??"workspace",relationship:s?.relationship,externalPath:f?p:void 0,runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:n,kit:x,modules:Pe(w.modules),ports:ye(w),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let u=new Map;for(let d of i){let s=ne(d.slug,d.relativePath),p=u.get(s);(!p||p.source!=="workspace"&&d.source==="workspace")&&u.set(s,d);}return {schemaVersion:R,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...u.values()]}}async function rt(e){let t=g__default.resolve(e.outputPath||a$2(e.workspacePath,E));if(await h.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await pe({workspacePath:e.workspacePath,now:e.now}),o=new Set,a={...r,projects:r.projects.map(i=>M(void 0,i,o).project)},c=await ue({workspacePath:e.workspacePath,contractPath:t,contract:a});if(e.strict&&c.status==="failed")throw new N(c);return await de({workspacePath:e.workspacePath,contractPath:t,contract:a,now:e.now}),{contractPath:t,contract:a}}async function ot(e){let t=g__default.resolve(e.workspacePath),r=a$2(t,E),o=await d$1(t,E)??r,a=await pe({workspacePath:t,now:e.now}),c=await h.pathExists(o)?await h.readJson(o):null,i=new Map((c?.projects||[]).map(f=>[f.slug,f])),l=new Set,u=[],d=[],s=[];for(let f of a.projects){let P=i.get(f.slug),y=M(P,f,l);P?y.changed&&d.push(f.slug):u.push(f.slug),s.push(y.project),i.delete(f.slug);}for(let f of i.values()){if(f.source)continue;let P=M(f,f,l);s.push(P.project);}let p={schemaVersion:R,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...c?.workspace||{},...a.workspace,name:a.workspace.name||c?.workspace?.name||g__default.basename(t)},projects:s.sort((f,P)=>f.slug.localeCompare(P.slug))},k=await ue({workspacePath:t,contractPath:r,contract:p});if(e.strict&&k.status==="failed")throw new N(k);return await de({workspacePath:t,contractPath:r,contract:p,now:e.now}),{contractPath:r,contract:p,addedProjects:u,updatedProjects:d,verification:k}}async function se(e){return await h.pathExists(e)?{exists:true,contents:await h.readFile(e)}:{exists:false}}async function ce(e,t){if(!t.exists){await h.remove(e);return}await h.outputFile(e,t.contents);}async function de(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-GPJEL7K7.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),a=a$2(e.workspacePath,r),c$1=i=>{if(!i||typeof i!="object"||Array.isArray(i))return JSON.stringify(i);let{generatedAt:l,...u}=i;return JSON.stringify(u)};if(await h.pathExists(e.contractPath)&&await h.pathExists(a)){let[i,l]=await Promise.all([h.readJson(e.contractPath),h.readJson(a)]);if(c$1(i)===c$1(e.contract)&&c$1(l)===c$1(o))return}b$1(E,e.contract),b$1(r,o),await c(e.workspacePath,E,async()=>{let[i,l]=await Promise.all([se(e.contractPath),se(a)]);try{if(e.contractPath===a$2(e.workspacePath,E)?await e$2(e.workspacePath,E,e.contract):(await h.ensureDir(g__default.dirname(e.contractPath)),await h.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await e$2(e.workspacePath,r,o);}catch(u){let s=(await Promise.allSettled([ce(e.contractPath,i),ce(a,l)])).filter(p=>p.status==="rejected");throw s.length>0?new AggregateError([u,...s.map(p=>p.reason)],"Workspace contract publication failed and rollback was incomplete."):u}});}async function le(e){let t=e.contractPath??(await d$1(e.workspacePath,E)||a$2(e.workspacePath,E)),r=await h.readJson(t);return {contractPath:t,contract:r}}var ve={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function We(e,t){return t.externalPath?g__default.resolve(t.externalPath):g__default.resolve(e,t.relativePath)}async function Se(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(ve))for(let a of o)await h.pathExists(g__default.join(e,a))&&t[r].push(a);try{let r=await h.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,a)=>o.localeCompare(a));return t}function A(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function Ae(e){try{let t=await h.readJson(g__default.join(e,"package.json")),r={runtime:A(t.dependencies),development:A(t.devDependencies),peer:A(t.peerDependencies),optional:A(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:A(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function Re(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await h.readFile(g__default.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,a)=>o.localeCompare(a))}catch{}return []}function xe(e,t){try{let r=w(e);if(r.engine!=="unknown")return r;let o=h.pathExistsSync(g__default.join(e,"package.json"))?"npm":h.pathExistsSync(g__default.join(e,"pyproject.toml"))?"python":h.pathExistsSync(g__default.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function _e(e,t,r){let o=e.projects.map(a=>({id:a.slug,path:a.relativePath,runtime:a.runtime,framework:a.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function nt(e){let{contractPath:t,contract:r}=await le(e),o=e.now??new Date,a$1=o.toISOString(),{buildWorkspaceModel:c,workspaceModelProjectTopology:i}=await import('./workspace-model-MNJOGBPP.js'),{hashWorkspaceModel:l}=await import('./workspace-model-hash-ZXYPIGCW.js'),u=await c({workspacePath:e.workspacePath,includeEvidence:false,now:o}),d=i(u)??_e(r,a$1,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(d.nodes.map(n=>[n.id,n.operationalProfile])),{buildWorkspaceKnowledgeGraph:p}=await import('./workspace-knowledge-graph-BMMM2FUE.js'),k=await p({workspacePath:e.workspacePath,workspace:{name:u.workspace.name,...u.workspace.profile?{profile:u.workspace.profile}:{}},contract:r,projectTopology:d,now:o,projects:u.projects.map(n=>({id:n.name,path:n.path,...n.absolutePath?{absolutePath:n.absolutePath}:{},runtime:n.runtime,runtimeCandidates:n.runtimeCandidates,framework:n.framework,...n.kit?{kit:n.kit}:{}})),source:{kind:"workspace-model",artifact:a.model,hashAlgorithm:"sha256",hash:l(u)}}),f=await Promise.all(r.projects.map(async n=>{let m=We(e.workspacePath,n),[_,v,me]=await Promise.all([Se(m),Ae(m),Re(m)]),C=xe(m,n);return {id:n.slug,label:n.slug,relativePath:n.relativePath,source:n.source,relationship:n.relationship,externalPath:n.externalPath,runtime:n.runtime??C.runtime,framework:n.framework??C.framework,kit:n.kit,modules:n.modules,ports:n.ports,apis:n.contracts.apis,owns:n.contracts.owns,env:[...new Set([...n.contracts.env,...me])].sort((ge,fe)=>ge.localeCompare(fe)),contracts:{owns:[...n.contracts.owns],apis:[...n.contracts.apis],publishes:[...n.contracts.publishes],consumes:[...n.contracts.consumes],dependsOn:[...n.contracts.dependsOn],env:[...n.contracts.env]},capabilities:{engine:C.engine,supportTier:C.frameworkSupportTier,runtimeSupportTier:C.runtimeSupportTier,doctorSupport:C.runtimeDoctorSupport,moduleSupport:C.moduleSupport,fleetStages:[...C.fleetStages],localOnlyCommands:[...C.localOnlyCommands],supportedCommands:[...C.supportedCommands]},files:_,...v?{package:v}:{},...s.get(n.slug)?{operationalProfile:s.get(n.slug)}:{}}})),P=new Set(f.map(n=>n.id)),y=new Map,w=[];for(let n of r.projects){for(let m of n.contracts.dependsOn||[])P.has(m)&&w.push({from:m,to:n.slug,type:"dependency",label:"dependsOn"});for(let m of n.contracts.publishes||[])y.has(m)||y.set(m,new Set),y.get(m)?.add(n.slug);}for(let n of r.projects)for(let m of n.contracts.consumes||[]){let _=y.get(m);if(_)for(let v of _)v!==n.slug&&w.push({from:v,to:n.slug,type:"event",label:m});}let x={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:a$1,nodes:f.sort((n,m)=>n.id.localeCompare(m.id)),edges:w.sort((n,m)=>`${n.from}:${n.to}:${n.type}:${n.label}`.localeCompare(`${m.from}:${m.to}:${m.type}:${m.label}`)),dependencyGraph:d,knowledgeGraph:k,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:f.length,dependencyEdges:w.filter(n=>n.type==="dependency").length,eventEdges:w.filter(n=>n.type==="event").length,portCount:f.reduce((n,m)=>n+m.ports.length,0),apiCount:f.reduce((n,m)=>n+m.apis.length,0),relationshipEdges:d.stats.edgeCount,inferredEdges:d.stats.inferredEdges,authoritativeEdges:d.stats.authoritativeEdges,orphanProjects:d.stats.orphanCount,hotspotProjects:d.stats.hotspotCount,evidenceCoverageRatio:d.stats.evidenceCoverageRatio,edgeCoverageRatio:d.stats.edgeCoverageRatio,connectedProjects:d.stats.connectedNodeCount,lowConfidenceEdges:d.stats.lowConfidenceEdges,hasCycle:d.stats.hasCycle,manifestCount:f.reduce((n,m)=>n+m.files.manifests.length,0),entrypointCount:f.reduce((n,m)=>n+m.files.entrypoints.length,0),diagnostics:d.diagnostics?.length??0,relationshipKinds:Object.fromEntries(re.map(n=>[n,d.edges.filter(m=>m.kind===n).length])),relationshipSources:Object.fromEntries(oe.map(n=>[n,d.edges.filter(m=>m.source===n).length])),entityCount:k.quality.entityCount,knowledgeRelations:k.quality.relationCount,proofCount:k.quality.proofCount,providerCount:k.providers.length,knowledgeUnknowns:k.quality.unknownCount}};return {contractPath:t,graph:x}}async function ue(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,E),contract:e.contract}:await le(e),{contractPath:r,contract:o}=t,a=[],c=[];o.kind!=="rapidkit.workspace.contract"&&a.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==R&&a.push(`Contract schemaVersion must be ${R}.`),o.workspace?.name||a.push("Contract workspace.name is required."),Array.isArray(o.projects)||a.push("Contract projects must be an array.");let i=new Set,l$1=new Map;for(let s of o.projects||[]){if(!s.slug){a.push("Every project must declare slug.");continue}i.has(s.slug)&&a.push(`Duplicate project slug: ${s.slug}.`),i.add(s.slug),s.relativePath?H(s.relativePath)||a.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):a.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||a.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),g__default.isAbsolute(s.externalPath)||a.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let p of s.ports||[]){(!Number.isInteger(p.port)||p.port<1||p.port>65535)&&a.push(`Project ${s.slug} declares invalid port: ${p.port}.`);let k=l$1.get(p.port);k&&a.push(`Port ${p.port} is claimed by both ${k} and ${s.slug}.`),l$1.set(p.port,s.slug);}for(let p of s.contracts?.apis||[])(!p.name?.trim()||!p.basePath?.startsWith("/"))&&a.push(`Project ${s.slug} declares invalid API contract.`);for(let p of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])p.trim()||a.push(`Project ${s.slug} declares an empty event contract.`);for(let p of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(p)||a.push(`Project ${s.slug} declares invalid env contract: ${p}.`);for(let p of s.contracts?.dependsOn||[])i.has(p);}for(let s of o.projects||[])for(let p of s.contracts?.dependsOn||[])i.has(p)||a.push(`Project ${s.slug} depends on unknown project: ${p}.`);c.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===R?"passed":"failed",message:"Contract schema and kind are valid."}),c.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),c.push({id:"ports",status:a.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),c.push({id:"dependencies",status:a.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),c.push({id:"contracts",status:a.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let u=await l(e.workspacePath);if(u.moduleCount>0){for(let s of u.issues)a.push(`${g__default.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);c.push({id:"module-paths",status:u.status,message:u.status==="passed"?`All ${u.moduleCount} registered module(s) resolve under canonical paths.`:`${u.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&c.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:a.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:c,violations:a}}async function at(e){let t=g__default.resolve(e.workspacePath),r={schemaVersion:we,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return e$2(t,ke,X(r))}
|
|
2
|
+
export{I as a,Te as b,Ve as c,X as d,Fe as e,re as f,E as g,ke as h,R as i,we as j,N as k,Ee as l,pe as m,rt as n,ot as o,le as p,nt as q,ue as r,at as s};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b}from'./chunk-
|
|
1
|
+
import {b}from'./chunk-FQLB4BIC.js';import {c,d,a,b as b$1}from'./chunk-MOSXTVPU.js';import n from'fs';import o from'path';function _(t){return b({startPath:t})?.workspacePath??null}function k(t){let s=o.resolve(t),p=n.existsSync(o.join(s,c))||n.existsSync(o.join(s,d))||n.existsSync(o.join(s,a,"workspace.json"))||n.existsSync(o.join(s,b$1,"workspace.json")),A=n.existsSync(o.join(s,a,"project.json"))||n.existsSync(o.join(s,a,"context.json"))||n.existsSync(o.join(s,b$1,"project.json"))||n.existsSync(o.join(s,b$1,"context.json"));return p&&!A}export{_ as a,k as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b}from'./chunk-
|
|
1
|
+
import {b}from'./chunk-44VJHNZB.js';var o="model-usage-event.v1",s=b.evaluationLive,a="workspace-intelligence-evaluation-comparison.v1",i=["provider-reported","tokenizer-counted","estimated","unavailable"];export{o as a,s as b,a as c,i as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {f,e as e$1,g as g$1}from'./chunk-M5ICGR55.js';import {b as b$2}from'./chunk-KVSYBHUR.js';import {b as b$6,a as a$3}from'./chunk-THIOE2PB.js';import {b as b$3}from'./chunk-
|
|
1
|
+
import {f,e as e$1,g as g$1}from'./chunk-M5ICGR55.js';import {b as b$2}from'./chunk-KVSYBHUR.js';import {b as b$6,a as a$3}from'./chunk-THIOE2PB.js';import {b as b$3}from'./chunk-2FJW6GSW.js';import {a as a$2}from'./chunk-3DONU3DU.js';import {e,g,f as f$2,b as b$5,c as c$2,d as d$2}from'./chunk-WJVB6SSD.js';import {d,b as b$1}from'./chunk-Y5YAP4F3.js';import {g as g$2}from'./chunk-MQ73VS4E.js';import {i,f as f$1,c as c$1,e as e$2}from'./chunk-VRW6KXNK.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {b,a,c,d as d$1}from'./chunk-MOSXTVPU.js';import {b as b$4,k,j,m,i as i$1,t,s,q as q$1}from'./chunk-RJIYCDVC.js';import {promises}from'fs';import*as P from'fs-extra';import p from'path';import r from'chalk';import {execa}from'execa';function st(e){let n=e.projectCount??0,t=n===1?"project":"projects",a=e.pythonEngine==="installed"?`Python ${e.pythonVersion||"3.10+"} \xB7 ${e.installMethod||"local environment"}`:e.pythonEngine==="skipped"?"Python engine not installed":"Runtime-neutral foundation";return ["","\u2713 Workspace ready",`${e.workspaceName} \xB7 ${e.profile} \xB7 ${n} registered ${t}`,`Location ${e.workspacePath}`,`Runtime ${a}`,...e.note?[`Note ${e.note}`]:[],"","Workspace Intelligence"," \u2713 Contract and project registry"," \u2713 Canonical model and proof-backed graph"," \u2713 Agent context, grounding, and evidence index","","Next",` ${g$1(e.workspacePath)}`," npx workspai create"," npx workspai workspace intelligence run --for-agent generic --strict --json","","Evidence .workspai/reports/INDEX.json","Guide README.md",""]}function q(e){let n=st(e);for(let t of n)t==="\u2713 Workspace ready"?console.log(r.green.bold(t)):t==="Workspace Intelligence"||t==="Next"?console.log(r.cyan.bold(t)):t.startsWith(" \u2713")?console.log(r.green(t)):t.startsWith("Location")||t.startsWith("Runtime")?console.log(r.gray(t)):console.log(t);}function M(){return i$1()}var lt="transactions";function ct(){return p.join(q$1(),lt)}async function Ve(){let e=ct();return await b$6(e),a$3({journalDirectory:e})}async function Ge(e){for(let n of s())await e.captureFile(n);}async function ae(e){let n=await Ve();try{return await Ge(n),await n.captureOwnedTree(e),n}catch(t){return K(n,t)}}async function pt(e){let n=await Ve();try{await Ge(n),await n.captureOwnedTree(p.join(e,a)),await n.captureOwnedTree(p.join(e,".venv"));let t=[c,".gitignore",p.join(a,"workspace.json"),p.join(a,"toolchain.lock"),p.join(a,"policies.yml"),p.join(a,"cache-config.yml"),g$2,a$2,"pyproject.toml","poetry.toml","poetry.lock","rapidkit","rapidkit.cmd","README.md",".rapidkit-global"];for(let a of t)await n.captureFile(p.join(e,a));return n}catch(t){return K(n,t)}}async function z(e){await e.commit(),e.journalPath&&await promises.rm(p.dirname(e.journalPath),{recursive:true,force:true}).catch(n=>f$1.debug(`Could not remove committed lifecycle journal: ${n}`));}async function K(e,n){try{await e.rollback();}catch(t){throw new AggregateError([n,t],"Workspace lifecycle failed and rollback was incomplete.")}throw n}async function B(e,n,t,a,s){let l=d(n,i(),t,s?.pythonEngine?{coreStatus:s.pythonEngine,...s.pythonEngineReason?{coreReason:s.pythonEngineReason}:{},...a?{pythonVersion:a}:{}}:void 0);a&&!s?.pythonEngine&&(l.metadata||(l.metadata={}),l.metadata.python={pythonVersion:a}),await b$1(e,l);}async function G(e){await P.outputFile(p.join(e,".gitignore"),`.venv/
|
|
2
2
|
__pycache__/
|
|
3
3
|
*.pyc
|
|
4
4
|
.env
|