workspai 0.55.1 → 0.56.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/contracts/artifact-remediation-plan.v1.json +110 -2
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +29 -1
- package/contracts/doctor-project-evidence.v1.json +68 -2
- package/contracts/doctor-remediation-plan.v1.json +29 -2
- package/contracts/doctor-workspace-evidence.v1.json +68 -2
- package/contracts/extension-cli-compatibility.v1.json +6 -1
- package/contracts/published-contract-catalog.v1.json +25 -0
- package/contracts/runtime-command-surface.v1.json +63 -0
- package/contracts/workspace-intelligence/doctor-capabilities.v1.json +133 -0
- package/contracts/workspace-intelligence/doctor-diagnosis.v1.json +273 -0
- package/contracts/workspace-intelligence/doctor-graph-diagnosis.v1.json +3 -0
- package/contracts/workspace-intelligence/doctor-receipt.v1.json +136 -0
- package/contracts/workspace-intelligence/doctor-summary.v1.json +99 -0
- package/contracts/workspace-intelligence/doctor-validation.v1.json +109 -0
- package/contracts/workspace-intelligence/project-context-agent.v1.json +110 -0
- package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +25 -0
- package/contracts/workspace-intelligence/workspace-knowledge-graph.v1.json +36 -0
- package/contracts/workspace-intelligence/workspace-knowledge-search.v1.json +54 -0
- package/dist/analyze-HJ774J3E.js +1 -0
- package/dist/{artifact-remediation-plan-O3YIULQN.js → artifact-remediation-plan-BPLON5VX.js} +1 -1
- package/dist/autopilot-release-CH57CGET.js +1 -0
- package/dist/capabilities-command-WEOGFCWF.js +1 -0
- package/dist/chunk-2647BYBC.js +1 -0
- package/dist/chunk-2L4PSZQB.js +1 -0
- package/dist/chunk-3U4VLIGW.js +1 -0
- package/dist/chunk-5BGPGNRQ.js +2 -0
- package/dist/chunk-5EPPPMAS.js +1 -0
- package/dist/{chunk-M5ICGR55.js → chunk-5RL254O2.js} +1 -1
- package/dist/chunk-5ZA4JYOP.js +1 -0
- package/dist/{chunk-AMB42V2F.js → chunk-64JUYYRC.js} +1 -1
- package/dist/chunk-664GXRLD.js +1 -0
- package/dist/chunk-6HCAGHCY.js +8 -0
- package/dist/chunk-7PNARN6S.js +4 -0
- package/dist/chunk-7Y3KVZJF.js +8 -0
- package/dist/{chunk-WIO6L24E.js → chunk-ADL3CK44.js} +1 -1
- package/dist/chunk-AO2ZI42U.js +4 -0
- package/dist/chunk-BDN32Y2N.js +81 -0
- package/dist/chunk-D4RST2HE.js +1 -0
- package/dist/{chunk-6HJJHEL6.js → chunk-DIZSHNZ5.js} +1 -1
- package/dist/chunk-DOIZANFA.js +2 -0
- package/dist/{chunk-HY3RMPW5.js → chunk-E53BGUOW.js} +1 -1
- package/dist/{chunk-FZCYTRBQ.js → chunk-ESWFBSYM.js} +1 -1
- package/dist/chunk-GBMCHFOV.js +1 -0
- package/dist/{chunk-HUPLAFZQ.js → chunk-HASVV34S.js} +1 -1
- package/dist/chunk-IZLEMTES.js +1 -0
- package/dist/chunk-KR7CIEQR.js +1 -0
- package/dist/chunk-KS4FB5W7.js +6 -0
- package/dist/chunk-LYVDRRDO.js +2 -0
- package/dist/{chunk-IBPPMOHM.js → chunk-NHTLE3WN.js} +1 -1
- package/dist/chunk-NS53IPAC.js +1 -0
- package/dist/{chunk-YTLUT6IA.js → chunk-OX53L237.js} +2 -2
- package/dist/chunk-PKIRVQLG.js +1 -0
- package/dist/chunk-QAF26ZQX.js +36 -0
- package/dist/{chunk-NWQ5VWUW.js → chunk-QFCKHUEP.js} +1 -1
- package/dist/chunk-QRWWYL52.js +88 -0
- package/dist/chunk-QTCZPS5I.js +1 -0
- package/dist/{chunk-WSAFBPS5.js → chunk-SV2SP22H.js} +4 -4
- package/dist/chunk-T5YRFRJV.js +1 -0
- package/dist/chunk-UQEQ6CXU.js +1 -0
- package/dist/chunk-V5EYVQ63.js +1 -0
- package/dist/chunk-VGJVIHHR.js +1 -0
- package/dist/{chunk-MRFN5ZQP.js → chunk-W5ZFXKSL.js} +1 -1
- package/dist/chunk-WLCBXCZV.js +5 -0
- package/dist/chunk-WOTTSPSF.js +2 -0
- package/dist/chunk-X7FYEKLI.js +1 -0
- package/dist/chunk-XH7PDHBF.js +1 -0
- package/dist/{chunk-KFKZOPZC.js → chunk-XMTLKDPP.js} +1 -1
- package/dist/chunk-YJTEMJFV.js +3 -0
- package/dist/chunk-YM77FQB3.js +8 -0
- package/dist/chunk-ZCPT6KC3.js +6 -0
- package/dist/chunk-ZPA6ECBJ.js +7 -0
- package/dist/{create-3NSOY7CA.js → create-DLUWG46F.js} +1 -1
- package/dist/doctor-IZ4YOCYE.js +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +168 -168
- package/dist/pipeline-IBQYDLFF.js +5 -0
- package/dist/{project-intelligence-lens-ZOAWXYC5.js → project-intelligence-lens-SIU7IXKG.js} +1 -1
- package/dist/project-test-coverage-FRMVYTFB.js +1 -0
- package/dist/verified-goal-M4GPOXNL.js +1 -0
- package/dist/{workspace-C4UETGY7.js → workspace-3AAOUELG.js} +1 -1
- package/dist/{workspace-agent-sync-446AXPHJ.js → workspace-agent-sync-QGYLY7HH.js} +1 -1
- package/dist/{workspace-archive-VHUPOBAV.js → workspace-archive-BA3ONVXX.js} +1 -1
- package/dist/{workspace-context-XSECHC7O.js → workspace-context-JCLPRYNC.js} +1 -1
- package/dist/workspace-contract-IUUPBQXU.js +1 -0
- package/dist/workspace-explain-CZGBVDE6.js +1 -0
- package/dist/workspace-explain-contract-KVQO57RC.js +1 -0
- package/dist/{workspace-feedback-WXE7NVMV.js → workspace-feedback-PCZKXG5R.js} +1 -1
- package/dist/{workspace-foundation-3EVAQ5X6.js → workspace-foundation-7IGMO4CW.js} +1 -1
- package/dist/{workspace-graph-stream-AJPS45FD.js → workspace-graph-stream-5YMLJXAJ.js} +1 -1
- package/dist/workspace-graph-token-efficiency-HK4KNWWP.js +1 -0
- package/dist/{workspace-history-YY7YRDOH.js → workspace-history-CHJOABME.js} +1 -1
- package/dist/{workspace-intelligence-FWRB47EJ.js → workspace-intelligence-XHSUFTAT.js} +1 -1
- package/dist/workspace-intelligence-evaluation-YMY3C5AW.js +1 -0
- package/dist/{workspace-intelligence-runner-SMEAB4CO.js → workspace-intelligence-runner-EN5V4KSC.js} +1 -1
- package/dist/workspace-intelligence-runtime-registry-NCVHKCMP.js +1 -0
- package/dist/workspace-knowledge-graph-VWQTIEYK.js +1 -0
- package/dist/{workspace-knowledge-graph-query-EKHIE3E2.js → workspace-knowledge-graph-query-TXA3KVUV.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-WB62AVDK.js +1 -0
- package/dist/workspace-mcp-serve-NCAGGWQS.js +3 -0
- package/dist/{workspace-model-MNJOGBPP.js → workspace-model-NXFIKX26.js} +1 -1
- package/dist/{workspace-onboarding-5KO7Z7AD.js → workspace-onboarding-OP22NHQ4.js} +1 -1
- package/dist/{workspace-readme-4S6PJ74A.js → workspace-readme-IVJXSIBS.js} +1 -1
- package/dist/{workspace-registry-summary-GPJEL7K7.js → workspace-registry-summary-A5VDPRHU.js} +1 -1
- package/dist/workspace-repair-engine-N4KXNSVL.js +3 -0
- package/dist/workspace-run-PXKC3ELS.js +1 -0
- package/dist/{workspace-verify-C6HWHRLJ.js → workspace-verify-TUVLFPPN.js} +1 -1
- package/dist/{workspace-watch-DLPHLF5R.js → workspace-watch-2ZNOYSUQ.js} +1 -1
- package/docs/commands-reference.md +35 -6
- package/docs/contracts/ARTIFACT_CATALOG.md +6 -1
- package/docs/contracts/README.md +5 -0
- package/docs/doctor-command.md +158 -7
- package/docs/graph-benchmark-methodology.md +13 -0
- package/docs/workspace-intelligence-runner.md +4 -0
- package/docs/workspace-knowledge-graph.md +53 -4
- package/docs/workspace-run.md +14 -3
- package/package.json +10 -3
- package/dist/analyze-AAZEJ4FC.js +0 -1
- package/dist/autopilot-release-3H5FTF6H.js +0 -1
- package/dist/chunk-2PY65U6X.js +0 -5
- package/dist/chunk-3DONU3DU.js +0 -1
- package/dist/chunk-44VJHNZB.js +0 -1
- package/dist/chunk-5XDPQ3CB.js +0 -1
- package/dist/chunk-7AR5PDLD.js +0 -1
- package/dist/chunk-7KKP7RNB.js +0 -3
- package/dist/chunk-7S4QNH5A.js +0 -5
- package/dist/chunk-7T4TSV5C.js +0 -1
- package/dist/chunk-BYVTHIC3.js +0 -2
- package/dist/chunk-CEIJIFY7.js +0 -88
- package/dist/chunk-D37NEYV6.js +0 -1
- package/dist/chunk-DPMO4U3Z.js +0 -8
- package/dist/chunk-DS4UYMLX.js +0 -1
- package/dist/chunk-FQLB4BIC.js +0 -7
- package/dist/chunk-GDU7VP6G.js +0 -1
- package/dist/chunk-H7P7SSUW.js +0 -75
- package/dist/chunk-KVUYAYTY.js +0 -8
- package/dist/chunk-MQ73VS4E.js +0 -2
- package/dist/chunk-NYHVCFBT.js +0 -1
- package/dist/chunk-OUBBBC7T.js +0 -36
- package/dist/chunk-P7K5RHJC.js +0 -2
- package/dist/chunk-PS5F4DCT.js +0 -1
- package/dist/chunk-QZ7PNMVP.js +0 -1
- package/dist/chunk-RA24WQLF.js +0 -1
- package/dist/chunk-RMXXK64P.js +0 -4
- package/dist/chunk-S7Z4DP3P.js +0 -2
- package/dist/chunk-SJLUE6AY.js +0 -1
- package/dist/chunk-TEHQ7XKK.js +0 -3
- package/dist/chunk-UFOCUHG3.js +0 -1
- package/dist/chunk-WD2XDMGB.js +0 -1
- package/dist/chunk-XVRJVKOX.js +0 -1
- package/dist/doctor-UEFFNAUD.js +0 -1
- package/dist/pipeline-B5S6P36F.js +0 -5
- package/dist/project-test-coverage-44ZPCOPV.js +0 -1
- package/dist/verified-goal-KOU3WJYN.js +0 -1
- package/dist/workspace-contract-AYFTZIKM.js +0 -1
- package/dist/workspace-explain-ZEWVKDBF.js +0 -1
- package/dist/workspace-explain-contract-6CCC26QT.js +0 -1
- package/dist/workspace-graph-token-efficiency-5FNH4JZ5.js +0 -1
- package/dist/workspace-intelligence-evaluation-UP2K3L35.js +0 -1
- package/dist/workspace-intelligence-runtime-registry-MRSF7RTT.js +0 -1
- package/dist/workspace-knowledge-graph-BMMM2FUE.js +0 -1
- package/dist/workspace-mcp-serve-X6C3AWTA.js +0 -3
- package/dist/workspace-repair-engine-GWTXVVKB.js +0 -3
- package/dist/workspace-run-FJTBX4JQ.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-A5FBGRJA.js';import {d as d$1,m}from'./chunk-DOIZANFA.js';import {d,e}from'./chunk-ADL3CK44.js';import {i,h}from'./chunk-5EPPPMAS.js';import {s}from'./chunk-MOSXTVPU.js';import {s as s$1,q}from'./chunk-RJIYCDVC.js';import a from'path';import {existsSync}from'fs';import m$1 from'fs-extra';var f=i.workspaceRegistry,w=h.workspaceRegistry.schemaVersion;function E(r){return {slug:r.slug,relativePath:r.relativePath,framework:r.framework,kit:r.kit,source:r.source}}async function b(r){let e=s(r,"workspace.json").find(t=>existsSync(t));if(!e)return {exists:false,legacyProjectCount:0};try{let t=await m$1.readJson(e),c=Array.isArray(t.projects)?t.projects.length:0,o=typeof t.workspace_name=="string"&&t.workspace_name.trim()||typeof t.name=="string"&&t.name.trim()||a.basename(r);return {exists:true,manifestPath:e,workspaceName:o,profile:typeof t.profile=="string"?t.profile:void 0,legacyProjectCount:c}}catch{return {exists:true,manifestPath:e,legacyProjectCount:0,workspaceName:a.basename(r)}}}async function _(r){let e=a$1(r);for(let t of s$1())if(await m$1.pathExists(t))try{let o=((await m$1.readJson(t)).workspaces||[]).find(s=>a$1(s.path)===e);if(o)return {exists:true,projectCount:Array.isArray(o.projects)?o.projects.length:0,registryPath:t}}catch{continue}return {exists:false,projectCount:0,registryPath:a.join(q(),"workspaces.json")}}async function T(r,e){let t=a.resolve(r),c=await d(t,d$1),o=await b(t),s=await _(t),i=e?.contract!==void 0||!!c,n=[];if(e?.contract)n=e.contract.projects||[];else if(i)try{let{contract:A}=await m({workspacePath:t});n=A.projects||[];}catch{n=[];}let d$2={contract:{exists:i,projectCount:n.length,path:d$1},globalRegistry:{exists:s.exists,projectCount:s.projectCount,path:s.registryPath},legacyWorkspaceJson:{exists:o.exists,projectCount:o.legacyProjectCount,path:o.manifestPath?a.relative(t,o.manifestPath):void 0}},p="none",u=[],y=0;return i?(p="workspace.contract.json",u=n.map(E),y=u.length):s.projectCount>0?(p="global-registry",y=s.projectCount):o.legacyProjectCount>0&&(p="legacy-workspace.json",y=o.legacyProjectCount),{contractExists:i,summary:{schemaVersion:w,kind:"rapidkit.workspace.registry",workspacePath:t,workspaceName:o.workspaceName||a.basename(t),profile:o.profile,projectCount:y,authority:p,contractPath:d$1,projects:u,sources:d$2}}}async function U(r){let e=await d(r,f);if(!e)return null;try{let t=await m$1.readJson(e);return t?.schemaVersion!==w?null:t}catch{return null}}async function D(r,e$1){let t=await M(r,e$1);return await e(r,f,t),t}async function M(r,e){return {...(await T(r,{contract:e?.contract})).summary,generatedAt:(e?.now??new Date).toISOString(),registrySummaryPath:f}}function F(r,e=""){return r.projectCount>0?r.authority==="workspace.contract.json"?`${r.projectCount} project(s) registered in workspace contract${e}.`:r.authority==="global-registry"?`${r.projectCount} project(s) registered in global workspace registry${e}.`:`${r.projectCount} project(s) registered in legacy workspace manifest${e}.`:`Workspace state exists, but no projects are registered yet${e}.`}export{f as a,w as b,T as c,U as d,D as e,M as f,F as g};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {c as c$1}from'./chunk-
|
|
1
|
+
import {c as c$1}from'./chunk-2L4PSZQB.js';import {a}from'./chunk-A5FBGRJA.js';import {a as a$2}from'./chunk-27UR373Z.js';import {b as b$1}from'./chunk-LYVDRRDO.js';import {i as i$1,h}from'./chunk-5EPPPMAS.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
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
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 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-
|
|
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-DLUWG46F.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 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-
|
|
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-A5VDPRHU.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:")}
|
|
@@ -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 $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
|
|
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,r){let t$1=r?.includePaths===true,o=r?.includeDoctorEvidence!==false,a=r?.includeBlueprint!==false,s$1=p.resolve(e),i=await L(s(s$1,"workspace.json")),n=typeof i?.workspace_name=="string"&&i.workspace_name.trim()||p.basename(s$1),d=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$1=await L(s(s$1,"workspace.contract.json")),j={schema_version:h.workspaceShareBundle.schemaVersion,generated_at:new Date().toISOString(),generated_by:"workspai",workspace:{name:n,relative_root:".",profile:d,rapidkit_version:u,...t$1?{absolute_root:s$1}:{}},summary:{project_count:m.length,doctor_evidence_included:o,contract_included:!!h$1},reports:{workspace:y},projects:m,...h$1?{contract:h$1}:{}};a&&(j.blueprint={schema_version:"rapidkit.workspace-blueprint.v1",purpose:"portable-reproducibility",workspace:{name:n,profile:d},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(i$1.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 @@
|
|
|
1
|
+
import {s,p as p$1}from'./chunk-MOSXTVPU.js';import c from'fs-extra';import*as p from'path';async function y(e,o){await c.ensureDir(p.dirname(e));let t=`${e}.${process.pid}.${Date.now()}.tmp`;try{await c.writeJSON(t,o,{spaces:2}),await c.move(t,e,{overwrite:true});}finally{await c.remove(t).catch(()=>{});}}function g(e){return p$1(e,"imported-projects.json")}async function f(e){let o=(await Promise.all(s(e,"imported-projects.json").map(async t=>await c.pathExists(t)?t:null))).find(t=>typeof t=="string");if(!o)return [];try{let t=await c.readJSON(o);if(!t||typeof t!="object"||t.version!==1||!Array.isArray(t.projects))throw new Error("expected a version 1 registry with a projects array");let i=t.projects,a=i.filter(s=>{if(!s||typeof s!="object")return false;let n=s;return typeof n.name=="string"&&typeof n.path=="string"&&typeof n.stack=="string"&&typeof n.confidence=="string"&&typeof n.importedAt=="string"});if(a.length!==i.length)throw new Error("one or more project entries are invalid");return a}catch(t){throw new Error(`Imported-project registry is invalid: ${o}`,{cause:t})}}async function P(e,o){if(o.length===0)return;let t=await f(e),i=new Map;for(let r of t)i.set(r.path,r);for(let r of o)i.set(r.path,r);let a=Array.from(i.values()).sort((r,l)=>r.name.localeCompare(l.name)).map(r=>({...r})),s={version:1,updatedAt:new Date().toISOString(),projects:a},n=g(e);await y(n,s);}async function k(e,o){if(o.length===0)return;let t=await f(e),i=new Set(o.map(r=>p.resolve(r))),a=t.filter(r=>!i.has(p.resolve(r.path))),s={version:1,updatedAt:new Date().toISOString(),projects:a},n=g(e);await y(n,s);}export{f as a,P as b,k as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {e,p,i,f as f$1,g}from'./chunk-5EPPPMAS.js';var l="workspai-workspace-intelligence-chain-v1",u="contracts/workspace-intelligence-chain.v1.json";function f(){let e$1=e,t=p,n=[{id:"model",ordinal:1,phase:"understand",label:"Model",command:[...t.model.command],consumes:["workspace markers","project metadata","registry","contract","policies"],inputRefs:["projects-repositories","runtime-dependencies","workspace-rules","existing-evidence"],consumesArtifacts:[],produces:[...t.model.produces],dependsOn:[],exitPolicy:"stop-on-error",purpose:"Build the canonical current model and its structurally bound, derived Knowledge Graph."},{id:"diff",ordinal:2,phase:"change",label:"Diff",command:[...t.diff.command],consumes:[e$1.model,e$1.snapshot],inputRefs:["changes","model-baseline"],consumesArtifacts:[e$1.model,e$1.snapshot],produces:[...t.diff.produces],dependsOn:["model"],exitPolicy:"stop-on-error",purpose:"Describe structural change against the selected baseline."},{id:"impact",ordinal:3,phase:"change",label:"Impact",command:[...t.impact.command],consumes:[e$1.model,e$1.diff],inputRefs:[],consumesArtifacts:[e$1.model,e$1.diff],produces:[...t.impact.produces],dependsOn:["diff"],exitPolicy:"stop-on-error",purpose:"Calculate transitive blast radius over the workspace graph."},{id:"doctor-evidence",ordinal:4,phase:"evidence",label:"Doctor Evidence",command:[...t["doctor-evidence"].command],consumes:["workspace runtime and project health signals"],inputRefs:["projects-repositories","runtime-dependencies","existing-evidence"],consumesArtifacts:[],produces:[...t["doctor-evidence"].produces],dependsOn:["impact"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh health evidence after the impact artifact exists."},{id:"contract-evidence",ordinal:5,phase:"evidence",label:"Contract Evidence",command:[...t["contract-evidence"].command],consumes:[i.workspaceContract],inputRefs:["workspace-rules"],consumesArtifacts:[],produces:[...t["contract-evidence"].produces],dependsOn:["impact"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh structural contract evidence without hiding failed verdicts."},{id:"analyze-evidence",ordinal:6,phase:"evidence",label:"Analyze Evidence",command:[...t["analyze-evidence"].command],consumes:[e$1.model,"workspace runtime and dependency signals"],inputRefs:["projects-repositories","runtime-dependencies","workspace-rules"],consumesArtifacts:[e$1.model],produces:[...t["analyze-evidence"].produces],dependsOn:["impact"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh analysis evidence required by the release-readiness gate."},{id:"readiness-evidence",ordinal:7,phase:"evidence",label:"Readiness Evidence",command:[...t["readiness-evidence"].command],consumes:["doctor, analysis, runtime, and release signals"],inputRefs:["runtime-dependencies","existing-evidence"],consumesArtifacts:[e$1.doctor,e$1.contractVerify,e$1.analyze],produces:[...t["readiness-evidence"].produces],dependsOn:["doctor-evidence","contract-evidence","analyze-evidence"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh release-readiness evidence before the definitive gate."},{id:"verify",ordinal:8,phase:"gate",label:"Verify",command:[...t.verify.command],consumes:[e$1.impact,e$1.doctor,e$1.contractVerify,e$1.readiness],inputRefs:[],consumesArtifacts:[e$1.impact,e$1.doctor,e$1.contractVerify,e$1.readiness],produces:[...t.verify.produces],dependsOn:["impact","doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence"],exitPolicy:"continue-on-structured-verdict",purpose:"Emit the definitive evidence-backed workspace gate."},{id:"context",ordinal:9,phase:"ground",label:"Agent Context",command:[...t.context.command],consumes:[e$1.model,e$1.impact,e$1.verify],inputRefs:[],consumesArtifacts:[e$1.model,e$1.impact,e$1.verify],produces:[...t.context.produces],dependsOn:["verify"],exitPolicy:"stop-on-error",purpose:"Build compact agent context from the same verified evidence."},{id:"agent-sync",ordinal:10,phase:"distribute",label:"Agent Grounding",command:[...t["agent-sync"].command],consumerArgs:{vscode:["--target","vscode"]},consumes:[e$1.agentContext],inputRefs:[],consumesArtifacts:[e$1.agentContext],produces:[...t["agent-sync"].produces],dependsOn:["context"],exitPolicy:"stop-on-error",purpose:"Distribute one context into portable agent and IDE surfaces."},{id:"explain",ordinal:11,phase:"explain",label:"Explain",command:[...t.explain.command],consumes:[e$1.verify,e$1.impact],inputRefs:[],consumesArtifacts:[e$1.verify,e$1.impact],produces:[...t.explain.produces],dependsOn:["verify"],exitPolicy:"continue-on-structured-verdict",purpose:"Translate evidence and blockers into a human and agent-readable narrative."}];return {schemaVersion:l,name:"Workspace Intelligence Chain",contractPath:u,invariant:"Every consumer must preserve step identity, dependencies, artifact flow, and verdict semantics; presentation may change, chain meaning may not.",invariants:["Missing or unreadable input is unknown or unavailable; it must not be presented as verified absence.","Freshness and provenance travel with evidence and must not be discarded by projections.","The current graph is an evidence-backed workspace knowledge graph with bounded source intelligence, not a complete cross-language symbol or call graph.","Simple and standard presentations summarize the contract; their contractRefs must preserve complete traceability.","Conditional provider outputs must be resolved through their dedicated inventory contract.","Auxiliary capabilities expose or refresh intelligence but are not mandatory execution-chain steps.","Canonical step commands are stage-pure: they must not implicitly execute a downstream chain step or regenerate an upstream artifact.","Canonical JSON artifacts must satisfy their registered schema both when produced and when consumed across CLI, MCP, IDE, and CI trust boundaries.","Schema validity is necessary but not sufficient: hashes, embedded models, summaries, counts, graph statistics, and artifact references must remain semantically coherent.","Persisted impact evidence must be rejected as stale when the current workspace model or Git observation no longer matches its embedded diff.","Canonical artifact replacement must be atomic and workspace-contained; an interrupted or denied write must preserve the last valid artifact.","Concurrent history updates must be serialized without silently dropping entries, and invalid history must never be overwritten as if it were absent.","The canonical global registry is ~/.workspai/workspaces.json; ~/.rapidkit/workspaces.json is a non-authoritative compatibility mirror for legacy consumers and must not diverge after a CLI registry mutation."],semantics:{workspace:"The governed operating boundary that relates one or more projects and repositories to shared metadata, policies, contracts, evidence, and consumers.",repository:"A source-control boundary that may contain one or more projects and may live inside or outside the workspace root.",project:"A discoverable build or runtime unit with its own path, metadata or observable manifests, command capabilities, and evidence.",evidence:"A sourced observation or generated verification result with provenance and freshness; evidence may be consumed by a later run.",artifact:"A durable generated file that another command or consumer can read without parsing terminal prose.",gate:"A structured verdict with reasons and exit semantics derived from current evidence."},workspaceLifecycle:{ingestionRoutes:[{id:"create",label:"Create",commands:["create workspace","create project"],result:"Create a workspace or supported project and write canonical Workspai metadata."},{id:"adopt",label:"Adopt",commands:["adopt"],result:"Register an existing project in place without requiring source relocation."},{id:"import",label:"Import",commands:["import","workspace import"],result:"Attach an existing project or repository path to the workspace inventory."}],durableState:[{id:"workspace-identity",paths:[".workspai-workspace",".workspai/workspace.json"],purpose:"Identify the workspace boundary, profile, and canonical root."},{id:"project-inventory",paths:[".workspai/project.json",".workspai/context.json",".workspai/adopt.json","~/.workspai/workspaces.json","~/.rapidkit/workspaces.json (legacy compatibility mirror)"],purpose:"Record native, adopted, imported, and globally registered project locations while preserving a non-authoritative mirror for legacy extension discovery."},{id:"governance",paths:[".workspai/policies.yml",i.workspaceContract],purpose:"Define workspace policy and explicit structural relationships."},{id:"graph-overrides",paths:[".workspai/workspace-graph.overrides.json"],purpose:"Provide explicit dependency edges that override inferred relationships."}],rule:"Create, adopt, and import are ingestion routes, not intelligence facts. Their durable state becomes observable input to Model."},runtimeRegistry:{authority:"contracts/workspace-intelligence-runtime-registry.ts",artifacts:Object.entries(e).map(([r,s])=>({id:r,path:s,schemaVersion:f$1[r],schemaContract:g[r]}))},executionEnvelope:{rule:"Sync and baseline resolution are deterministic execution prerequisites, not canonical intelligence stages; every run reports them separately and preserves the exact canonical stage sequence.",operations:[{id:"sync",executionPoint:"before:model",artifacts:[i.workspaceContract,i.workspaceRegistry],failurePolicy:"stop-and-report",purpose:"Reconcile portable workspace inventory and contract inputs before modeling."},{id:"baseline",executionPoint:"after:model-before:diff",artifacts:[e$1.snapshot],failurePolicy:"stop-and-report",purpose:"Create an initial structural baseline when absent or reuse the existing baseline before Diff."}],report:{artifact:e$1.intelligenceRun,schemaVersion:f$1.intelligenceRun,invariant:"The report must preserve exact preflight and stage order, registry-owned artifacts, failure propagation, and aggregate status/exit semantics."}},boundaries:{inputs:[{id:"projects-repositories",label:"Projects and repositories",sources:["projects","repositories","services","modules","imported paths"],entersAt:"model"},{id:"runtime-dependencies",label:"Runtime and dependencies",sources:["runtime manifests","lockfiles","scripts","framework markers","package dependencies","bounded multi-language source observations for supported file extensions"],entersAt:"model"},{id:"workspace-rules",label:"Workspace rules",sources:["workspace markers","registry","project metadata","contracts","policies","ownership","graph overrides"],entersAt:"model"},{id:"changes",label:"Changes",sources:["repository state","git state","model baseline","workspace diff"],entersAt:"diff"},{id:"model-baseline",label:"Explicit model baseline",sources:[e$1.snapshot],entersAt:"diff"},{id:"existing-evidence",label:"Existing evidence",sources:["doctor reports","analysis reports","contract verification","release readiness","pipeline results","tests and runtime evidence","previous intelligence artifacts"],entersAt:"doctor-evidence"}],outputs:[{id:"understanding",label:"System understanding",artifacts:[e$1.model,e$1.knowledgeGraph,e$1.diff,e$1.impact],producedBy:["model","diff","impact"],inventory:"complete-for-chain"},{id:"governance-evidence",label:"Governance evidence",artifacts:[e$1.doctor,e$1.contractVerify,e$1.analyze,e$1.readiness,e$1.verify,e$1.history],producedBy:["doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence","verify"],inventory:"complete-for-chain"},{id:"agent-grounding",label:"Agent grounding",artifacts:[e$1.agentContext,e$1.agentIndex,e$1.agentCustomizationPack,e$1.skillsIndex,e$1.agents],producedBy:["context","agent-sync"],inventory:"canonical-minimum",inventoryContract:"contracts/agent-customization-pack.v1.json"},{id:"explanations",label:"Explainable decisions",artifacts:[e$1.explain],producedBy:["explain"],inventory:"complete-for-chain"}],consumers:[{id:"developers",label:"Developers",channels:["CLI","reports","AGENTS.md"]},{id:"ci",label:"CI",channels:["JSON artifacts","exit codes","release gates"]},{id:"ides",label:"IDEs",channels:["synced contracts","extension","agent context"]},{id:"ai-agents",label:"AI agents",channels:["INDEX.json","context","skills","MCP"]}]},deliveryChannels:[{id:"artifacts",carries:["reports","models","context","grounding","skills"],authority:"canonical"},{id:"json-stdout",carries:["structured command results"],authority:"projection"},{id:"human-cli",carries:["summaries","diagnostics","next actions"],authority:"projection"},{id:"exit-codes",carries:["gate and command status"],authority:"projection"},{id:"watch-events",carries:["incremental workspace change events"],authority:"projection"},{id:"mcp",carries:["read-mostly access to current workspace artifacts"],authority:"projection"}],feedback:{from:["developers","ci","ides","ai-agents"],signals:["source commits","dependency updates","policy and contract edits","repairs","test and runtime results","agent action outcomes"],reentersThrough:["projects-repositories","runtime-dependencies","workspace-rules","changes","existing-evidence"],rule:"Consumer actions are not silently treated as truth. They re-enter as observable changes or evidence and must be modeled and verified again."},auxiliaryCapabilities:[{id:"graph",commands:["workspace graph emit","workspace graph explain","workspace graph entities","workspace graph evidence","workspace graph path","workspace graph search","workspace graph benchmark","workspace graph overlay","workspace graph dot","workspace graph mermaid","workspace graph jsonld","workspace graph graphml","workspace graph gexf"],reads:[e$1.model,e$1.knowledgeGraph],role:"Query the proof-backed graph derived from the canonical workspace model.",chainStep:false},{id:"evaluation",commands:["workspace eval init","workspace eval record","workspace eval status","workspace eval report","workspace eval compare"],reads:[e$1.evaluationLive,e$1.evaluationLastRun],produces:[e$1.evaluationLive,e$1.evaluationLastRun],role:"Measure model usage, activity, cost provenance, and verified outcomes without storing prompt or response bodies.",chainStep:false},{id:"watch",commands:["workspace watch"],reads:["workspace inputs",e$1.model],role:"Refresh the model incrementally and emit deterministic change events.",chainStep:false},{id:"mcp",commands:["workspace mcp serve"],reads:["workspace evidence artifacts"],role:"Expose read-mostly workspace evidence to compatible clients.",chainStep:false}],presentations:{simple:{layers:["inputs","intelligence","outputs","consumers"],nodes:[{id:"input-layer",kind:"inputs",label:"Input Layer",summary:"Projects \xB7 Repositories \xB7 Dependencies \xB7 Changes",contractRefs:["projects-repositories","runtime-dependencies","workspace-rules","changes","model-baseline","existing-evidence"]},{id:"workspace-intelligence",kind:"intelligence",label:"Workspace Intelligence",summary:"Model \xB7 Graph \xB7 Impact \xB7 Verify",contractRefs:n.map(r=>r.id)},{id:"agent-grounding",kind:"outputs",label:"Agent Grounding",summary:"AGENTS.md \xB7 Skills \xB7 Context",contractRefs:["agent-grounding"]},{id:"evidence-and-decisions",kind:"outputs",label:"Evidence Contracts",summary:"Reports \xB7 Artifacts \xB7 Gates",contractRefs:["understanding","governance-evidence","explanations"]},{id:"shared-consumers",kind:"consumers",label:"Shared Consumers",summary:"Developers \xB7 CI \xB7 IDEs \xB7 AI agents",contractRefs:["developers","ci","ides","ai-agents"]}],rule:"Use concrete user-facing language for first-contact explanations. Every input, output, consumer, and chain step must remain traceable through contractRefs even when details are summarized."},standard:{phases:["understand","change","evidence","gate","ground","distribute","explain"],nodes:[{id:"understand",label:"Understand",question:"What exists in the current workspace?",stepRefs:["model"]},{id:"change",label:"Change",question:"What changed, and what can it affect?",stepRefs:["diff","impact"]},{id:"evidence",label:"Evidence",question:"What health, contract, and readiness facts were observed?",stepRefs:["doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence"]},{id:"gate",label:"Gate",question:"Is the current state acceptable and trustworthy?",stepRefs:["verify"]},{id:"ground",label:"Ground",question:"What should an agent know before acting?",stepRefs:["context"]},{id:"distribute",label:"Distribute",question:"Which durable agent and IDE surfaces receive that context?",stepRefs:["agent-sync"]},{id:"explain",label:"Explain",question:"Why did the system reach this result or verdict?",stepRefs:["explain"]}],rule:"Use for architecture education and product surfaces. Every phase must appear once and in order."},advanced:{steps:n.map(r=>r.id),requiredFields:["command","inputRefs","consumesArtifacts","produces","dependsOn","exitPolicy","purpose"],rule:"Use for implementers, adapters, IDEs, and CI. Preserve every step and its artifact and verdict semantics."}},steps:n,diagram:{direction:"TB",nodes:n.map(({id:r,label:s,phase:p})=>({id:r,label:s,phase:p})),edges:n.flatMap(r=>r.dependsOn.map(s=>({from:s,to:r.id,meaning:"required before"})))},consumers:{agents:{canonicalReadOrder:[e$1.agentIndex,e$1.agentContext,e$1.verify,e$1.impact,e$1.explain,e$1.model,e$1.knowledgeGraph,e$1.agentCustomizationPack,e$1.skillsIndex],entrypoints:[e$1.agents,".workspai/AGENT-GROUNDING.md"],rule:"Agents must cite current artifacts, preserve verified versus inferred status, and re-run the producing step when evidence is missing or stale."},ideAndCi:{requiredArtifacts:[e$1.model,e$1.knowledgeGraph,e$1.impact,e$1.verify],rule:"IDEs and CI must consume structured artifacts and verdict exit semantics rather than parse human help or terminal prose."},docsAndDiagrams:{rule:"Documentation and diagrams must derive labels, ordering, and edges from this contract and must not invent implemented steps."}}}}export{l as a,f as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {f}from'./chunk-5EPPPMAS.js';var o="model-usage-event.v1",s=f.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var Y="workspace-knowledge-search.v1";function m(e){return e.trim().toLowerCase()}var z=new WeakMap;function R(e){let t=z.get(e);if(t)return t;let o=new Map(e.relations.map(s=>[s.id,s])),a=new Map(e.entities.map(s=>[s.id,s])),l=new Map(e.proofs.map(s=>[s.id,s])),r=new Map,d=new Map,f=(s,p)=>{let g=d.get(s)??[];g.push(p),d.set(s,g);};for(let s of e.entities){let p=[s.id,s.label,s.identity.key,...s.kind==="project"&&s.projectId?[s.projectId]:[],...s.identity.aliases];for(let g of new Set(p.map(m))){let y=r.get(g)??[];y.push(s),r.set(g,y);}}for(let s of e.relations)f(s.from,{from:s.from,to:s.to,relationId:s.id,kind:s.kind,direction:"forward",proofIds:s.proofIds}),f(s.to,{from:s.to,to:s.from,relationId:s.id,kind:s.kind,direction:"reverse",proofIds:s.proofIds});for(let s of r.values())s.sort((p,g)=>p.id.localeCompare(g.id));for(let s of d.values())s.sort((p,g)=>p.to.localeCompare(g.to)||p.relationId.localeCompare(g.relationId));let c={entitiesById:a,relationsById:o,entitiesByAlias:r,proofsById:l,adjacency:d};return z.set(e,c),c}function _(e,t){let o=R(e),a=o.relationsById.get(t);if(a)return {found:true,targetType:"relation",relation:a};let l=m(t),r=o.entitiesByAlias.get(l)??[];return r.length===1?{found:true,targetType:"entity",entity:r[0]}:{found:false,query:t,candidates:r.map(d=>d.id).sort()}}function he(e,t){let o=_(e,t);if(!o.found)return {query:t,found:false,target:null,proofs:[],candidates:o.candidates};let a=o.targetType==="entity"?o.entity:o.relation,l=new Set(a.proofIds);return {query:t,found:true,target:a,candidates:[],proofs:[...l].map(r=>R(e).proofsById.get(r)).filter(r=>!!r).sort((r,d)=>r.id.localeCompare(d.id))}}function fe(e,t,o){let a=_(e,t),l=_(e,o);if(!a.found||a.targetType!=="entity"||!l.found||l.targetType!=="entity")return {from:t,to:o,found:false,resolvedFrom:a.found&&a.targetType==="entity"?a.entity.id:null,resolvedTo:l.found&&l.targetType==="entity"?l.entity.id:null,entityPath:[],hops:[],proofs:[]};let r=R(e),d=[a.entity.id],f=new Map,c=new Set(d),s=0;for(;s<d.length&&!c.has(l.entity.id);){let h=d[s++];for(let k of r.adjacency.get(h)??[])c.has(k.to)||(c.add(k.to),f.set(k.to,k),d.push(k.to));}if(!c.has(l.entity.id))return {from:t,to:o,found:false,resolvedFrom:a.entity.id,resolvedTo:l.entity.id,entityPath:[],hops:[],proofs:[]};let p=[],g=l.entity.id;for(;g!==a.entity.id;){let h=f.get(g);if(!h)break;p.push(h),g=h.from;}p.reverse();let y=new Set(p.flatMap(h=>h.proofIds));return {from:t,to:o,found:true,resolvedFrom:a.entity.id,resolvedTo:l.entity.id,entityPath:[a.entity.id,...p.map(h=>h.to)],hops:p,proofs:[...y].map(h=>r.proofsById.get(h)).filter(h=>!!h).sort((h,k)=>h.id.localeCompare(k.id))}}function ue(e,t){return e.entities.filter(o=>!t||o.kind===t).sort((o,a)=>o.kind.localeCompare(a.kind)||o.label.localeCompare(a.label))}var b={relations:24,relatedEntities:24,proofs:16,proofIdsPerItem:4,aliasesPerEntity:8,attributeArrayItems:8,attributeStringCharacters:256};function X(e){let t=[],o=new Set;for(let a=0;a<b.proofIdsPerItem&&t.length<b.proofs;a+=1)for(let l of e){let r=l.proofIds[a];if(!(!r||o.has(r))&&(o.add(r),t.push(r),t.length>=b.proofs))break}return t}function Z(e,t,o){let a=e.identity.aliases.slice(0,b.aliasesPerEntity);o.aliases+=e.identity.aliases.length-a.length;let l=Object.fromEntries(Object.entries(e.attributes).map(([d,f])=>{if(Array.isArray(f)){let c=f.slice(0,b.attributeArrayItems);return o.attributeValues+=f.length-c.length,[d,c]}return typeof f=="string"&&f.length>b.attributeStringCharacters?(o.attributeValues+=1,[d,f.slice(0,b.attributeStringCharacters)]):[d,f]})),r=e.proofIds.filter(d=>t.has(d)).slice(0,b.proofIdsPerItem);return o.proofReferences+=e.proofIds.length-r.length,{...e,identity:{...e.identity,aliases:a},attributes:l,proofIds:r}}function J(e){let t=Object.values(e.attributes).flatMap(o=>Array.isArray(o)?o:[o]);return [e.id,e.kind,e.label,e.projectId??"",e.identity.key,...e.identity.aliases,...t.map(o=>String(o??""))].join(" ").toLowerCase()}var ee=new Set(["a","an","and","are","as","at","be","been","being","by","can","check","could","did","do","does","find","for","from","give","had","has","have","how","i","in","into","is","it","its","may","might","of","on","or","our","show","should","that","the","their","them","then","there","these","they","this","those","tell","to","was","we","were","what","when","where","which","who","why","will","with","would","you","your"]);function j(e){let t=o=>m(o).split(/[^a-z0-9]+/u).filter(a=>a.length>1);return [...new Set([...t(e),...t(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2"))])]}function te(e){let t=m(e.label),o=m(e.identity.key),a=e.identity.aliases.map(m),l=J(e);return {entity:e,label:t,identity:o,aliases:a,haystack:l,labelTokens:new Set(j(e.label)),identityTokens:new Set(j(e.identity.key)),aliasTokens:new Set(e.identity.aliases.flatMap(j)),allTokens:new Set(j(l))}}function S(e,t){return e.has(t)||t.length>=3&&[...e].some(o=>o.startsWith(t))}function O(e,t){return S(e.labelTokens,t)||S(e.identityTokens,t)||S(e.aliasTokens,t)||S(e.allTokens,t)}function ne(e,t,o,a){let{label:l,identity:r,aliases:d,haystack:f}=e,c=0;(l===t||r===t||d.includes(t))&&(c+=1e4),(l.startsWith(t)||r.startsWith(t))&&(c+=250),f.includes(t)&&(c+=100);let s=0;for(let p of o){let g=a.get(p)??1,y=S(e.labelTokens,p),h=S(e.identityTokens,p),k=S(e.aliasTokens,p),u=O(e,p);u&&(s+=1),l===p?c+=80*g:y&&(c+=36*g),h&&(c+=24*g),k&&(c+=20*g),u&&(c+=10*g);}return o.length>0&&(c+=s/o.length*120),c}function oe(e,t){return t.filter(o=>O(e,o)).length}var se=new Map([["clojure","clojure"],["cplusplus","cpp"],["cpp","cpp"],["typescript","typescript"],["ts","typescript"],["javascript","javascript"],["js","javascript"],["nodejs","javascript"],["python","python"],["py","python"],["go","go"],["golang","go"],["csharp","csharp"],["dotnet","csharp"],["dart","dart"],["elixir","elixir"],["fsharp","fsharp"],["java","java"],["kotlin","kotlin"],["lua","lua"],["php","php"],["ruby","ruby"],["rust","rust"],["scala","scala"],["svelte","svelte"],["swift","swift"],["vue","vue"]]);function ae(e){return new Set(e.map(t=>se.get(t)).filter(t=>!!t))}function F(e){let t=e.attributes.language;return typeof t=="string"?m(t):null}function re(e){return {project:1e3,service:900,api:900,package:850,endpoint:800,container:700,deployment:700,environment:650,pipeline:600,"test-suite":550,owner:500,decision:450,document:400}[e.kind]??0}function ie(e,t){let o=t.has("language")||t.has("languages"),a=t.has("binding")||t.has("bindings")||t.has("bridge")||t.has("bridges"),l=t.has("dependency")||t.has("dependencies")||t.has("depends"),r=t.has("core")||t.has("runtime"),d=t.has("owner")||t.has("owners")||t.has("ownership")||t.has("maintainer"),f=t.has("ci")||t.has("pipeline")||t.has("pipelines")||t.has("workflow"),c=t.has("deploy")||t.has("deployment")||t.has("infrastructure")||t.has("container"),s=t.has("doc")||t.has("docs")||t.has("document")||t.has("documentation"),p=t.has("service")||t.has("services")||t.has("api")||t.has("rpc"),g=t.has("schema")||t.has("schemas")||t.has("message")||t.has("protobuf")||t.has("proto")||t.has("contract"),y=typeof e.attributes.mechanism=="string"?m(e.attributes.mechanism):"",h=typeof e.attributes.specification=="string"?m(e.attributes.specification):"",k=m(e.label),u=0;if(o&&e.kind==="language"){let A=typeof e.attributes.fileCount=="number"?e.attributes.fileCount:0;u+=900+Math.min(A,1e4)/10;}return a&&e.kind==="protocol"&&(u+=800),l&&e.kind==="package"&&(u+=650),r&&e.kind==="package"&&/(?:^|[_-])core(?:$|[_-])/u.test(k)&&(u+=700),r&&e.kind==="protocol"&&y.includes("core")&&(u+=300),d&&e.kind==="owner"&&(u+=850),f&&e.kind==="pipeline"&&(u+=800),c&&["deployment","container","environment"].includes(e.kind)&&(u+=775),s&&["document","decision"].includes(e.kind)&&(u+=725),p&&["api","endpoint","service"].includes(e.kind)&&(u+=700),g&&(e.kind==="schema"||(e.kind==="api"||e.kind==="protocol")&&(h.includes("protobuf")||y.includes("protobuf")))&&(u+=750),u}function ce(e){return [e.has("language")||e.has("languages"),e.has("binding")||e.has("bindings")||e.has("bridge")||e.has("bridges"),e.has("dependency")||e.has("dependencies")||e.has("depends"),e.has("core")||e.has("runtime"),e.has("owner")||e.has("ownership")||e.has("maintainer"),e.has("ci")||e.has("pipeline")||e.has("workflow"),e.has("deploy")||e.has("deployment")||e.has("infrastructure"),e.has("doc")||e.has("docs")||e.has("documentation"),e.has("service")||e.has("api")||e.has("rpc"),e.has("schema")||e.has("protobuf")||e.has("proto")||e.has("contract")].filter(Boolean).length>=3}function ke(e,t){let o=m(t.query),a=[...new Set(j(t.query))],l=new Set(j(t.projectId??"")),r=t.projectId?a.filter(n=>!l.has(n)):a,d=!!(t.projectId&&a.length>0&&r.length===0),f=r.filter(n=>!ee.has(n)),c=f.length>0?f:r,s=ae(c),p=new Set(c),g=c.length<=1?c.length:Math.min(3,Math.ceil(c.length/3)),y=Math.max(1,Math.min(Math.trunc(t.limit??12),100)),h=Math.max(0,Math.min(Math.trunc(t.relationsPerEntity??4),20)),k=new Set;if(t.projectId){let n=new Set(e.entities.filter(i=>i.kind==="project"&&(i.projectId===t.projectId||i.label===t.projectId)).map(i=>i.id));for(let i of e.relations)n.has(i.from)&&k.add(i.to),n.has(i.to)&&k.add(i.from);}let u=e.entities.filter(n=>(!t.kind||n.kind===t.kind)&&(!t.projectId||n.projectId===t.projectId||n.projectId===void 0&&k.has(n.id))).map(te),A=new Map(c.map(n=>{let i=u.filter(w=>O(w,n)).length;return [n,Math.log((u.length+1)/(i+1))+1]})),P=u.map(n=>{let i=oe(n,c),w=F(n.entity),I=w&&s.has(w)?400:0,K=ie(n.entity,p);return {entity:n.entity,matchedTerms:i,intentScore:K,score:d?re(n.entity):ne(n,o,c,A)+I+K}}).filter(n=>{let i=F(n.entity);return (s.size===0||i===null||s.has(i))&&(o.length===0||n.score>0&&(d||n.matchedTerms>=g||n.intentScore>0))}).sort((n,i)=>i.score-n.score||n.entity.kind.localeCompare(i.entity.kind)||n.entity.label.localeCompare(i.entity.label)),E=(ce(p)?(()=>{let n=[],i=[],w=new Map,I=new Set;for(let K of P){let q=w.get(K.entity.kind)??0,V=m(K.entity.label);q<2&&!I.has(V)?(n.push(K),w.set(K.entity.kind,q+1),I.add(V)):i.push(K);}return [...n,...i]})():P).slice(0,y).map(n=>n.entity),M=new Set(E.map(n=>n.id)),G=new Map,x=e.relations.filter(n=>{if(!(M.has(n.from)||M.has(n.to)))return false;let w=M.has(n.from)?n.from:n.to,I=G.get(w)??0;return I>=h?false:(G.set(w,I+1),true)}),W=t.projection==="agent",T=W?x.slice(0,b.relations):x,D=R(e),B=[...new Set(T.flatMap(n=>[n.from,n.to]).filter(n=>!M.has(n)))].map(n=>D.entitiesById.get(n)).filter(n=>!!n).map(({id:n,kind:i,label:w,projectId:I})=>({id:n,kind:i,label:w,...I?{projectId:I}:{}})).sort((n,i)=>n.kind.localeCompare(i.kind)||n.label.localeCompare(i.label)),H=W?B.slice(0,b.relatedEntities):B,L=new Set([...E.flatMap(n=>n.proofIds),...T.flatMap(n=>n.proofIds)]),U=W?X([...E,...T]):[...L],v=new Set(U),C={entities:P.length-E.length,relations:x.length-T.length,relatedEntities:B.length-H.length,proofs:L.size-v.size,proofReferences:0,aliases:0,attributeValues:0},N=W?E.map(n=>Z(n,v,C)):E,Q=W?T.map(n=>{let i=n.proofIds.filter(w=>v.has(w)).slice(0,b.proofIdsPerItem);return C.proofReferences+=n.proofIds.length-i.length,{...n,proofIds:i}}):T,$=[...v].map(n=>D.proofsById.get(n)).filter(n=>!!n).sort((n,i)=>n.id.localeCompare(i.id));return {schemaVersion:Y,query:t.query,kind:t.kind??null,...t.projectId?{projectId:t.projectId}:{},limit:y,totalMatches:P.length,truncated:P.length>N.length||W&&Object.values(C).some(n=>n>0),entities:N,relatedEntities:H,relations:Q,proofs:$,...W?{budget:{mode:"agent",limits:{...b},omitted:C}}:{}}}export{Y as a,_ as b,he as c,fe as d,ue as e,ke as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b}from'./chunk-
|
|
1
|
+
import {b}from'./chunk-ZPA6ECBJ.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};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import {d,b,e}from'./chunk-IZLEMTES.js';import {a}from'./chunk-2647BYBC.js';import {d as d$2}from'./chunk-S5KTATOU.js';import {a as a$1}from'./chunk-27UR373Z.js';import {p as p$1,w,t as t$1}from'./chunk-DIZSHNZ5.js';import {h,j,f,e as e$2}from'./chunk-ZCPT6KC3.js';import {d as d$1}from'./chunk-ADL3CK44.js';import {e as e$1,i}from'./chunk-5EPPPMAS.js';import {a as a$2}from'./chunk-TQEMLBAG.js';import {t,p,s}from'./chunk-MOSXTVPU.js';import {e as e$3,g}from'./chunk-RJIYCDVC.js';import U from'fs';import k from'path';import T from'chalk';import {execa}from'execa';function Le(e){return U.existsSync(k.join(e,"bun.lock"))||U.existsSync(k.join(e,"bunfig.toml"))?"bun":U.existsSync(k.join(e,"pnpm-lock.yaml"))?"pnpm":U.existsSync(k.join(e,"yarn.lock"))?"yarn":(U.existsSync(k.join(e,"package-lock.json")),"npm")}function Ge(e,r,t=Le(e)){return t==="npm"?`npm run ${r}`:`${t} run ${r}`}function Be(e,r=Le(e)){return `${r} install`}var ct={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},dt={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],c:["cmake -S . -B build"],cpp:["cmake -S . -B build"],elixir:["mix deps.get"],ruby:["bundle install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],c:["ctest --test-dir build --output-on-failure"],cpp:["ctest --test-dir build --output-on-failure"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],c:["cmake --build build"],cpp:["cmake --build build"],elixir:["mix compile"],ruby:["gem build *.gemspec"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],c:[],cpp:[],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function te(e,r){if(r){let t=r.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=e$2(r),s=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:t==="fiber"?"fiber":t==="aspnetcore"||t==="asp-net-core"?"aspnetcore":t}`;return ct[s]}}function He(e,r,t){if(r){let n=te(e,r);if(n&&n.commands[t])return n.commands[t]}if(["init","test","build","start"].includes(t)){let n=dt[t]?.[e]??[];return n.length>0?n[0]:void 0}}var lt={test:"test",build:"build",start:"start"};function ge(e){if(e.stage==="init")return e.runtime==="node"?Be(e.projectPath):He(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let r=lt[e.stage];if(r){let t=t$1(e.projectPath,r,{framework:e.framework});if(t)return Ge(e.projectPath,t.scriptName)}}return He(e.runtime,e.framework,e.stage)}function mt(e){let r=h(e).map(t=>t==="python"?"python":t==="node"||t==="bun"?"node":t==="go"?"go":t==="java"?"java":t==="php"?"php":t==="rust"?"rust":t==="dotnet"?"dotnet":t==="elixir"?"elixir":t==="ruby"?"ruby":t==="clojure"||t==="scala"||t==="kotlin"?"jvm-generic":null).filter(t=>t!==null).filter((t,n,o)=>o.indexOf(t)===n);return {primary:r.length>0?r[0]:"unknown",secondary:r.slice(1)}}function ze(e){return mt(e).primary}function ye(e,r){if(!e)return "unknown";r||(r={setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[t,n]of Object.entries(r))for(let o of n)if(new RegExp(o,"i").test(e))return t;return "unknown"}async function re(e){let r=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(r))return {valid:true};try{let n=process.platform==="win32"?"where":"which";if((await execa(n,[r],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${r}' not found or not executable`}}function Je(e,r,t){if(!r)return e;let n=typeof r=="object"&&!Array.isArray(r)&&("dev"in r||"staging"in r||"prod"in r||"default"in r)&&!Object.keys(r).some(o=>["init","test","build","start"].includes(o))?r:{};return t&&typeof n[t]=="string"?n[t]:typeof n.default=="string"?n.default:e}async function qe(e,r){if(!e)return {healthy:true};switch(e.type){case "port":{let t=e.value;try{let n=await import('net');return new Promise(o=>{let s=new n.Socket,u=5e3;s.setTimeout(u),s.on("connect",()=>{s.destroy(),o({healthy:true,reason:`Port ${t} is listening`});}),s.on("timeout",()=>{s.destroy(),o({healthy:false,reason:`Port ${t} timeout after ${u}ms`});}),s.on("error",c=>{s.destroy(),o({healthy:false,reason:`Port ${t} error: ${String(c)}`});}),s.connect(t,"localhost");})}catch(n){return {healthy:false,reason:`Port check error: ${n instanceof Error?n.message:String(n)}`}}}case "http":{let t=e.value,n;try{let o=new AbortController;n=setTimeout(()=>o.abort(),5e3);let s=await fetch(t,{method:"GET",signal:o.signal});return {healthy:s.status===200,reason:`HTTP ${s.status}`,metadata:{status:s.status}}}catch(o){return {healthy:false,reason:`HTTP check error: ${o instanceof Error?o.message:String(o)}`}}finally{n&&clearTimeout(n);}}case "log":{let t=e.value;if(!r)return {healthy:true};try{let n=[k.join(r,".workspai","last-run.log"),k.join(r,".rapidkit","last-run.log")].find(o=>U.existsSync(o));if(n){let o=U.readFileSync(n,"utf-8"),s=new RegExp(t,"i");return {healthy:s.test(o),reason:s.test(o)?"Log pattern found":"Log pattern not found"}}return {healthy:true,reason:"No log file to check"}}catch(n){return {healthy:false,reason:`Log check error: ${n instanceof Error?n.message:String(n)}`}}}case "command":{let t=e.value;try{let n=await execa(t,[],{cwd:r,reject:false,shell:true});return {healthy:n.exitCode===0,reason:n.exitCode===0?"Health check passed":"Health check failed",metadata:{exitCode:n.exitCode}}}catch(n){return {healthy:false,reason:`Command check error: ${n instanceof Error?n.message:String(n)}`}}}default:return {healthy:true}}}var Ye={init:"init",test:"test",build:"build",start:"start"};function pt(e){return e in Ye?Ye[e]:null}function ft(e,r){let n=p$1(e)?.contextJson?.commands;if(!n||typeof n!="object"||Array.isArray(n))return;let o=n[r];if(typeof o=="string"&&o.trim().length>0)return o.trim();if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,u=s.default??s.dev;if(typeof u=="string"&&u.trim().length>0)return u.trim()}}function Qe(e,r,t=w(e)){let n=pt(r);if(!n)return ft(e,r)?{supported:true}:{supported:false,reason:`Workspace stage "${r}" is not part of the Workspai fleet contract.`};if(!t.projectRoot)return {supported:false,reason:"No Workspai project metadata was detected for this target."};let o=t.commandMap[n];if(!o||o.status!=="supported"){let s=t.runtimeSupportTier==="observed"||t.frameworkSupportTier==="observed";return {supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!s}}return {supported:true}}var gt=new Set(["init","test","build","start"]),yt=new Set([".git","node_modules",".workspai",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function B(e){try{return await U.promises.access(e,U.constants.F_OK),true}catch{return false}}async function ht(e){for(let r of e)if(await B(r))return true;return false}async function kt(e,r,t){if(r==="python"){let o=[k.join(e,".workspai","cli.py"),k.join(e,".rapidkit","cli.py")];for(let s of o)if(await B(s))return {valid:true};return {valid:false,reason:"Project-local .workspai/cli.py is missing. Run `workspai init` in this project first."}}let n=t.trim().split(/\s+/)[0];if(n&&["npm","npx","pnpm","yarn"].includes(n)){let o=e$3(n);if((await execa(o.command,[...o.prefixArgs,"--version"],{reject:false,env:g()})).exitCode===0)return {valid:true}}return re(t)}async function ne(e){let r=await U.promises.readFile(e,"utf-8");return JSON.parse(r)}function D(e){return e.replace(/\\/g,"/")}function bt(e){let r=e?.trim();return r?r.startsWith("project:")?r.slice(8).trim()||null:r:null}async function wt(e){let r=k.join(e,e$1.model);if(await B(r))try{let n=((await ne(r)).projects??[]).map(o=>typeof o.path=="string"?k.resolve(e,o.path):null).filter(o=>!!o).filter((o,s,u)=>u.indexOf(o)===s).filter(o=>U.existsSync(o));if(n.length>0)return n.sort()}catch{}return a$1(e,{skipDirs:yt,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t$1,n)=>await ht([...t(t$1,"context.json"),...t(t$1,"project.json")])?true:k.resolve(t$1)===k.resolve(n)?false:h(t$1).length>0})}async function xt(e){for(let r of [k.join(".workspai","project.json"),k.join(".workspai","context.json"),k.join(".rapidkit","project.json"),k.join(".rapidkit","context.json")]){let t=k.join(e,r);if(await B(t))try{let n=await ne(t),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function vt(e,r,t){let n=bt(t);if(!n)return {projects:r,normalizedScope:null};let o=D(n).toLowerCase(),s=[];for(let u of r){let c=D(k.relative(e,u)),m=k.basename(u),p=await xt(u);[c,m,p].filter(i=>typeof i=="string"&&i.length>0).map(i=>D(i).toLowerCase()).includes(o)&&s.push(u);}if(s.length===0)throw new Error(`Workspace run scope did not match any project: ${t}`);return {projects:s,normalizedScope:n}}async function Rt(e,r,t){let n=await execa("git",["diff","--name-only",`${t}...HEAD`],{cwd:e,reject:false,env:a$2()});if(n.exitCode!==0)return new Set(r);let o=n.stdout.split(/\r?\n/).map(u=>u.trim()).filter(u=>u.length>0).map(u=>D(u));if(o.length===0)return new Set;let s=new Set;for(let u of r){let c=D(k.relative(e,u));if(!c||c===".")continue;let m=`${c}/`;o.some(p=>p===c||p.startsWith(m))&&s.add(u);}return s}async function St(e,r,t){let n=await d$1(e,i.workspaceContract)??p(e,"workspace.contract.json");if(await B(n))try{let d=await Ct(e,r,t,n);if(d.graphStatus!=="missing")return d}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let o=await d$1(e,".workspai/workspace-dependency-graph.json")??p(e,"workspace-dependency-graph.json");if(!await B(o))return {expanded:t,graphStatus:"missing",expansionDepth:0};let s;try{s=await ne(o);}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let u=new Set(r.map(d=>k.resolve(d))),c=new Map;if(!s||typeof s!="object"||Array.isArray(s))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let m=Array.isArray(s.projects)?s.projects:[];for(let d of m){if(!d||typeof d!="object"||Array.isArray(d))continue;let i=d,l=typeof i.path=="string"?i.path:"",y=k.resolve(e,l);if(!u.has(y))continue;let b=Array.isArray(i.dependsOn)?i.dependsOn.filter(S=>typeof S=="string"):[];for(let S of b){let g=k.resolve(e,S);u.has(g)&&(c.has(g)||c.set(g,new Set),c.get(g)?.add(y));}}let p$1=d$2(c,t);return {expanded:p$1.reached,graphStatus:"loaded",expansionDepth:p$1.added}}async function Ct(e,r,t,n){let o=await ne(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let s=o,u=Array.isArray(s.projects)?s.projects:null;if(!u)return {expanded:t,graphStatus:"invalid",expansionDepth:0};let c=new Map,m=new Map;for(let y of r){let b=D(k.relative(e,y));m.set(b,k.resolve(y));}let p=new Map,d=new Map,i=new Map;for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=typeof b.relativePath=="string"?D(b.relativePath):S,v=m.get(g);!S||!v||c.set(S,v);}for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=c.get(S);if(!g)continue;let v=b.contracts&&typeof b.contracts=="object"&&!Array.isArray(b.contracts)?b.contracts:{},E=Array.isArray(v.dependsOn)?v.dependsOn.filter(R=>typeof R=="string"):[],W=Array.isArray(v.publishes)?v.publishes.filter(R=>typeof R=="string"):[],_=Array.isArray(v.consumes)?v.consumes.filter(R=>typeof R=="string"):[];for(let R of E){let j=c.get(R);j&&(i.has(j)||i.set(j,new Set),i.get(j)?.add(g));}for(let R of W)p.has(R)||p.set(R,new Set),p.get(R)?.add(g);for(let R of _)d.has(R)||d.set(R,new Set),d.get(R)?.add(g);}for(let[y,b]of p.entries()){let S=d.get(y);if(S)for(let g of b){i.has(g)||i.set(g,new Set);for(let v of S)v!==g&&i.get(g)?.add(v);}}let l=d$2(i,t);return {expanded:l.reached,graphStatus:"loaded",expansionDepth:l.added}}async function Et(e,r){if(typeof r=="boolean")return r;let t=s(e,"policies.yml").find(s=>U.existsSync(s))??p(e,"policies.yml");if(!await B(t))return true;let n="";try{n=await U.promises.readFile(t,"utf-8");}catch{return true}let o=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o?o[1]==="true":true}function jt(e){let r=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(r){let t=Number.parseInt(r,10);if(Number.isFinite(t)&&t>0)return t}return e==="init"?12e4:9e4}function Xe(e,r){let t=Number.parseInt(process.env[e]??"",10);return Number.isFinite(t)&&t>0?t:r}function he(e){return new Promise(r=>setTimeout(r,e))}async function Pt(e){let r=process.argv[1];if(e.useRapidkitWrapper&&!r)return {exitCode:1,stdout:"",stderr:"Workspai entrypoint is unavailable for startup verification.",healthStatus:{healthy:false,reason:"Workspai entrypoint is unavailable."}};let t=e.useRapidkitWrapper&&r?execa(process.execPath,[r,"start"],{cwd:e.projectPath,reject:false,timeout:e.timeoutMs,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}}):execa(e.finalCommand,[],{cwd:e.projectPath,reject:false,shell:true,timeout:e.timeoutMs}),n=Promise.resolve(t).then(d=>({kind:"exit",result:d}),d=>({kind:"error",error:d})),o=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_GRACE_MS",2e3),s=await Promise.race([n,he(o).then(()=>({kind:"alive"}))]);if(s.kind==="error"){let d=typeof s.error=="object"&&s.error!==null&&"timedOut"in s.error&&!!s.error.timedOut;return {exitCode:d?124:1,stdout:"",stderr:s.error instanceof Error?s.error.message:String(s.error),timedOut:d,healthStatus:{healthy:false,reason:"The start command failed before readiness."}}}if(s.kind==="exit"){let d=Number(s.result.exitCode??0);return {exitCode:d,stdout:String(s.result.stdout??""),stderr:String(s.result.stderr??""),healthStatus:{healthy:d===0,reason:d===0?"The start command completed successfully.":`The start command exited with code ${d} before readiness.`}}}let u=te(e.runtime,e.framework)?.healthCheck,c=u?{healthy:false,reason:"The configured health check has not passed yet."}:{healthy:true,reason:`The service remained alive for ${o}ms (bounded startup smoke).`};if(u){let d=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_HEALTH_TIMEOUT_MS",15e3),i=Date.now()+d;for(;Date.now()<i;){let l=await qe(u,e.projectPath);if(c={healthy:l.healthy,reason:l.reason},l.healthy)break;if((await Promise.race([n,he(350).then(()=>({kind:"alive"}))])).kind!=="alive"){c={healthy:false,reason:"The service exited before its configured health check passed."};break}}}try{t.kill?.("SIGTERM",{forceKillAfterDelay:1e3});}catch{try{t.kill?.();}catch{}}let m=await Promise.race([n,he(2e3).then(()=>({kind:"alive"}))]),p=m.kind==="exit"?m.result:void 0;return {exitCode:c.healthy?0:1,stdout:String(p?.stdout??""),stderr:String(p?.stderr??""),healthStatus:c}}async function ke(e,r,t){let n=process.argv[1];if(!n)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};try{let o=await execa(process.execPath,[n,...e],{cwd:r,reject:false,timeout:t,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr}}catch(o){return {exitCode:typeof o=="object"&&o!==null&&"timedOut"in o&&!!o.timedOut?124:1,stdout:typeof o=="object"&&o!==null&&"stdout"in o?String(o.stdout??""):"",stderr:typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr??""):o instanceof Error?o.message:String(o)}}}function At(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"||e==="rust"||e==="php"}function Ft(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}function Ot(e,r=8){if(e.length<=r)return e.join(`
|
|
2
|
+
`);let t=3;return [...e.slice(0,t),...e.slice(-(r-t))].join(`
|
|
3
|
+
`)}function Tt(e){let r=/(?:\bnot found\b|\bno such\b|\bmissing\b|\bfailed\b|\berror\b|\bexception\b|\bcannot\b|\bdenied\b|\btimeout\b|\btimed out\b|\benoent\b|\beacces\b|\beperm\b)/i;return [...e].reverse().find(t=>r.test(t))??e.at(-1)}async function Mt(e){let r=process.cwd();try{process.chdir(e);let{handleInitCommand:t}=await import('./index.js');return {exitCode:await t(["init"]),stdout:"",stderr:""}}finally{process.chdir(r);}}async function Ze(e){let r=i=>{let l=f(i);return l==="node"||l==="bun"?"node":l==="python"?"python":l==="go"?"go":l==="java"?"java":l==="php"?"php":l==="ruby"?"ruby":l==="rust"?"rust":l==="dotnet"?"dotnet":l==="elixir"?"elixir":l==="clojure"||l==="scala"||l==="kotlin"?"jvm-generic":ze(e)},t=i=>{if(!i)return;let l=e$2(i);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(l))return l},n=p$1(e),o=n?.detection??j(e,n?.projectJson??null),s=n?.contextJson,u=r(o.runtime),c=t(o.key),m={},p=new Set(["init","test","build","start"]);if(s?.commands&&typeof s.commands=="object")for(let[i,l]of Object.entries(s.commands))typeof l=="string"&&p.has(i)&&(m[i]=l);let d;if(s?.commandEnvironments&&typeof s.commandEnvironments=="object"){let i=s.commandEnvironments;d={dev:typeof i.dev=="string"?i.dev:void 0,staging:typeof i.staging=="string"?i.staging:void 0,prod:typeof i.prod=="string"?i.prod:void 0,default:typeof i.default=="string"?i.default:void 0};}return {runtime:u,framework:c,commandOverrides:Object.keys(m).length>0?m:void 0,environmentCommandVariants:d,environment:typeof s?.environment=="string"?s.environment:void 0}}async function et(e,r,t,n,o,s,u){let c=!o?.[r]&&At(t),m;if(o&&o[r]?m=o[r]:c?m=`rapidkit ${r}`:m=ge({projectPath:e,runtime:t,framework:n,stage:r}),!m)return {exitCode:127,command:`<stage not supported for ${t}>`,message:`No stage command found for runtime '${t}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let p=Je(m,s,u);if(!p)return {exitCode:127,command:m,message:"Failed to resolve stage command",errorCategory:"runtime"};let d=ge({projectPath:e,runtime:t,framework:n,stage:r});if(c){if(d){let x=c?await kt(e,t,d):await re(d);if(!x.valid)return {exitCode:127,command:p,message:x.reason||"Command not available",errorCategory:"setup"}}}else {let x=await re(p);if(!x.valid)return {exitCode:127,command:p,message:x.reason||"Command not available",errorCategory:"setup"}}let i=0,l="",y="",b,S,g=jt(r),v=Date.now();try{let x=r==="start"?await Pt({projectPath:e,finalCommand:p,useRapidkitWrapper:c,runtime:t,framework:n,timeoutMs:g}):c?r==="init"&&Ft()?await Mt(e):await ke([r],e,g):await execa(p,[],{cwd:e,reject:false,shell:true,timeout:g});if(i=Number(x.exitCode??0),l=x.stdout,y=x.stderr,S=r==="start"?x.healthStatus:void 0,i!==0){let I=`${l}
|
|
4
|
+
${y}`,V=Date.now()-v;b=i===124||ye(I)==="timeout"||i===143&&V>=Math.floor(g*.8)?"timeout":ye(I);}}catch(x){let I=typeof x=="object"&&x!==null&&"timedOut"in x&&!!x.timedOut;return {exitCode:I?124:1,command:p,message:I?`Stage timed out after ${g}ms`:x instanceof Error?x.message:"Command execution failed",errorCategory:I?"timeout":"runtime"}}let E=`${l}
|
|
5
|
+
${y}`.split(/\r?\n/).map(x=>x.trim()).filter(Boolean),W=Ot(E),_=Tt(E),R=Date.now()-v,j=i===124||b==="timeout"||i===143&&R>=Math.floor(g*.8),P=i===0?void 0:j?"timeout":b,$=i===0||!P?void 0:{category:P,exitCode:i,command:p,timedOut:j,timeoutMs:g,...W?{outputExcerpt:W}:{}};return {exitCode:i,command:p,errorCategory:P,healthStatus:S,failureDiagnostic:$,message:j?`Stage timed out after ${g}ms`:i!==0?_?`Stage failed with exit code ${i}: ${_}`:`Stage failed with exit code ${i}`:void 0}}function tt(e){try{return JSON.parse(e)}catch{return null}}function Nt(e){switch(e){case "dotnet":return "Install .NET 8+ SDK, then rerun `npx workspai setup dotnet` or `npx workspai init`.";case "go":return "Install Go 1.21+, then rerun `npx workspai setup go` or `npx workspai init`.";case "java":case "jvm-generic":return "Install Java 21+ and Maven/Gradle, then rerun `npx workspai setup java` or `npx workspai init`.";case "node":return "Install Node.js LTS and npm/pnpm/yarn, then rerun `npx workspai setup node` or `npx workspai init`.";case "python":return "Install Python 3.10+ and pip/Poetry, then rerun `npx workspai setup python` or `npx workspai init`.";default:return null}}async function Dt(e){let r=[],t=await ke(["doctor","workspace","--json"],e);if(t.exitCode!==0)r.push({gate:"doctor-workspace",status:"fail",summary:"doctor workspace command failed"});else {let s=tt(t.stdout)?.healthScore,u=Number(s?.errors??0);Number.isFinite(u)&&u>0?r.push({gate:"doctor-workspace",status:"fail",summary:`doctor workspace reports ${u} error(s)`}):r.push({gate:"doctor-workspace",status:"pass",summary:"doctor workspace passed"});}let n=await ke(["readiness","--json"],e);if(n.exitCode!==0)r.push({gate:"readiness",status:"fail",summary:"readiness command failed"});else {let o=tt(n.stdout),s=String(o?.overallStatus??"").toLowerCase();s==="fail"?r.push({gate:"readiness",status:"fail",summary:"readiness overall status is fail"}):s==="warn"?r.push({gate:"readiness",status:"warn",summary:"readiness overall status is warn"}):r.push({gate:"readiness",status:"pass",summary:"readiness overall status is pass"});}return r}var Wt=new Set(["dev","stop"]);function $t(e){let r=e.trim();return !r||Wt.has(r.toLowerCase())?false:gt.has(r)?true:/^[a-z][a-z0-9_-]*$/i.test(r)}function rt(e,r,t){let n=D(k.relative(t,r));return (Array.isArray(e.projects)?e.projects:[]).some(s=>{if(!s||typeof s!="object")return false;let u=s,c=[u.relativePath,u.path].filter(m=>typeof m=="string"&&m.length>0).map(m=>D(m));return u.status==="passed"&&(c.includes(n)||c.some(m=>m.endsWith(`/${n}`)))})}function It(e,r){return te(e,r)?.dependencies??[]}function _t(e,r){let t=Math.max(1,Math.min(4,r)),n=Number(e??t);return Number.isFinite(n)?Math.max(1,Math.min(16,Math.trunc(n))):t}async function vr(e$1){if(!$t(e$1.stage))throw new Error(`Unsupported workspace run stage: ${e$1.stage}`);let r=Date.now(),t=k.resolve(e$1.workspacePath),n=await d(t),o=await wt(t),{projects:s,normalizedScope:u}=await vt(t,o,e$1.scope),c=e$1.affected===true,m=e$1.blastRadius===true,p=e$1.since?.trim()||"HEAD~1",d$1=c?await Rt(t,s,p):new Set(s),i,l="not-applicable",y=0,b$1="all";if(c&&m){let f=await St(t,o,d$1);i=f.expanded,l=f.graphStatus,y=f.expansionDepth,b$1="affected+blast-radius";}else c?(i=d$1,b$1="affected"):(i=d$1,b$1="all");let S=e$1.stage==="init"||e$1.planOnly===true?false:await Et(t,e$1.enforceGates),g=S?await Dt(t):[{gate:"doctor-workspace",status:"skipped",summary:"workspace run gates disabled"},{gate:"readiness",status:"skipped",summary:"workspace run gates disabled"}],v=g.find(f=>f.status==="fail"),E=s.filter(f=>i.has(f)),W=e$1.continueOnError===true||e$1.stage==="init",_=e$1.parallel===true,R=_t(e$1.maxWorkers,E.length),j=E.length,P=0;e$1.json||console.log(T.gray(`Workspace run (${e$1.stage}) started: ${j} target(s), ${_?`parallel x${R}`:"sequential"}`));let $=new Map;for(let f of o){let h=D(k.relative(t,f)),a=s.includes(f),M=a&&i.has(f);$.set(f,{path:f,relativePath:h,projectName:k.basename(h)||k.basename(f),selected:M,affected:M,status:"skipped",exitCode:null,durationMs:0,reason:M?void 0:a?"not affected":"outside scope",framework:void 0,runtimeDetected:void 0,executionCommand:void 0});}if(v)for(let f of E){let h=$.get(f);h&&(h.status="skipped",h.reason=`blocked by ${v.gate}`);}else {let f=async h=>{let a$1=$.get(h);if(!a$1)return;let M=D(k.relative(t,h));e$1.json||console.log(T.gray(`\u23F3 [${P}/${j}] ${e$1.stage} ${M}`)),a$1.selected=true,a$1.affected=true;let A=Date.now(),N=a(h),F=e$1.runtime?.trim().toLowerCase(),L=N.units.filter(w=>!F||w.runtime===F).map(w=>({unit:w,stage:w.stages.find(O=>O.stage===e$1.stage)})).filter(w=>!!w.stage),z=L.map(({unit:w,stage:O})=>({unitId:w.id,runtime:w.runtime,role:w.role,root:w.root,manifest:w.manifest,stage:O.stage,command:O.command,status:"planned",exitCode:null,durationMs:0}));if(a$1.runtimeExecutions=z,e$1.planOnly){a$1.runtimeDetected=L[0]?.unit.runtime,a$1.status="skipped",a$1.reason=L.length>0?`plan only: ${L.length} runtime unit(s)`:F?`no ${F} runtime unit supports stage "${e$1.stage}"`:`no runtime unit supports stage "${e$1.stage}"`,a$1.durationMs=Date.now()-A,P+=1;return}if(N.polyglot||F){if(L.length===0){a$1.status="failed",a$1.reason=F?`No ${F} runtime unit supports stage "${e$1.stage}"`:`No runtime unit supports stage "${e$1.stage}"`,a$1.errorCategory="setup",a$1.errorMessage=a$1.reason,a$1.exitCode=127,a$1.durationMs=Date.now()-A,P+=1;return}let w;for(let C=0;C<L.length;C+=1){let{unit:ve,stage:Re}=L[C],Y=z[C],Se=k.resolve(h,ve.root),ut=Date.now(),ue=await Ze(Se),K=await et(Se,e$1.stage,ve.runtime,ue.framework,{[e$1.stage]:Re.command},ue.environmentCommandVariants,ue.environment);if(Y.durationMs=Date.now()-ut,Y.exitCode=K.exitCode,Y.status=K.exitCode===0?"passed":"failed",Y.reason=K.message,K.exitCode!==0&&!w&&(w=K.message??Re.command),K.exitCode!==0&&!W){for(let Ce of z.slice(C+1))Ce.status="skipped",Ce.reason="stopped after runtime-unit failure";break}}let O=z.find(C=>C.status==="failed");a$1.runtimeDetected=L[0]?.unit.runtime,a$1.executionCommand=z.filter(C=>C.status!=="skipped").map(C=>`[${C.runtime}:${C.root}] ${C.command}`).join(" && "),a$1.durationMs=Date.now()-A,a$1.exitCode=O?.exitCode??0,a$1.status=O?"failed":"passed",a$1.reason=O?w??"runtime-unit stage failed":void 0,a$1.errorCategory=O?"runtime":void 0,a$1.errorMessage=a$1.reason,P+=1;return}let{runtime:se,framework:ae,commandOverrides:st,environmentCommandVariants:at,environment:it}=await Ze(h);a$1.runtimeDetected=se,a$1.framework=ae;let ie=Qe(h,e$1.stage);if(!ie.supported){a$1.status=ie.shouldFail===false?"skipped":"failed",a$1.reason=ie.reason??`stage "${e$1.stage}" unsupported for project`,a$1.durationMs=Date.now()-A,a$1.exitCode=a$1.status==="failed"?127:null,a$1.status==="failed"&&(a$1.errorCategory="setup",a$1.errorMessage=a$1.reason),P+=1;return}if(e$1.reusePassed&&n){let w=n.stages[e$1.stage]??n.stages[e$1.stage];if(w&&rt(w,h,t)){a$1.status="passed",a$1.reason="reused passed result from workspace-run-last.json",a$1.durationMs=Date.now()-A,a$1.exitCode=0,P+=1,e$1.json||console.log(T.gray(`\u21BA reused passed cache for ${M}`));return}}let xe=It(se,ae).filter(w=>w!==e$1.stage);if(xe.length>0&&n){let w=xe.find(O=>{let C=n.stages[O];return !C||!rt(C,h,t)});if(w){a$1.status="skipped",a$1.reason=`dependency stage "${w}" not satisfied in workspace-run-last.json`,a$1.durationMs=Date.now()-A,a$1.exitCode=null,P+=1;return}}let G=await et(h,e$1.stage,se,ae,st,at,it);if(a$1.executionCommand=G.command,a$1.errorCategory=G.errorCategory,a$1.healthStatus=G.healthStatus,a$1.failureDiagnostic=G.failureDiagnostic,a$1.durationMs=Date.now()-A,a$1.exitCode=G.exitCode,G.exitCode===0?(a$1.status="passed",a$1.reason=void 0):(a$1.status="failed",a$1.reason=G.message||"stage command failed",a$1.errorMessage=G.message),P+=1,!e$1.json){let w=j>0?Math.round(P/j*100):100,O=a$1.status==="passed"?T.green("\u2705"):T.red("\u274C");if(console.log(T.gray(`${O} [${P}/${j}] (${w}%) ${M} ${a$1.durationMs}ms`)),a$1.status==="failed"){a$1.reason&&console.log(T.red(` Reason: ${a$1.reason}`)),a$1.executionCommand&&console.log(T.gray(` Command: ${a$1.executionCommand}`));let C=Nt(a$1.runtimeDetected);C&&a$1.errorCategory==="setup"&&console.log(T.gray(` Hint: ${C}`));}}};if(_&&E.length>1){let h=0,a=false,M=new Array(R).fill(null).map(async()=>{for(;h<E.length;){if(a&&!W)return;let A=h;h+=1;let N=E[A];await f(N),$.get(N)?.status==="failed"&&(a=true);}});if(await Promise.all(M),!W&&a){let A=false;for(let N of E){let F=$.get(N);if(F){if(F.status==="failed"){A=true;continue}A&&F.status==="skipped"&&(F.reason=F.reason||"stopped after failure");}}}}else for(let h of E){await f(h);let a=$.get(h);if(!W&&a?.status==="failed"){let M=E.slice(E.indexOf(h)+1);for(let A of M){let N=$.get(A);N&&(N.status="skipped",N.reason="stopped after failure");}break}}}let x=[];for(let f of o){let h=$.get(f);h&&x.push(h);}let I=x.filter(f=>f.status==="passed").length,V=x.filter(f=>f.status==="failed").length,oe=x.filter(f=>f.status==="skipped").length,be=e$1.strict===true,nt=V>0||be&&g.some(f=>f.status==="fail"||f.status==="warn")?1:0,we={schemaVersion:"1.0",workspacePath:t,stage:e$1.stage,generatedAt:new Date().toISOString(),durationMs:Date.now()-r,options:{affected:c,blastRadius:m,since:c?p:null,parallel:_,maxWorkers:R,continueOnError:W,strict:be,enforceGates:S,scope:u,reusePassed:e$1.reusePassed===true,planOnly:e$1.planOnly===true,runtime:e$1.runtime?.trim()||null},selection:{mode:b$1,since:c?p:null,scope:u,graphStatus:l,expansionDepth:y},gates:{enforced:S,results:g,blocked:!!v,blockingGate:v?.gate},summary:{projectCount:o.length,selectedCount:E.length,passed:I,failed:V,skipped:oe,exitCode:nt},projects:x,enterpriseControls:{jsonReady:true,evidencePath:b}},ot=k.join(t,b);return await e(t,we),e$1.json||(v&&(console.log(T.red(`\u274C Workspace run blocked by ${v.gate}`)),console.log(T.gray(` ${v.summary}`))),console.log(T.cyan(`Workspace run (${e$1.stage}) => passed: ${I}, failed: ${V}, skipped: ${oe}`)),console.log(T.gray(`Report: ${ot}`))),we}export{vr as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-UQEQ6CXU.js';import {c}from'./chunk-7Y3KVZJF.js';import {p,h,i as i$1}from'./chunk-5ZA4JYOP.js';import {a}from'./chunk-DOIZANFA.js';import {e as e$1,d}from'./chunk-ADL3CK44.js';import {f,e}from'./chunk-5EPPPMAS.js';import I from'path';import R from'fs-extra';var G=f.agentContext,V=e.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$1){return {id:e$1.id,scope:e$1.scope,display:l(e$1.args),execute:M(e$1.args),description:e$1.description,...e$1.project?{project:e$1.project}:{},freshness:h({id:`command.${e$1.id}`,label:`${e$1.id} command`,scope:"command",value:{display:l(e$1.args),execute:M(e$1.args)},...e$1.project?{project:e$1.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e$1.generatedAt,now:e$1.now,sourceArtifact:e.model,sourcePath:`safeCommands.${e$1.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(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$1){let t=e$1.model??await p({workspacePath:e$1.workspacePath,includeEvidence:e$1.includeEvidence===true,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),n=q(e$1.agent),r=z(t,e$1.scope),c$1=B(t,e$1.scope,r);if(e$1.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=e$1.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$1.workspacePath),y=I.join(e$1.workspacePath,e.knowledgeGraph),d=await R.pathExists(y)?await R.readJson(y).catch(()=>null):null,C=false;if(d?.schemaVersion===f.knowledgeGraph)try{c(d,t),C=true;}catch{}let v=X(t),j=K(t,r,a),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,sourceArtifact:e.agentContext,sourcePath:`safeCommands.${o.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),b$1=[...w,...O],f$1=i$1({facts:b$1,generatedAt:a.toISOString(),now:a}),h$1=b();return {schemaVersion:G,generatedAt:a.toISOString(),agent:n,workspaceSummary:v,modelRef:e.model,knowledgeGraph:{artifact:e.knowledgeGraph,schemaVersion:f.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$1.scope??"workspace",...r?{activeProject:r.name}:{}},projects:_,safeCommands:j,facts:b$1,factFreshness:f$1,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 \`${e.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 \`${e.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$1.verifyBeforeUseFacts>0?[`${f$1.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
|
+
`)}}async function de(e,t){return e$1(t,V,a(e))}export{G as a,V as b,pe as c,de as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function i(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:null}function b(s){return Array.isArray(s)?s.map(i).filter(o=>o!==null):[]}function l(s){return typeof s=="number"&&Number.isInteger(s)&&s>=0?s:0}function C(s){return typeof s=="number"&&Number.isFinite(s)&&s>=0&&s<=100?s:null}function j(s){let o=b(s.projects),d=i(s.summary),g=i(s.healthScore),e=i(s.evidenceFreshness),m=i(s.contract),r=0,a=0,p=0,n=0,t=[],c=0;for(let h of o){let F=i(h.diagnosis),f=i(F?.coverage);if(!F||!f)continue;c+=1,r+=l(f.blockingFindings),a+=l(f.advisoryFindings),p+=l(f.unknownFindings),n+=l(f.contradictionCount);let k=C(f.diagnosisCompleteness);k!==null&&t.push(k);}let u=c>0||m?.scoringPolicyVersion==="doctor-score-policy-v2",y=u&&(o.length===0||c===o.length);return y||(r=Math.max(r,l(d?.blockingFindings),l(g?.errors)),a=Math.max(a,l(d?.advisoryFindings),l(g?.warnings))),{canonical:y,projectCount:o.length,diagnosedProjectCount:c,missingDiagnosisProjects:u?Math.max(0,o.length-c):0,blockingFindings:r,advisoryFindings:a,unknownFindings:p,contradictionCount:n,minimumDiagnosisCompleteness:t.length>0?Math.min(...t):o.length===0||!u?100:0,staleEvidence:e?.status==="stale",unknownFreshness:e?.status==="unknown",hasSystemErrors:d?.hasSystemErrors===true||l(g?.errors)>r}}function v(s){let o=b(s.projects),d=0,g=0,e=0,m=0,r=0,a=0,p=0;for(let n of o){n.depsInstalled===false&&(m+=1),p+=l(n.vulnerabilities);let t=i(n.dependencyAudit);t?.status==="tool-unavailable"||t?.status==="unsupported"?r+=1:t?.status==="failed"&&(a+=1);let c=i(n.diagnosis);for(let u of b(c?.findings))u.issueClass!=="dependency"&&u.issueClass!=="security"||(u.status==="blocking"?d+=1:u.status==="advisory"&&(g+=1),(u.status==="unknown"||u.diagnosisState==="unknown")&&(e+=1));}return {blockingFindings:d,advisoryFindings:g,unknownFindings:e,missingDependencies:m,auditUnavailable:r,auditFailed:a,vulnerableDependencies:p}}function A(s){let o=[],d=i(s.project),g=b(s.projects);d&&g.push(d);for(let e of g){let m=typeof e.name=="string"?e.name:"project",r=i(e.diagnosis),a=b(r?.findings);if(a.length>0){for(let n of a){let t=n.status;if(!["blocking","advisory","unknown"].includes(String(t)))continue;let c=typeof n.symptom=="string"?n.symptom.trim():typeof n.label=="string"?n.label.trim():"";c&&o.push({projectName:m,status:t,message:c,...typeof n.id=="string"?{id:n.id}:{},...typeof n.causalKey=="string"?{causalKey:n.causalKey}:{},...typeof n.issueClass=="string"?{issueClass:n.issueClass}:{}});}continue}let p=Array.isArray(e.issues)?e.issues.filter(n=>typeof n=="string"):[];for(let n of p)o.push({projectName:m,status:"blocking",message:n.trim()});for(let n of b(e.probes)){if(n.status!=="fail"&&n.status!=="warn")continue;let t=typeof n.reason=="string"?n.reason.trim():typeof n.label=="string"?n.label.trim():"";t&&o.push({projectName:m,status:n.status==="fail"?"blocking":"advisory",message:t,...typeof n.id=="string"?{id:n.id}:{}});}}return [...new Map(o.map(e=>[`${e.projectName}:${e.causalKey??e.id??""}:${e.status}:${e.message}`,e])).values()]}export{j as a,v as b,A as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b,c,d as d$1}from'./chunk-ESWFBSYM.js';import {a as a$1,b as b$1}from'./chunk-PYCJWW4B.js';import {c as c$2}from'./chunk-IZLEMTES.js';import {c as c$1,d as d$4}from'./chunk-2L4PSZQB.js';import {p as p$1,a,o,g,d as d$3,f as f$1}from'./chunk-5BGPGNRQ.js';import {a as a$4}from'./chunk-X7FYEKLI.js';import {p,l,f as f$2}from'./chunk-5ZA4JYOP.js';import {d}from'./chunk-EWZZUQBR.js';import {a as a$2}from'./chunk-DOIZANFA.js';import {d as d$2,e as e$1}from'./chunk-ADL3CK44.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import {f,e,i,g as g$1,h}from'./chunk-5EPPPMAS.js';import m from'path';import v from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return f$2({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function me(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function ge(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function tt(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=f.verify,G=e.verify;function Ae(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ke(e){let t=await v.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f$1)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$3(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$3(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let o=s.transitiveImpact.reduce((u,d)=>Math.max(u,d.distance??0),0);s.summary.blastRadius.maxDistance!==o&&i.push("blastRadius.maxDistance does not match transitive impact distances");let k=l(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==k&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ee(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function We(e$1,t){if(e$1.id==="workspace.doctor")return m.join(t,e.doctor);if(e$1.id==="workspace.contract.verify")return m.join(t,e.contractVerify);if(e$1.id==="workspace.readiness")return m.join(t,e.readiness);if(e$1.id==="workspace.analyze")return m.join(t,".workspai","reports","analyze-last-run.json");if(e$1.id==="workspace.pipeline")return m.join(t,".workspai","reports","pipeline-last-run.json");if(e$1.id==="workspace.doctor-fix")return m.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e$1.id.startsWith("project.")&&e$1.id.includes("."))return m.join(t,".workspai","reports","workspace-run-last.json")}function C(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function je(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$4(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function xe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function Pe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===h.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s.length>0)return {status:"fail",message:`Doctor fix result reports ${s.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function Fe(e,t){let r=await d$2(e,i.doctorRemediationPlan);if(!r)return false;try{let s=C(await v.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let o=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!o||!t)return true;let k=Date.parse(o),u=Date.parse(t);return !Number.isFinite(k)||!Number.isFinite(u)?true:k>=u}catch{return false}}function $e(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=$e(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let o=i.stage;if(s&&o!==s)return {status:"missing",message:`Workspace run evidence is for stage "${o}", expected "${s}".`};let k=Array.isArray(i.projects)?i.projects:[],u=t.project?.toLowerCase();if(!u)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=k.find(g=>{let c=C(g);if(!c)return false;let n=typeof c.projectName=="string"?c.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(f=>c[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return n===u||a.some(f=>f.endsWith(`/${u}`)||f===u)});if(d){let g=R(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(g)return {status:"fail",message:g};let c=C(d),n=typeof c?.status=="string"?c.status:"unknown";return n==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:n==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:n==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${n} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function R(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function Be(e){if(e.id==="workspace.doctor")return g$1.doctor;if(e.id==="workspace.readiness")return g$1.readiness;if(e.id==="workspace.contract.verify")return g$1.contractVerify;if(e.id==="workspace.analyze")return g$1.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function _e(e,t,r,s){let i=We(e,t),o=i?m.relative(t,i).split(m.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=i?await d$2(t,o??""):null;if(!i||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:o,message:o?`Missing evidence report: ${o}`:"No evidence mapping exists for this command."};let u;try{u=await v.readJson(k);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=C(u);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:"Evidence report is not a JSON object."};let g=Be(e);if(g)try{a$3(d,g,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=R(d.generatedAt,s,"Doctor evidence");n?c={status:"fail",message:n}:c=je(d);}else if(e.id==="workspace.readiness"){let n=R(d.generatedAt,s,"Release readiness evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.contract.verify"){let n=R(d.generatedAt,s,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.analyze"){let n=R(d.generatedAt,s,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=R(d.generatedAt,s,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===h.doctorFixResult.schemaVersion?d:d.fixResult,a=C(n),f=typeof a?.generatedAt=="string"?a.generatedAt:void 0,y=R(f,s,"Doctor fix result");y?c={status:"fail",message:y}:await Fe(t,f)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=De(d,e,s);else {let n=R(d.generatedAt,s,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:o,message:c.message}}function Ne(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,o=e.filter(n=>n.status==="missing").length,k=e.filter(n=>n.status==="skipped").length,u=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,g="ready",c=0;return u.length>0||t.blockingReasons.length>0?(g="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(g="needs-attention",c=1),{verdict:g,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:o,stepsSkipped:k}}function He(e,t){let r=x(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),s=new Set(r.map(a=>a.toLowerCase())),i=x(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!s.has(a.toLowerCase()))),o=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let f=a.project.toLowerCase(),y=o.get(f)??[];y.push(a),o.set(f,y);}let k=[],u=[],d=[],g=[],c=false,n=(a,f)=>{let y=o.get(a.toLowerCase())??[];if(y.length===0){d.push(a);return}let P=y.filter(p=>p.status==="fail"),b=P.filter(p=>p.required),I=y.filter(p=>p.status==="missing"),E=I.filter(p=>p.required),V=y.some(p=>p.status==="pass"||p.status==="warn");if(b.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has failed verification evidence (${b.map(p=>p.id).join(", ")}).`);return}if(P.length>0){u.push(a),c=true;return}if(E.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has missing required verification evidence (${E.map(p=>p.id).join(", ")}).`);return}if(I.length>0){u.push(a),c=true;return}if(V){k.push(a);return}d.push(a);};for(let a of r)n(a,"directly-changed");for(let a of i)n(a,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:x(k),uncovered:x(u),unverifiable:x(d)},blockingReasons:g,needsAttention:c}}function x(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Me(e$1){let t=m.resolve(e$1.workspacePath);if(e$1.fromImpactPath){let o=Ae(t,e$1.fromImpactPath);return {impact:await ke(o),fromImpactRef:m.relative(t,o).split(m.sep).join("/"),impactFromDisk:true}}let r=m.join(t,g);if(await v.pathExists(r))return {impact:await ke(r),fromImpactRef:g,impactFromDisk:true};let s=m.join(t,d$3);if(await v.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e$1.scope,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await p({workspacePath:t,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now});return {impact:{schemaVersion:f$1,generatedAt:(e$1.now??new Date).toISOString(),fromRef:"baseline",diffRef:e.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:l(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:f.diff,generatedAt:(e$1.now??new Date).toISOString(),fromRef:"baseline",toRef:e.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Te(e,t){if(t)return e.generatedAt}async function bt(e){let t=m.resolve(e.workspacePath),{impact:r,fromImpactRef:s,impactFromDisk:i}=await Me(e),o$1=r.diff.currentModel,k=i?await p({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):o$1,u=[];if(i){let l=await p$1({workspacePath:t,fromPath:r.diff.fromRef,diff:r.diff,scope:e.scope,now:e.now}),W=[r.affectedProjects,r.transitiveImpact,r.verificationPlan],A=[l.affectedProjects,l.transitiveImpact,l.verificationPlan];JSON.stringify(W)!==JSON.stringify(A)&&u.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(k)!==r.diff.toHash&&u.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r.diff.git;if(i&&d$2?.available){let l=a(t,{ref:d$2.ref}),W=r.diff.changes.filter(h=>h.type.startsWith("git.")).map(h=>`${h.type}:${h.target.replace(/^git:/,"")}`).sort(),A=[...l.changedFiles.map(h=>`git.file.changed:${h}`),...l.untrackedFiles.map(h=>`git.untracked:${h}`),...l.deletedFiles.map(h=>`git.deleted:${h}`)].sort();(!l.available||l.commit!==d$2.commit||JSON.stringify(A)!==JSON.stringify(W))&&u.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let g=Te(r,i),c$1=Ee([...o(),...r.verificationPlan]).filter(l=>Se(e.scope,l)),n=[];for(let l of c$1)n.push(await _e(l,t,o$1.contracts.exists===true,g));let a$2=He(r,n),f=a$1(l(o$1)??{nodes:[],edges:[]}),y=b(o$1),P=await Ke(t),b$2=c(y,P?.freshness?.projectHashes),I={verdict:b$2.verdict,baseline:b$2.baseline,changed:b$2.changed,added:b$2.added,removed:b$2.removed,projectHashes:d$1(y)},E=b$1(f),V=o$1.policies?.mode??"warn",p$2=await Le(o$1,t),B=qe(V,p$2),S=Ne(n,{blockingReasons:[...a$2.blockingReasons,...E,...B.blockingReasons,...u],needsAttention:a$2.needsAttention||B.needsAttention}),he=n.filter(l=>l.status==="missing"&&l.evidencePath).map(l=>l.evidencePath),_=[...n.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),...a$2.blockingReasons,...E,...B.blockingReasons,...u],ve=p$2.filter(l=>l.severity==="error").length,be=o$1.summary?.projectCount??o$1.projects.length,U=ge({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(l=>l.trim()).filter(Boolean))).slice(0,12).map((l,W)=>{let A=n.find(h=>l.startsWith(`${h.id}:`));return me({reason:l,blockerId:`blocker-${W+1}`,sourceCommand:A?.command.display,sourceArtifact:A?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r.summary.changed,risk:r.summary.risk,affectedProjects:r.summary.affectedProjects,recommendedCommands:r.summary.recommendedCommands},summary:S,steps:n,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:a$2.subgraph,graphIntegrity:f,freshness:I,policyMode:V,policyViolations:p$2}}async function Le(e$1,t){let r=[];for(let i of e$1.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await d$2(t,e.contractVerify);try{if(s&&await v.pathExists(s)){let i=await v.readJson(s);if(Array.isArray(i.violations))for(let o of i.violations)typeof o=="string"&&o.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:o});}}catch{}return r.sort((i,o)=>i.source!==o.source?i.source.localeCompare(o.source):i.code!==o.code?i.code.localeCompare(o.code):i.message.localeCompare(o.message))}function qe(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function Ke(e){let t=m.join(e,G);try{if(!await v.pathExists(t))return null;let r=await v.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function wt(e,t){return e$1(t,G,a$2(e))}function ze(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Rt(e,t){return ze(e,t).exitCode}export{fe as a,tt as b,ye as c,G as d,He as e,bt as f,wt as g,ze as h,Rt as i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {h}from'./chunk-5EPPPMAS.js';var i=h.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="workspai.doctor-summary.v1";var m="doctor-graph-diagnosis.v1";export{i as a,n as b,a as c,m as d,g as e};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-D4RST2HE.js';import {b as b$1}from'./chunk-AO2ZI42U.js';import {a,e,b}from'./chunk-ADL3CK44.js';import {i,h}from'./chunk-5EPPPMAS.js';import w from'path';import {existsSync}from'fs';import Z from'fs-extra';var G=[{artifactKind:"bootstrap-compliance",cardId:"bootstrap",fileNames:["bootstrap-compliance.latest.json"]},{artifactKind:"doctor-workspace",cardId:"doctor",fileNames:["doctor-remediation-plan-last-run.json","doctor-last-run.json"]},{artifactKind:"analyze",cardId:"analyze",fileNames:["analyze-last-run.json"]},{artifactKind:"readiness",cardId:"readiness",fileNames:["release-readiness-last-run.json"]},{artifactKind:"pipeline",cardId:"pipeline",fileNames:["pipeline-last-run.json"]},{artifactKind:"workspace-run",cardId:"workspaceRun",fileNames:["workspace-run-last.json"]},{artifactKind:"workspace-verify",cardId:"workspaceVerify",fileNames:["workspace-verify-last-run.json"]}];function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function A(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0):[]}function I(e){return [...new Set(e.map(r=>r.trim()).filter(Boolean))]}function W(e){return (e.notes.includes("Doctor finding status: blocking")?16:0)+(e.transaction?8:0)+(e.operation?4:0)+(e.invocation?2:0)+(e.strategy?.length?1:0)}function Q(e){let r=W(e.incoming)>W(e.existing),o=structuredClone(r?e.incoming:e.existing),a=r?e.existing:e.incoming,t=a.sourceStepId;return o.order=e.existing.order,o.files=I([...o.files,...a.files]),o.notes=I([...o.notes,...a.notes.filter(i=>!i.startsWith("Source Doctor capability:")&&!i.startsWith("Doctor finding status:")),...t?[`Also satisfies Doctor capability: ${t}`]:[]]),o}function S(e,r,o){return o?r:w.relative(e,r).split(w.sep).join("/")}function X(e){let r=e?.trim()||"npx workspai bootstrap";if(!/(?:^|\s)--ci(?:\s|$)/.test(r)&&/(?:^|\s)--json(?:\s|$)/.test(r))return r.replace(/(?:^|\s)--json(?:\s|$)/,a=>{let t=a.startsWith(" ")?" ":"",i=a.endsWith(" ")?" ":"";return `${t}--ci --json${i}`}).trim();let o=/(?:^|\s)--ci(?:\s|$)/.test(r)?r:`${r} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(o)?o:`${o} --json`}function Y(e){return `${JSON.stringify({schemaVersion:h.compatibilityMatrix.schemaVersion,generatedAt:e,source:"workspai workspace remediation-plan",runtimes:{},notes:["Minimal enterprise baseline. Add runtime and toolchain entries as governance matures."]},null,2)}
|
|
2
|
+
`}function ee(e){return `${JSON.stringify({schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:e,note:"Minimal enterprise baseline. Set enabled: true and add artifact entries to activate mirroring."},null,2)}
|
|
3
|
+
`}function te(e){let r=e.payload,o=A(r.blockers),a=A(r.blockingReasons),t=A(r.failures),i=A(r.reasons),d=A(r.policyViolations),s=g(r.summary),m=A(s?.blockers);if(e.artifactKind==="analyze"){let c=(Array.isArray(r.findings)?r.findings:[]).map(y=>g(y)).filter(y=>!!y).map(y=>String(y.message??y.title??y.id??"").trim()).filter(Boolean);return I([...o,...c,...a])}if(e.artifactKind==="workspace-run"){let b=g(r.stages),c=Object.entries(b??{}).flatMap(([y,f])=>{let n=g(f);return (Array.isArray(n?.projects)?n.projects:[]).map(l=>g(l)).filter(l=>!!l).filter(l=>l.status==="failed"||l.ok===false).map(l=>`${y}: ${String(l.project??l.name??"project")} failed`)});return I([...o,...c,...a])}return I([...o,...a,...t,...i,...d,...m])}function R(e){let r=e.findingId?.trim()||e.sourceStepId?.trim()||e.id,o=e.findingStatus??"blocking",a=e.causalKey?.trim()||[e.cardId,e.projectName??e.scope??"workspace",r].map(t=>String(t).trim().toLowerCase()).join(":");return {id:e.id,artifactKind:e.artifactKind,cardId:e.cardId,title:e.title,order:e.order,phase:e.phase,scope:e.scope??"workspace",...e.projectName?{projectName:e.projectName}:{},...e.projectPath?{projectPath:e.projectPath}:{},...e.sourceStepId?{sourceStepId:e.sourceStepId}:{},findingId:r,findingStatus:o,causalKey:a,...e.dependsOn?{dependsOn:e.dependsOn}:{},...e.strategy?{strategy:structuredClone(e.strategy)}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},status:e.status??"ready",mode:e.mode,risk:e.risk,requiresApproval:true,blocker:e.blocker,summary:e.summary,...e.command?{command:e.command}:{},...e.invocation?{invocation:structuredClone(e.invocation)}:{},verifyCommand:e.verifyCommand,cwd:e.cwd??"workspace",files:e.files??[],...e.operation?{operation:e.operation}:{},rollback:e.rollback??(e.operation?{available:true,strategy:"idempotent"}:{available:false,strategy:"none"}),notes:e.notes??[]}}function re(e){return (Array.isArray(e.report.payload.steps)?e.report.payload.steps:[]).flatMap((o,a)=>{let t=g(o),i=typeof t?.id=="string"?t.id.trim():"",d=typeof t?.projectName=="string"?t.projectName.trim():"",s=typeof t?.projectPath=="string"?t.projectPath.trim():"",m=typeof t?.originalCommand=="string"?t.originalCommand.trim():"";if(!t||!i||!d||!s)return [];let b=g(t.studioStatus),c=b?.state==="ready"||b?.state==="review-required"||b?.state==="blocked"||b?.state==="guidance-only"?b.state:"guidance-only",y=t.risk==="safe"||t.risk==="guarded"||t.risk==="invasive"?t.risk:"guarded",f=g(t.preview),n=S(e.workspacePath,s,e.includeAbsolutePaths),u=z({capability:{...t,command:m},absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),l=q({capability:t,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),v=E({operation:t.operation,absoluteProjectPath:s}),k=t.findingStatus==="blocking"||t.findingStatus==="advisory"||t.findingStatus==="informational"?t.findingStatus:"unknown",p=typeof t.diagnosisFindingId=="string"&&t.diagnosisFindingId.trim()?t.diagnosisFindingId.trim():typeof t.issueId=="string"&&t.issueId.trim()?t.issueId.trim():i,h=typeof t.causalKey=="string"&&t.causalKey.trim()?t.causalKey.trim():void 0,C=t.executableInCurrentEnvironment===true&&!!u,$=J({strategy:t.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),j=g(t.transaction),x=j?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(j):void 0;return x&&(x.projectPath=n),[R({id:`doctor.${i}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof f?.title=="string"&&f.title.trim()?f.title.trim():`Repair ${d}`,order:e.startOrder+a,phase:typeof t.phase=="string"?t.phase:"doctor-remediation",blocker:typeof f?.summary=="string"&&f.summary.trim()?f.summary.trim():`Doctor remediation is pending for ${d}.`,summary:typeof f?.summary=="string"&&f.summary.trim()?f.summary.trim():`Execute the CLI-authored Doctor step for ${d}.`,mode:C?"run-command":"manual-guidance",risk:y,status:c,...C&&u?{command:u}:{},...C&&l?{invocation:l}:{},...v?{operation:v}:{},verifyCommand:typeof t.verifyCommand=="string"&&t.verifyCommand.trim()?t.verifyCommand.trim():"npx workspai doctor project --json",files:A(t.files).map(P=>{let O=w.isAbsolute(P)?P:w.resolve(s,P);return S(e.workspacePath,O,e.includeAbsolutePaths)}),notes:[`Source Doctor step: ${i}`,`Doctor finding id: ${p}`,`Doctor finding status: ${k}`,...typeof b?.reason=="string"?[b.reason]:[]],scope:"project",projectName:d,projectPath:n,sourceStepId:i,findingId:p,findingStatus:k,causalKey:h,dependsOn:A(t.dependsOn).map(P=>`doctor.${P}`),strategy:$,transaction:x,cwd:"project",...g(t.rollback)?.available===true?{rollback:{available:true,strategy:"manual"}}:{}})]})}function z(e){let r=typeof e.capability.command=="string"?e.capability.command.trim():"";if(e.includeAbsolutePaths&&r)return r;let o=E({operation:e.capability.operation,absoluteProjectPath:e.absoluteProjectPath});if(o)return b$1(o);let a=g(e.capability.invocation),t=typeof a?.executable=="string"?a.executable.trim():"",i=A(a?.args);if(t)return [t,...i].map(s=>/^[a-zA-Z0-9_./:@=+-]+$/.test(s)?s:JSON.stringify(s)).join(" ");if(!r)return;let d=e.absoluteProjectPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return r.replace(new RegExp(`^cd\\s+["']?${d}["']?\\s*&&\\s*`,"i"),"").replaceAll(e.absoluteProjectPath,".")}function q(e){let r=g(e.capability.invocation),o=typeof r?.executable=="string"?r.executable.trim():"",a=A(r?.args);if(!(!o||a.length!==(Array.isArray(r?.args)?r.args.length:0)))return {cwd:e.includeAbsolutePaths?e.absoluteProjectPath:".",executable:o,args:a}}function E(e){let r=g(e.operation);if(!r||typeof r.type!="string")return;let o=structuredClone(r);for(let a of ["path","sourcePath"]){let t=o[a];if(typeof t!="string")continue;let i=w.isAbsolute(t)?w.relative(e.absoluteProjectPath,t):t;if(!i||i===".."||i.startsWith(`..${w.sep}`)||w.isAbsolute(i))return;o[a]=i.split(w.sep).join("/");}return o}function J(e){if(!Array.isArray(e.strategy))return;let r=structuredClone(e.strategy);if(!e.includeAbsolutePaths)for(let o of r)o.invocation&&(o.invocation.cwd=".");return r}function oe(e){let r=Array.isArray(e.report.payload.projects)?e.report.payload.projects:e.report.payload.project?[e.report.payload.project]:[],o=new Set,a=[];for(let t of r){let i=g(t);if(!i)continue;let d=typeof i.name=="string"?i.name.trim():"",s=typeof i.path=="string"?i.path.trim():"";if(!d||!s)continue;let m=Array.isArray(i.repairCapabilities)?i.repairCapabilities:Array.isArray(i.probes)?i.probes.map(f=>g(f)?.repairCapability).filter(f=>f!==void 0):[],b=new Map,c=new Map,y=g(i.diagnosis);for(let f of Array.isArray(y?.findings)?y.findings:[]){let n=g(f),u=g(n?.repair),l=typeof u?.capabilityId=="string"?u.capabilityId.trim():"",v=typeof n?.id=="string"?n.id.trim():"",k=typeof n?.causalKey=="string"?n.causalKey.trim():"",p=n?.status==="blocking"||n?.status==="advisory"||n?.status==="informational"||n?.status==="unknown"?n.status:"unknown";l&&v&&k&&c.set(l,{findingId:v,causalKey:k,findingStatus:p});}for(let f of Array.isArray(i.probes)?i.probes:[]){let n=g(f),u=g(n?.repairCapability),l=typeof u?.id=="string"?u.id.trim():"";l&&b.set(l,n?.status==="fail"?"blocking":"advisory");}for(let f of m){let n=g(f),u=typeof n?.id=="string"?n.id.trim():"";if(!n||!u)continue;let l=`${d}:${u}`;if(o.has(l))continue;o.add(l);let v=n.risk==="safe"||n.risk==="guarded"||n.risk==="invasive"?n.risk:"guarded",k=z({capability:n,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),p=q({capability:n,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),h=E({operation:n.operation,absoluteProjectPath:s}),C=n.status==="available"&&!!k,$=g(n.transaction),j=$?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone($):void 0,x=c.get(u),P=x?.findingStatus??b.get(u)??(j?"blocking":"advisory");j&&(j.projectPath=S(e.workspacePath,s,e.includeAbsolutePaths));let O=J({strategy:n.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),U=A(n.files).map(K=>S(e.workspacePath,K,e.includeAbsolutePaths)),T=R({id:`doctor.${d}.${u}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof n.title=="string"&&n.title.trim()?n.title.trim():`Repair ${d}`,order:e.startOrder+a.length,phase:j?"dependency-remediation":"doctor-remediation",blocker:typeof n.reason=="string"&&n.reason.trim()?n.reason.trim():`Doctor remediation is pending for ${d}.`,summary:typeof n.reason=="string"&&n.reason.trim()?n.reason.trim():`Execute the Doctor-authored repair capability for ${d}.`,mode:C?n.canEditFiles===true?"edit-file":"run-command":"manual-guidance",risk:v,status:C?"ready":n.status==="manual"?"guidance-only":"blocked",...k?{command:k}:{},...p?{invocation:p}:{},verifyCommand:typeof n.verifyCommand=="string"&&n.verifyCommand.trim()?n.verifyCommand.trim():"npx workspai doctor project --json",files:U,notes:[`Source Doctor capability: ${u}`,`Doctor finding status: ${P}`,...A(n.limitations)],scope:"project",projectName:d,projectPath:S(e.workspacePath,s,e.includeAbsolutePaths),sourceStepId:u,findingId:x?.findingId??(typeof n.issueId=="string"&&n.issueId.trim()?n.issueId.trim():u),findingStatus:P,causalKey:x?.causalKey,strategy:O,transaction:j,cwd:"project",...h?{operation:h,rollback:{available:true,strategy:"manual"}}:{}}),M=k?a.findIndex(K=>K.projectName===d&&K.command===k&&K.cwd==="project"):-1;if(M>=0){a[M]=Q({existing:a[M],incoming:T});continue}a.push(T);}}return a}function ie(e){let r=[],o=X("npx workspai bootstrap --json");for(let a of e.blockers)a.includes("profile.enterprise.ci")&&r.push(R({id:"bootstrap.enterprise-ci",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Run bootstrap in deterministic CI mode",order:10,phase:"bootstrap-preflight",blocker:a,summary:"Enterprise bootstrap compliance requires --ci for deterministic execution.",mode:"run-command",risk:"safe",command:o,verifyCommand:o})),a.includes("profile.enterprise.compatibility-matrix")&&r.push(R({id:"bootstrap.compatibility-matrix",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise compatibility matrix baseline",order:20,phase:"bootstrap-config",blocker:a,summary:"Create the missing compatibility matrix baseline without overwriting user data.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[i.compatibilityMatrix],operation:{type:"file-create",path:i.compatibilityMatrix,content:Y(e.generatedAt),overwrite:false}})),a.includes("profile.enterprise.mirror-config")&&r.push(R({id:"bootstrap.mirror-config",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise mirror config baseline",order:30,phase:"bootstrap-config",blocker:a,summary:"Create the missing mirror configuration baseline without enabling mirroring.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[".workspai/mirror-config.json"],operation:{type:"file-create",path:".workspai/mirror-config.json",content:ee(e.generatedAt),overwrite:false}}));return r}function ae(e){let r=Array.isArray(e.report.payload.steps)?e.report.payload.steps:[],o=[],a=new Map;for(let t of r){let i=g(t),d=g(i?.command),s=typeof i?.id=="string"?i.id.trim():"",m=typeof i?.project=="string"?i.project.trim():"",b=typeof i?.status=="string"?i.status:"",c=typeof d?.display=="string"?d.display.trim():"",y=i?.required===true;if(!s.startsWith("project.")||!m||!y||b!=="fail"&&b!=="missing"||!/^npx\s+workspai\s+workspace\s+run\s+/i.test(c))continue;let f=s.split(".").at(-1)??"stage",n=`workspaceVerify.${s}`,u=a.get(m),l=/(?:^|\s)--no-gates(?:\s|$)/.test(c)?c:`${c} --no-gates`;o.push(R({id:n,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof i.label=="string"&&i.label.trim()?i.label.trim():`Run ${f} for ${m}`,order:e.startOrder+o.length,phase:"fleet-run",blocker:typeof i.message=="string"&&i.message.trim()?i.message.trim():`${f} evidence is not current for ${m}.`,summary:`Produce fresh ${f} evidence for ${m} without re-entering the blocked aggregate gates.`,mode:"run-command",risk:f==="start"?"guarded":"safe",status:"ready",command:l,verifyCommand:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",scope:"project",projectName:m,projectPath:m,sourceStepId:s,...u?{dependsOn:[u]}:{},cwd:"workspace",notes:[`Source Workspace Verify step: ${s}`,"Aggregate verification must run only after this project evidence producer completes."]})),a.set(m,n);}return o}function ne(e){let r=I(e.blockers.flatMap(a=>{let t=a.match(/(?:project runtimes?|workspace)\s*\(([^)]+)\)\s+(?:is|are) not pinned/i);return t?.[1]?t[1].split(",").map(i=>i.trim().toLowerCase()).filter(i=>/^(python|node|go|java|dotnet|rust|php)$/.test(i)):[]})),o=[];for(let a of r){let t=`readiness.toolchain.${a}.setup`,i=e.blockers.find(d=>d.toLowerCase().includes(`(${a})`))??`The ${a} runtime is not pinned in the canonical workspace toolchain.`;o.push(R({id:t,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Pin ${a} in the workspace toolchain`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:i,summary:`Detect and persist the current ${a} runtime in the canonical workspace toolchain lock.`,mode:"run-command",risk:"safe",command:`npx workspai setup ${a} --json`,verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Run from the workspace root so the canonical toolchain.lock is updated."]})),o.push(R({id:`readiness.toolchain.${a}.bootstrap`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Reconcile the ${a} workspace foundation`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:`The ${a} runtime pin must be reconciled with the workspace foundation.`,summary:"Refresh the workspace foundation after the runtime pin is written.",mode:"run-command",risk:"guarded",command:"npx workspai bootstrap --ci --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:[t]}));}return o}function se(e){if(e.report.artifactKind==="readiness"&&/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(e.blocker))return R({id:`${e.report.cardId}.doctor-owner.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:"Resolve dependency vulnerability through Doctor",order:e.order,phase:"dependency-remediation",blocker:e.blocker,summary:"Release Readiness is the aggregate gate; use the project-scoped Doctor remediation capability that owns this dependency failure.",mode:"verify-before-fix",risk:"guarded",status:"review-required",command:"npx workspai doctor workspace --plan --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Read doctor-remediation-plan-last-run.json and execute the matching surface-security-hygiene capability before rerunning Readiness.","Do not treat a Readiness refresh as remediation for a source dependency vulnerability."]});let o={analyze:{title:"Refresh analyze evidence",phase:"analysis",command:"npx workspai analyze --strict --json",verify:"npx workspai analyze --strict --json"},readiness:{title:"Refresh release readiness",phase:"release-readiness",command:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",verify:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json"},pipeline:{title:"Rerun governance pipeline",phase:"governance-pipeline",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"},"workspace-run":{title:"Rerun failed workspace stage",phase:"fleet-run",command:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json",verify:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json"},"workspace-verify":{title:"Refresh workspace verify gate",phase:"verification",command:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",verify:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json"},"doctor-workspace":{title:"Use Doctor remediation plan",phase:"doctor-remediation",command:"npx workspai doctor workspace --plan --json",verify:"npx workspai doctor workspace --json"}}[e.report.artifactKind]??{title:"Refresh artifact evidence",phase:"evidence-refresh",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"};return R({id:`${e.report.cardId}.refresh.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:o.title,order:e.order,phase:o.phase,blocker:e.blocker,summary:"No deterministic file operation is available for this artifact yet; refresh the evidence and continue with the card-specific plan.",mode:e.report.artifactKind==="doctor-workspace"?"verify-before-fix":"run-command",risk:"guarded",status:e.report.artifactKind==="doctor-workspace"?"review-required":"ready",command:o.command,verifyCommand:o.verify,notes:e.report.artifactKind==="doctor-workspace"?["Read doctor-remediation-plan-last-run.json for ordered file-level steps."]:[]})}async function ce(e){let r=[a(e,".workspai/reports"),b(e,".workspai/reports")],o=[],a$1=new Set;for(let t of G)for(let i of t.fileNames){let d=(await Promise.all(r.map(s=>w.join(s,i)))).find(s=>existsSync(s));if(!(!d||a$1.has(`${t.artifactKind}:${i}`))){a$1.add(`${t.artifactKind}:${i}`);try{let s=await Z.readJSON(d),m=g(s);if(!m)continue;o.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:i,absolutePath:d,payload:m});break}catch{o.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:i,absolutePath:d,payload:{blockers:[`${t.artifactKind}: report exists but could not be parsed.`]}});break}}}return o}async function ke(e){let r=w.resolve(e.workspacePath),o=e.includeAbsolutePaths===true,a$2=e.ciMode===true,t=new Date().toISOString(),i=a(r,".workspai/reports"),d=await ce(r),s=[],m=1;for(let c of d){if(c.artifactKind==="doctor-workspace"){let p=Array.isArray(c.payload.steps)?re({report:c,workspacePath:r,includeAbsolutePaths:o,startOrder:m}):oe({report:c,workspacePath:r,includeAbsolutePaths:o,startOrder:m});s.push(...p),m+=p.length;continue}let y=te(c);if(y.length===0)continue;if(c.artifactKind==="bootstrap-compliance"){s.push(...ie({blockers:y,generatedAt:t})),m=s.length+1;continue}if(c.artifactKind==="workspace-verify"){let p=ae({report:c,startOrder:m,ciMode:a$2});if(p.length>0){s.push(...p),m+=p.length;continue}}if(c.artifactKind==="readiness"){let p=ne({report:c,blockers:y,startOrder:m,ciMode:a$2});if(p.length>0){s.push(...p),m+=p.length;continue}}let f=s.some(p=>p.transaction?.kind==="dependency-security"),n=c.artifactKind==="readiness"&&y.some(p=>/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(p));if(f&&n)continue;let u=y[0],l=se({report:c,blocker:u,order:m,ciMode:a$2}),k={readiness:new Set(["bootstrap","doctor"]),pipeline:new Set(["bootstrap","doctor","analyze","readiness"]),workspaceVerify:new Set(["bootstrap","doctor","readiness","workspaceRun"])}[c.cardId];if(c.cardId==="pipeline"){let p=["doctor","analyze","readiness"].find(h=>u.toLowerCase().includes(h));p&&(k=new Set([p]));}if(k){let p=s.filter(h=>k.has(h.cardId)&&h.risk!=="invasive"&&h.status!=="blocked"&&h.status!=="guidance-only").map(h=>h.id);p.length>0&&(l.dependsOn=I([...l.dependsOn??[],...p]),l.notes.push("This aggregate gate must run after its contract-owned upstream remediation actions."));}y.length>1&&l.notes.push(...y.slice(1,8).map(p=>`Related blocker: ${p}`)),s.push(l),m+=1;}let b={safe:s.filter(c=>c.risk==="safe").length,guarded:s.filter(c=>c.risk==="guarded").length,invasive:s.filter(c=>c.risk==="invasive").length};return {schemaVersion:a$1,generatedAt:t,workspace:{name:w.basename(r),...o?{path:r}:{}},source:{command:"workspace remediation-plan",reportsDir:S(r,i,o),includeAbsolutePaths:o,ciMode:a$2},summary:{artifactsScanned:d.length,cardsCovered:I(s.map(c=>c.cardId)).length,totalActions:s.length,executableActions:s.filter(c=>c.status==="ready").length,risk:b},actions:s}}async function he(e$1,r){return e(r,i.artifactRemediationPlan,e$1)}export{ke as a,he as b};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import {f as f$1,e as e$1}from'./chunk-T3GJ7YVG.js';import {a,b}from'./chunk-W5ZFXKSL.js';import {a as a$1}from'./chunk-27UR373Z.js';import {a as a$2}from'./chunk-T5YRFRJV.js';import {h,j as j$1}from'./chunk-ZCPT6KC3.js';import {e as e$2}from'./chunk-ADL3CK44.js';import {e,f}from'./chunk-5EPPPMAS.js';import {j,s,t}from'./chunk-MOSXTVPU.js';import w from'fs';import c from'path';import i from'chalk';var L=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function D(e){try{return await w.promises.access(e,w.constants.F_OK),true}catch{return false}}async function z(e){try{let t=JSON.parse(await w.promises.readFile(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function K(e){try{return await w.promises.readFile(e,"utf-8")}catch{return ""}}function B(e){return a(e)}async function U(e,t$1){return await M([...t(e,"project.json"),...t(e,"context.json")])?true:b(e)?false:c.resolve(e)===c.resolve(t$1)?h(e).length>0:h(e).length>0}async function V(e){let t=await a$1(e,{skipDirs:L,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:U}),r=(await a$2(e)).filter(o=>o.relationship==="adopted"||o.source==="adopted-local").map(o=>c.resolve(o.path)).filter(o=>w.existsSync(o)),s=[...new Set([...t.map(o=>c.resolve(o)),...r])];return s.length>0?s:b(e)?[]:h(e).length>0?[e]:[]}function q(e,t){return c.relative(e,t).replace(/\\/g,"/")||"."}async function A(e,t){for(let n of t)if(await D(c.join(e,n)))return true;return false}async function M(e){for(let t of e)if(await D(t))return true;return false}async function Q(e){if(await A(e,[".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml"]))return true;try{return (await w.promises.readdir(c.join(e,".github","workflows"),{withFileTypes:true})).some(n=>n.isFile()&&/\.(?:ya?ml)$/i.test(n.name)&&!n.name.startsWith("."))}catch{return false}}async function O(e){for(let t of e){let n=await z(t);if(n)return n}return null}async function X(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 Y(e){if(await A(e,["tests","test","__tests__","src/__tests__","pytest.ini","vitest.config.ts","jest.config.ts"]))return true;let n=await z(c.join(e,"package.json")),r=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return typeof r.test=="string"&&r.test.trim().length>0}async function Z(e){let t=await z(c.join(e,"package.json")),n=t?.scripts&&typeof t.scripts=="object"?t.scripts:{};return Object.keys(n).sort()}function g(e,t,n,r,s,o){return {id:e,severity:t,target:n,title:r,detail:s,remediation:o}}function ee(e){let t=e.reduce((n,r)=>r.severity==="fail"?n+28:r.severity==="warn"?n+12:n+3,0);return Math.max(0,100-t)}async function ne(e,t$1){let n=await O(t(t$1,"project.json")),r=j$1(t$1,n),s=h(t$1),o=r.runtime==="unknown"?s[0]||"unknown":r.runtime,a=q(e,t$1),p=a,u=await Z(t$1),f=await M([...t(t$1,"project.json"),...t(t$1,"context.json")]),l=await Y(t$1),h$1=await A(t$1,["Dockerfile","dockerfile"]),k=await A(t$1,[".env.example","env.example","config/env.example"]),P=await Q(t$1),C=await X(t$1),m=[];return r.key==="unknown"&&m.push(g("project.stack.unknown","fail",p,"Project stack is unknown","Workspai cannot confidently classify this backend project.","Add .workspai/project.json metadata or import the project with `workspai import`.")),f||m.push(g("project.marker.missing","warn",p,"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.")),l||m.push(g("project.tests.missing","warn",p,"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(g("project.env.example.missing","info",p,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.")),P||m.push(g("project.ci.missing","warn",p,"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(g("project.health.missing","info",p,"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(g("project.container.missing","info",p,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.")),{name:typeof n?.name=="string"&&n.name.trim()?n.name.trim():c.basename(t$1),path:t$1,relativePath:a,runtime:o,framework:r.key,confidence:r.confidence,supportTier:r.supportTier,hasRapidKitMarker:f,hasTests:l,hasDockerfile:h$1,hasEnvExample:k,hasCiConfig:P,hasHealthEndpoint:C,scripts:u,findings:m,score:ee(m)}}function te(e){return e.name.toLowerCase()}async function re(e){let t=new Map(e.map(s=>[te(s),s])),n=[];for(let s of e){let o=await z(c.join(s.path,"package.json")),a={...o?.dependencies??{},...o?.devDependencies??{},...o?.peerDependencies??{}};for(let u of Object.keys(a)){let f=u.replace(/^@[^/]+\//,"").toLowerCase(),l=t.get(f);l&&l.relativePath!==s.relativePath&&n.push({from:s.relativePath,to:l.relativePath,kind:"package"});}let p=await K(c.join(s.path,"pyproject.toml"));for(let u of e)u.relativePath!==s.relativePath&&p.includes(u.name)&&n.push({from:s.relativePath,to:u.relativePath,kind:"workspace-reference"});}let r=new Set;return n.filter(s=>{let o=`${s.from}\0${s.to}\0${s.kind}`;return r.has(o)?false:(r.add(o),true)})}function se(e,t){let n=new Map;for(let r of e)n.set(r.relativePath,{project:r.relativePath,directDependents:0,directDependencies:0});for(let r of t){let s=n.get(r.from),o=n.get(r.to);s&&(s.directDependencies+=1),o&&(o.directDependents+=1);}return Array.from(n.values()).sort((r,s)=>s.directDependents-r.directDependents||s.directDependencies-r.directDependencies)}async function oe(e){let t=await O(s(e,"workspace.json"));return typeof t?.profile=="string"?t.profile:null}function ie(e){return {fail:e.filter(t=>t.severity==="fail").length,warn:e.filter(t=>t.severity==="warn").length,info:e.filter(t=>t.severity==="info").length}}function ae(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 t=[];return e.findings.some(n=>n.id==="workspace.marker.missing")&&t.push("Initialize workspace metadata with `workspai bootstrap --profile polyglot`."),e.findings.some(n=>n.id==="project.marker.missing")&&t.push("Register detected projects with `workspai import <path>` or recreate them via `workspai create project`."),e.findings.some(n=>n.id==="project.tests.missing")&&t.push("Add test entrypoints, then gate changes with `workspai workspace run test --affected --strict`."),e.findings.some(n=>n.id==="project.ci.missing")&&t.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(n=>n.id==="project.health.missing")&&t.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasGraph||t.push("Create `.workspai/workspace-dependency-graph.json` or use analyze output as the first graph seed."),t.push("Run `workspai autopilot release --mode audit --json` before release."),Array.from(new Set(t))}async function ve(e$3={}){let t=c.resolve(e$3.workspacePath||process.cwd());if(!await D(t))throw new Error(`Workspace path does not exist: ${t}`);let n=B(t)??t,r=j(n),s=await oe(n),o=await V(n),a=await Promise.all(o.map(d=>ne(n,d))),p=await re(a),u=se(a,p),f$2=[];r||f$2.push(g("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.")),a.length===0&&f$2.push(g("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 l=[...f$2,...a.flatMap(d=>d.findings)],h=ie(l),k={};for(let d of a)k[d.runtime]=(k[d.runtime]||0)+1;let P=a.length>0?Math.round(a.reduce((d,y)=>d+y.score,0)/a.length):0,C=f$2.reduce((d,y)=>d+(y.severity==="fail"?20:y.severity==="warn"?8:2),0),m=Math.max(0,P-C),J=a.length===0&&h.fail===0&&l.length>0&&l.every(d=>d.id==="workspace.projects.missing"&&d.severity==="warn"),H=h.fail>0||e$3.strict&&h.warn>0&&!J?"blocked":h.warn>0?"needs-attention":"ready",j$1={schemaVersion:f.analyze,generatedAt:new Date().toISOString(),workspacePath:n,workspaceDetected:r,profile:s,summary:{score:m,verdict:H,projectCount:a.length,runtimeCount:Object.keys(k).length,findings:h},runtimes:k,projects:a,dependencyGraph:{status:p.length>0?"generated":"empty",edges:p,topImpactedProjects:u.slice(0,5)},findings:l,nextActions:ae({findings:l,projectCount:a.length,hasGraph:p.length>0,workspaceDetected:r}),enterpriseControls:{jsonReady:true,ciGateCommand:"workspai analyze --json --strict",releaseGateCommand:"workspai autopilot release --mode enforce --json",evidencePath:e.analyze}};if(e$3.output&&(await w.promises.mkdir(c.dirname(c.resolve(e$3.output)),{recursive:true}),await w.promises.writeFile(c.resolve(e$3.output),`${JSON.stringify(j$1,null,2)}
|
|
2
|
+
`)),!e$3.output&&r){let d=f$1(j$1,{commandId:"workspaceAnalyze",exitCode:j$1.summary.verdict==="blocked"?2:j$1.summary.verdict==="needs-attention"?1:0,generatedAt:j$1.generatedAt,blockers:j$1.findings.filter(y=>y.severity==="fail").map(y=>y.title).slice(0,12),runId:e$1()});await e$2(n,e.analyze,d);}return j$1}function be(e){let t=e.summary.verdict==="ready"?i.green:e.summary.verdict==="needs-attention"?i.yellow:i.red;if(console.log(i.bold(`
|
|
3
|
+
Workspai Workspace Analysis
|
|
4
|
+
`)),console.log(i.cyan("Workspace:"),e.workspacePath),console.log(i.cyan("Profile:"),e.profile||"not configured"),console.log(i.cyan("Score:"),`${e.summary.score}/100`),console.log(i.cyan("Verdict:"),t(e.summary.verdict)),console.log(i.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(i.bold(`
|
|
5
|
+
Projects`));for(let n of e.projects){let r=n.score>=85?i.green("pass"):n.score>=65?i.yellow("watch"):i.red("risk");console.log(` ${n.relativePath} ${i.gray(`${n.runtime}/${n.framework}`)} ${r} ${n.score}/100`);}}if(e.dependencyGraph.status==="generated"&&(console.log(i.bold(`
|
|
6
|
+
Dependency Graph`)),console.log(i.gray(` edges: ${e.dependencyGraph.edges.length}`)),e.dependencyGraph.topImpactedProjects.length>0)){console.log(i.gray(" Top impacted projects:"));for(let n of e.dependencyGraph.topImpactedProjects.slice(0,3))console.log(` ${n.project} (${n.directDependents} dependents, ${n.directDependencies} dependencies)`);}if(e.findings.length>0){console.log(i.bold(`
|
|
7
|
+
Top Findings`));for(let n of e.findings.slice(0,8)){let r=n.severity==="fail"?i.red:n.severity==="warn"?i.yellow:i.gray;console.log(` ${r(n.severity.toUpperCase())} ${n.target}: ${n.title}`),console.log(i.gray(` ${n.remediation}`));}}console.log(i.bold(`
|
|
8
|
+
Next Actions`));for(let n of e.nextActions.slice(0,5))console.log(i.gray(` - ${n}`));console.log();}export{ve as a,be as b};
|