workspai 0.56.0 → 0.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -8
- package/contracts/adopt-effects.v1.json +72 -0
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +4 -0
- package/contracts/doctor-project-evidence.v1.json +27 -0
- package/contracts/doctor-workspace-evidence.v1.json +29 -0
- package/contracts/extension-cli-compatibility.v1.json +1 -0
- package/contracts/published-contract-catalog.v1.json +5 -0
- package/contracts/workspace-intelligence/doctor-summary.v1.json +3 -1
- package/dist/autopilot-release-WIFFFQKW.js +1 -0
- package/dist/capabilities-command-44JVOE5S.js +1 -0
- package/dist/{chunk-XH7PDHBF.js → chunk-6OFGLNFS.js} +1 -1
- package/dist/{chunk-QTCZPS5I.js → chunk-75HOCFNH.js} +1 -1
- package/dist/{chunk-5RL254O2.js → chunk-7WUT5ZSO.js} +1 -1
- package/dist/{chunk-KR7CIEQR.js → chunk-AA4PNQKR.js} +1 -1
- package/dist/chunk-CNWUIXF3.js +1 -0
- package/dist/{chunk-6HCAGHCY.js → chunk-DF4NWPB7.js} +1 -1
- package/dist/chunk-DT4X7I5M.js +81 -0
- package/dist/chunk-GDKFN3CM.js +8 -0
- package/dist/{chunk-WLCBXCZV.js → chunk-GTJY55QK.js} +1 -1
- package/dist/{chunk-5ZA4JYOP.js → chunk-GXTCU4WF.js} +1 -1
- package/dist/{chunk-SV2SP22H.js → chunk-IUYZ3NHS.js} +3 -3
- package/dist/{chunk-KS4FB5W7.js → chunk-IXOLHPTN.js} +1 -1
- package/dist/{chunk-2L4PSZQB.js → chunk-L36ZASME.js} +1 -1
- package/dist/{chunk-7PNARN6S.js → chunk-N2BIIUDH.js} +1 -1
- package/dist/{chunk-QFCKHUEP.js → chunk-P475BOJW.js} +1 -1
- package/dist/{chunk-5BGPGNRQ.js → chunk-QHY6F4SS.js} +1 -1
- package/dist/chunk-QK5QOXOE.js +13 -0
- package/dist/{chunk-QAF26ZQX.js → chunk-RPHM7LQW.js} +1 -1
- package/dist/chunk-SNO3WG4V.js +2 -0
- package/dist/chunk-TTFQWH55.js +91 -0
- package/dist/{chunk-HASVV34S.js → chunk-VL3APTVB.js} +1 -1
- package/dist/{chunk-WOTTSPSF.js → chunk-VUR7H2FU.js} +1 -1
- package/dist/chunk-VZPWIILU.js +1 -0
- package/dist/chunk-WP3CXMVA.js +2 -0
- package/dist/{chunk-ESWFBSYM.js → chunk-Z57G62KE.js} +1 -1
- package/dist/{create-DLUWG46F.js → create-O2KLTN5H.js} +1 -1
- package/dist/{doctor-IZ4YOCYE.js → doctor-AL5YWO5X.js} +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +166 -164
- package/dist/{pipeline-IBQYDLFF.js → pipeline-4ST4BQWY.js} +1 -1
- package/dist/{project-intelligence-lens-SIU7IXKG.js → project-intelligence-lens-JHYECYOK.js} +1 -1
- package/dist/{verified-goal-M4GPOXNL.js → verified-goal-KFNRGOKT.js} +1 -1
- package/dist/{workspace-3AAOUELG.js → workspace-O4E5CCGK.js} +1 -1
- package/dist/{workspace-agent-sync-QGYLY7HH.js → workspace-agent-sync-N5DPGU2E.js} +1 -1
- package/dist/{workspace-context-JCLPRYNC.js → workspace-context-ETZNEHOJ.js} +1 -1
- package/dist/{workspace-contract-IUUPBQXU.js → workspace-contract-OSI7NBXS.js} +1 -1
- package/dist/{workspace-explain-CZGBVDE6.js → workspace-explain-EM7IUV6L.js} +1 -1
- package/dist/{workspace-foundation-7IGMO4CW.js → workspace-foundation-QQHX66KE.js} +1 -1
- package/dist/{workspace-graph-stream-5YMLJXAJ.js → workspace-graph-stream-UZJQ75XZ.js} +1 -1
- package/dist/workspace-graph-token-efficiency-TF23UYEF.js +1 -0
- package/dist/{workspace-intelligence-XHSUFTAT.js → workspace-intelligence-A7O7MN6T.js} +1 -1
- package/dist/{workspace-intelligence-runner-EN5V4KSC.js → workspace-intelligence-runner-4EF66L66.js} +1 -1
- package/dist/{workspace-knowledge-graph-VWQTIEYK.js → workspace-knowledge-graph-BVN4NTJ6.js} +1 -1
- package/dist/{workspace-knowledge-graph-query-TXA3KVUV.js → workspace-knowledge-graph-query-6DAOXGGT.js} +1 -1
- package/dist/{workspace-knowledge-graph-snapshot-WB62AVDK.js → workspace-knowledge-graph-snapshot-XSQADCNR.js} +1 -1
- package/dist/{workspace-mcp-serve-NCAGGWQS.js → workspace-mcp-serve-TKX4J3SX.js} +1 -1
- package/dist/{workspace-model-NXFIKX26.js → workspace-model-7ESEP366.js} +1 -1
- package/dist/{workspace-onboarding-OP22NHQ4.js → workspace-onboarding-SY255V7L.js} +1 -1
- package/dist/{workspace-registry-summary-A5VDPRHU.js → workspace-registry-summary-7ISKYEPM.js} +1 -1
- package/dist/{workspace-repair-engine-N4KXNSVL.js → workspace-repair-engine-GMA2YTCF.js} +1 -1
- package/dist/workspace-run-ZZXVNFUS.js +1 -0
- package/dist/{workspace-verify-TUVLFPPN.js → workspace-verify-CNXZPWS5.js} +1 -1
- package/dist/{workspace-watch-2ZNOYSUQ.js → workspace-watch-HGFL2EU3.js} +1 -1
- package/docs/From Code to Shared Understanding-B.png +0 -0
- package/docs/From Code to Shared Understanding.png +0 -0
- package/docs/README_CONTENT_CONTRACT.md +25 -12
- package/docs/ci-workflows.md +9 -1
- package/docs/commands-reference.md +1 -1
- package/docs/contracts/README.md +16 -12
- package/docs/doctor-command.md +35 -11
- package/docs/from-code-to-shared-understanding.md +22 -17
- package/docs/real-world-qualification.md +73 -0
- package/docs/workspace-knowledge-graph.md +24 -3
- package/docs/workspace-operations.md +14 -2
- package/docs/workspace-run.md +16 -4
- package/package.json +5 -1
- package/dist/autopilot-release-CH57CGET.js +0 -1
- package/dist/capabilities-command-WEOGFCWF.js +0 -1
- package/dist/chunk-664GXRLD.js +0 -1
- package/dist/chunk-7Y3KVZJF.js +0 -8
- package/dist/chunk-BDN32Y2N.js +0 -81
- package/dist/chunk-DIZSHNZ5.js +0 -2
- package/dist/chunk-DOIZANFA.js +0 -2
- package/dist/chunk-OX53L237.js +0 -13
- package/dist/chunk-QRWWYL52.js +0 -88
- package/dist/chunk-VGJVIHHR.js +0 -1
- package/dist/workspace-graph-token-efficiency-HK4KNWWP.js +0 -1
- package/dist/workspace-run-PXKC3ELS.js +0 -1
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import {c}from'./chunk-ZPA6ECBJ.js';import {c as c$1}from'./chunk-X7FYEKLI.js';import {d as d$1,b as b$1,a as a$1}from'./chunk-3RBUSW7H.js';import {d}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-AFIFZTOY.js';import {h,e,i}from'./chunk-5EPPPMAS.js';import {t,h as h$1,g}from'./chunk-MOSXTVPU.js';import te from'crypto';import D from'fs';import j from'fs/promises';import p from'path';import {execa}from'execa';import ae from'fs-extra';var ce=h.projectContextAgent.schemaVersion,De=["managed","local","off"],ne="<!-- WORKSPAI:PROJECT-GROUNDING:START -->",re="<!-- WORKSPAI:PROJECT-GROUNDING:END -->";function z(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}async function b(e){try{return JSON.parse(await j.readFile(e,"utf8"))}catch(n){return null}}function R(e){return e.replace(/\\/g,"/").replace(/^\.\/+/,"")}function x(e,n,r){let o=e.replace(/\\/g,"/"),i=/^[A-Za-z]:\//.test(o);if(!p.isAbsolute(e)&&!i)return R(o);if(i&&process.platform!=="win32")return null;let c=p.resolve(e),a=p.relative(r,c);if(a&&!a.startsWith("..")&&!p.isAbsolute(a))return R(a);let l=p.relative(n,c);return l&&!l.startsWith("..")&&!p.isAbsolute(l)?`workspace:${R(l)}`:null}function y(e,n,r){return [[r,"project:"],[r.replace(/\\/g,"/"),"project:"],[n,"workspace:"],[n.replace(/\\/g,"/"),"workspace:"]].reduce((i,[c,a])=>c.length>0?i.split(c).join(a):i,e)}function oe(e,n){return z(e?.adoption)?.mode==="linked"?"adopted":z(e?.import)?"imported":n}function le(e){if(!e.model)return null;let n=R(e.relativePath);return e.model.projects.find(r=>r.name===e.projectName||R(r.path)===n)??null}function X(e,n){e[n]=(e[n]??0)+1;}var pe=["project","language","service","api","endpoint","schema","protocol","runtime-unit","lifecycle-stage","database","queue","container","deployment","pipeline","environment","test-suite","owner","decision","document","package","file","module","symbol"];function de(e,n=160){let r={language:32,api:32,service:32,endpoint:32,schema:32,protocol:32,"runtime-unit":32,"lifecycle-stage":32,file:8,module:8,symbol:8},o=[];for(let i of pe){let c=e.filter(a=>a.kind===i).sort((a,l)=>a.label.localeCompare(l.label)||a.id.localeCompare(l.id)).slice(0,r[i]??32);for(let a of c){if(o.length>=n)return o;o.push(a);}}return o}function ge(e,n){if(!e)return {entityCount:0,relationCount:0,proofCount:0,entitiesByKind:{},relationsByKind:{},languages:{},semantic:{protocolConceptCount:0,protocolImplementationBindings:0,equivalenceBindings:0,generationBindings:0,runtimeUnitCount:0,lifecycleStageCount:0,runtimeCoverage:[]},relatedProjects:[],proofArtifacts:[],entities:[],relations:[],proofs:[],topology:{status:"unavailable",dependencies:[],dependents:[]},diagnostics:[]};let r=e.entities.find(t=>t.kind==="project"&&(t.id===n||t.label===n||t.projectId===n)),o=new Set(e.entities.filter(t=>t.projectId===n||t.id===r?.id||t.kind==="project"&&t.label===n).map(t=>t.id));r&&o.add(r.id);let i=e.relations.filter(t=>o.has(t.from)||o.has(t.to)),c=new Set(o);for(let t of i)c.add(t.from),c.add(t.to);let a=e.entities.filter(t=>c.has(t.id)),l=new Set,d={},u={},m={},k=new Set(a.filter(t=>t.kind==="language").map(t=>t.attributes.language).filter(t=>typeof t=="string"));for(let t of a){X(d,t.kind);let s=typeof t.attributes.language=="string"?t.attributes.language:void 0;if(s&&t.kind==="language")m[s]={fileCount:typeof t.attributes.fileCount=="number"?t.attributes.fileCount:0,symbolCount:m[s]?.symbolCount??0,generatedFileCount:typeof t.attributes.generatedFileCount=="number"?t.attributes.generatedFileCount:0};else if(s&&(t.kind==="file"||t.kind==="symbol")){let h=m[s]??{fileCount:0,symbolCount:0,generatedFileCount:0};t.kind==="file"&&!k.has(s)?(h.fileCount+=1,t.attributes.generated===true&&(h.generatedFileCount+=1)):t.kind==="symbol"&&(h.symbolCount+=1),m[s]=h;}for(let h of t.proofIds)l.add(h);}for(let t of i){X(u,t.kind);for(let s of t.proofIds)l.add(s);}let w=e.proofs.filter(t=>l.has(t.id)),P=[...new Set(e.entities.filter(t=>c.has(t.id)&&t.projectId&&t.projectId!==n).map(t=>t.projectId))].sort(),f=e.diagnostics.filter(t=>t.entityIds?.some(s=>c.has(s))||t.relationIds?.some(s=>i.some(h=>h.id===s))).map(t=>({code:t.code,severity:t.severity,message:t.message,...t.recommendation?{recommendation:t.recommendation}:{}})),g=(t,s)=>({project:s,kind:t.kind,source:t.source,confidence:t.confidence,evidence:[...new Set(t.evidence.map(h=>h.file.replace(/\\/g,"/")))].sort()}),C=e.projectTopology.edges.filter(t=>t.from===n).map(t=>g(t,t.to)).sort((t,s)=>`${t.project}:${t.kind}`.localeCompare(`${s.project}:${s.kind}`)),S=e.projectTopology.edges.filter(t=>t.to===n).map(t=>g(t,t.from)).sort((t,s)=>`${t.project}:${t.kind}`.localeCompare(`${s.project}:${s.kind}`)),T=de(a),$=a.filter(t=>t.kind==="runtime-unit"),A=new Set(T.map(t=>t.id)),L=[...i].sort((t,s)=>{let h=Number(A.has(t.from)||A.has(t.to));return Number(A.has(s.from)||A.has(s.to))-h||t.id.localeCompare(s.id)}).slice(0,128),I=new Set([...T.flatMap(t=>t.proofIds),...L.flatMap(t=>t.proofIds)]);return {entityCount:a.length,relationCount:i.length,proofCount:w.length,entitiesByKind:d,relationsByKind:u,languages:Object.fromEntries(Object.entries(m).sort(([t],[s])=>t.localeCompare(s))),semantic:{protocolConceptCount:d.protocol??0,protocolImplementationBindings:u["implements-protocol"]??0,equivalenceBindings:u["equivalent-to"]??0,generationBindings:(u["generated-from"]??0)+(u["generated-by"]??0),runtimeUnitCount:$.length,lifecycleStageCount:d["lifecycle-stage"]??0,runtimeCoverage:[...new Set($.map(t=>t.attributes.runtime).filter(t=>typeof t=="string"))].sort()},relatedProjects:P,proofArtifacts:[...new Set(w.map(t=>t.artifact))].sort(),entities:T,relations:L,proofs:w.filter(t=>I.has(t.id)).sort((t,s)=>t.id.localeCompare(s.id)).slice(0,128),topology:{status:C.length>0||S.length>0?"proven":e.projectTopology.nodes.some(t=>t.id===n)?"unproven":"unavailable",dependencies:C,dependents:S},diagnostics:f}}function se(e,n,r){return Array.isArray(e)?e.map(o=>typeof o=="string"?y(o,n,r):o):typeof e=="string"?y(e,n,r):e}function ue(e,n,r){return {id:e.id,kind:e.kind,label:y(e.label,n,r),attributes:Object.fromEntries(Object.entries(e.attributes).map(([o,i])=>[o,se(i,n,r)])),proofIds:[...e.proofIds].sort()}}function me(e,n,r){let o=(...c)=>e.filter(a=>c.includes(a.kind)).map(a=>ue(a,n,r)).slice(0,32),i=[];for(let c of e){for(let[a,l]of Object.entries(c.attributes))if(/(?:^|[-_.])ports?(?:$|[-_.])/i.test(a)&&(i.push({entityId:c.id,label:y(c.label,n,r),attribute:a,value:se(l,n,r)}),i.length>=32))break;if(i.length>=32)break}return {services:o("service"),packages:o("package"),protocols:o("protocol"),runtimeUnits:o("runtime-unit"),lifecycleStages:o("lifecycle-stage"),apis:o("api"),endpoints:o("endpoint"),dataStores:o("database","queue"),deployments:o("container","deployment","environment"),pipelines:o("pipeline"),tests:o("test-suite"),owners:o("owner"),decisions:o("decision"),ports:i}}function fe(e,n,r){let o=x(e.artifact,n,r);return o?{id:e.id,provider:e.provider,artifact:o,...e.pointer?{pointer:y(e.pointer,n,r)}:{},...e.line!==void 0?{line:e.line}:{},derivation:e.derivation,trust:e.trust,confidence:e.confidence,freshness:e.freshness}:null}async function he(e,n,r){let o=[],i=await b(p.join(e,".workspai","reports","INDEX.json"));if(Array.isArray(i?.blockers))for(let a of i.blockers)typeof a=="string"&&(a.startsWith(`${r}:`)||a.includes(`project:${r}`)||a.includes(`project ${r}`))&&o.push({source:"workspace-report-index",severity:"error",message:y(a,e,n)});let c=await b(p.join(e,".workspai","reports","doctor-project-last-run.json"));if(c?.projectName===r)for(let a of c$1({project:c.project}))o.push({source:"doctor-project",severity:a.status==="blocking"?"error":"warning",message:y(a.message,e,n),...a.id?{code:a.id}:{}});return [...new Map(o.map(a=>[`${a.source}:${a.code??""}:${a.message}`,a])).values()].slice(0,32)}function M(e,n=[]){return typeof e=="string"?/^[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(e)||n.some(r=>r.length>0&&(e.includes(r)||e.includes(r.replace(/\\/g,"/")))):Array.isArray(e)?e.some(r=>M(r,n)):e&&typeof e=="object"?Object.values(e).some(r=>M(r,n)):false}function ke(e){return te.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function je(e$1){let n=p.resolve(e$1.workspacePath),r=p.resolve(e$1.projectPath),o=t(r,"project.json").find(s=>D.existsSync(s)),i$1=o?await b(o):null,c=await b(p.join(n,".workspai","workspace.contract.json")),a$1=p.resolve(r),l=c?.projects?.find(s=>s.externalPath?p.resolve(s.externalPath)===a$1:!s.relativePath||s.relativePath.startsWith("external/")?false:p.resolve(n,s.relativePath)===a$1)??c?.projects?.find(s=>s.slug===e$1.projectName||s.slug===p.basename(r)),d$1=e$1.projectName??(typeof i$1?.name=="string"?i$1.name:void 0)??l?.slug??p.basename(r),u=l?.relativePath??(()=>{let s=R(p.relative(n,r));return !s||s.startsWith("..")?`external/${d$1}`:s})(),m=await b(p.join(n,e.model)),k=await b(p.join(n,e.knowledgeGraph)),w=m?d(m):void 0,P=!!(w&&k?.source.hash===w),f=le({model:m,projectName:d$1,relativePath:u}),g=ge(P?k:null,d$1),C=await he(n,r,d$1),S=g.proofs.map(s=>s.freshness),T=k?!P||S.includes("stale")?"stale":S.includes("unknown")?"unknown":"fresh":"missing",$=m?m.factFreshness?.status??"unknown":"missing",A=[...m?[]:[{code:"project.context.model-missing",severity:"warning",message:"The canonical Workspace Model has not been generated yet. Refresh workspace intelligence before relying on project topology."}],...m&&!f?[{code:"project.context.project-not-materialized",severity:"warning",message:"The project is registered in the workspace contract but is not present in the current Workspace Model."}]:[],...k?[]:[{code:"project.context.graph-missing",severity:"warning",message:"The Workspace Knowledge Graph has not been generated yet. Run the workspace intelligence loop to build proof-backed relationships."}],...k&&!P?[{code:"project.context.graph-model-mismatch",severity:"warning",message:"The persisted Knowledge Graph does not match the current Workspace Model and was excluded from this project lens."}]:[]],L=oe(i$1,e$1.relationship??l?.relationship??"managed"),I={schemaVersion:ce,generatedAt:(e$1.now??new Date).toISOString(),workspace:{name:c?.workspace?.name??m?.workspace.name??p.basename(n),...c?.workspace?.profile||m?.workspace.profile?{profile:c?.workspace?.profile??m?.workspace.profile}:{},relationship:L,contract:i.workspaceContract,model:e.model,knowledgeGraph:e.knowledgeGraph,access:{localBinding:i.projectWorkspaceLink,canonicalEvidenceAvailableAtGeneration:true}},project:{name:d$1,relativePath:u,...f?.kind?{kind:f.kind}:{},...f?.runtime||l?.runtime?{runtime:f?.runtime??l?.runtime}:{},...f?.runtimeCandidates?.length?{runtimeCandidates:[...f.runtimeCandidates].sort()}:{},...f?.framework||l?.framework?{framework:f?.framework??l?.framework}:{},...f?.kit||l?.kit?{kit:f?.kit??l?.kit}:{},...f?.supportTier?{supportTier:f.supportTier}:{},commands:{supported:[...f?.commands.supported??[]].sort(),unsupported:[...f?.commands.unsupported??[]].sort(),fleetStages:[...f?.commands.fleetStages??[]].sort()},importantFiles:[...new Set((f?.importantFiles??[]).map(s=>x(s,n,r)).filter(s=>s!==null))].sort()},intelligence:{...m?.generatedAt?{modelGeneratedAt:m.generatedAt}:{},...k?.generatedAt?{graphGeneratedAt:k.generatedAt}:{},...k?.source.hash?{graphModelHash:k.source.hash}:{},entityCount:g.entityCount,relationCount:g.relationCount,proofCount:g.proofCount,entitiesByKind:g.entitiesByKind,relationsByKind:g.relationsByKind,languages:g.languages,semantic:g.semantic,relatedProjects:g.relatedProjects,freshness:{model:$,graph:T,graphMatchesModel:P},topology:{...g.topology,dependencies:g.topology.dependencies.map(s=>({...s,evidence:s.evidence.map(h=>x(h,n,r)).filter(h=>h!==null)})),dependents:g.topology.dependents.map(s=>({...s,evidence:s.evidence.map(h=>x(h,n,r)).filter(h=>h!==null)}))},surfaces:me(g.entities,n,r),diagnostics:[...A,...g.diagnostics].map(s=>({...s,message:y(s.message,n,r),...s.recommendation?{recommendation:y(s.recommendation,n,r)}:{}}))},evidence:{readOrder:[".workspai/PROJECT-GROUNDING.md",i.projectContextAgent,"AGENTS.md","workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json",`workspace:${e.model}`,`workspace:${e.knowledgeGraph}`],projectProofArtifacts:[...new Set(g.proofArtifacts.map(s=>x(s,n,r)).filter(s=>s!==null))],relations:g.relations.map(s=>({id:s.id,from:s.from,to:s.to,kind:s.kind,derivation:s.derivation,trust:s.trust,confidence:s.confidence,proofIds:[...s.proofIds].sort()})),proofs:g.proofs.map(s=>fe(s,n,r)).filter(s=>s!==null)},blockers:C,agentRouting:{enforcement:"required",mandatoryPreflight:{command:"npx workspai project workspace status --json",successCondition:"resolved"},workspaceEvidenceRequiredFor:["repository-analysis","architecture-analysis","change-impact","cross-project-change","contract-change","infrastructure-change","release-readiness"],requiredReadOrder:[i.projectContextAgent,"command:npx workspai project workspace status --json","workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json",`command:npx workspai workspace graph search ${JSON.stringify(d$1)} --scope ${JSON.stringify(`project:${d$1}`)} --limit 12 --json`],degradedMode:{allowCompleteArchitectureClaims:false,requireDisclosure:true}},commands:{refresh:"npx workspai workspace intelligence run --for-agent generic --strict --json",verify:"npx workspai workspace verify --strict --json",graphSearch:`npx workspai workspace graph search ${JSON.stringify(d$1)} --scope ${JSON.stringify(`project:${d$1}`)} --limit 12 --json`,doctor:"npx workspai doctor project --json",workspaceStatus:"npx workspai project workspace status --json"}};if(M(I,[n,r]))throw new Error("Project context lens rejected a non-portable absolute path.");let t$1={...I,integrity:{algorithm:"sha256",...w?{modelHash:w}:{},payloadHash:ke(I),portable:true,absolutePathsEmitted:false}};return a(t$1,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent"),t$1}function we(e){let n=e.intelligence.relatedProjects.length>0?e.intelligence.relatedProjects.map(i=>`\`${i}\``).join(", "):"No proven cross-project relation is currently available.",r=e.intelligence.diagnostics.length>0?e.intelligence.diagnostics.slice(0,8).map(i=>`- **${i.severity} \xB7 ${i.code}:** ${i.message}`).join(`
|
|
2
|
+
`):"- No project-scoped graph diagnostic is currently recorded.",o=e.blockers.length>0?e.blockers.slice(0,12).map(i=>`- **${i.severity}${i.code?` \xB7 ${i.code}`:""}:** ${i.message}`).join(`
|
|
3
|
+
`):"- No current project-scoped blocker is recorded.";return `# Workspai project grounding
|
|
4
|
+
|
|
5
|
+
This project is part of the **${e.workspace.name}** Workspai workspace.
|
|
6
|
+
Commands launched from this project resolve that workspace automatically; you do not need to change directories first.
|
|
7
|
+
|
|
8
|
+
## Start here
|
|
9
|
+
|
|
10
|
+
This is a mandatory agent preflight, not optional background material:
|
|
11
|
+
|
|
12
|
+
1. Read \`.workspai/reports/project-context-agent.json\` before broad source discovery.
|
|
13
|
+
2. Run \`${e.commands.workspaceStatus}\` and require a resolved workspace.
|
|
14
|
+
3. For repository analysis, architecture analysis, change impact, contracts, infrastructure, or release readiness, read the canonical workspace \`.workspai/reports/INDEX.json\` and \`workspace-context-agent.json\` even when the request names only this repository.
|
|
15
|
+
4. Run the bounded agent graph search below before broad source scanning, then use targeted graph evidence/path queries as needed.
|
|
16
|
+
5. Use source inspection to verify and deepen the workspace evidence, not to silently replace it.
|
|
17
|
+
6. Do not claim complete architecture, independence, health, readiness, or verification without current Workspai evidence.
|
|
18
|
+
|
|
19
|
+
If workspace resolution, required reports, or graph retrieval is unavailable, explicitly report degraded mode and the missing evidence. In degraded mode an agent may inspect source, but must not claim a complete architectural understanding.
|
|
20
|
+
|
|
21
|
+
The Workspace Model owns canonical project identity and its compact \`projectTopology\`.
|
|
22
|
+
The Workspace Knowledge Graph is a separate, proof-backed enrichment containing
|
|
23
|
+
files, symbols, APIs, infrastructure, tests, owners, and decisions. Do not treat
|
|
24
|
+
an unproven topology edge as proof that two projects are independent.
|
|
25
|
+
|
|
26
|
+
## Project
|
|
27
|
+
|
|
28
|
+
- Name: \`${e.project.name}\`
|
|
29
|
+
- Workspace-relative identity: \`${e.project.relativePath}\`
|
|
30
|
+
- Runtime: \`${e.project.runtime??"unknown"}\`
|
|
31
|
+
- Framework: \`${e.project.framework??"unknown"}\`
|
|
32
|
+
- Relationship: \`${e.workspace.relationship}\`
|
|
33
|
+
- Related projects: ${n}
|
|
34
|
+
- Topology status: \`${e.intelligence.topology.status}\`
|
|
35
|
+
- Model freshness: \`${e.intelligence.freshness.model}\`
|
|
36
|
+
- Knowledge Graph freshness: \`${e.intelligence.freshness.graph}\`
|
|
37
|
+
|
|
38
|
+
## Current evidence coverage
|
|
39
|
+
|
|
40
|
+
- Project-scoped entities: ${e.intelligence.entityCount}
|
|
41
|
+
- Project-scoped relations: ${e.intelligence.relationCount}
|
|
42
|
+
- Portable proofs: ${e.intelligence.proofCount}
|
|
43
|
+
|
|
44
|
+
${r}
|
|
45
|
+
|
|
46
|
+
## Current project blockers
|
|
47
|
+
|
|
48
|
+
${o}
|
|
49
|
+
|
|
50
|
+
## Safe commands from this project
|
|
51
|
+
|
|
52
|
+
\`\`\`bash
|
|
53
|
+
${e.commands.workspaceStatus}
|
|
54
|
+
${e.commands.doctor}
|
|
55
|
+
${e.commands.graphSearch}
|
|
56
|
+
${e.commands.verify}
|
|
57
|
+
\`\`\`
|
|
58
|
+
|
|
59
|
+
The machine-local workspace path lives only in \`.workspai/workspace-link.local.json\`, which is gitignored. Portable grounding files never publish that path.
|
|
60
|
+
`}function ye(e){return `# Workspai project boundary
|
|
61
|
+
|
|
62
|
+
- Project: \`${e.project.name}\`
|
|
63
|
+
- Canonical workspace: \`${e.workspace.name}\`
|
|
64
|
+
- Portable project lens: \`.workspai/reports/project-context-agent.json\`
|
|
65
|
+
- Project grounding: \`.workspai/PROJECT-GROUNDING.md\`
|
|
66
|
+
- Workspace discovery: run \`npx workspai project workspace status --json\`
|
|
67
|
+
|
|
68
|
+
Before broad source discovery, every agent must read the project lens and run \`${e.commands.workspaceStatus}\`; continue as fully grounded only when workspace resolution succeeds. Repository analysis, architecture analysis, change impact, contracts, APIs, infrastructure, and release readiness always require canonical workspace evidence and the bounded agent graph search, even when the request names only this repository. Source inspection verifies and deepens that evidence; it does not replace it silently. If required evidence is unavailable or stale, disclose degraded mode and do not claim complete architecture, independence, health, readiness, or verification. The user does not need to preload the graph. \`projectTopology\` is the compact project dependency view in the canonical Workspace Model, while the Workspace Knowledge Graph is the proof-backed detail layer. Workspai commands launched here resolve the canonical workspace automatically. Never copy the machine-local workspace link into answers, commits, or generated portable artifacts.`}function Z(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(e,n){return new RegExp(`${Z(e)}[\\s\\S]*?${Z(n)}`,"m")}function ie(e){let n=e.replace(Y(ne,re),"");return d$1(n)?.includes("# Workspai project boundary")&&(n=n.replace(Y(a$1,b$1),"")),n.replace(/\n{3,}/g,`
|
|
69
|
+
|
|
70
|
+
`).trim()}function Pe(e,n){let r=ie(e),o=`${ne}
|
|
71
|
+
${n.trim()}
|
|
72
|
+
${re}`;return r?`${r}
|
|
73
|
+
|
|
74
|
+
${o}
|
|
75
|
+
`:`${o}
|
|
76
|
+
`}async function O(e,n){await j.mkdir(p.dirname(e),{recursive:true});let r=`${e}.${process.pid}.${te.randomUUID()}.tmp`;try{await j.writeFile(r,n,"utf8");try{await j.rename(r,e);}catch(o){let i=o.code;if(i!=="EEXIST"&&i!=="EPERM")throw o;await ae.move(r,e,{overwrite:true});}}finally{await j.rm(r,{force:true}).catch(()=>{});}}async function be(e,n){let r;try{r=await execa("git",["rev-parse","--show-toplevel"],{cwd:e,reject:false});}catch{return false}if(r?.exitCode!==0)return false;let o=r.stdout.trim();if(!o)return false;let i,c;try{[i,c]=await Promise.all([j.realpath(p.resolve(o)),j.realpath(e)]);}catch{return false}let a=p.resolve(c,n),l=p.relative(i,a).replace(/\\/g,"/");if(!l||p.isAbsolute(l)||l===".."||l.startsWith("../"))return false;let d;try{d=await execa("git",["cat-file","-e",`HEAD:${l}`],{cwd:i,reject:false});}catch{return false}if(d?.exitCode!==0)return false;let u;try{u=await execa("git",["ls-files","--deleted","--error-unmatch","--",`:(top)${l}`],{cwd:i,reject:false});}catch{return false}return u?.exitCode===0}async function Q(e,n){let r=p.join(e,".gitignore"),o=await j.readFile(r,"utf8").catch(l=>{if(l.code==="ENOENT")return "";throw l}),i=[g,h$1],c=o.split(/\r?\n/).filter(l=>l.trim()!=="# Workspai local project grounding"&&!i.includes(l.trim()));for(;c.length>0&&c[c.length-1]==="";)c.pop();n==="local"&&(c.length>0&&c.push(""),c.push("# Workspai local project grounding",...i));let a=c.length>0?`${c.join(`
|
|
77
|
+
`)}
|
|
78
|
+
`:"";a!==o&&await O(r,a);}async function ee(e,n,r){let o=p.join(e,"AGENTS.md"),i=await j.lstat(o).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(i?.isSymbolicLink())return;let c=i?.isFile()===true,a=await j.readFile(o,"utf8").catch(u=>{if(u.code==="ENOENT")return "";throw u});if(n==="managed"&&!r)throw new Error("Managed project grounding requires a project context.");if(n==="managed"&&!c&&await be(e,"AGENTS.md"))return;let l=n==="managed"&&r?Pe(a,ye(r)):ie(a);if(!l){c&&await j.rm(o,{force:true});return}let d=`${l.trimEnd()}
|
|
79
|
+
`;return d!==a&&await O(o,d),n==="managed"?o:void 0}async function ve(e){let n=e.mode??"managed",r=p.resolve(e.workspacePath),o=p.resolve(e.projectPath);if(n==="off"){let k=t(o,"project.json").find(C=>D.existsSync(C)),w=k?await b(k):null,P=e.projectName??(typeof w?.name=="string"?w.name:void 0)??p.basename(o),f=oe(w,e.relationship??"managed"),g$1=await c({workspacePath:r,projectPath:o,projectName:P,relationship:f,now:e.now});return await Q(o,n),await ee(o,n),await Promise.all([j.rm(p.join(o,h$1),{force:true}),j.rm(p.join(o,g),{force:true})]),{mode:n,projectPath:o,linkPath:g$1.linkPath,writtenFiles:[i.projectWorkspaceLink]}}let i$1=await je(e),c$1=i$1.workspace.relationship,a=await c({workspacePath:r,projectPath:o,projectName:i$1.project.name,relationship:c$1,workspaceName:i$1.workspace.name,relativePath:i$1.project.relativePath,now:e.now});await Q(o,n);let l=await ee(o,n,i$1),d=p.join(o,h$1),u=p.join(o,g);await O(d,`${JSON.stringify(i$1,null,2)}
|
|
80
|
+
`),await O(u,`${we(i$1).trimEnd()}
|
|
81
|
+
`);let m=[i.projectWorkspaceLink,h$1,g];return l&&m.push("AGENTS.md"),{mode:n,projectPath:o,linkPath:a.linkPath,groundingPath:u,contextPath:d,agentsPath:l,writtenFiles:m}}async function Fe(e){let n=p.resolve(e.workspacePath),r=e.mode??"managed",o=await Ee(n),i=[],c=[];for(let a of o.resolved)try{i.push(await ve({workspacePath:n,projectPath:a.projectPath,projectName:a.name,relationship:a.relationship,mode:r,now:e.now}));}catch(l){c.push({name:a.name,reason:l instanceof Error?l.message:String(l)});}return {workspacePath:n,mode:r,projects:i,skipped:[...o.skipped,...c]}}async function Ee(e){let n=p.resolve(e),r=await b(p.join(n,".workspai","workspace.contract.json")),o=[],i=[];for(let c of r?.projects??[]){let a=c.slug??c.relativePath??"unknown-project",l=typeof c.externalPath=="string"?p.resolve(c.externalPath):typeof c.relativePath=="string"&&!c.relativePath.startsWith("external/")?p.resolve(n,c.relativePath):null;if(!l||!D.existsSync(l)){i.push({name:a,reason:"project path is unavailable on this machine"});continue}o.push({name:a,projectPath:l,relationship:c.relationship??"managed"});}return {resolved:o,skipped:i}}export{ce as a,De as b,ne as c,re as d,je as e,ve as f,Fe as g,Ee as h};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-2647BYBC.js';import {l}from'./chunk-GXTCU4WF.js';import {d,c}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-GR6442P7.js';import {f,e,i}from'./chunk-5EPPPMAS.js';import p from'path';import {createHash}from'crypto';import {createReadStream}from'fs';import {execFile}from'child_process';import {promisify}from'util';import S from'fs-extra';import {parseAllDocuments}from'yaml';var pe=f.knowledgeGraph;var Yt=e.knowledgeGraph;function Xt(e$1,t){if(e$1.source.kind!=="workspace-model")throw new Error(`Workspace knowledge graph is not bound to the canonical workspace model (source: ${e$1.source.kind}).`);if(e$1.source.artifact!==e.model)throw new Error(`Workspace knowledge graph source artifact is ${e$1.source.artifact}; expected ${e.model}.`);if(e$1.source.hashAlgorithm!=="sha256")throw new Error(`Workspace knowledge graph source hash algorithm is ${e$1.source.hashAlgorithm}; expected sha256.`);let o=d(t);if(e$1.source.hash!==o)throw new Error("Workspace knowledge graph is stale: its source hash does not match the canonical workspace model.");if(e$1.workspace.name!==t.workspace.name||(e$1.workspace.profile??void 0)!==(t.workspace.profile??void 0))throw new Error("Workspace knowledge graph identity does not match the canonical workspace model.");let i=l(t);if(!i)throw new Error("Canonical workspace model has no project topology for the workspace knowledge graph.");let r=c=>({...c,generatedAt:"<ignored>"});if(c(r(e$1.projectTopology))!==c(r(i)))throw new Error("Workspace knowledge graph project topology does not match the canonical workspace model.")}var De=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","venv","vendor","node_modules","dist","build","target","coverage",".next",".turbo",".cache",".vscode-test","graphify-out",".pytest_cache",".mypy_cache",".ruff_cache",".tox",".gradle","fixture","fixtures","__fixtures__","testdata"]),Me=new Set(["test","tests","spec","specs","e2e","integration","integration-tests","integration_tests","__tests__","fixture","fixtures","__fixtures__","testdata"]),ze=new Set(["examples","samples","worked"]);function se(e,t){let o=p.relative(e,t).split(p.sep).map(r=>r.toLowerCase()),i=p.basename(t).toLowerCase();return o.some(r=>Me.has(r))||/(?:\.test|\.spec|_test)\.[a-z0-9]+$/i.test(i)||/^test_.+\.[a-z0-9]+$/i.test(i)||/(?:tests?|specs?)\.(?:cs|fs|vb|java|kt|kts)$/i.test(i)}function ie(e,t){return p.relative(e,t).split(p.sep).map(o=>o.toLowerCase()).some(o=>ze.has(o))}function M(e,t){return se(e,t)||ie(e,t)}function oe(e,t){return p.relative(e,t).split(p.sep).some(o=>o.toLowerCase()==="generated")}var fe=new Set(["package.json","pyproject.toml","requirements.txt","Pipfile","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts","composer.json","Gemfile","mix.exs","pubspec.yaml","Package.swift","CMakeLists.txt","deno.json","deno.jsonc","project.clj","deps.edn","build.sbt","BUILD","BUILD.bazel","WORKSPACE.bazel"]),Be=new Set(["get","put","post","delete","options","head","patch","trace"]),T=new Set([".c",".cc",".cpp",".cs",".dart",".ex",".exs",".go",".h",".hpp",".java",".js",".jsx",".kt",".kts",".mjs",".php",".py",".r",".rb",".rs",".scala",".svelte",".swift",".ts",".tsx",".vue",".clj",".cljs",".fs",".fsx",".lua",".vb"]);function F(e,t){let o=p.extname(e).toLowerCase();return o===".h"&&t==="cpp"?"cpp":{".c":"c",".cc":"cpp",".cpp":"cpp",".cs":"csharp",".dart":"dart",".ex":"elixir",".exs":"elixir",".go":"go",".h":"c",".hpp":"cpp",".java":"java",".js":"javascript",".jsx":"javascript",".kt":"kotlin",".kts":"kotlin",".mjs":"javascript",".php":"php",".py":"python",".r":"r",".rb":"ruby",".rs":"rust",".scala":"scala",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescript",".vue":"vue",".clj":"clojure",".cljs":"clojure",".fs":"fsharp",".fsx":"fsharp",".lua":"lua",".vb":"visual-basic"}[o]??o.slice(1)}function Ge(e,t){if(e.length<=t)return [...e];let o=new Map;for(let c of e){let s=F(c),a=o.get(s)??[];a.push(c),o.set(s,a);}let i=new Set,r=Math.max(1,Math.min(25,Math.floor(t/Math.max(o.size,1))));for(let c of [...o.values()])for(let s of c.slice(0,r))i.add(s);for(let c of e){if(i.size>=t)break;i.add(c);}return [...i].sort((c,s)=>c.localeCompare(s))}function Q(e,t,o){let i=[],r=e.split(/\r?\n/);for(let c=0;c<r.length&&i.length<o;c+=1)for(let s of t){let n=r[c].match(s.pattern)?.[1]?.trim();if(n){i.push({name:n,line:c+1,detail:s.detail});break}}return i}var xe=[{pattern:/^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/,detail:"function"},{pattern:/^\s*(?:export\s+)?(?:abstract\s+)?(?:class|interface|enum|type)\s+([A-Za-z_$][\w$]*)/,detail:"type"},{pattern:/^\s*(?:export\s+)?(?:declare\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)/,detail:"value"},{pattern:/^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*class\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*type\s+([A-Za-z_]\w*)\s+/,detail:"type"},{pattern:/^\s*(?:public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+)*(?:class|interface|record|enum)\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*(?:public|protected|internal)\s+(?:(?:static|virtual|override|abstract|async|sealed|final|synchronized|native|unsafe|partial|extern|new)\s+)*(?:<[^>]+>\s*)?[A-Za-z_$][\w$<>,.?\[\]: ]*\s+([A-Za-z_$][\w$]*)\s*\(/,detail:"method"},{pattern:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|trait|enum|type)\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*(?:public\s+|private\s+|protected\s+)?function\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*(?:class|module|struct|protocol|mixin)\s+([A-Za-z_]\w*)/,detail:"type"}],qe=[{pattern:/^\s*import(?:.+?from\s*)?["']([^"']+)["']/,detail:"import"},{pattern:/require\(["']([^"']+)["']\)/,detail:"require"},{pattern:/^\s*from\s+([A-Za-z0-9_.]+)\s+import\s+/,detail:"import"},{pattern:/^\s*import\s+([A-Za-z0-9_.]+)(?:\s|$)/,detail:"import"},{pattern:/^\s*(?:import|using|use)\s+([A-Za-z0-9_:.*\\/.-]+)/,detail:"import"},{pattern:/^\s*require(?:_relative)?\s+["']([^"']+)["']/,detail:"require"}];function Ze(e,t,o,i){let r=p.extname(e).toLowerCase()===".py",c;if(r){let d=t.match(/^\.+/)?.[0].length??0,l=d>0?p.dirname(e):p.resolve(i??"");for(let u=1;u<d;u+=1)l=p.dirname(l);let m=t.slice(d).replace(/\./g,p.sep);c=m?p.join(l,m):l;}else {if(!t.startsWith("."))return null;c=p.resolve(p.dirname(e),t);}let s=p.extname(c).toLowerCase(),a=T.has(s),n=new Set([c]);if(r&&(n.add(`${c}.py`),n.add(p.join(c,"__init__.py"))),a){let d=c.slice(0,-s.length);if([".js",".jsx",".mjs"].includes(s))for(let l of [".ts",".tsx",".js",".jsx",".mjs"])n.add(`${d}${l}`);}else for(let d of T)n.add(`${c}${d}`),n.add(p.join(c,`index${d}`));return [...n].find(d=>o.has(p.resolve(d)))??null}function He(e,t){let o=t.trimStart(),i=p.extname(e).toLowerCase();return [".py",".rb",".sh",".bash",".zsh"].includes(i)?o.startsWith("#"):[".sql",".lua",".hs"].includes(i)?o.startsWith("--"):o.startsWith("//")||o.startsWith("/*")||o.startsWith("*")}function Ve(e,t){if(p.extname(e).toLowerCase()!==".py")return t;let o=null;return t.split(/\r?\n/).map(i=>{let r=0,c="";for(;r<i.length;){if(o){let l=i.indexOf(o,r);if(l<0)return c;r=l+3,o=null;continue}let s=i.indexOf("'''",r),a=i.indexOf('"""',r),n=i.indexOf("#",r),d=s<0?a:a<0?s:Math.min(s,a);if(n>=0&&(d<0||n<d)){c+=i.slice(r,n);break}if(d<0){c+=i.slice(r);break}c+=i.slice(r,d),o=i.startsWith("'''",d)?"'''":'"""',r=d+3;}return c}).join(`
|
|
2
|
+
`)}function Je(e,t){if(![".js",".jsx",".mjs",".ts",".tsx"].includes(p.extname(e).toLowerCase()))return t;let o=false,i=false;return t.split(/\r?\n/).map(r=>{let c="",s=null,a=false;for(let n=0;n<r.length;n+=1){let d=r[n],l=r[n+1];if(o){c+=" ",d==="*"&&l==="/"&&(c+=" ",n+=1,o=false);continue}if(i){c+=" ",d==="`"&&!a&&(i=false),a=d==="\\"&&!a,d!=="\\"&&(a=false);continue}if(s){c+=d,d===s&&!a&&(s=null),a=d==="\\"&&!a,d!=="\\"&&(a=false);continue}if(d==="/"&&l==="/")return c.padEnd(r.length," ");if(d==="/"&&l==="*"){c+=" ",n+=1,o=true;continue}if(d==="`"){c+=" ",i=true,a=false;continue}(d==="'"||d==='"')&&(s=d),c+=d;}return c}).join(`
|
|
3
|
+
`)}function Ue(e,t){return Je(e,Ve(e,t))}var Ye=[{pattern:/@(?:Get|Post|Put|Delete|Patch|Options|Head)\s*\(\s*["']([^"']*)["']/i,detail:"decorated route"},{pattern:/\b(?:app|router|server|api|route|fastify|fiber)\.(?:get|post|put|delete|patch|options|head)\s*\(\s*["']([^"']+)["']/i,detail:"router route"},{pattern:/@(?:GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|RequestMapping)\s*\([^"']*["']([^"']*)["']/,detail:"mapped route"},{pattern:/\[Http(?:Get|Post|Put|Delete|Patch)\s*\(\s*["']([^"']*)["']/i,detail:"HTTP route"},{pattern:/^\s*(?:get|post|put|delete|patch)\s+["']([^"']+)["']/i,detail:"HTTP route"}];function V(e){return createHash("sha256").update(e).digest("hex")}function E(e,t){return `wkg:${e}:${V(`${e}\0${t}`).slice(0,20)}`}function O(e){return e.replace(/\\/g,"/")}function x(e){let t=O(e).replace(/^\.\//,"");return !t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")?"unknown":t}function j(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function b(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function K(e){if(Array.isArray(e))return e.filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean).sort();let t=j(e);return t?Object.keys(t).map(o=>o.trim()).filter(Boolean).sort():[]}function Xe(e){if(Array.isArray(e))return e.map(o=>typeof o=="string"?o.split("=",1)[0]?.trim():"").filter(o=>!!o).sort();let t=j(e);return t?Object.keys(t).sort():[]}function Qe(e){return Object.fromEntries(Object.entries(e).filter(t=>t[1]!==void 0).sort(([t],[o])=>t.localeCompare(o)))}async function q(e,t){let o=[],i=[e],r=0;for(;r<i.length&&o.length<t;){let c=i[r++],s;try{s=await S.readdir(c,{withFileTypes:true});}catch{continue}s.sort((a,n)=>a.name.localeCompare(n.name));for(let a$1 of s){if(o.length>=t)break;if(a$1.isSymbolicLink())continue;let n=p.join(c,a$1.name);a$1.isDirectory()?!De.has(a$1.name)&&!a(a$1.name)&&i.push(n):a$1.isFile()&&o.push(n);}}return o.sort((c,s)=>c.localeCompare(s))}async function Se(e){return new Promise(t=>{let o=createHash("sha256"),i=createReadStream(e);i.on("data",r=>o.update(r)),i.on("error",r=>{t(`unreadable:${r.code??"unknown"}`);}),i.on("end",()=>t(o.digest("hex")));})}var et=promisify(execFile);async function D(e,t){let o=await et("git",t,{cwd:e,encoding:"buffer",maxBuffer:268435456,windowsHide:true});return Buffer.isBuffer(o.stdout)?o.stdout:Buffer.from(o.stdout)}async function tt(e){try{let t=(await D(e.root,["rev-parse","--show-prefix"])).toString("utf8").trim().replace(/\\/gu,"/"),o=t?`${t.replace(/^\/+|\/+$/gu,"")}/`:"";if(p.posix.isAbsolute(o)||o==="../"||o.startsWith("../")||o.includes("/../"))return null;let i=o.replace(/\/$/u,""),r=i?`HEAD:${i}`:"HEAD^{tree}",[c,s,a,n,d,l]=await Promise.all([D(e.root,["rev-parse",r]),D(e.root,["diff","--no-ext-diff","--no-textconv","--binary","HEAD","--","."]),D(e.root,["ls-files","--full-name","--others","--exclude-standard","-z","--","."]),D(e.root,["ls-files","--full-name","--others","--ignored","--exclude-standard","-z","--","."]),D(e.root,["ls-files","-v","--","."]),D(e.root,["ls-files","--full-name","-s","--","."])]);if(d.toString("utf8").split(/\r?\n/u).some(f=>/^[a-z] /u.test(f)))return null;let m=e.files.map(f=>{let y=O(p.relative(e.root,f));return `${o}${y}`});if(l.toString("utf8").split(/\r?\n/u).filter(f=>f.startsWith("160000 ")).map(f=>f.split(" ",2)[1]).filter(f=>!!f).map(f=>f.replace(/\\/gu,"/").replace(/\/$/u,"")).some(f=>m.some(y=>y.startsWith(`${f}/`))))return null;let v=new Set(m),g=Buffer.concat([a,n]).toString("utf8").split("\0").filter(Boolean).map(f=>f.replace(/\\/gu,"/")).filter(f=>v.has(f)),w=await Ae([...new Set(g)].sort((f,y)=>f.localeCompare(y)),16,async f=>{let y=o?f.slice(o.length):f;return {path:y,hash:await Se(p.resolve(e.root,...y.split("/").filter(Boolean)))}}),P=createHash("sha256");P.update(`git-worktree-v2\0${e.kind}\0${e.id}\0${e.fileLimit}\0`),P.update(c),P.update(createHash("sha256").update(s).digest());for(let f of w)P.update(`${f.path}\0${f.hash}\0`);return {kind:e.kind,id:e.id,strategy:"git-worktree-v2",hash:P.digest("hex"),fileCount:e.files.length,fileLimit:e.fileLimit,truncated:e.files.length>=e.fileLimit}}catch{return null}}async function Ae(e,t,o){let i=new Array(e.length),r=0,c=Array.from({length:Math.min(t,Math.max(e.length,1))},async()=>{for(;r<e.length;){let s=r++;i[s]=await o(e[s]);}});return await Promise.all(c),i}async function ue(e){let t=await tt(e);if(t)return t;let o=await Ae(e.files,16,async r=>({path:O(p.relative(e.root,r)),hash:await Se(r)}));o.sort((r,c)=>r.path.localeCompare(c.path));let i=createHash("sha256");i.update(`content-merkle-v1\0${e.kind}\0${e.id}\0${e.fileLimit}\0`);for(let r of o)i.update(`${r.path}\0${r.hash}\0`);return {kind:e.kind,id:e.id,strategy:"content-merkle-v1",hash:i.digest("hex"),fileCount:o.length,fileLimit:e.fileLimit,truncated:o.length>=e.fileLimit}}async function ot(e){let t=p.resolve(e.workspacePath),o=[...e.projects].sort((s,a)=>s.id.localeCompare(a.id)),i=e.inventories?.workspaceFiles??await q(t,e.workspaceFileLimit),r=await Promise.all([ue({kind:"workspace",id:"workspace",root:t,files:i,fileLimit:e.workspaceFileLimit}),...o.map(async s=>{let a=s.absolutePath?p.resolve(s.absolutePath):p.resolve(t,s.path),n=e.inventories?.projectFiles?.get(s.id)??await q(a,e.projectFileLimit);return ue({kind:"project",id:s.id,root:a,files:n,fileLimit:e.projectFileLimit})})]);r.sort((s,a)=>s.kind.localeCompare(a.kind)||s.id.localeCompare(a.id));let c=createHash("sha256");c.update("workspace-knowledge-graph-inputs.v1\0hybrid-git-content-v2\0");for(let s of r)c.update(`${s.kind}\0${s.id}\0${s.hash}\0${s.fileCount}\0${s.fileLimit}\0${s.truncated}\0`);return {schemaVersion:"workspace-knowledge-graph-inputs.v1",strategy:"hybrid-git-content-v2",hashAlgorithm:"sha256",hash:c.digest("hex"),scopes:r}}async function B(e){let t=await S.readFile(e,"utf8");if(e.toLowerCase().endsWith(".json")){let o=JSON.parse(t),i=j(o);return i?[i]:[]}return parseAllDocuments(t,{logLevel:"silent"}).map(o=>j(o.toJSON())).filter(o=>o!==null)}function J(e){return [...new Set([...e.workspaceFiles,...e.projects.flatMap(t=>e.filesByProject.get(t.id)??[])])].sort((t,o)=>t.localeCompare(o))}function me(e){return /^(?:openapi|swagger)(?:\.[^.]+)?\.(?:json|ya?ml)$/i.test(p.basename(e))}function ge(e){let t=p.basename(e).toLowerCase();return /\.(?:graphql|gql|proto)$/.test(t)||/^asyncapi(?:\.[^.]+)?\.(?:json|ya?ml)$/.test(t)}function he(e){let t=p.basename(e);return /^Dockerfile(?:\..+)?$/i.test(t)||/\.tf$/i.test(t)||t==="Chart.yaml"}function ye(e){return /(?:^|[\\/])(?:README|ARCHITECTURE|CONTRIBUTING|SECURITY)\.md$/i.test(e)}function rt(e,t){let o=O(p.relative(e,t));return /^\.github\/workflows\/.+\.ya?ml$/i.test(o)||/^(?:\.gitlab-ci\.ya?ml|azure-pipelines\.ya?ml|Jenkinsfile|bitbucket-pipelines\.ya?ml|\.woodpecker\.ya?ml)$/i.test(o)||/^\.circleci\/config\.ya?ml$/i.test(o)}function ve(e,t){let o=O(p.relative(e,t));return /(?:^|\/)(?:adr|adrs|decisions)(?:\/).+\.md$/i.test(o)||/(?:^|\/)ADR[-_0-9].+\.md$/i.test(o)}async function ke(e){let t=new Set;for(let o of [e.workspacePath,...e.projects.map(i=>i.root)])for(let i of ["compose.yml","compose.yaml","docker-compose.yml","docker-compose.yaml"]){let r=p.join(o,i);await S.pathExists(r)&&t.add(r);}return [...t].sort((o,i)=>o.localeCompare(i))}async function be(e){let o=[e.workspacePath,...e.projects.map(r=>r.root)].flatMap(r=>[p.join(r,"CODEOWNERS"),p.join(r,".github","CODEOWNERS"),p.join(r,"docs","CODEOWNERS")]),i=await Promise.all(o.map(async r=>await S.pathExists(r)?r:null));return [...new Set(i.filter(r=>!!r))].sort((r,c)=>r.localeCompare(c))}function we(e){let t=[{root:e.workspacePath,files:e.workspaceFiles},...e.projects.map(o=>({root:o.root,files:e.filesByProject.get(o.id)??[]}))];return [...new Set(t.flatMap(o=>o.files.filter(i=>rt(o.root,i))))].sort((o,i)=>o.localeCompare(i))}async function Pe(e){let t=[];for(let o of J(e))if(/\.ya?ml$/i.test(o))try{(await B(o)).some(r=>{let c=j(r.metadata);return !!(b(r.apiVersion)&&b(r.kind)&&b(c?.name))})&&t.push(o);}catch{}return t.sort((o,i)=>o.localeCompare(i))}function N(e,t){let o=p.resolve(t);return e.filter(i=>o===i.root||o.startsWith(`${i.root}${p.sep}`)).sort((i,r)=>r.root.length-i.root.length)[0]??null}var re=class{constructor(t,o,i){this.workspacePath=t;this.now=o;this.workspaceName=i;}workspacePath;now;workspaceName;entities=new Map;relations=new Map;proofs=new Map;providers=[];diagnostics=[];contentHashes=new Map;attributeConflicts=new Set;emptyLabelDiagnostics=new Set;artifactPath(t,o){if(o){let i=O(p.relative(o.root,t));return x(p.posix.join(o.artifactPrefix,i))}return x(p.relative(this.workspacePath,t))}async addProof(t){let o;if(t.absolutePath){if(!this.contentHashes.has(t.absolutePath))try{this.contentHashes.set(t.absolutePath,V(await S.readFile(t.absolutePath)));}catch{this.contentHashes.set(t.absolutePath,null);}o=this.contentHashes.get(t.absolutePath)??void 0;}let i=x(t.artifact),r=E("proof",[t.provider,i,t.pointer??"",t.line??"",t.detail??""].join("\0"));return this.proofs.has(r)||this.proofs.set(r,{id:r,provider:t.provider,artifact:i,...t.pointer?{pointer:t.pointer}:{},...t.line?{line:t.line}:{},...t.column?{column:t.column}:{},...o?{contentHash:o}:{},observedAt:this.now.toISOString(),derivation:t.derivation??"extracted",trust:t.trust??"observed",confidence:t.confidence??"high",freshness:"fresh",...t.detail?{detail:t.detail}:{}}),r}addEntity(t){let o=E(t.kind,t.key),i=Qe(t.attributes??{}),r=this.entities.get(o),c=t.label.trim(),s=c||r?.label||t.key.trim()||t.kind;!c&&!this.emptyLabelDiagnostics.has(o)&&(this.emptyLabelDiagnostics.add(o),this.diagnostics.push({code:"graph.knowledge.empty_label_normalized",severity:"warning",message:`An empty ${t.kind} label was normalized to ${s}.`,entityIds:[o],recommendation:"Inspect the provider proof and preserve a non-empty source identifier before publishing the entity."}));let a={...r?.attributes??{}};for(let[l,m]of Object.entries(i)){if(l in a&&JSON.stringify(a[l])!==JSON.stringify(m)){let u=`${o}\0${l}`;this.attributeConflicts.has(u)||(this.attributeConflicts.add(u),this.diagnostics.push({code:"graph.knowledge.attribute_conflict",severity:"warning",message:`Conflicting ${l} values were observed for ${t.kind} ${s}.`,entityIds:[o],recommendation:"Inspect the entity proof paths and make the authoritative source explicit."}));continue}a[l]=m;}let n=[...new Set([...r?.identity.aliases??[],...t.aliases??[]].map(l=>l.trim()).filter(Boolean))].sort(),d=[...new Set([...r?.proofIds??[],...t.proofIds??[]])].sort();return this.entities.set(o,{id:o,kind:t.kind,label:s,...t.projectId?{projectId:t.projectId}:{},identity:{key:t.key,scope:t.projectId?"project":"workspace",aliases:n,fingerprint:V(JSON.stringify({kind:t.kind,key:t.key,attributes:a}))},attributes:a,proofIds:d}),o}addRelation(t){let o=E("relation",`${t.from}\0${t.kind}\0${t.to}`),i=this.relations.get(o),r=[...new Set([...i?.proofIds??[],...t.proofIds])].sort(),c=new Set(r.map(n=>this.proofs.get(n)?.provider).filter(Boolean)).size,s=t.trust??i?.trust??"observed",a=c>=2&&s!=="ambiguous"?"corroborated":s;return this.relations.set(o,{id:o,from:t.from,to:t.to,kind:t.kind,derivation:t.derivation??i?.derivation??"extracted",trust:a,confidence:a==="corroborated"?"high":t.confidence??i?.confidence??"high",proofIds:r}),o}};function ee(e){let t=[],o=null;for(let i of e.split(/\r?\n/)){let r=i.match(/^\s*\[\[([^\]]+)\]\]\s*(?:#.*)?$/)?.[1]?.trim()??i.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/)?.[1]?.trim();if(r){o&&t.push({name:o.name,body:o.lines.join(`
|
|
4
|
+
`)}),o={name:r,lines:[]};continue}o?.lines.push(i);}return o&&t.push({name:o.name,body:o.lines.join(`
|
|
5
|
+
`)}),t}function st(e){return [...e.matchAll(/["']([^"']+)["']/g)].map(t=>t[1])}function $e(e,t){let o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^\\s*${o}\\s*=\\s*\\[`,"m").exec(e);if(!i)return [];let r=i.index+i[0].lastIndexOf("["),c=null,s=false;for(let a=r+1;a<e.length;a+=1){let n=e[a];if(c){n===c&&!s&&(c=null),s=n==="\\"&&!s,n!=="\\"&&(s=false);continue}if(n==="'"||n==='"'){c=n;continue}if(n==="]")return st(e.slice(r+1,a))}return []}function je(e){return e.trim().match(/^([A-Za-z0-9][A-Za-z0-9_.-]*)/)?.[1]??""}function ne(e){return e.replace(/\.(?:workspace|version|path|git|optional|features|default-features|package)$/,"")}function it(e,t){let o=p.basename(e);try{if(o==="package.json"||o==="composer.json"){let s=JSON.parse(t);return {ecosystem:o==="package.json"?"npm":"composer",name:b(s.name),version:b(s.version),dependencies:[...K(s.dependencies),...K(s.devDependencies),...K(s.require),...K(s["require-dev"])].filter((a,n,d)=>d.indexOf(a)===n).sort(),metadata:o==="package.json"?{entrypoints:[b(s.main),b(s.module),b(s.types)].filter(a=>!!a),exports:j(s.exports)?Object.keys(j(s.exports)).sort():b(s.exports)?["."]:[],executables:j(s.bin)?Object.keys(j(s.bin)).sort():b(s.bin)?[b(s.name)??"default"]:[],runtimeConstraints:Object.entries(j(s.engines)??{}).map(([a,n])=>`${a}:${String(n)}`).sort()}:void 0}}if(o==="deno.json"||o==="deno.jsonc"){let s=JSON.parse(t.replace(/\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm,""));return {ecosystem:"deno",name:b(s.name),version:b(s.version),dependencies:K(s.imports)}}}catch{}let i=s=>t.match(s)?.[1]?.trim();if(o==="pyproject.toml"){let a=ee(t).filter(({name:n})=>n==="project"||n==="project.optional-dependencies"||n==="dependency-groups"||n==="tool.poetry.dependencies"||/^tool\.poetry\.group\.[^.]+\.dependencies$/.test(n)).flatMap(({name:n,body:d})=>n==="project"?$e(d,"dependencies").map(je):n==="project.optional-dependencies"||n==="dependency-groups"?[...d.matchAll(/^\s*(?:["']([^"']+)["']|([A-Za-z0-9_.-]+))\s*=\s*\[/gm)].flatMap(l=>$e(d,l[1]??l[2])).map(je):[...d.matchAll(/^\s*(?:["']([^"']+)["']|([A-Za-z0-9_.-]+))\s*=/gm)].map(l=>l[1]??l[2]).filter(l=>l!=="python"));return {ecosystem:"python",name:i(/^(?:name)\s*=\s*["']([^"']+)["']/m),version:i(/^(?:version)\s*=\s*["']([^"']+)["']/m),dependencies:a.filter(Boolean).filter((n,d,l)=>l.indexOf(n)===d).sort(),metadata:{requiresPython:i(/^requires-python\s*=\s*["']([^"']+)["']/m)??"unknown"}}}if(o==="go.mod")return {ecosystem:"go",name:i(/^module\s+(\S+)/m),dependencies:[...t.matchAll(/^\s*([A-Za-z0-9_.~/-]+)\s+v\d+/gm)].map(s=>s[1]).sort(),metadata:{goVersion:i(/^go\s+(\S+)/m)??"unknown"}};if(o==="Cargo.toml"){let s=ee(t).filter(({name:a})=>/(?:^|\.)(?:dev-|build-)?dependencies$/.test(a)).map(({body:a})=>a).join(`
|
|
6
|
+
`);return {ecosystem:"cargo",name:i(/^name\s*=\s*["']([^"']+)["']/m),version:i(/^version\s*=\s*["']([^"']+)["']/m),dependencies:[...s.matchAll(/^\s*(?:["']([^"']+)["']|([A-Za-z0-9_.-]+))\s*=/gm)].map(a=>a[1]??a[2]).map(ne).filter((a,n,d)=>d.indexOf(a)===n).sort(),metadata:{edition:i(/^edition\s*=\s*["']([^"']+)["']/m)??"unknown",rustVersion:i(/^rust-version\s*=\s*["']([^"']+)["']/m)??"unknown",features:ee(t).find(({name:a})=>a==="features")?.body.match(/^\s*([A-Za-z0-9_.-]+)\s*=/gm)?.map(a=>a.split("=",1)[0].trim()).sort()??[]}}}if(o==="pom.xml"){let s=[...t.matchAll(/<dependency>([\s\S]*?)<\/dependency>/g)].map(a=>{let n=a[1].match(/<groupId>([^<]+)<\/groupId>/)?.[1]?.trim(),d=a[1].match(/<artifactId>([^<]+)<\/artifactId>/)?.[1]?.trim();return n&&d?`${n}:${d}`:d}).filter(a=>!!a);return {ecosystem:"maven",name:i(/<artifactId>([^<]+)<\/artifactId>/),version:i(/<version>([^<]+)<\/version>/),dependencies:s.filter((a,n,d)=>d.indexOf(a)===n).sort(),metadata:{groupId:i(/<groupId>([^<]+)<\/groupId>/)??"unknown",packaging:i(/<packaging>([^<]+)<\/packaging>/)??"jar"}}}if(/\.(?:cs|fs|vb)proj$/i.test(o))return {ecosystem:"nuget",name:i(/<AssemblyName>([^<]+)<\/AssemblyName>/)??o.replace(/\.[^.]+$/,""),version:i(/<Version>([^<]+)<\/Version>/),dependencies:[...t.matchAll(/<PackageReference\s+Include=["']([^"']+)["']/g)].map(s=>s[1]).sort(),metadata:{targetFrameworks:(i(/<TargetFrameworks?>([^<]+)<\/TargetFrameworks?>/)??"unknown").split(";"),rootNamespace:i(/<RootNamespace>([^<]+)<\/RootNamespace>/)??"unknown"}};let r={"requirements.txt":"python",Pipfile:"python","build.gradle":"gradle","build.gradle.kts":"gradle",Gemfile:"ruby","mix.exs":"elixir","pubspec.yaml":"dart","Package.swift":"swift","CMakeLists.txt":"cmake","deno.json":"deno","deno.jsonc":"deno","project.clj":"clojure","deps.edn":"clojure","build.sbt":"scala",BUILD:"bazel","BUILD.bazel":"bazel","WORKSPACE.bazel":"bazel"},c=o==="requirements.txt"?t.split(/\r?\n/).map(s=>s.trim().match(/^([A-Za-z0-9_.-]+)/)?.[1]):o.startsWith("build.gradle")?[...t.matchAll(/(?:implementation|api|compileOnly|runtimeOnly|testImplementation)\s*\(?["']([^:"']+):([^:"']+)/g)].map(s=>`${s[1]}:${s[2]}`):o==="Gemfile"?[...t.matchAll(/^\s*gem\s+["']([^"']+)["']/gm)].map(s=>s[1]):o==="mix.exs"?[...t.matchAll(/\{:\s*([A-Za-z0-9_]+)\s*,/g)].map(s=>s[1]):o==="pubspec.yaml"?[...t.matchAll(/^\s{2}([A-Za-z0-9_]+):\s+/gm)].map(s=>s[1]):o==="Package.swift"?[...t.matchAll(/\.package\s*\(\s*url:\s*["']([^"']+)["']/g)].map(s=>s[1]):o==="CMakeLists.txt"?[...t.matchAll(/find_package\s*\(\s*([A-Za-z0-9_.+-]+)/gi)].map(s=>s[1]):o==="project.clj"||o==="deps.edn"?[...t.matchAll(/\[?([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\s+/g)].map(s=>s[1]):o==="build.sbt"?[...t.matchAll(/["']([^"']+)["']\s*%%?\s*["']([^"']+)["']/g)].map(s=>`${s[1]}:${s[2]}`):[];return {ecosystem:r[o]??"unknown",dependencies:c.filter(s=>!!s).filter((s,a,n)=>n.indexOf(s)===a).sort()}}function Ie(e,t){let o=e==="cargo"?ne(t):t;return e==="cargo"?o.toLowerCase().replace(/[-_]/g,""):o.toLowerCase()}function nt(e,t){let o=[...e.entities.values()].filter(r=>r.kind==="package"&&r.projectId===t),i=new Map;for(let r of o){let c=String(r.attributes.ecosystem??"unknown");for(let s of new Set([r.label,...r.identity.aliases])){let a=`${c}\0${Ie(c,s)}`,n=i.get(a)??[];n.push(r),i.set(a,n);}}for(let r of o){let c=String(r.attributes.ecosystem??"unknown"),s=Array.isArray(r.attributes.dependencies)?r.attributes.dependencies.filter(a=>typeof a=="string"):[];for(let a of s){let n=`${c}\0${Ie(c,a)}`,d=(i.get(n)??[]).filter(u=>u.id!==r.id);if(d.length!==1)continue;let l=d[0];e.addRelation({from:r.id,to:l.id,kind:"depends-on",trust:"authoritative",derivation:"authored",confidence:"high",proofIds:r.proofIds});let m=E("module",`dependency:${c}:${ne(a)}`);e.relations.delete(E("relation",`${r.id}\0depends-on\0${m}`));}}for(let r of [...e.entities.values()]){if(r.kind!=="module"||r.projectId)continue;[...e.relations.values()].some(s=>s.from===r.id||s.to===r.id)||e.entities.delete(r.id);}}var at={id:"workspace-foundation",version:"1.0.0",async run(e){let{state:t}=e,o=await t.addProof({provider:this.id,artifact:i.workspaceContract,absolutePath:p.join(e.workspacePath,".workspai","workspace.contract.json"),trust:"authoritative",derivation:"authored",detail:"Workspace identity and project registry boundary"}),i$1=t.addEntity({kind:"workspace",key:`workspace:${t.workspaceName}`,label:t.workspaceName,aliases:[t.workspaceName],proofIds:[o]});for(let r of e.projects){let c=e.filesByProject.get(r.id)??[],s=c.find(v=>/[\\/]\.(?:workspai|rapidkit)[\\/](?:project|context)\.json$/.test(v)),a=c.find(v=>fe.has(p.basename(v))),n=s??a,d=await t.addProof({provider:this.id,artifact:n?t.artifactPath(n,r):x(p.posix.join(r.artifactPrefix,".workspai/project.json")),...n?{absolutePath:n}:{},trust:s?"authoritative":"observed",derivation:s?"authored":"inferred",detail:`Project ${r.id}`}),l=t.addEntity({kind:"project",key:`project:${r.id}`,label:r.id,projectId:r.id,aliases:[r.id,r.path],attributes:{path:r.path,runtime:r.runtime,runtimeCandidates:r.runtimeCandidates,framework:r.framework,kit:r.kit,kind:r.kind,category:r.category},proofIds:[d]});t.addRelation({from:i$1,to:l,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[d]});let m=new Set,u=[];for(let v of c){let g=p.basename(v);if(/^(?:\.env\.example|\.env\.sample|\.env\.template)$/i.test(g))try{let P=await S.readFile(v,"utf8");for(let f of P.split(/\r?\n/)){let y=f.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[1];y&&m.add(y);}}catch{}let w=se(r.root,v);if(w&&u.push(v),!(w||ie(r.root,v))&&!(!fe.has(g)&&!/\.(?:cs|fs|vb)proj$/i.test(g)))try{let P=await S.readFile(v,"utf8"),f=it(v,P),y=await t.addProof({provider:this.id,artifact:t.artifactPath(v,r),absolutePath:v,pointer:"/",confidence:f.name?"high":"medium",detail:`${f.ecosystem} manifest`}),$=t.addEntity({kind:"package",key:`package:${r.id}:${f.ecosystem}:${f.name??t.artifactPath(v,r)}`,label:f.name??`${r.id}/${O(p.relative(r.root,v))}`,projectId:r.id,aliases:[g,...f.name?[f.name]:[]],attributes:{ecosystem:f.ecosystem,version:f.version,manifest:t.artifactPath(v,r),dependencies:f.dependencies,...f.metadata??{}},proofIds:[y]});t.addRelation({from:l,to:$,kind:"contains",proofIds:[y]});for(let k of f.dependencies.slice(0,500)){let C=t.addEntity({kind:"module",key:`dependency:${f.ecosystem}:${k}`,label:k,aliases:[k],attributes:{ecosystem:f.ecosystem,external:true},proofIds:[y]});t.addRelation({from:$,to:C,kind:"depends-on",trust:"authoritative",derivation:"authored",proofIds:[y]});}}catch{}}if(nt(t,r.id),m.size>0){let v=c.find(g=>/^\.env\.(?:example|sample|template)$/i.test(p.basename(g)));if(v){let g=await t.addProof({provider:this.id,artifact:t.artifactPath(v,r),absolutePath:v,detail:"Public environment template keys only; values are intentionally excluded"}),w=t.addEntity({kind:"environment",key:`environment:${r.id}:template`,label:`${r.id} environment contract`,projectId:r.id,attributes:{keys:[...m].sort(),valuesEmitted:false},proofIds:[g]});t.addRelation({from:l,to:w,kind:"configured-by",proofIds:[g]});}}if(u.length>0){let v=await t.addProof({provider:this.id,artifact:t.artifactPath(u[0],r),absolutePath:u[0],detail:`${u.length} test file(s) discovered`}),g=t.addEntity({kind:"test-suite",key:`tests:${r.id}`,label:`${r.id} tests`,projectId:r.id,attributes:{fileCount:u.length},proofIds:[v]});t.addRelation({from:g,to:l,kind:"tests",proofIds:[v]});let w=new Map;for(let P of u){if(!T.has(p.extname(P).toLowerCase()))continue;let f=F(P,r.runtime),y=w.get(f)??[];y.push(P),w.set(f,y);}for(let[P,f]of [...w].sort(([y],[$])=>y.localeCompare($))){let y=await t.addProof({provider:this.id,artifact:t.artifactPath(f[0],r),absolutePath:f[0],detail:`${f.length} ${P} test source file(s) discovered`}),$=t.addEntity({kind:"test-suite",key:`tests:${r.id}:${P}`,label:`${r.id} ${P} tests`,projectId:r.id,attributes:{fileCount:f.length,language:P},proofIds:[y]});t.addRelation({from:$,to:l,kind:"tests",proofIds:[y]});}}}}};function te(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ct(e){if(Array.isArray(e))return e.length;let t=j(e);return t?Object.keys(t).length:0}var dt={id:"vscode-extension-manifest",version:"1.0.0",async applicable(e){for(let t of e.projects){let o=p.join(t.root,"package.json");try{let i=j(await S.readJson(o));if(b(j(i?.engines)?.vscode)||j(i?.contributes))return true}catch{}}return false},async run(e){for(let t of e.projects){let o=p.join(t.root,"package.json"),i=null;try{i=j(await S.readJson(o));}catch{continue}let r=j(i?.contributes),c=b(j(i?.engines)?.vscode);if(!c&&!r)continue;let s=e.state.artifactPath(o,t),a=await e.state.addProof({provider:this.id,artifact:s,absolutePath:o,pointer:"/",trust:"authoritative",derivation:"authored",confidence:"high",detail:`VS Code extension manifest for ${t.id}`}),n=e.state.addEntity({kind:"project",key:`project:${t.id}`,label:t.id,projectId:t.id,attributes:{vscodeExtension:true,vscodeEngine:c,extensionEntry:b(i?.main)??b(i?.browser),extensionKind:K(i?.extensionKind),activationEvents:K(i?.activationEvents),contributionCounts:Object.entries(r??{}).map(([y,$])=>`${y}:${ct($)}`).sort()},proofIds:[a]}),d=Array.isArray(r?.commands)?r.commands:[],l=j(r?.menus),m=Object.values(l??{}).flatMap(y=>Array.isArray(y)?y:[]),u=Array.isArray(r?.keybindings)?r.keybindings:[];for(let[y,$]of d.entries()){let k=j($),C=b(k?.command);if(!C)continue;let R=`/contributes/commands/${y}`,h=await e.state.addProof({provider:this.id,artifact:s,absolutePath:o,pointer:R,trust:"authoritative",derivation:"authored",confidence:"high",detail:`VS Code command ${C}`}),I=m.filter(W=>b(j(W)?.command)===C).length,A=u.filter(W=>b(j(W)?.command)===C).length,_=e.state.addEntity({kind:"api",key:`vscode-command:${t.id}:${C}`,label:C,projectId:t.id,aliases:[b(k?.title),b(k?.shortTitle)].filter(W=>!!W),attributes:{surface:"vscode-command",title:b(k?.title),shortTitle:b(k?.shortTitle),category:b(k?.category),enablement:b(k?.enablement),icon:b(k?.icon),menuCount:I,keybindingCount:A,manifest:s,pointer:R},proofIds:[h]});e.state.addRelation({from:n,to:_,kind:"exposes",trust:"authoritative",derivation:"authored",confidence:"high",proofIds:[h]});}let v=j(r?.viewsContainers),g=new Map;for(let[y,$]of Object.entries(v??{}))if(Array.isArray($))for(let[k,C]of $.entries()){let R=j(C),h=b(R?.id);if(!h)continue;let I=`/contributes/viewsContainers/${te(y)}/${k}`,A=await e.state.addProof({provider:this.id,artifact:s,absolutePath:o,pointer:I,trust:"authoritative",derivation:"authored",detail:`VS Code view container ${h}`}),_=e.state.addEntity({kind:"service",key:`vscode-view-container:${t.id}:${h}`,label:h,projectId:t.id,aliases:[b(R?.title)].filter(W=>!!W),attributes:{surface:"vscode-view-container",title:b(R?.title),location:y,icon:b(R?.icon),manifest:s,pointer:I},proofIds:[A]});g.set(h,_),e.state.addRelation({from:n,to:_,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[A]});}let w=j(r?.views);for(let[y,$]of Object.entries(w??{}))if(Array.isArray($))for(let[k,C]of $.entries()){let R=j(C),h=b(R?.id);if(!h)continue;let I=`/contributes/views/${te(y)}/${k}`,A=await e.state.addProof({provider:this.id,artifact:s,absolutePath:o,pointer:I,trust:"authoritative",derivation:"authored",detail:`VS Code view ${h}`}),_=e.state.addEntity({kind:"service",key:`vscode-view:${t.id}:${h}`,label:h,projectId:t.id,aliases:[b(R?.name),b(R?.contextualTitle)].filter(W=>!!W),attributes:{surface:R?.type==="webview"?"vscode-webview":"vscode-view",name:b(R?.name),contextualTitle:b(R?.contextualTitle),containerId:y,viewType:b(R?.type)??"tree",manifest:s,pointer:I},proofIds:[A]});e.state.addRelation({from:g.get(y)??n,to:_,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[A]});}let P=Array.isArray(r?.configuration)?r.configuration:r?.configuration?[r.configuration]:[];for(let[y,$]of P.entries()){let k=j($),C=j(k?.properties);for(let[R,h]of Object.entries(C??{})){let I=j(h),_=`${Array.isArray(r?.configuration)?`/contributes/configuration/${y}`:"/contributes/configuration"}/properties/${te(R)}`,W=await e.state.addProof({provider:this.id,artifact:s,absolutePath:o,pointer:_,trust:"authoritative",derivation:"authored",detail:`VS Code configuration ${R}`}),L=e.state.addEntity({kind:"schema",key:`vscode-configuration:${t.id}:${R}`,label:R,projectId:t.id,attributes:{surface:"vscode-configuration",title:b(k?.title),type:b(I?.type),scope:b(I?.scope),description:b(I?.description)??b(I?.markdownDescription),manifest:s,pointer:_},proofIds:[W]});e.state.addRelation({from:n,to:L,kind:"configured-by",trust:"authoritative",derivation:"authored",proofIds:[W]});}}let f=Array.isArray(r?.chatParticipants)?r.chatParticipants:[];for(let[y,$]of f.entries()){let k=j($),C=b(k?.id);if(!C)continue;let R=`/contributes/chatParticipants/${y}`,h=await e.state.addProof({provider:this.id,artifact:s,absolutePath:o,pointer:R,trust:"authoritative",derivation:"authored",detail:`VS Code chat participant ${C}`}),I=e.state.addEntity({kind:"api",key:`vscode-chat-participant:${t.id}:${C}`,label:C,projectId:t.id,aliases:[b(k?.name),b(k?.fullName)].filter(A=>!!A),attributes:{surface:"vscode-chat-participant",name:b(k?.name),fullName:b(k?.fullName),description:b(k?.description),manifest:s,pointer:R},proofIds:[h]});e.state.addRelation({from:n,to:I,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[h]});}}}};function Ee(e,t){let o=[],i=false;for(let r of e.split(/\r?\n/)){let c=r.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/)?.[1]?.trim();if(c){i=c===t;continue}if(!i||/^\s*(?:#|$)/.test(r))continue;let s=r.match(/^\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_.-]+))\s*=\s*["']([^"']+)["']/),a=s?.[1]??s?.[2]??s?.[3],n=s?.[4];a&&n&&o.push([a,n]);}return o}var lt={id:"python-project-manifest",version:"1.0.0",async applicable(e){for(let t of e.projects){let o=(e.filesByProject.get(t.id)??[]).find(i=>p.dirname(i)===t.root&&p.basename(i).toLowerCase()==="pyproject.toml");if(o)try{if(Ee(await S.readFile(o,"utf8"),"project.scripts").length>0)return true}catch{}}return false},async run(e){for(let t of e.projects){let o=(e.filesByProject.get(t.id)??[]).find(n=>p.dirname(n)===t.root&&p.basename(n).toLowerCase()==="pyproject.toml");if(!o)continue;let i=await S.readFile(o,"utf8"),r=Ee(i,"project.scripts"),c=e.state.artifactPath(o,t),s=await e.state.addProof({provider:this.id,artifact:c,absolutePath:o,pointer:"/project",trust:"authoritative",derivation:"authored",detail:"Python project manifest"}),a=e.state.addEntity({kind:"project",key:`project:${t.id}`,label:t.id,projectId:t.id,attributes:{pythonProject:true,requiresPython:i.match(/^requires-python\s*=\s*["']([^"']+)["']/m)?.[1],buildBackend:i.match(/^build-backend\s*=\s*["']([^"']+)["']/m)?.[1],consoleScriptCount:r.length},proofIds:[s]});for(let[n,d]of r){let l=`/project/scripts/${n}`,m=await e.state.addProof({provider:this.id,artifact:c,absolutePath:o,pointer:l,trust:"authoritative",derivation:"authored",detail:`Python console script ${n}`}),u=e.state.addEntity({kind:"api",key:`python-console-script:${t.id}:${n}`,label:n,projectId:t.id,aliases:[d],attributes:{surface:"python-console-script",entrypoint:d,manifest:c,pointer:l},proofIds:[m]});e.state.addRelation({from:a,to:u,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[m]});}}}},pt={id:"source-language-inventory",version:"1.0.0",applicable(e){return e.projects.some(t=>(e.semanticFilesByProject.get(t.id)??[]).some(o=>T.has(p.extname(o).toLowerCase())))},async run(e){for(let t of e.projects){let o=e.semanticFilesByProject.get(t.id)??[],i=o.filter(s=>T.has(p.extname(s).toLowerCase())),r=new Map;for(let s of i){let a=F(s,t.runtime),n=r.get(a)??{files:[],production:[],tests:[],examples:[],generated:[],extensions:new Set};n.files.push(s),n.extensions.add(p.extname(s).toLowerCase()),oe(t.root,s)&&n.generated.push(s),se(t.root,s)?n.tests.push(s):ie(t.root,s)?n.examples.push(s):n.production.push(s),r.set(a,n);}let c=E("project",`project:${t.id}`);for(let[s,a]of [...r].sort(([n],[d])=>n.localeCompare(d))){let n=[a.production[0],a.tests[0],a.examples[0],a.generated[0],a.files[0]].filter((u,v,g)=>!!u&&g.indexOf(u)===v),d=await Promise.all(n.map(u=>e.state.addProof({provider:this.id,artifact:e.state.artifactPath(u,t),absolutePath:u,derivation:"extracted",trust:"observed",confidence:"high",detail:`${s} source-language inventory evidence`}))),l=[...a.production.length>0?["production"]:[],...a.tests.length>0?["test"]:[],...a.examples.length>0?["example"]:[],...a.generated.length>0?["generated"]:[]],m=e.state.addEntity({kind:"language",key:`language:${t.id}:${s}`,label:`${t.id} programming language: ${s}`,projectId:t.id,aliases:[s,`${s} source`,`${s} programming language`,"programming languages actually used"],attributes:{language:s,usage:"source-build-test",roles:l,fileCount:a.files.length,productionFileCount:a.production.length,testFileCount:a.tests.length,exampleFileCount:a.examples.length,generatedFileCount:a.generated.length,extensions:[...a.extensions].sort(),inventoryTruncated:o.length>=e.semanticScanLimit},proofIds:d});e.state.addRelation({from:c,to:m,kind:"uses-language",derivation:"extracted",trust:"observed",confidence:o.length>=e.semanticScanLimit?"medium":"high",proofIds:d});}o.length>=e.semanticScanLimit&&e.state.diagnostics.push({code:"graph.provider.source_language_inventory.limit_reached",severity:"warning",message:`Language inventory for ${t.id} reached ${e.semanticScanLimit} files. Counts are lower bounds.`,recommendation:"Increase maxFilesPerProject or use a scoped project run before treating language counts as complete."});}}},ft={id:"source-structure",version:"1.0.0",applicable(e){return e.projects.some(t=>(e.filesByProject.get(t.id)??[]).some(o=>T.has(p.extname(o).toLowerCase())&&!M(t.root,o)))},async run(e){for(let t of e.projects){let o=(e.filesByProject.get(t.id)??[]).filter(d=>!M(t.root,d)),i=e.semanticFilesByProject.get(t.id)??o,r=Ge((e.filesByProject.get(t.id)??[]).filter(d=>T.has(p.extname(d).toLowerCase())&&!M(t.root,d)),1e3),c=new Set(i.filter(d=>!M(t.root,d)).map(d=>p.resolve(d))),s=new Map;await Promise.all(o.map(async d=>{try{let l=await S.stat(d);if(l.isFile()&&l.size<=2*1024*1024){let m=p.resolve(d);c.add(m),s.set(m,l.size);}}catch{}}));let a=0,n=0;for(let d of r){let l;try{if((await S.stat(d)).size>2*1024*1024)continue;l=await S.readFile(d,"utf8");}catch{continue}let m=Ue(d,l),u=e.state.artifactPath(d,t),v=await e.state.addProof({provider:this.id,artifact:u,absolutePath:d,derivation:"extracted",trust:"observed",confidence:"high",detail:`${F(d,t.runtime)} source file`}),g=e.state.addEntity({kind:"file",key:`file:${t.id}:${u}`,label:u,projectId:t.id,aliases:[p.basename(d)],attributes:{artifact:u,language:F(d,t.runtime),bytes:Buffer.byteLength(l),...oe(t.root,d)?{generated:true}:{}},proofIds:[v]});e.state.addRelation({from:E("project",`project:${t.id}`),to:g,kind:"contains",proofIds:[v]});let w=Q(m,qe,250);for(let f of w){let y=await e.state.addProof({provider:this.id,artifact:u,absolutePath:d,line:f.line,derivation:"extracted",trust:"observed",confidence:"medium",detail:`${f.detail}: ${f.name}`}),$=Ze(d,f.name,c,t.root);if($){let k=e.state.artifactPath($,t),C=E("file",`file:${t.id}:${k}`);if(!e.state.entities.has(C)){let R=await S.stat($).catch(()=>null),h=await e.state.addProof({provider:this.id,artifact:k,...R?.isFile()&&R.size<=2*1024*1024?{absolutePath:$}:{},derivation:"extracted",trust:"observed",confidence:"high",detail:"Locally imported artifact resolved from the project inventory"}),I=e.state.addEntity({kind:"file",key:`file:${t.id}:${k}`,label:k,projectId:t.id,aliases:[p.basename($)],attributes:{artifact:k,language:F($,t.runtime),bytes:s.get(p.resolve($))??(R?.isFile()?R.size:void 0)},proofIds:[h]});e.state.addRelation({from:E("project",`project:${t.id}`),to:I,kind:"contains",proofIds:[h]});}e.state.addRelation({from:g,to:C,kind:"imports",confidence:"high",proofIds:[y]});}else {let k=f.name.startsWith(".");k&&(n+=1);let C=e.state.addEntity({kind:"module",key:`module:${t.id}:${f.name}`,label:f.name,projectId:t.id,aliases:[f.name],attributes:{specifier:f.name,resolution:k?"unresolved-local":"external"},proofIds:[y]});e.state.addRelation({from:g,to:C,kind:"imports",confidence:k?"low":"medium",proofIds:[y]});}}if(a<1e4){let f=Q(m,xe,Math.min(100,1e4-a));a+=f.length;for(let y of f){let $=await e.state.addProof({provider:this.id,artifact:u,absolutePath:d,line:y.line,derivation:"extracted",trust:"observed",confidence:"medium",detail:`${y.detail}: ${y.name}`}),k=e.state.addEntity({kind:"symbol",key:`symbol:${t.id}:${u}:${y.detail}:${y.name}`,label:y.name,projectId:t.id,attributes:{symbolKind:y.detail,language:F(d,t.runtime),...oe(t.root,d)?{generated:true}:{}},proofIds:[$]});e.state.addRelation({from:g,to:k,kind:"defines",confidence:"medium",proofIds:[$]});}}let P=t.framework!=="vscode-extension"&&t.kind!=="extension";for(let f of P?Q(m,Ye,100):[]){let y=l.split(/\r?\n/)[f.line-1]??"";if(He(d,y))continue;let $=y.match(/(?:@|\.|\[|^\s*)(get|post|put|delete|patch|options|head)/i)?.[1]?.toUpperCase()??"HTTP",k=await e.state.addProof({provider:this.id,artifact:u,absolutePath:d,line:f.line,derivation:"extracted",trust:"observed",confidence:"medium",detail:`${$} ${f.name}`}),C=e.state.addEntity({kind:"endpoint",key:`source-endpoint:${t.id}:${u}:${$}:${f.name}`,label:`${$} ${f.name||"/"}`,projectId:t.id,attributes:{method:$,path:f.name||"/",source:u},proofIds:[k]});e.state.addRelation({from:g,to:C,kind:"defines",confidence:"medium",proofIds:[k]});}}(r.length>=1e3||a>=1e4)&&e.state.diagnostics.push({code:"graph.provider.source_structure.limit_reached",severity:"info",message:`Source extraction for ${t.id} sampled ${r.length} file(s) from ${o.length} indexed candidate(s).`,recommendation:"Use bounded graph search, evidence, and path queries for proof-backed retrieval; do not treat the sampled symbol inventory as exhaustive."}),n>0&&e.state.diagnostics.push({code:"graph.provider.source_structure.unresolved_local_imports",severity:"warning",message:`${n} local import(s) in ${t.id} could not be resolved to an indexed source file.`,recommendation:"Check path aliases, generated sources, extension mapping, or provider limits before treating the import graph as complete."});}}};function ut(e){let o=e.slice(0,12e3).match(/(?:code generated by|generated from:|@generated by)\s*(?:(?:\/\/|#|\*)\s*)?[`"']?([^`"'\s;*]+)/i)?.[1];return !o||!p.posix.basename(o.replace(/\\/g,"/"))?null:o}function mt(e,t){let o=0,i=null,r=false;for(let c=t;c<e.length;c+=1){let s=e[c];if(i){s===i&&!r&&(i=null),r=s==="\\"&&!r,s!=="\\"&&(r=false);continue}if(s==='"'){i=s;continue}if(s==="("&&(o+=1),s===")"&&(o-=1,o===0))return e.slice(t+1,c)}return null}function gt(e){let t=[],o=/(?:deno_core::)?extension!\s*\(/g;for(let i of e.matchAll(o)){let r=(i.index??0)+i[0].lastIndexOf("("),c=mt(e,r);if(!c)continue;let s=c.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*,/)?.[1];if(!s)continue;let a=[...new Set([...c.matchAll(/\bops\s*=\s*\[([\s\S]*?)\]/g)].flatMap(d=>[...d[1].matchAll(/\b(op_[A-Za-z0-9_]+)\b/g)].map(l=>l[1])))].sort(),n=[...new Set([...c.matchAll(/\b(?:esm|js|lazy_loaded_esm|lazy_loaded_js)\s*=\s*\[([\s\S]*?)\]/g)].flatMap(d=>[...d[1].matchAll(/["']([^"']+\.(?:[cm]?[jt]s|tsx?|jsx?))["']/g)].map(l=>l[1])))].sort();t.push({name:s,line:e.slice(0,i.index??0).split(/\r?\n/).length,operations:a,scripts:n});}return t}function Ce(e,t){let o=e.indexOf(t);return o<0?void 0:e.slice(0,o).split(/\r?\n/).length}var ht={id:"runtime-bridge-semantics",version:"1.0.0",async applicable(e){for(let t of e.projects)for(let o of e.semanticFilesByProject.get(t.id)??[])if(!(p.extname(o).toLowerCase()!==".rs"||M(t.root,o)))try{let i=await S.readFile(o,"utf8");if(/(?:deno_core::)?extension!\s*\(/.test(i))return true}catch{}return false},async run(e){for(let t of e.projects){let i=(e.semanticFilesByProject.get(t.id)??[]).filter(r=>p.extname(r).toLowerCase()===".rs"&&!M(t.root,r));for(let r of i){let c="";try{if((await S.stat(r)).size>2*1024*1024)continue;c=await S.readFile(r,"utf8");}catch{continue}let s=gt(c);if(s.length===0)continue;let a=e.state.artifactPath(r,t),n=await e.state.addProof({provider:this.id,artifact:a,absolutePath:r,derivation:"extracted",trust:"observed",confidence:"high",detail:"Deno Core Rust extension declaration"}),d=e.state.addEntity({kind:"file",key:`file:${t.id}:${a}`,label:a,projectId:t.id,aliases:[p.basename(r)],attributes:{artifact:a,language:"rust",runtimeBridge:"deno-core"},proofIds:[n]});e.state.addRelation({from:E("project",`project:${t.id}`),to:d,kind:"contains",proofIds:[n]});for(let l of s){let m=await e.state.addProof({provider:this.id,artifact:a,absolutePath:r,line:l.line,derivation:"extracted",trust:"observed",confidence:"high",detail:`Deno Core extension ${l.name}`}),u=e.state.addEntity({kind:"protocol",key:`runtime-bridge:${t.id}:deno-core:${a}:${l.name}`,label:`${l.name} Rust JavaScript runtime bridge`,projectId:t.id,aliases:[l.name,`${l.name} cross-language bridge`,"Rust JavaScript TypeScript bridge"],attributes:{mechanism:"deno_core::extension!",languages:["javascript","rust","typescript"]},proofIds:[m]});e.state.addRelation({from:E("project",`project:${t.id}`),to:u,kind:"contains",proofIds:[m]}),e.state.addRelation({from:d,to:u,kind:"implements-protocol",proofIds:[m]});for(let g of ["rust","javascript","typescript"]){let w=E("language",`language:${t.id}:${g}`);e.state.entities.has(w)&&e.state.addRelation({from:u,to:w,kind:"uses-language",proofIds:[m]});}let v=new Map;for(let g of l.operations){let w=Ce(c,g),P=await e.state.addProof({provider:this.id,artifact:a,absolutePath:r,...w?{line:w}:{},derivation:"extracted",trust:"observed",confidence:"high",detail:`Rust op2 bridge operation ${g}`}),f=e.state.addEntity({kind:"symbol",key:`symbol:${t.id}:${a}:function:${g}`,label:g,projectId:t.id,aliases:[`rust:${g}`,`javascript:${g}`],attributes:{symbolKind:"function",language:"rust",bridgeMechanism:"op2"},proofIds:[P]});v.set(g,f),e.state.addRelation({from:d,to:f,kind:"defines",proofIds:[P]}),e.state.addRelation({from:f,to:u,kind:"implements-protocol",proofIds:[P,m]});}for(let g of l.scripts){let w=p.resolve(p.dirname(r),g);if(!await S.pathExists(w))continue;let P="";try{P=await S.readFile(w,"utf8");}catch{continue}let f=e.state.artifactPath(w,t),y=await e.state.addProof({provider:this.id,artifact:f,absolutePath:w,derivation:"extracted",trust:"observed",confidence:"high",detail:`${l.name} JavaScript/TypeScript extension source`}),$=e.state.addEntity({kind:"file",key:`file:${t.id}:${f}`,label:f,projectId:t.id,aliases:[p.basename(w)],attributes:{artifact:f,language:F(w,t.runtime),runtimeBridge:"deno-core"},proofIds:[y]});e.state.addRelation({from:d,to:$,kind:"references",confidence:"high",proofIds:[m,y]}),e.state.addRelation({from:$,to:u,kind:"implements-protocol",proofIds:[y,m]});for(let[k,C]of v){let R=Ce(P,k);if(!R)continue;let h=await e.state.addProof({provider:this.id,artifact:f,absolutePath:w,line:R,derivation:"extracted",trust:"observed",confidence:"high",detail:`JavaScript/TypeScript call to Rust operation ${k}`});e.state.addRelation({from:$,to:C,kind:"calls",confidence:"high",proofIds:[h,m]});}}}}}}},yt=/^[A-Z][A-Za-z0-9_]{3,}$/,vt=new Set(["Client","Config","Context","Data","Error","Event","Message","Options","Request","Response","Result","Schema","Type","Value"]),kt={id:"polyglot-semantics",version:"1.0.0",applicable(e){return e.projects.some(t=>(t.runtimeCandidates?.length??0)>1||a$1(t.root).polyglot)},async run(e){for(let t of e.projects){let o=E("project",`project:${t.id}`),i=e.filesByProject.get(t.id)??[],r=a$1(t.root),c=[...e.state.entities.values()].filter(n=>n.kind==="package"&&n.projectId===t.id);for(let n of r.units){let d=n.runtime,l=p.resolve(t.root,n.manifest),m=e.state.artifactPath(l,t),u=c.find(f=>f.attributes.manifest===m),v=u?.proofIds??[await e.state.addProof({provider:this.id,artifact:m,absolutePath:l,derivation:"extracted",trust:"observed",confidence:"high",detail:`${d} runtime-unit manifest`})],g=e.state.artifactPath(p.dirname(l),t),w=Object.fromEntries(n.stages.map(f=>[f.stage,f.command])),P=e.state.addEntity({kind:"runtime-unit",key:`runtime-unit:${t.id}:${d}:${m}`,label:`${d}:${g}:${p.basename(l)}`,projectId:t.id,aliases:[d,g],attributes:{runtime:d,root:g,ecosystem:n.ecosystem,role:n.role,manifest:m,stages:Object.keys(w).sort(),orchestrationMode:"native-manifest"},proofIds:v});e.state.addRelation({from:o,to:P,kind:"contains",confidence:"high",proofIds:v}),u&&e.state.addRelation({from:P,to:u.id,kind:"configured-by",confidence:"high",proofIds:v});for(let f of n.stages){let{stage:y,command:$}=f,k=e.state.addEntity({kind:"lifecycle-stage",key:`lifecycle-stage:${t.id}:${d}:${m}:${y}`,label:`${y} \xB7 ${d}:${g}:${p.basename(l)}`,projectId:t.id,aliases:[`${d}:${y}`,y],attributes:{stage:y,command:$,runtime:d,workingDirectory:g,commandConfidence:f.confidence,preflight:f.preflight},proofIds:v});e.state.addRelation({from:P,to:k,kind:"contains",confidence:"high",proofIds:v});}}for(let n of i.filter(d=>T.has(p.extname(d).toLowerCase()))){let d="";try{d=await S.readFile(n,"utf8");}catch{continue}let l=ut(d);if(!l)continue;let m=e.state.artifactPath(n,t),u=E("file",`file:${t.id}:${m}`);if(!e.state.entities.has(u))continue;let v=await e.state.addProof({provider:this.id,artifact:m,absolutePath:n,line:1,derivation:"extracted",trust:"observed",confidence:"high",detail:`Generated from ${l}`}),g=e.state.entities.get(u);g&&e.state.addEntity({kind:"file",key:g.identity.key,label:g.label,projectId:t.id,aliases:g.identity.aliases,attributes:{...g.attributes,generated:true},proofIds:[...g.proofIds,v]});let w=[...e.state.relations.values()].filter(k=>k.kind==="defines"&&k.from===u).map(k=>e.state.entities.get(k.to)).filter(k=>k?.kind==="symbol");for(let k of w)e.state.addEntity({kind:"symbol",key:k.identity.key,label:k.label,projectId:t.id,aliases:k.identity.aliases,attributes:{...k.attributes,generated:true},proofIds:[...k.proofIds,v]});let P=l.replace(/^\.\//,"").replace(/[.,:]$/,""),y=[p.resolve(t.root,P),p.resolve(p.dirname(n),P)].find(k=>i.includes(k));if(y){let k=e.state.artifactPath(y,t),C=E("file",`file:${t.id}:${k}`);if(e.state.entities.has(C)){e.state.addRelation({from:u,to:C,kind:"generated-by",derivation:"extracted",trust:"observed",confidence:"high",proofIds:[v]});continue}}let $=e.state.addEntity({kind:"schema",key:`generation-source:${t.id}:${P}`,label:p.posix.basename(P),projectId:t.id,aliases:[P],attributes:{sourceReference:P,discoveredFromGeneratedHeader:true},proofIds:[v]});e.state.addRelation({from:u,to:$,kind:"generated-from",derivation:"extracted",trust:"observed",confidence:"medium",proofIds:[v]});}let s=[...e.state.entities.values()].filter(n=>n.projectId===t.id&&n.kind==="symbol"&&n.attributes.generated===true&&n.attributes.symbolKind==="type"&&typeof n.attributes.language=="string"&&yt.test(n.label)&&!vt.has(n.label)),a=new Map;for(let n of s){let d=a.get(n.label)??[];d.push(n),a.set(n.label,d);}for(let[n,d]of [...a.entries()].filter(([,l])=>new Set(l.map(m=>m.attributes.language)).size>1).sort(([l],[m])=>l.localeCompare(m)).slice(0,1e3)){let l=d.sort((w,P)=>String(w.attributes.language).localeCompare(String(P.attributes.language))||w.id.localeCompare(P.id)),m=[...new Set(l.map(w=>String(w.attributes.language)))],u=[...new Set(l.flatMap(w=>w.proofIds))],v=e.state.addEntity({kind:"protocol",key:`protocol:${t.id}:${n}`,label:n,projectId:t.id,aliases:m.map(w=>`${w}:${n}`),attributes:{languages:m,implementationCount:l.length,source:"generated-types"},proofIds:u});for(let w of l)e.state.addRelation({from:w.id,to:v,kind:"implements-protocol",derivation:"inferred",trust:"corroborated",confidence:"high",proofIds:w.proofIds});let g=l[0];for(let w of l.slice(1))e.state.addRelation({from:w.id,to:g.id,kind:"equivalent-to",derivation:"inferred",trust:"corroborated",confidence:"high",proofIds:[...g.proofIds,...w.proofIds]});}}}},bt={id:"workspace-service-contract",version:"1.0.0",applicable(e){return !!e.contract?.projects.some(t=>t.ports.length>0||t.contracts.owns.length>0||t.contracts.apis.length>0||t.contracts.publishes.length>0||t.contracts.consumes.length>0||t.contracts.env.length>0)},async run(e){if(!e.contract)return;let t=new Map;for(let o of [...e.contract.projects].sort((i,r)=>i.slug.localeCompare(r.slug))){let i$1=o.contracts;if(o.ports.length===0&&i$1.owns.length===0&&i$1.apis.length===0&&i$1.publishes.length===0&&i$1.consumes.length===0&&i$1.env.length===0)continue;let r=await e.state.addProof({provider:this.id,artifact:i.workspaceContract,absolutePath:p.join(e.workspacePath,".workspai","workspace.contract.json"),pointer:`/projects/${o.slug}/contracts`,trust:"authoritative",derivation:"authored",detail:`Service contract for ${o.slug}`}),c=E("project",`project:${o.slug}`),s=e.state.addEntity({kind:"service",key:`contract-service:${o.slug}`,label:o.slug,projectId:o.slug,attributes:{ports:o.ports.map(a=>`${a.protocol}:${a.port}`),owns:[...i$1.owns].sort(),environmentKeys:[...i$1.env].sort()},proofIds:[r]});e.state.addRelation({from:c,to:s,kind:"implements",trust:"authoritative",derivation:"authored",proofIds:[r]});for(let a of [...i$1.apis].sort((n,d)=>n.name.localeCompare(d.name))){let n=e.state.addEntity({kind:"api",key:`contract-api:${o.slug}:${a.name}:${a.basePath}`,label:a.name,projectId:o.slug,attributes:{basePath:a.basePath},proofIds:[r]});e.state.addRelation({from:s,to:n,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[r]});}for(let a of [...i$1.publishes,...i$1.consumes].sort())t.has(a)||t.set(a,e.state.addEntity({kind:"queue",key:`event:${a}`,label:a,attributes:{protocol:"workspace-event"},proofIds:[r]}));for(let a of [...i$1.publishes].sort()){let n=t.get(a);n&&e.state.addRelation({from:s,to:n,kind:"publishes",trust:"authoritative",derivation:"authored",proofIds:[r]});}for(let a of [...i$1.consumes].sort()){let n=t.get(a);n&&e.state.addRelation({from:s,to:n,kind:"consumes",trust:"authoritative",derivation:"authored",proofIds:[r]});}}}},wt={id:"openapi",version:"1.0.0",applicable(e){return e.projects.some(t=>(e.filesByProject.get(t.id)??[]).some(me))},async run(e){for(let t of e.projects){let o=(e.filesByProject.get(t.id)??[]).filter(me);for(let i of o){let r;try{r=await B(i);}catch(c){e.state.diagnostics.push({code:"graph.provider.openapi.parse_failed",severity:"warning",message:`Could not parse ${e.state.artifactPath(i,t)}: ${c instanceof Error?c.message:String(c)}`});continue}for(let c of r){if(!("openapi"in c)&&!("swagger"in c))continue;let s=j(c.info),a=b(s?.title)??`${t.id} API`,n=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(i,t),absolutePath:i,pointer:"/info",trust:"authoritative",detail:"Authored OpenAPI contract"}),d=E("project",`project:${t.id}`),l=e.state.addEntity({kind:"api",key:`api:${t.id}:${a}`,label:a,projectId:t.id,attributes:{version:b(s?.version),specification:b(c.openapi)??b(c.swagger)},proofIds:[n]});e.state.addRelation({from:d,to:l,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[n]});let m=j(j(c.components)?.schemas)??j(c.definitions),u=new Map;for(let g of Object.keys(m??{}).sort()){let w=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(i,t),absolutePath:i,pointer:`/components/schemas/${g}`,trust:"authoritative",detail:`OpenAPI schema ${g}`}),P=e.state.addEntity({kind:"schema",key:`schema:${t.id}:${a}:${g}`,label:g,projectId:t.id,proofIds:[w]});u.set(g,P),e.state.addRelation({from:l,to:P,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[w]});}let v=j(c.paths);for(let g of Object.keys(v??{}).sort()){let w=j(v?.[g]);for(let P of Object.keys(w??{}).filter(f=>Be.has(f.toLowerCase())).sort()){let f=j(w?.[P]),y=`/paths/${g.replace(/~/g,"~0").replace(/\//g,"~1")}/${P}`,$=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(i,t),absolutePath:i,pointer:y,trust:"authoritative",detail:`${P.toUpperCase()} ${g}`}),k=e.state.addEntity({kind:"endpoint",key:`endpoint:${t.id}:${a}:${P.toUpperCase()}:${g}`,label:`${P.toUpperCase()} ${g}`,projectId:t.id,aliases:K(f?.tags),attributes:{method:P.toUpperCase(),path:g,operationId:b(f?.operationId),deprecated:typeof f?.deprecated=="boolean"?f.deprecated:void 0,tags:K(f?.tags)},proofIds:[$]});e.state.addRelation({from:l,to:k,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[$]});let C=JSON.stringify(f??{});for(let[R,h]of u)C.includes(`/${R}`)&&e.state.addRelation({from:k,to:h,kind:"references",trust:"authoritative",derivation:"authored",proofIds:[$]});}}}}}}},Pt={id:"interface-contracts",version:"1.0.0",applicable(e){return e.projects.some(t=>(e.filesByProject.get(t.id)??[]).some(ge))},async run(e){for(let t of e.projects){let o=(e.filesByProject.get(t.id)??[]).filter(ge);for(let i of o){let r=e.state.artifactPath(i,t),c=p.extname(i).toLowerCase();if(c===".graphql"||c===".gql"){let s=await S.readFile(i,"utf8"),a=await e.state.addProof({provider:this.id,artifact:r,absolutePath:i,trust:"authoritative",derivation:"authored",detail:"GraphQL schema"}),n=e.state.addEntity({kind:"api",key:`graphql:${t.id}:${r}`,label:`${t.id} GraphQL API`,projectId:t.id,attributes:{specification:"graphql",artifact:r},proofIds:[a]});e.state.addRelation({from:E("project",`project:${t.id}`),to:n,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[a]});for(let d of s.matchAll(/^\s*(?:type|input|interface|enum|scalar|union)\s+([A-Za-z_]\w*)/gm)){let l=e.state.addEntity({kind:"schema",key:`graphql-schema:${t.id}:${r}:${d[1]}`,label:d[1],projectId:t.id,proofIds:[a]});e.state.addRelation({from:n,to:l,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[a]});}continue}if(c===".proto"){let s=await S.readFile(i,"utf8"),a=V(s.replace(/\r\n/g,`
|
|
7
|
+
`).trim()),n=s.match(/^\s*package\s+([A-Za-z_][\w.]*)\s*;/m)?.[1],d=n||"unscoped",l=a.slice(0,16),m=await e.state.addProof({provider:this.id,artifact:r,absolutePath:i,trust:"authoritative",derivation:"authored",detail:"Protocol Buffers contract"});for(let u of s.matchAll(/^\s*service\s+([A-Za-z_]\w*)/gm)){let v=e.state.addEntity({kind:"api",key:`protobuf-service:${d}:${u[1]}:${l}`,label:u[1],aliases:[...n?[`${n}.${u[1]}`]:[],u[1]],attributes:{specification:"protobuf",package:n,definitionHash:a},proofIds:[m]});e.state.addRelation({from:E("project",`project:${t.id}`),to:v,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[m]});}for(let u of s.matchAll(/^\s*message\s+([A-Za-z_]\w*)/gm)){let v=e.state.addEntity({kind:"schema",key:`protobuf-message:${d}:${u[1]}:${l}`,label:u[1],aliases:[...n?[`${n}.${u[1]}`]:[],u[1]],attributes:{specification:"protobuf",package:n,definitionHash:a},proofIds:[m]});e.state.addRelation({from:E("project",`project:${t.id}`),to:v,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[m]});}continue}try{let s=(await B(i))[0];if(!s||!("asyncapi"in s))continue;let a=await e.state.addProof({provider:this.id,artifact:r,absolutePath:i,trust:"authoritative",derivation:"authored",detail:"AsyncAPI contract"}),n=e.state.addEntity({kind:"api",key:`asyncapi:${t.id}:${r}`,label:b(j(s.info)?.title)??`${t.id} AsyncAPI`,projectId:t.id,attributes:{specification:`asyncapi ${String(s.asyncapi)}`,artifact:r},proofIds:[a]});e.state.addRelation({from:E("project",`project:${t.id}`),to:n,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[a]});for(let d of Object.keys(j(s.channels)??{}).sort()){let l=e.state.addEntity({kind:"queue",key:`asyncapi-channel:${t.id}:${d}`,label:d,projectId:t.id,attributes:{protocol:"asyncapi"},proofIds:[a]});e.state.addRelation({from:n,to:l,kind:"publishes",trust:"authoritative",derivation:"authored",proofIds:[a]});}}catch{}}}}},$t={id:"infrastructure-as-code",version:"1.0.0",applicable(e){return J(e).some(he)},async run(e){let t=J(e).filter(he);for(let o of t){let i=N(e.projects,o),r=i?.id??e.state.workspaceName,c=i?E("project",`project:${i.id}`):E("workspace",`workspace:${e.state.workspaceName}`),s=e.state.artifactPath(o,i),a=await S.readFile(o,"utf8"),n=await e.state.addProof({provider:this.id,artifact:s,absolutePath:o,trust:"authoritative",derivation:"authored",detail:"Infrastructure definition"});if(/^Dockerfile/i.test(p.basename(o))){let l=[...a.matchAll(/^\s*FROM\s+([^\s]+)(?:\s+AS\s+([^\s]+))?/gim)],m=e.state.addEntity({kind:"container",key:`dockerfile:${r}:${s}`,label:`${r} container image`,...i?{projectId:i.id}:{},attributes:{artifact:s,baseImages:l.map(u=>u[1])},proofIds:[n]});e.state.addRelation({from:c,to:m,kind:"deploys",trust:"authoritative",derivation:"authored",proofIds:[n]});continue}if(/\.tf$/i.test(o)){for(let l of a.matchAll(/^\s*resource\s+["']([^"']+)["']\s+["']([^"']+)["']/gm)){let m=l[1],u=/(?:db|sql|rds|database)/i.test(m)?"database":/(?:queue|kafka|sqs|pubsub|servicebus)/i.test(m)?"queue":"deployment",v=e.state.addEntity({kind:u,key:`terraform:${r}:${m}:${l[2]}`,label:`${m}.${l[2]}`,...i?{projectId:i.id}:{},attributes:{resourceType:m,artifact:s},proofIds:[n]});e.state.addRelation({from:c,to:v,kind:"deploys",trust:"authoritative",derivation:"authored",proofIds:[n]});}continue}let d=e.state.addEntity({kind:"deployment",key:`helm:${r}:${s}`,label:`${r} Helm chart`,...i?{projectId:i.id}:{},attributes:{artifact:s,format:"helm"},proofIds:[n]});e.state.addRelation({from:c,to:d,kind:"deploys",trust:"authoritative",derivation:"authored",proofIds:[n]});}}};function Re(e){let t=e.toLowerCase();return /(?:postgres|mysql|mariadb|mongo|cassandra|cockroach|mssql|oracle)/.test(t)?"database":/(?:rabbitmq|kafka|nats|pulsar|activemq|redis)/.test(t)?"queue":"container"}var jt={id:"compose",version:"1.0.0",async applicable(e){return (await ke(e)).length>0},async run(e){for(let t of await ke(e)){let o;try{o=(await B(t))[0];}catch(s){e.state.diagnostics.push({code:"graph.provider.compose.parse_failed",severity:"warning",message:`Could not parse ${e.state.artifactPath(t)}: ${s instanceof Error?s.message:String(s)}`});}let i=j(o?.services);if(!i)continue;let r=N(e.projects,t),c=new Map;for(let s of Object.keys(i).sort()){let a=j(i[s]),n=a?.build,d=b(n)??b(j(n)?.context),l=d?N(e.projects,p.resolve(p.dirname(t),d)):e.projects.find(g=>g.id.toLowerCase()===s.toLowerCase()||p.basename(g.path).toLowerCase()===s.toLowerCase())??r,m=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(t,r),absolutePath:t,pointer:`/services/${s}`,trust:"authoritative",derivation:"authored",detail:`Compose service ${s}`}),u=b(a?.image),v=e.state.addEntity({kind:"service",key:`compose-service:${e.state.artifactPath(t,r)}:${s}`,label:s,...l?{projectId:l.id}:{},attributes:{image:u,ports:K(a?.ports).map(String),networks:K(a?.networks),environmentKeys:Xe(a?.environment)},proofIds:[m]});if(c.set(s,v),l&&e.state.addRelation({from:E("project",`project:${l.id}`),to:v,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[m]}),u){let g=e.state.addEntity({kind:Re(u),key:`image:${u}`,label:u,...l?{projectId:l.id}:{},attributes:{image:u},proofIds:[m]});e.state.addRelation({from:v,to:g,kind:Re(u)==="container"?"runs-on":"depends-on",trust:"authoritative",derivation:"authored",proofIds:[m]});}}for(let s of Object.keys(i).sort()){let a=j(i[s]),n=c.get(s);if(n)for(let d of K(a?.depends_on)){let l=c.get(d);if(!l)continue;let m=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(t,r),absolutePath:t,pointer:`/services/${s}/depends_on/${d}`,trust:"authoritative",derivation:"authored",detail:`${s} depends on ${d}`});e.state.addRelation({from:n,to:l,kind:"depends-on",trust:"authoritative",derivation:"authored",proofIds:[m]});}}}}},It={id:"documentation",version:"1.0.0",applicable(e){return J(e).some(ye)},async run(e){let t=new Set,o=[e.workspaceFiles,...e.projects.map(i=>e.filesByProject.get(i.id)??[])];for(let i of o){let r=i.filter(c=>ye(c)&&!e.projects.some(s=>c.startsWith(`${s.root}${p.sep}`)&&M(s.root,c)));for(let c of r){if(t.has(c))continue;t.add(c);let s=N(e.projects,c),n=(await S.readFile(c,"utf8")).match(/^#\s+(.+)$/m)?.[1]?.trim()??p.basename(c),d=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(c,s),absolutePath:c,line:1,trust:"authoritative",derivation:"authored",detail:`Documentation: ${n}`}),l=e.state.addEntity({kind:"document",key:`document:${e.state.artifactPath(c,s)}`,label:n,...s?{projectId:s.id}:{},attributes:{artifact:e.state.artifactPath(c,s)},proofIds:[d]}),m=s?E("project",`project:${s.id}`):E("workspace",`workspace:${e.state.workspaceName}`);e.state.addRelation({from:l,to:m,kind:"documents",trust:"authoritative",derivation:"authored",proofIds:[d]});}}}},Et={id:"kubernetes",version:"1.0.0",async applicable(e){return (await Pe(e)).length>0},async run(e){for(let t of await Pe(e)){let o=N(e.projects,t),i=o?E("project",`project:${o.id}`):E("workspace",`workspace:${e.state.workspaceName}`),r=await B(t);for(let c=0;c<r.length;c+=1){let s=r[c],a=b(s.kind),n=j(s.metadata),d=b(n?.name);if(!a||!d)continue;let l=b(n?.namespace)??"default",m=/Deployment|StatefulSet|DaemonSet/i.test(a)?"deployment":/Service|Ingress/i.test(a)?"service":/ConfigMap|Secret/i.test(a)?"environment":"deployment",u=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(t,o),absolutePath:t,pointer:`/documents/${c}`,trust:"authoritative",derivation:"authored",detail:`${a} ${l}/${d}`}),v=e.state.addEntity({kind:m,key:`kubernetes:${a}:${l}:${d}`,label:`${a}/${d}`,...o?{projectId:o.id}:{},attributes:{resourceKind:a,namespace:l,secret:a==="Secret",keys:a==="Secret"||a==="ConfigMap"?Object.keys(j(s.data)??{}).sort():void 0},proofIds:[u]});e.state.addRelation({from:i,to:v,kind:m==="deployment"?"deploys":"contains",trust:"authoritative",derivation:"authored",proofIds:[u]});let g=e.state.addEntity({kind:"environment",key:`kubernetes-namespace:${l}`,label:`Kubernetes namespace ${l}`,attributes:{namespace:l},proofIds:[u]});e.state.addRelation({from:v,to:g,kind:"runs-on",trust:"authoritative",derivation:"authored",proofIds:[u]});}}}},Ct={id:"ci-workflow",version:"1.0.0",applicable(e){return we(e).length>0},async run(e){let t=we(e);for(let o of t){let i=N(e.projects,o),r=e.state.artifactPath(o,i),c=p.basename(o)==="Jenkinsfile",s=p.basename(o),a=[],n=[];if(c)a=[...(await S.readFile(o,"utf8")).matchAll(/\bstage\s*\(\s*["']([^"']+)["']/g)].map(u=>u[1]);else {let m;try{m=(await B(o))[0];}catch{continue}if(!m)continue;s=b(m.name)??s;let u=O(p.relative(i?.root??e.workspacePath,o));if(/^\.gitlab-ci\./i.test(u)){let v=new Set(["stages","variables","workflow","include","default","image","services","cache","before_script","after_script"]);a=Object.keys(m).filter(g=>!g.startsWith(".")&&!v.has(g)).sort();}else a=[...new Set([...Object.keys(j(m.jobs)??{}),...Object.keys(j(j(m.workflows)?.jobs)??{}),...K(m.stages)])].sort();n=K(m.on);}a.length===0&&(a=["pipeline"]);let d=await e.state.addProof({provider:this.id,artifact:r,absolutePath:o,...c?{}:{pointer:"/jobs"},trust:"authoritative",derivation:"authored",detail:"CI/CD workflow"}),l=e.state.addEntity({kind:"pipeline",key:`pipeline:${r}`,label:s,attributes:{jobs:a,triggers:n,artifact:r},proofIds:[d]});e.state.addRelation({from:i?E("project",`project:${i.id}`):E("workspace",`workspace:${e.state.workspaceName}`),to:l,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[d]});}}},Rt={id:"codeowners",version:"1.0.0",async applicable(e){return (await be(e)).length>0},async run(e){for(let t of await be(e)){let o=N(e.projects,t),r=(await S.readFile(t,"utf8")).split(/\r?\n/);for(let c=0;c<r.length;c+=1){let s=r[c].trim();if(!s||s.startsWith("#"))continue;let[a,...n]=s.split(/\s+/);for(let d of n.filter(l=>l.startsWith("@"))){let l=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(t,o),absolutePath:t,line:c+1,trust:"authoritative",derivation:"authored",detail:`${a} ${d}`}),m=e.state.addEntity({kind:"owner",key:`owner:${d.toLowerCase()}`,label:d,aliases:[d],proofIds:[l]}),u=e.projects.filter(g=>{let w=a.replace(/^\//,"").replace(/\*.*$/,""),P=p.dirname(t),f=[".github","docs"].includes(p.basename(P))?p.dirname(P):P,y=O(p.relative(f,g.root));return w&&(y==="."||y.startsWith(w.replace(/\/$/,""))||g.path.startsWith(w.replace(/\/$/,"")))}),v=u.length>0?u.map(g=>E("project",`project:${g.id}`)):o?[E("project",`project:${o.id}`)]:[E("workspace",`workspace:${e.state.workspaceName}`)];for(let g of v)e.state.addRelation({from:m,to:g,kind:"owns",trust:"authoritative",derivation:"authored",proofIds:[l]});}}}}},St={id:"architecture-decisions",version:"1.0.0",applicable(e){return [{root:e.workspacePath,files:e.workspaceFiles},...e.projects.map(t=>({root:t.root,files:e.filesByProject.get(t.id)??[]}))].some(t=>t.files.some(o=>ve(t.root,o)))},async run(e){let t=new Set,o=[{root:e.workspacePath,files:e.workspaceFiles},...e.projects.map(i=>({root:i.root,files:e.filesByProject.get(i.id)??[]}))];for(let i of o){let r=i.files.filter(c=>ve(i.root,c));for(let c of r){if(t.has(c))continue;t.add(c);let s=N(e.projects,c),a=await S.readFile(c,"utf8"),n=a.match(/^#\s+(.+)$/m)?.[1]?.trim()??p.basename(c,".md"),d=a.match(/^status\s*:\s*(.+)$/im)?.[1]?.trim(),l=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(c,s),absolutePath:c,line:1,trust:"authoritative",derivation:"authored",detail:`Architecture decision: ${n}`}),m=e.state.addEntity({kind:"decision",key:`decision:${e.state.artifactPath(c,s)}`,label:n,...s?{projectId:s.id}:{},attributes:{status:d,artifact:e.state.artifactPath(c,s)},proofIds:[l]}),u=s?E("project",`project:${s.id}`):E("workspace",`workspace:${e.state.workspaceName}`);e.state.addRelation({from:u,to:m,kind:"decided-by",trust:"authoritative",derivation:"authored",proofIds:[l]});}}}},At=[at,dt,lt,pt,ft,ht,kt,bt,wt,Pt,jt,$t,Et,Ct,Rt,It,St];async function Wt(e$1,t){for(let o of t.edges){let i=[];for(let r of o.evidence){let c=x(r.file);i.push(await e$1.addProof({provider:"project-topology",artifact:c,absolutePath:p.resolve(e$1.workspacePath,c),derivation:o.source==="inferred"?"inferred":"authored",trust:o.source==="inferred"?"observed":"authoritative",confidence:o.confidence,detail:r.detail??`${o.kind} relationship`}));}i.length===0&&i.push(await e$1.addProof({provider:"project-topology",artifact:e.model,derivation:"inferred",trust:"ambiguous",confidence:o.confidence,detail:`${o.kind} relationship without source locator`})),e$1.addRelation({from:E("project",`project:${o.from}`),to:E("project",`project:${o.to}`),kind:o.kind==="event-pub-sub"?"consumes":"depends-on",derivation:o.source==="inferred"?"inferred":"authored",trust:o.source==="inferred"?"observed":"authoritative",confidence:o.confidence,proofIds:i});}}function _t(e){let t=[...e.entities.values()].filter(i=>i.kind==="endpoint"),o=new Map;for(let i of t){let r=String(i.attributes.method??"").toUpperCase(),c=String(i.attributes.path??"");if(!i.projectId||!r||!c)continue;let s=`${i.projectId}\0${r}\0${c}`,a=o.get(s)??[];a.push(i),o.set(s,a);}for(let i of o.values()){if(i.length<2)continue;let r=i.find(c=>c.proofIds.some(s=>e.proofs.get(s)?.trust==="authoritative"));if(r)for(let c of i.filter(s=>s.id!==r.id))e.addRelation({from:c.id,to:r.id,kind:"implements",derivation:"extracted",trust:"corroborated",confidence:"high",proofIds:[...c.proofIds,...r.proofIds]});}}function H(e,t){let o=[...new Set(e)],i=o.filter(r=>t.has(r)).length;return {eligibleCount:o.length,boundCount:i,unknownCount:o.length-i,coverageRatio:o.length===0?null:i/o.length}}function Kt(e,t){let o=e.filter(n=>n.kind==="project").map(n=>n.id),i=e.filter(n=>n.kind==="endpoint").map(n=>n.id),r=new Set(t.filter(n=>n.kind==="implements").flatMap(n=>[n.from,n.to])),c=new Set(t.filter(n=>n.kind==="tests").flatMap(n=>[n.from,n.to]).filter(n=>o.includes(n))),s=new Set(t.filter(n=>n.kind==="deploys").flatMap(n=>[n.from,n.to]).filter(n=>o.includes(n))),a=new Set(t.filter(n=>n.kind==="owns").flatMap(n=>[n.from,n.to]).filter(n=>o.includes(n)));return {apiImplementation:H(i,r),projectTests:H(o,c),projectDeployment:H(o,s),projectOwnership:H(o,a)}}async function Qt(e){let t=p.resolve(e.workspacePath),o=e.now??new Date,i=e.projects.map(h=>{let I=h.absolutePath?p.resolve(h.absolutePath):p.resolve(t,h.path),A=p.relative(t,I),_=A.startsWith(`..${p.sep}`)||A===".."||p.isAbsolute(A);return {...h,root:I,artifactPrefix:_?`external/${h.id}`:O(A||h.id)}}).sort((h,I)=>h.id.localeCompare(I.id)),r=new re(t,o,e.workspace.name),c=Math.max(100,Math.min(e.maxFilesPerProject??2e3,1e4)),s=Math.min(Math.max(c*10,2e4),5e4),a=new Map(await Promise.all(i.map(async h=>[h.id,await q(h.root,c)]))),n=new Map(await Promise.all(i.map(async h=>[h.id,await q(h.root,s)]))),d=Math.min(c*Math.max(i.length,1),2e4),l=await q(t,d),m=await ot({workspacePath:t,projects:i,projectFileLimit:s,workspaceFileLimit:d,inventories:{workspaceFiles:l,projectFiles:n}}),u={workspacePath:t,projects:i,filesByProject:a,semanticFilesByProject:n,semanticScanLimit:s,workspaceFiles:l,now:o,maxFilesPerProject:c,contract:e.contract??null,state:r};for(let h of At){let I={entities:r.entities.size,relations:r.relations.size,proofs:r.proofs.size,diagnostics:r.diagnostics.length},A="passed",_=null;try{if(!(h.applicable?await h.applicable(u):true))A="skipped";else {await h.run(u);let Z=r.entities.size-I.entities,We=r.relations.size-I.relations,_e=r.proofs.size-I.proofs;Z===0&&We===0&&_e===0?(A="partial",r.diagnostics.push({code:`graph.provider.${h.id}.empty_result`,severity:"warning",message:`${h.id} found an applicable source surface but produced no graph evidence.`,recommendation:"Inspect the matching source format or extend the provider before treating this graph dimension as complete."})):r.diagnostics.length>I.diagnostics&&(A="partial");}}catch(L){A="failed";let Z=L instanceof Error?L.message:String(L);_=Z,r.diagnostics.push({code:`graph.provider.${h.id}.failed`,severity:"warning",message:`${h.id} provider failed: ${Z}`,recommendation:"Repair the referenced source artifact and rerun workspace graph emit."});}let W=r.diagnostics.slice(I.diagnostics).map(L=>`${L.code}: ${L.message}`);_&&W.length===0&&W.push(_),r.providers.push({id:h.id,version:h.version,status:A,permission:"filesystem-read",discoveredEntities:r.entities.size-I.entities,discoveredRelations:r.relations.size-I.relations,proofCount:r.proofs.size-I.proofs,diagnostics:W});}_t(r),await Wt(r,e.projectTopology);let v=[...r.entities.values()].sort((h,I)=>h.id.localeCompare(I.id)),g=[...r.relations.values()].sort((h,I)=>h.id.localeCompare(I.id)),w=[...r.proofs.values()].sort((h,I)=>h.id.localeCompare(I.id)),P=v.filter(h=>h.proofIds.length>0).length,f=g.filter(h=>h.proofIds.length>0).length,y=r.providers.filter(h=>h.status!=="failed").length,$=e.projectTopology.diagnostics?.filter(h=>h.code==="graph.edges.missing").flatMap(h=>h.nodeIds??[])??[];$.length>0&&r.diagnostics.push({code:"graph.knowledge.project_relationships_unknown",severity:"warning",message:`${$.length} project(s) have no proven inter-project relationship. This is unknown topology, not proof of independence.`,entityIds:$.map(h=>E("project",`project:${h}`)),recommendation:"Author service contracts or add OpenAPI, Compose, Kubernetes, package or import evidence."});let k=r.diagnostics.filter(h=>h.code.includes("unknown")||h.code.includes("unresolved")||h.code.includes("limit_reached")||h.code.endsWith(".empty_result")).reduce((h,I)=>h+Math.max(I.entityIds?.length??0,I.relationIds?.length??0,1),0),C=Kt(v,g),R=Object.values(C).reduce((h,I)=>h+I.unknownCount,0);return {schemaVersion:pe,generatedAt:o.toISOString(),source:{...e.source,inputs:m},workspace:e.workspace,projectTopology:e.projectTopology,entities:v,relations:g,proofs:w,providers:[...r.providers].sort((h,I)=>h.id.localeCompare(I.id)),quality:{entityCount:v.length,relationCount:g.length,proofCount:w.length,entityProofCoverageRatio:v.length===0?1:P/v.length,relationProofCoverageRatio:g.length===0?1:f/g.length,providerSuccessRatio:r.providers.length===0?1:y/r.providers.length,conflictCount:r.diagnostics.filter(h=>h.code.includes("conflict")).length,unknownCount:k+R,bindingCoverage:C,portable:true,secretValuesEmitted:false},diagnostics:[...r.diagnostics].sort((h,I)=>h.code.localeCompare(I.code)||h.message.localeCompare(I.message))}}function eo(e,t){return E(e,t)}
|
|
8
|
+
export{pe as a,Yt as b,Xt as c,ot as d,Qt as e,eo as f};
|
|
@@ -1,4 +1,4 @@
|
|
|
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(`
|
|
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-WP3CXMVA.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
2
|
`);let t=3;return [...e.slice(0,t),...e.slice(-(r-t))].join(`
|
|
3
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
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}
|