workspai 0.52.3 → 0.53.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 +1 -0
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +36 -0
- 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/workspace-repair-proposal.v1.json +78 -0
- package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +249 -0
- package/contracts/workspace-intelligence-chain.v1.json +6 -0
- package/contracts/workspace-repair-capabilities.v1.json +316 -0
- package/dist/analyze-AAZEJ4FC.js +1 -0
- package/dist/artifact-remediation-plan-CJSPCMWA.js +1 -0
- package/dist/autopilot-release-LZWNQQLY.js +1 -0
- package/dist/chunk-27AXFTKW.js +1 -0
- package/dist/{chunk-OTDGTAZJ.js → chunk-2FJW6GSW.js} +1 -1
- package/dist/chunk-3DONU3DU.js +1 -0
- package/dist/chunk-44VJHNZB.js +1 -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-BYVTHIC3.js +2 -0
- package/dist/chunk-E5YYVFM2.js +1 -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-HOVJUP7K.js +8 -0
- package/dist/{chunk-MZFSINY7.js → chunk-HRN5J6PW.js} +12 -12
- package/dist/chunk-HY3RMPW5.js +10 -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-SUV7Y2FH.js +3 -0
- package/dist/chunk-T6JI7GYZ.js +88 -0
- package/dist/chunk-USMLRNZ7.js +5 -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/{create-ESK3CQPK.js → create-R6A7EHQZ.js} +1 -1
- package/dist/{doctor-MYRJ5BFF.js → doctor-KNIYGDM7.js} +1 -1
- package/dist/index.d.ts +92 -23
- package/dist/index.js +246 -244
- package/dist/pipeline-PVCLAQDI.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-MCSNMA3P.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-JNCQLUH7.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-SRWECKZO.js +3 -0
- package/dist/workspace-run-3U77TMKX.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 +10 -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 +113 -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/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 {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
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import {b as b$4,a as a$1}from'./chunk-THIOE2PB.js';import {b as b$2,f as f$2,j,k,h as h$2,i as i$1,l,m,n,o,p as p$2,q,r,t,v as v$1,x,s,u as u$1,w,y,z,A,B,C as C$1,D,E,F,G,H as H$1,a as a$3,I}from'./chunk-AMB42V2F.js';import {b as b$1,c,d as d$1}from'./chunk-P7K5RHJC.js';import {b as b$3}from'./chunk-RA24WQLF.js';import {d as d$3}from'./chunk-XVRJVKOX.js';import {h,g as g$1}from'./chunk-H7P7SSUW.js';import {p,k as k$1,f as f$3}from'./chunk-7AR5PDLD.js';import {p as p$1}from'./chunk-MQ73VS4E.js';import {d}from'./chunk-WIO6L24E.js';import {a as a$2,b as b$5}from'./chunk-BYVTHIC3.js';import {b,a,e,d as d$2}from'./chunk-44VJHNZB.js';import {f,g,h as h$1}from'./chunk-MOSXTVPU.js';import i from'path';import f$1 from'fs-extra';var ee=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var ht="workspace-operational-skill.v1";function At(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function et(e){let t=At(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:ht,skillId:t,canonicalPath:H$1(t),title:e.title,triggers:[...e.triggers].sort((r,n)=>r.localeCompare(n)),requiredReports:[...e.requiredReports].sort((r,n)=>r.localeCompare(n)),scopedProjects:[...e.scopedProjects??[]].sort((r,n)=>r.localeCompare(n)),verificationCommands:[...e.verificationCommands],answerContractSections:[...ee],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var wt=b.skillsIndex;function tt(e){let t=[...e.skills].sort((n,c)=>n.skillId.localeCompare(c.skillId)),r=e.inputsHash??f$3({skillIds:t.map(n=>n.skillId),paths:t.map(n=>n.canonicalPath)});return {schemaVersion:wt,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(n=>({skillId:n.skillId,path:n.canonicalPath,schemaVersion:n.schemaVersion,title:n.title}))}}var rt=[a.agentIndex,b$1,d$3],Pt=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${a.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${a.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."]},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${a.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${a.verify}\` for verdict and blocking reasons.`,`Read \`${e.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."]},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Require project-scoped test/build commands before promoting the migration.","Document rollback and verification signals."]},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Prefer workspace run test/build for affected projects.","Re-run `workspace verify` after evidence refresh."]},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${e.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."]}];function te(e){return `npx workspai ${e}`.trim()}function Rt(e){let t=[`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",...rt.map(r=>`- \`${r}\``),"","## Procedure","",...e.template.steps.map((r,n)=>`${n+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",te("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
|
|
2
|
+
`)}function St(e){return e?.safeCommands?.length?e.safeCommands.slice(0,8).map(t=>t.display):[te("workspace verify --json"),te("doctor workspace --json")]}function Ct(e){return e?.projects?.length?e.projects.slice(0,12).map(r=>{let n=r.contracts?.owns?.join(", ")||"none",c=r.contracts?.publishes?.join(", ")||"none",l=r.contracts?.consumes?.join(", ")||"none";return `- **${r.slug}**: owns \`${n}\`; publishes \`${c}\`; consumes \`${l}\``}).join(`
|
|
3
|
+
`):void 0}function nt(e){let t=e.model.workspace.name,r=e.model.projects.map(l=>l.name).sort(),n=St(e.context??null),c=Ct(e.contract??null);return Pt.map(l=>{let p=Rt({template:l,workspaceName:t,scopedProjects:r,verificationCommands:n,contractSummary:c});return et({skillId:l.skillId,title:l.title,triggers:l.triggers,requiredReports:[...rt],scopedProjects:r,verificationCommands:n,promptStem:I[l.skillId],markdown:p})})}async function at(e){let t=i.resolve(e.workspacePath),r=[],n=f$3({skills:e.skills.map(l=>({id:l.skillId,path:l.canonicalPath,hash:f$3({markdown:l.markdown})}))}),c=tt({generatedAt:e.generatedAt,skills:e.skills,inputsHash:n});if(e.write){for(let p of e.skills){let o=i.join(t,p.canonicalPath);await f$1.ensureDir(i.dirname(o)),await f$1.writeFile(o,p.markdown,"utf8"),r.push(p.canonicalPath);}let l=i.join(t,b$2);await f$1.ensureDir(i.dirname(l)),await f$1.writeJson(l,c,{spaces:2}),r.push(b$2);}return {skills:e.skills,index:c,writtenPaths:r}}function ot(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.workspai/skills/` before generic repo scans. Legacy `.rapidkit/skills/` playbooks are read only when already present from older workspaces:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",te("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
4
|
+
`)}var yt={"workspai-diagnose-api-failure":p$2,"workspai-release-readiness":t},Ie="## Workspace verification (hydrated)";function Et(e){let t=[Ie,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx workspai workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`
|
|
5
|
+
`)}async function it(e){let t=i.resolve(e.workspacePath),r=[];for(let n of e.skills){let c=yt[n.skillId];if(!c)continue;let l=i.join(t,c);if(!await f$1.pathExists(l))continue;let p=await f$1.readFile(l,"utf8"),o=Et(n),w=p.includes(Ie)?p.replace(new RegExp(`${Ie}[\\s\\S]*$`),o.trimEnd()):`${p.trimEnd()}
|
|
6
|
+
|
|
7
|
+
${o}`;e.write&&await f$1.writeFile(l,`${w.trimEnd()}
|
|
8
|
+
`,"utf8"),r.push(c);}return r}var xt="workspai-agent-customization-pack-capabilities.v1";function st(){return {schemaVersion:xt,presets:{minimal:{meaning:"Generate the portable grounding index, AGENTS.md, and provider-specific lightweight instructions.",requiredOutputs:[a.agentIndex,a.agentCustomizationPack,a.agents]},enterprise:{meaning:"Generate the full VS Code-native pack: instructions, prompts, skills, custom agents, and validation metadata.",requiredOutputs:[a.agentIndex,a.agentCustomizationPack,a.agents,l,p$2,B,".github/agents/workspai-advisor.agent.md",D,b$2]}},targets:{all:{meaning:"Generate every supported customization surface.",outputFamilies:["portable","vscode","copilot","cursor","claude"]},vscode:{meaning:"Generate VS Code-native customizations for Copilot Chat and agent workflows.",outputFamilies:["instructions","prompts","skills","agents","hooks"]},agents:{meaning:"Generate portable AGENTS.md grounding for any agent.",outputFamilies:["portable"]},copilot:{meaning:"Generate GitHub Copilot instructions, prompts, and skills.",outputFamilies:["instructions","prompts","skills"]},cursor:{meaning:"Generate Cursor rules.",outputFamilies:["rules"]},claude:{meaning:"Generate Claude Code grounding files.",outputFamilies:["rules","portable"]},codex:{meaning:"Use AGENTS.md and the report index as the Codex grounding layer.",outputFamilies:["portable"]},orca:{meaning:"Use AGENTS.md and the report index as the Orca/Grok grounding layer.",outputFamilies:["portable"]}},standardAnswerContract:[...ee],requiredReports:K.map(e=>({path:e.relativePath,label:e.label,required:e.required})),strictRules:["Required reports must exist.","Generated report paths must stay inside the workspace root.","Generated customization text must be English-only.","Agent answers must not claim pass, ready, or healthy without cited evidence.","Commands must distinguish display guidance from execution requests.","Agent hook files must be advisory and disabled by default unless the user explicitly enables them.","MCP design artifacts must stay read-mostly until write tools have explicit approval boundaries."],outputKinds:["report","grounding","instruction","prompt","skill","skill-resource","operational-skill","skills-index","explain-report","agent","rule","hook","mcp-design"],pathLayers:{l1CanonicalRoots:[".workspai/reports/",`${a$3}/`],l2PrefixedMirrorRoots:[".github/",".cursor/",".claude/"],l3SharedIndustryFiles:["AGENTS.md",".github/copilot-instructions.md","CLAUDE.md"]}}}var It=b.agentIndex,Ot=b.agentCustomizationPack,H=a.agentIndex,M=a.agentCustomizationPack;var K=[{relativePath:b$1,label:"Agent context pack",required:true},{relativePath:b$2,label:"Operational skills index",required:true},{relativePath:a.model,label:"Workspace model",required:false},{relativePath:a.knowledgeGraph,label:"Workspace knowledge graph",required:false},{relativePath:a.evaluationLastRun,label:"Workspace Intelligence evaluation",required:false},{relativePath:a.doctor,label:"Workspace doctor",required:false},{relativePath:e.doctorProject,label:"Project doctor",required:false},{relativePath:e.doctorRemediationPlan,label:"Doctor remediation plan",required:false},{relativePath:e.artifactRemediationPlan,label:"Artifact remediation plan",required:false},{relativePath:e.doctorFixResult,label:"Doctor fix result",required:false},{relativePath:a.analyze,label:"Workspace analyze",required:false},{relativePath:e.pipelineLastRun,label:"Governance pipeline",required:false},{relativePath:a.readiness,label:"Release readiness",required:false},{relativePath:a.impact,label:"Workspace impact",required:false},{relativePath:a.verify,label:"Workspace verify",required:false},{relativePath:a.snapshot,label:"Workspace model snapshot",required:false},{relativePath:a.diff,label:"Workspace model diff",required:false},{relativePath:a.explain,label:"Workspace explain",required:false},{relativePath:a.contractVerify,label:"Workspace contract verify",required:false},{relativePath:a.history,label:"Workspace intelligence history",required:false}];function bt(){let e=K.map(n=>n.relativePath),r=b$3().consumers.agents.canonicalReadOrder.filter(n=>n!==H&&e.includes(n));return [...new Set([...r,...e])]}function P(e){return `npx workspai ${e}`.trim()}function Te(e){return e&&typeof e=="object"?e:null}function Oe(e,t=12){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0).slice(0,t):[]}function _t(e){let t=Oe(e.blockers,12);if(t.length>0)return t;let r=Oe(e.blockingReasons,12);if(r.length>0)return r;let n=Te(e.summary);return n&&Array.isArray(n.blockingReasons)?Oe(n.blockingReasons,12):[]}function Tt(e){let t=[...new Set(e.map(r=>r.trim()).filter(Boolean))];return t.filter(r=>{let n=r.toLowerCase();return !t.some(c=>{if(c===r||!c.includes(":"))return false;let l=c.toLowerCase();return l.length>n.length&&l.endsWith(n)})})}function vt(e){for(let t of ["generatedAt","updatedAt","timestamp"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}if(Array.isArray(e.entries)){let t=e.entries.map(r=>Te(r)?.generatedAt).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim()).filter(r=>Number.isFinite(Date.parse(r)));if(t.length>0)return t.reduce((r,n)=>Date.parse(n)>Date.parse(r)?n:r)}}function Wt(e,t,r){if(!e)return true;let n=Date.parse(e);return Number.isFinite(n)?r.getTime()-n>t*60*60*1e3:true}function jt(e,t,r){return e.path===a.snapshot?false:Wt(e.generatedAt,t,r)}function Lt(e){let t=e&&e.length>0?e:["all"];return t.includes("all")?new Set(["all","vscode","agents","copilot","cursor","claude","codex","orca"]):new Set(t)}function C(e,t){return e.has("all")||e.has(t)}function Nt(e){return C(e,"copilot")||C(e,"vscode")}function Gt(e){return e??"enterprise"}function Dt(e){return e===b$2?"skills-index":e.includes("workspace-explain-last-run.json")?"explain-report":(e.startsWith(`${a$3}/`)||e.startsWith(".rapidkit/skills/"))&&e.endsWith(".md")?"operational-skill":e.includes("hooks")||e===F||e===G?"hook":e.includes("mcp")||e===D||e===E?"mcp-design":e.endsWith(".json")?"report":e.includes("/instructions/")||e.endsWith("copilot-instructions.md")?"instruction":e.includes("/prompts/")?"prompt":e.includes("/skills/")&&e.endsWith("/SKILL.md")?"skill":e.includes("/skills/")?"skill-resource":e.includes("/agents/")?"agent":e.includes("/rules/")||e.endsWith(".mdc")?"rule":"grounding"}function $t(e){return e.startsWith(".github/")?["vscode","copilot"]:e.startsWith(".cursor/")?["cursor"]:e.startsWith(".claude/")||e==="CLAUDE.md"?["claude"]:e==="AGENTS.md"||e.startsWith(".rapidkit/")?["agents","codex","orca","vscode"]:e.startsWith(".vscode/")?["vscode"]:["agents"]}function Kt(e,t){return st().presets[t].requiredOutputs.includes(e)}async function Mt(e,t){if(t)return t;let r=await d(e,k$1)??i.join(e,k$1);if(await f$1.pathExists(r))try{let n=await f$1.readJson(r);return b$5(k$1,n,r),n}catch{}return p({workspacePath:e,includeEvidence:true})}function Ht(e){return e.length>0&&!i.isAbsolute(e)&&!e.split(/[\\/]+/).includes("..")}function qt(e){return Object.fromEntries(["all","vscode","agents","copilot","cursor","claude","codex","orca"].map(r=>[r,{enabled:e.targets.includes("all")||e.targets.includes(r),outputs:e.outputs.filter(n=>n.targets.includes(r)).map(n=>n.path).sort()}]))}async function Vt(e,t){try{if(!await f$1.pathExists(e))return {payload:null,exists:false,validity:"missing"};let r=await f$1.readJson(e),n=Te(r);return n?a$2(t)?(b$5(t,n,e),{payload:n,exists:true,validity:"valid"}):{payload:n,exists:true,validity:"uncontracted"}:{payload:null,exists:true,validity:"invalid",validationError:"Artifact root must be a JSON object"}}catch(r){return {payload:null,exists:true,validity:"invalid",validationError:r instanceof Error?r.message:String(r)}}}async function ct(e){let t=e.now??new Date,r=e.staleAfterHours??24,n=[],c=[];for(let o of K){let w=await d(e.workspacePath,o.relativePath)??i.join(e.workspacePath,o.relativePath),h=await Vt(w,o.relativePath),g=h.payload;h.validity==="invalid"?c.push(`Invalid evidence contract: ${o.relativePath}`):g&&c.push(..._t(g)),n.push({path:o.relativePath,label:o.label,required:o.required,exists:h.exists,validity:h.validity,validationError:h.validationError,generatedAt:g?vt(g):void 0,commandId:typeof g?.commandId=="string"?g.commandId:void 0,exitCode:typeof g?.exitCode=="number"?g.exitCode:void 0});}let l=Tt(c).slice(0,16),p=b$3();return {schemaVersion:It,generatedAt:t.toISOString(),workspaceRoot:e.workspacePath,intelligenceChain:{schemaVersion:p.schemaVersion,contractPath:p.contractPath,currentStep:"agent-sync"},readOrder:bt(),blockers:l,staleAfterHours:r,reports:n,refreshCommand:P("workspace agent-sync --write --refresh-context")}}function lt(e){let t=["# Workspai agent grounding","","Cross-tool instructions for Copilot, Cursor, Claude Code, Codex, Grok, and other agents.","","## Read order (mandatory before workspace diagnosis)","",`1. \`${a.agentIndex}\` \u2014 latest blockers, timestamps, and report paths`,`2. \`${a.agentContext}\` \u2014 read only task-relevant context`,"3. Read only the task-relevant evidence artifacts listed in the index.","4. Use `workspace graph search <query> --limit 12 --json` or MCP `searchWorkspaceGraph` before loading the full graph.","","Do **not** full-repo scan or inject the complete graph when a bounded query can answer the task.","","## Regenerate intelligence","","```bash",P("workspace agent-sync --write --refresh-context"),P("workspace context --for-agent --json --write"),P("pipeline --json --write"),"```",""];if(e.index.blockers.length>0){t.push("## Current blockers","");for(let r of e.index.blockers.slice(0,12))t.push(`- ${r}`);t.push("");}if(e.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let r of e.context.safeCommands.slice(0,10))t.push(`- \`${r.display}\` \u2014 ${r.description}`);t.push("");}return t.push("## Rules","","- Treat `.workspai/reports/*` as the source of truth for health, gates, and release posture.","- Prefer deterministic Workspai CLI commands over heuristic framework guesses.","- If evidence is missing or stale, run the refresh commands above before proposing fixes.","- Keep project-scoped advice aligned with the active project named in the context pack.",""),t.join(`
|
|
9
|
+
`)}function Ut(e){return ["# Workspai agent grounding","",`Generated: ${e.generatedAt}`,"",`This file is tool-agnostic. Synced agents should read it together with \`${a.agentIndex}\`.`,"","## Mandatory read order","",...e.readOrder.map((t,r)=>`${r+1}. \`${t}\``),"",e.blockers.length>0?"## Blockers":"",...e.blockers.length>0?e.blockers.map(t=>`- ${t}`):[],"","## Refresh","","```bash",e.refreshCommand,"```",""].filter(t=>t!=="").join(`
|
|
10
|
+
`)}function Ft(){return ["# Workspai workspace grounding","","Before answering workspace, release, or architecture questions:","","1. Read `AGENTS.md` (managed Workspai section).",`2. Read \`${a.agentIndex}\` and only task-relevant context from \`${a.agentContext}\`.`,"3. Use bounded `workspace graph search` or MCP `searchWorkspaceGraph` before scanning the full repository.","","Regenerate stale intelligence:","","```bash",P("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
11
|
+
`)}function zt(){return ["## Claude Code","",`- Load \`${a.agentIndex}\` before diagnosing blockers.`,"- Use `.claude/rules/workspai-evidence.md` for scoped Workspai evidence rules.","- Treat `.claude/rules/rapidkit-evidence.md` as a legacy compatibility mirror.","- Refresh grounding with `npx workspai workspace agent-sync --write`.",""].join(`
|
|
12
|
+
`)}function Bt(){return ["---","description: Workspai workspace evidence and intelligence grounding","globs: []","alwaysApply: true","---","","Before proposing fixes in this workspace:","",`1. Read \`${a.agents}\` and \`${a.agentIndex}\`.`,`2. Read only task-relevant context from \`${a.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","Refresh when stale:","","```bash",P("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
13
|
+
`)}function Jt(){return ["---",'applyTo: ".workspai/**,**/.workspai/**,.rapidkit/**,**/.rapidkit/**"',"description: Workspai evidence and intelligence artifacts","---","","When working under `.workspai/` or legacy `.rapidkit/`:","","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.",`- Start from \`${a.agentIndex}\` for read order and blockers.`,"- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.",""].join(`
|
|
14
|
+
`)}function Yt(){return ["---",'applyTo: "**"',"description: Workspai workspace scope, evidence, and command discipline","---","","# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Scope rules","",`- Start from \`${a.agentIndex}\`; read only task-relevant context and evidence.`,"- Prefer bounded `workspace graph search` or MCP `searchWorkspaceGraph` over loading the complete graph.","- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","- Do not translate unsupported stack requests into unrelated native kits.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
|
|
15
|
+
`)}function Xt(){return ["# Workspai evidence","","Applies when reading or editing `.workspai/reports/*`.","","- Start from `INDEX.json`, then `workspace-context-agent.json`.","- Use report blockers as the primary fix target.","- Regenerate with `npx workspai workspace agent-sync --write`.",""].join(`
|
|
16
|
+
`)}function Zt(){return ["# Legacy RapidKit evidence alias","","Compatibility path only. Use `.claude/rules/workspai-evidence.md` as the canonical rule.",""].join(`
|
|
17
|
+
`)}function Qt(){return ["---","description: Legacy RapidKit metadata compatibility alias",'globs: [".rapidkit/**", "**/.rapidkit/**"]',"alwaysApply: false","---","","Use `.cursor/rules/workspai-grounding.mdc` for canonical Workspai grounding.",""].join(`
|
|
18
|
+
`)}function dt(e){return ["---",'applyTo: ".rapidkit/**,**/.rapidkit/**"',"description: Legacy RapidKit metadata compatibility alias","---","",`Use \`.github/instructions/workspai-${e}.instructions.md\` as the canonical Workspai instruction.`,""].join(`
|
|
19
|
+
`)}function pt(){return ["---","description: Diagnose Workspai workspace blockers from evidence reports","---","","Diagnose this workspace using Workspai evidence only.","","Read:","",`- \`${a.agentIndex}\``,`- \`${a.agentContext}\``,"- Any fail/warn reports referenced in the index","","Return:","","1. Root cause grounded in report blockers","2. Smallest safe fix path (commands + file edits)","3. One verification command to prove recovery",""].join(`
|
|
20
|
+
`)}function re(e){return ["---",`description: ${e.description}`,"---","",e.objective,"","Read first:","",`- \`${a.agentIndex}\``,`- \`${a.agentContext}\``,"- Any report referenced by the current blocker or task","","Return:","",...e.expectedOutput.map((t,r)=>`${r+1}. ${t}`),"","Use the standard Workspai answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
|
|
21
|
+
`)}function v(e){return ["# "+e.title,"",...e.lines,""].join(`
|
|
22
|
+
`)}function er(){return v({title:"MCP Tool Design",lines:["Workspai MCP is a read-mostly bridge over contract-validated workspace artifacts.","","Candidate read tools:",`- \`getWorkspaceModel\` \u2014 read \`${a.model}\`.`,`- \`getWorkspaceKnowledgeGraph\` \u2014 read \`${a.knowledgeGraph}\`.`,`- \`getWorkspaceEvaluation\` \u2014 read \`${a.evaluationLastRun}\` (or the live evaluation when requested).`,"- `queryWorkspaceEntities` \u2014 filter proof-backed graph entities by kind.","- `searchWorkspaceGraph` \u2014 retrieve bounded proof-backed context by text query.","- `getWorkspaceGraphEvidence` \u2014 resolve evidence for an entity or relation.","- `findWorkspaceGraphPath` \u2014 find a shortest proof-carrying relationship path.",`- \`getEvidenceIndex\` \u2014 read \`${a.agentIndex}\`.`,"- `getBlockers` \u2014 derive current blockers from INDEX and gate reports.","- `getSafeCommands` \u2014 read safe commands from `workspace-context-agent.json`.","- `getProjectContext` \u2014 return one project-scoped slice of the workspace model.","- `getArtifact` \u2014 read one explicit artifact path inside the workspace root.",`- \`listOperationalSkills\` \u2014 read \`${a.skillsIndex}\`.`,"- `getWorkspaceExplain` \u2014 read/build workspace explain for release-blocked or project scope.","- `refreshWorkspaceIntelligence` \u2014 explicit user-approved refresh command only.","","Write or repair tools require explicit approval boundaries and are intentionally not part of the first read-mostly design."]})}function tr(e$1){return `${JSON.stringify({schemaVersion:d$2.workspaiMcpDesign.schemaVersion,generatedAt:e$1.generatedAt,workspaceRoot:e$1.workspacePath,status:"design-only",mode:"read-mostly",safety:{writeToolsEnabled:false,approvalRequiredForRefresh:true,artifactReadsMustStayInsideWorkspace:true},candidateTools:[{name:"getWorkspaceModel",reads:[a.model],mutates:false},{name:"getWorkspaceKnowledgeGraph",reads:[a.knowledgeGraph],mutates:false},{name:"getWorkspaceEvaluation",reads:[a.evaluationLive,a.evaluationLastRun],mutates:false},{name:"queryWorkspaceEntities",reads:[a.knowledgeGraph],mutates:false},{name:"searchWorkspaceGraph",reads:[a.knowledgeGraph],mutates:false},{name:"getWorkspaceGraphEvidence",reads:[a.knowledgeGraph],mutates:false},{name:"findWorkspaceGraphPath",reads:[a.knowledgeGraph],mutates:false},{name:"getEvidenceIndex",reads:[a.agentIndex],mutates:false},{name:"getBlockers",reads:[a.agentIndex,a.verify,e.pipelineLastRun],mutates:false},{name:"getSafeCommands",reads:[a.agentContext],mutates:false},{name:"getProjectContext",reads:[a.model,a.agentContext],mutates:false},{name:"getArtifact",reads:["requested workspace-relative artifact path"],mutates:false},{name:"listOperationalSkills",reads:[a.skillsIndex],mutates:false},{name:"getWorkspaceExplain",reads:[a.explain,a.verify,a.impact],mutates:false},{name:"refreshWorkspaceIntelligence",command:P("workspace agent-sync --write --refresh-context"),mutates:true,approvalRequired:true}]},null,2)}
|
|
23
|
+
`}function rr(e){return `${JSON.stringify({schemaVersion:d$2.agentHooks.schemaVersion,generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,enabledByDefault:false,mode:"advisory",hooks:[{name:"workspai-pre-tool-use-workspace-boundary",event:"PreToolUse",purpose:"Block or warn on state-changing commands outside the active workspace root.",defaultAction:"warn",rules:["Allow read-only commands.","Warn before write/delete commands outside workspaceRoot.","Never run destructive commands without explicit user approval."]},{name:"workspai-post-tool-use-verify-suggestion",event:"PostToolUse",purpose:"Suggest non-destructive verification commands after edits.",defaultAction:"suggest",commands:[P("doctor workspace"),P("workspace verify --strict --json")]},{name:"workspai-user-prompt-submit-scope-hint",event:"UserPromptSubmit",purpose:"Inject lightweight workspace scope and evidence index hints.",defaultAction:"inject-context-hint",reads:[a.agentIndex,a.agentContext]}]},null,2)}
|
|
24
|
+
`}function ut(e){let t=["---","name: workspai-workspace-intelligence","description: Use Workspai workspace intelligence reports to answer, repair, verify, and release with evidence","---","","# Workspai Workspace Intelligence","","Use this skill for workspace architecture, project lifecycle, blocker repair, release readiness, agent grounding, and CI evidence questions.","","## Decision flow","","1. Load `resources/scope-model.md`.",`2. Load \`${a.agentIndex}\`.`,`3. Load \`${a.agentContext}\`.`,`4. Load \`${a.skillsIndex}\` when operational playbooks are needed.`,"5. Load the smallest evidence report required for the task.","6. Answer with Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Rules","","- Prefer Workspai reports over full-repo scans.","- Never claim a gate passed without a cited report.","- Separate display commands from execution requests.","- Keep project-scoped fixes inside the active project unless workspace evidence says otherwise.",""];return e?.trim()&&t.push(e.trim(),""),t.join(`
|
|
25
|
+
`)}function ne(e){return ["---",`name: ${e.name}`,`description: ${e.description}`,`tools: [${e.tools.map(t=>`'${t}'`).join(", ")}]`,"---","",`You are the ${e.name} agent for Workspai Workspace Intelligence.`,"",`Mode: ${e.mode}.`,"",`Start every task by reading \`${a.agentIndex}\` and \`${a.agentContext}\`.`,"","Use this answer contract:","","- Scope","- Evidence","- Diagnosis","- Fix Plan","- Run","- Verify","- Assumptions","","Do not invent health, readiness, or policy status. Cite report paths and command outputs.",""].join(`
|
|
26
|
+
`)}function gt(){return ["---","name: workspai-grounding","description: Load Workspai workspace intelligence reports before diagnosing or changing code","---","","# Workspai grounding","","Use when the user asks about workspace health, release gates, doctor/pipeline failures, or project structure.","","## Workflow","",`1. Read \`${a.agentIndex}\``,`2. Read \`${a.agentContext}\``,"3. Read fail/warn evidence artifacts listed in the index","4. Propose the smallest safe fix with explicit verification commands","","## Refresh stale evidence","","```bash",P("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
27
|
+
`)}async function u(e,t,r){return r?(await f$1.ensureDir(i.dirname(e)),await f$1.writeFile(e,t,"utf8"),"written"):"skipped"}async function be(e){if(!e.write)return "skipped";let t=await f$1.pathExists(e.absolutePath)?await f$1.readFile(e.absolutePath,"utf8"):null,{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),n=r(t,e.generatedBody),c=e.preamble?`${e.preamble.trimEnd()}
|
|
28
|
+
|
|
29
|
+
${n}`:n;return await f$1.ensureDir(i.dirname(e.absolutePath)),await f$1.writeFile(e.absolutePath,c,"utf8"),"written"}function Jr(e){if(!e?.trim())return;let t=new Set(["all","vscode","agents","copilot","cursor","claude","codex","orca"]),r=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>t.has(n));return r.length>0?r:void 0}function nr(e){let t=[...e.outputs].sort((n,c)=>n.path.localeCompare(c.path)),r=b$3();return {schemaVersion:Ot,generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,preset:e.preset,targets:[...e.targets].sort(),sourceReports:e.index.reports.filter(n=>n.exists).map(n=>n.path).sort(),intelligenceChain:{schemaVersion:r.schemaVersion,contractPath:r.contractPath,currentStep:"agent-sync"},outputInventory:t,capabilityMatrix:qt({targets:e.targets,outputs:t}),drift:{missingRequired:e.missingRequired,staleReports:e.staleReports,strictViolations:e.strictViolations},answerContract:["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"],refreshCommand:P(`workspace agent-sync --write --refresh-context --preset ${e.preset}`),experimental:{hooksEnabled:e.experimentalHooks,mcpReady:t.some(n=>n.kind==="mcp-design")}}}async function _e(e){let t$1=i.resolve(e.workspacePath),r$1=e.now??new Date,n$1=e.staleAfterHours??24,c$1=Lt(e.targets),l$1=[...c$1].sort(),p$3=Gt(e.preset),o$1=e.write===true,w$1=e.strict===true,h,g=null,ae=e.model;e.refreshContext&&(ae??=await p({workspacePath:t$1,includeEvidence:true}),g=await c({workspacePath:t$1,model:ae,agent:e.agent??"generic",scope:e.scope,includeEvidence:true}),o$1&&(h=await d$1(g,t$1)));let _=[],oe=[],ie=[],se=[],d=(s,k)=>{s==="written"?oe.push(k):ie.push(k),se.push({path:k,kind:Dt(k),targets:$t(k),required:Kt(k,p$3),status:s==="written"?"written":e.dryRun?"planned":"skipped"});},ce="",mt=await Mt(t$1,ae),le=null;try{le=(await p$1({workspacePath:t$1})).contract;}catch{le=null;}let kt=nt({model:mt,context:g,contract:le}),de=await at({workspacePath:t$1,skills:kt,generatedAt:r$1.toISOString(),write:o$1});for(let s of de.skills)d(o$1?"written":"skipped",s.canonicalPath);d(o$1?"written":"skipped",b$2),ce=ot(de.index);let y$1=await ct({workspacePath:t$1,staleAfterHours:n$1,now:r$1});if(d(await u(i.join(t$1,H),`${JSON.stringify(y$1,null,2)}
|
|
30
|
+
`,o$1),H),d(await u(i.join(t$1,f$2),`${Ut(y$1)}
|
|
31
|
+
`,o$1),f$2),(C(c$1,"agents")||C(c$1,"vscode"))&&d(await be({absolutePath:i.join(t$1,"AGENTS.md"),generatedBody:lt({index:y$1,context:g}),write:o$1}),"AGENTS.md"),C(c$1,"claude")){let s=i.join(t$1,"CLAUDE.md");if(o$1){let{upsertManagedAgentSection:k}=await import('./managed-agent-markers-COE5DJ3W.js'),m=await f$1.pathExists(s)?await f$1.readFile(s,"utf8"):"",A=k(m,zt()),E=A.includes("@AGENTS.md")?A:`@AGENTS.md
|
|
32
|
+
|
|
33
|
+
${A}`;await f$1.ensureDir(i.dirname(s)),await f$1.writeFile(s,E,"utf8"),oe.push("CLAUDE.md");}else ie.push("CLAUDE.md");d(await u(i.join(t$1,j),`${Xt()}
|
|
34
|
+
`,o$1),j),d(await u(i.join(t$1,k),`${Zt()}
|
|
35
|
+
`,o$1),k);}if(C(c$1,"cursor")&&(d(await u(i.join(t$1,h$2),Bt(),o$1),h$2),d(await u(i.join(t$1,i$1),Qt(),o$1),i$1)),Nt(c$1)){if(d(await be({absolutePath:i.join(t$1,".github/copilot-instructions.md"),generatedBody:Ft(),write:o$1}),".github/copilot-instructions.md"),d(await u(i.join(t$1,l),Yt(),o$1),l),d(await u(i.join(t$1,m),dt("workspace"),o$1),m),d(await u(i.join(t$1,n),Jt(),o$1),n),d(await u(i.join(t$1,o),dt("evidence"),o$1),o),d(await u(i.join(t$1,p$2),pt(),o$1),p$2),d(await u(i.join(t$1,q),pt(),o$1),q),p$3==="enterprise"){let s$1=[[r,re({description:"Repair Workspai blockers with evidence and verification",objective:"Plan the smallest safe repair for the current Workspai blocker.",expectedOutput:["Blocker and affected workspace/project scope","Evidence paths and exact failing signals","Minimal fix plan","Human-run commands","Verification command and expected success signal"]})],[t,re({description:"Assess Workspai release readiness from evidence",objective:"Assess whether this workspace is release-ready using Workspai gates.",expectedOutput:["Readiness verdict with cited reports","Blocking gates","Safe next command","Verification checklist"]})],[v$1,re({description:"Onboard a project into Workspai Workspace Intelligence",objective:"Guide project onboarding using workspace model and create planner capabilities.",expectedOutput:["Target project scope","Native create, official generator, or existing lane","Safe commands","Post-onboarding verification"]})],[x,re({description:"Adopt an existing project into Workspai governance",objective:"Adopt an existing project without changing its runtime behavior.",expectedOutput:["Detected stack and confidence","Adoption plan","Generated metadata expectations","Doctor and workspace model verification"]})]];for(let[m,A]of s$1)d(await u(i.join(t$1,m),A,o$1),m);let k=[[s,s$1[0][1]],[u$1,s$1[1][1]],[w,s$1[2][1]],[y,s$1[3][1]]];for(let[m,A]of k)d(await u(i.join(t$1,m),A,o$1),m);if(e.hydratePrompts===true)for(let m of await it({workspacePath:t$1,skills:de.skills,write:o$1}))d(o$1?"written":"skipped",m);}if(d(await u(i.join(t$1,z),gt(),o$1),z),d(await u(i.join(t$1,A),gt(),o$1),A),p$3==="enterprise"){d(await u(i.join(t$1,B),ut(ce),o$1),B),d(await u(i.join(t$1,C$1),ut(ce),o$1),C$1);let s=[["artifact-map.md",v({title:"Artifact Map",lines:K.map(m=>`- \`${m.relativePath}\` \u2014 ${m.label}`)})],["command-map.md",v({title:"Command Map",lines:["- `npx workspai workspace agent-sync --write --refresh-context` \u2014 refresh agent grounding.","- `npx workspai workspace model --json --write` \u2014 refresh workspace model.","- `npx workspai doctor workspace` \u2014 refresh health evidence.","- `npx workspai workspace verify --strict --json` \u2014 verify release gates."]})],["scope-model.md",v({title:"Scope Model",lines:["- Workspace scope is the default source of truth.","- Project scope is selected only when the active task targets a specific project.","- Always name the workspace and project when giving repair or lifecycle advice."]})],["runtime-support.md",v({title:"Runtime Support",lines:["- Native create is available only for Workspai-owned scaffold contracts.","- Unsupported stacks should use the official lane when a stable ecosystem generator exists.","- Existing projects should use the existing lane when native create is unavailable."]})],["create-planner-capabilities.md",v({title:"Create Planner Capabilities",lines:["- Use `contracts/create-planner-capabilities.v1.json` to decide native, official, or existing.","- Do not map PHP, WordPress, Laravel, Rails, or Symfony requests to unrelated native kits.","- Explain unsupported native create requests and guide users to adopt/import."]})],["mcp-tools.md",er()]];for(let[m,A]of s){let E=`${i.dirname(B)}/resources/${m}`;d(await u(i.join(t$1,E),A,o$1),E);let We=`${i.dirname(C$1)}/resources/${m}`;d(await u(i.join(t$1,We),A,o$1),We);}let k=[["workspai-advisor.agent.md",ne({name:"Workspai Advisor",description:"Read-only workspace and project guidance using Workspai evidence",mode:"read-only",tools:["search","read"]})],["workspai-repair.agent.md",ne({name:"Workspai Repair",description:"Turn Workspai blockers into minimal fixes and verification steps",mode:"repair",tools:["search","read","edit"]})],["workspai-release.agent.md",ne({name:"Workspai Release",description:"Assess readiness, governance gates, and release safety from evidence",mode:"release",tools:["search","read"]})],["workspai-project-onboarder.agent.md",ne({name:"Workspai Project Onboarder",description:"Guide create, import, and adopt flows with Workspai contracts",mode:"onboard",tools:["search","read","edit"]})]];for(let[m,A]of k){let E=`.github/agents/${m}`;d(await u(i.join(t$1,E),A,o$1),E);}}}if(p$3==="enterprise"){let s=tr({workspacePath:t$1,generatedAt:y$1.generatedAt});b$5(D,JSON.parse(s)),d(await u(i.join(t$1,D),s,o$1),D),d(await u(i.join(t$1,E),s,o$1),E);}if(p$3==="enterprise"&&e.experimentalHooks===true){let s=rr({workspacePath:t$1,generatedAt:y$1.generatedAt});b$5(F,JSON.parse(s)),d(await u(i.join(t$1,F),s,o$1),F),d(await u(i.join(t$1,G),s,o$1),G);}(C(c$1,"codex")||C(c$1,"orca"))&&(C(c$1,"agents")||d(await be({absolutePath:i.join(t$1,"AGENTS.md"),generatedBody:lt({index:y$1,context:g}),write:o$1}),"AGENTS.md"));let pe=o$1?await ct({workspacePath:t$1,staleAfterHours:n$1,now:r$1}):y$1,q$1=pe.reports.filter(s=>s.required&&!s.exists).map(s=>s.path),V=pe.reports.filter(s=>s.exists&&jt(s,n$1,r$1)).map(s=>s.path);if(w$1){q$1.length>0&&_.push(`Missing required reports: ${q$1.join(", ")}`),V.length>0&&_.push(`Stale reports (>${n$1}h): ${V.join(", ")}`);let s=se.map(k=>k.path).filter(k=>!Ht(k));s.length>0&&_.push(`Unsafe generated output paths: ${s.join(", ")}`);}let U=o$1?await g$1({workspacePath:t$1,mode:e.projectGrounding??"managed",now:r$1}):void 0;w$1&&U&&U.skipped.length>0&&_.push(`Project grounding incomplete: ${U.skipped.map(s=>`${s.name} (${s.reason})`).join(", ")}`);let ve=nr({workspacePath:t$1,generatedAt:r$1.toISOString(),preset:p$3,targets:l$1,index:pe,outputs:[...se,{path:M,kind:"report",targets:["agents","vscode","copilot","codex","orca"],required:true,status:o$1?"written":e.dryRun?"planned":"skipped"}],missingRequired:q$1,staleReports:V,strictViolations:_,experimentalHooks:e.experimentalHooks===true});if(o$1&&process.env.WORKSPAI_TEST_FAIL_AGENT_SYNC_BEFORE_PACK==="1")throw new Error("Injected agent-sync failure before generation commit.");return d(await u(i.join(t$1,M),`${JSON.stringify(ve,null,2)}
|
|
36
|
+
`,o$1),M),{workspacePath:t$1,indexPath:i.join(t$1,H),packPath:i.join(t$1,M),pack:ve,contextPath:h,writtenFiles:oe,skippedFiles:ie,blockers:y$1.blockers,missingRequired:q$1,staleReports:V,strictViolations:_,projectLenses:U}}async function Yr(e){if(e.write!==true)return _e(e);let t=i.resolve(e.workspacePath),r=i.join(t,".workspai","transactions","agent-sync");await b$4(r);let n=await _e({...e,write:false,dryRun:true});if(!n.pack)throw new Error("Agent-sync dry run did not produce an output inventory.");let c=[...n.pack.outputInventory.map(p=>p.path),H,M],l=await a$1({journalDirectory:r});try{for(let w of [...new Set(c)].sort()){let h=i.resolve(t,w),g=i.relative(t,h);if(g===".."||g.startsWith(`..${i.sep}`)||i.isAbsolute(g))throw new Error(`Agent-sync output escapes workspace root: ${w}`);await l.captureFile(h);}let p=await h(t);for(let w of p.resolved)for(let h of [f,g,h$1,"AGENTS.md",".gitignore"])await l.captureFile(i.join(w.projectPath,h));let o=await _e(e);return await l.commit(),o}catch(p){try{await l.rollback();}catch(o){throw new AggregateError([p,o],"Agent-sync generation failed and rollback was incomplete.")}throw p}}export{ht as a,wt as b,xt as c,It as d,Ot as e,H as f,M as g,K as h,bt as i,ct as j,Jr as k,Yr as l};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-
|
|
1
|
+
import {b as b$1}from'./chunk-RA24WQLF.js';import {c}from'./chunk-7KKP7RNB.js';import {p,h,i as i$1}from'./chunk-7AR5PDLD.js';import {d}from'./chunk-MQ73VS4E.js';import {e,d as d$1}from'./chunk-WIO6L24E.js';import {b,a}from'./chunk-44VJHNZB.js';import I from'path';import R from'fs-extra';var G=b.agentContext,V=a.agentContext;function q(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="orca"?t:"generic"}function M(e){return `npx --yes --package workspai workspai ${e}`.trim()}function l(e){return `npx workspai ${e}`.trim()}function i(e){return {id:e.id,scope:e.scope,display:l(e.args),execute:M(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:h({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:l(e.args),execute:M(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:a.model,sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function F(e,t){return `workspace run ${t} --scope project:${e.name}`}function L(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function D(e){return [e.name,e.path,I.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function K(e,t,n){let r={generatedAt:e.generatedAt,now:n},c=[i({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...r}),i({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...r}),i({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...r}),i({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...r}),i({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...r}),i({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...r}),i({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...r}),i({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...r})],a=t?[t]:e.projects;for(let s of a)s.commands.fleetStages.includes("test")&&c.push(i({id:`project.${s.name}.test`,scope:"project",project:s.name,args:F(s,"test"),description:`Run tests for ${s.name} through workspace orchestration.`,...r})),s.commands.fleetStages.includes("build")&&c.push(i({id:`project.${s.name}.build`,scope:"project",project:s.name,args:F(s,"build"),description:`Build ${s.name} through workspace orchestration.`,...r}));return c}function H(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function z(e,t){if(!t?.startsWith("project:"))return;let n=L(t);if(n)return e.projects.find(r=>D(r).includes(n))}function B(e,t,n){let r=[...e.validation?.issues??[]];t?.startsWith("project:")&&!n&&r.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let c=r.filter(s=>s.severity==="error").length,a=r.filter(s=>s.severity==="warning").length;return {status:c>0?"failed":a>0?"warning":"passed",errors:c,warnings:a,issues:r}}async function U(e,t){let n=[],r=[];for(let[c,a]of Object.entries(e.evidence))a&&await d$1(t,a.path)!==null?n.push(`${c}: ${a.path}`):r.push(c);return {available:n.sort(),missing:r.sort()}}function X(e){let t=e.summary.projectCount,n=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",r=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${n}, and ${r}.`}function J(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),e.summary.observedProjects>0&&t.push("Some projects are observed rather than first-class; command support may be partial."),t}async function pe(e){let t=e.model??await p({workspacePath:e.workspacePath,includeEvidence:e.includeEvidence===true,observableScanDepth:e.observableScanDepth,now:e.now}),n=q(e.agent),r=z(t,e.scope),c$1=B(t,e.scope,r);if(e.strict===true&&c$1.status!=="passed"){let o=c$1.issues.map(m=>`${m.severity}:${m.code}:${m.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${o}`)}let a$1=e.now??new Date,s=t.facts??[],T=new Set((r?[r]:t.projects).map(o=>o.name)),w=s.filter(o=>o.project?T.has(o.project):true),_=(r?[r]:t.projects).map(o=>{let m=w.filter(N=>N.project===o.name);return {name:o.name,path:o.path,kind:o.kind,category:o.category,runtime:o.runtime,framework:o.frameworkDisplayName,...o.generator?{generator:o.generator}:{},createCapability:o.createCapability,supportTier:o.supportTier,safeCommands:H(o),importantFiles:o.importantFiles,facts:m}}),u=await U(t,e.workspacePath),y=I.join(e.workspacePath,a.knowledgeGraph),d=await R.pathExists(y)?await R.readJson(y).catch(()=>null):null,C=false;if(d?.schemaVersion===b.knowledgeGraph)try{c(d,t),C=true;}catch{}let v=X(t),j=K(t,r,a$1),O=j.map(o=>h({id:`context.command.${o.id}`,label:`${o.id} safe command`,scope:"command",value:{display:o.display,execute:o.execute,scope:o.scope},...o.project?{project:o.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:a$1,sourceArtifact:a.agentContext,sourcePath:`safeCommands.${o.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),b$2=[...w,...O],f=i$1({facts:b$2,generatedAt:a$1.toISOString(),now:a$1}),h$1=b$1();return {schemaVersion:G,generatedAt:a$1.toISOString(),agent:n,workspaceSummary:v,modelRef:a.model,knowledgeGraph:{artifact:a.knowledgeGraph,schemaVersion:b.knowledgeGraph,available:C,...typeof d?.quality?.entityCount=="number"?{entityCount:d.quality.entityCount}:{},...typeof d?.quality?.relationCount=="number"?{relationCount:d.quality.relationCount}:{},...typeof d?.quality?.proofCount=="number"?{proofCount:d.quality.proofCount}:{},queryCommands:[l("workspace graph search <query> --limit 12 --json"),l("workspace graph entities [kind] --json"),l("workspace graph evidence <entity-or-relation> --json"),l("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:h$1.schemaVersion,contractPath:h$1.contractPath,currentStep:"context",canonicalReadOrder:[...h$1.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:t.workspace.root,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e.scope??"workspace",...r?{activeProject:r.name}:{}},projects:_,safeCommands:j,facts:b$2,factFreshness:f,evidence:u,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:c$1,agentInstructions:[`Read \`${a.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${a.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...J(t),...f.verifyBeforeUseFacts>0?[`${f.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[v,`Evidence available: ${u.available.length}. Missing evidence groups: ${u.missing.join(", ")||"none"}.`,r?`Active project scope: ${r.name} (${r.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
|
|
2
2
|
`)}}async function de(e$1,t){return e(t,V,d(e$1))}export{G as a,V as b,pe as c,de as d};
|