workspai 0.77.0 → 0.79.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/contracts/create-planner-capabilities.v1.json +27 -3
- package/contracts/runtime-command-surface.v1.json +2 -0
- package/contracts/workspace-intelligence-architecture.v1.json +2 -0
- package/dist/analyze-SKOIUD6F.js +1 -0
- package/dist/autopilot-release-MDMVMU67.js +1 -0
- package/dist/{chunk-UP3UWAJV.js → chunk-2ZVE7VE2.js} +1 -1
- package/dist/{chunk-47UR6ZH4.js → chunk-3O344BX3.js} +1 -1
- package/dist/{chunk-IDETNYCF.js → chunk-4H3VNKOJ.js} +1 -1
- package/dist/{chunk-LUPKDFQ3.js → chunk-7EMG3C3H.js} +2 -2
- package/dist/{chunk-O3TVVQ6X.js → chunk-7HV4U2OV.js} +1 -1
- package/dist/{chunk-DWKCFHHL.js → chunk-7MIOAM4A.js} +1 -1
- package/dist/{chunk-E7WJ2QX7.js → chunk-7SN4V3RC.js} +1 -1
- package/dist/{chunk-X5XFT5UZ.js → chunk-BGUCDG5N.js} +1 -1
- package/dist/{chunk-IAXRGH4Q.js → chunk-CJBDYDVC.js} +1 -1
- package/dist/{chunk-UTIK3K3M.js → chunk-EPFEUMYF.js} +1 -1
- package/dist/{chunk-4CXV3PPV.js → chunk-ETTZXKAS.js} +1 -1
- package/dist/{chunk-V6HVDVKJ.js → chunk-FVG5FBA4.js} +5 -5
- package/dist/{chunk-J2MPBSQJ.js → chunk-GUCZOQUS.js} +1 -1
- package/dist/{chunk-SC43A6LH.js → chunk-H24MEOML.js} +50 -50
- package/dist/{chunk-ZIWWE4BQ.js → chunk-HXTNPR3M.js} +1 -1
- package/dist/chunk-ICPL4WNK.js +2 -0
- package/dist/{chunk-475GQJ2D.js → chunk-KRTVIBPC.js} +1 -1
- package/dist/{chunk-GLBFY7AB.js → chunk-KTOKU6HQ.js} +2 -2
- package/dist/{chunk-QCX6BO2M.js → chunk-MNZAJ6PP.js} +1 -1
- package/dist/chunk-O4TZKLEC.js +1 -0
- package/dist/{chunk-HRVHQBTA.js → chunk-R7R5FX4B.js} +1 -1
- package/dist/chunk-RQXZF7BZ.js +1 -0
- package/dist/{chunk-UNEK3VVR.js → chunk-RRZQPFFR.js} +2171 -109
- package/dist/{chunk-3EPR3D5Q.js → chunk-SKHRUHXO.js} +1 -1
- package/dist/{chunk-WC2K5QFI.js → chunk-SV7X5LJW.js} +1 -1
- package/dist/{chunk-TGNPMOM6.js → chunk-TQW2SZHH.js} +1 -1
- package/dist/{chunk-JVZA35OL.js → chunk-U5WP4HDH.js} +1 -1
- package/dist/{chunk-223SWPTL.js → chunk-VT4WPXTO.js} +1 -1
- package/dist/chunk-WU5M6UP7.js +2 -0
- package/dist/{chunk-3EMAC3MF.js → chunk-ZDLF77IS.js} +1 -1
- package/dist/{chunk-3SQIV3F4.js → chunk-ZONAHZBG.js} +1 -1
- package/dist/{create-YPAZJYCE.js → create-M3TWRHV6.js} +1 -1
- package/dist/{doctor-W5PXJ5FL.js → doctor-FF3WLJSP.js} +1 -1
- package/dist/{goal-lifecycle-5R55CA7H.js → goal-lifecycle-O4MYYTRU.js} +1 -1
- package/dist/{goal-pack-IS6GGJPH.js → goal-pack-NUDKANPM.js} +1 -1
- package/dist/index.js +92 -91
- package/dist/{pipeline-LW3SW2WT.js → pipeline-V5P2FX2P.js} +1 -1
- package/dist/{project-agent-entry-5TYKK5IV.js → project-agent-entry-6O7FKWSL.js} +1 -1
- package/dist/{project-intelligence-lens-TEOSTKNU.js → project-intelligence-lens-OQTZ4K7L.js} +1 -1
- package/dist/{project-test-coverage-T4TIWGKN.js → project-test-coverage-EJ3MBSZ3.js} +1 -1
- package/dist/{proof-carrying-change-2TKRADCW.js → proof-carrying-change-GV37YLDQ.js} +1 -1
- package/dist/{verified-goal-RN4TOV34.js → verified-goal-VB7IOTNO.js} +1 -1
- package/dist/{workspace-A33YMF2N.js → workspace-AXU6ODER.js} +1 -1
- package/dist/{workspace-agent-sync-VCA4G4DT.js → workspace-agent-sync-6427FNME.js} +1 -1
- package/dist/{workspace-context-YBWLSKR6.js → workspace-context-VVZARI5K.js} +1 -1
- package/dist/{workspace-contract-3QUZDBMM.js → workspace-contract-N2BJCAJ7.js} +1 -1
- package/dist/{workspace-explain-NXYRAQFI.js → workspace-explain-5WKK6ENK.js} +1 -1
- package/dist/{workspace-foundation-DZ52PECX.js → workspace-foundation-GYL3D7TW.js} +1 -1
- package/dist/{workspace-graph-stream-4VT46HZ7.js → workspace-graph-stream-26ME2JJS.js} +1 -1
- package/dist/{workspace-intelligence-FKYQQDJ6.js → workspace-intelligence-ZTET7JHS.js} +1 -1
- package/dist/{workspace-intelligence-runner-3K2JZH6Q.js → workspace-intelligence-runner-2EJ7GXG5.js} +1 -1
- package/dist/{workspace-knowledge-graph-CPBKNXQI.js → workspace-knowledge-graph-4RSZTEFJ.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-UTJHALST.js +1 -0
- package/dist/{workspace-mcp-serve-UXPKX7K6.js → workspace-mcp-serve-BSA6Q4EB.js} +1 -1
- package/dist/{workspace-model-POCPMNRT.js → workspace-model-LBICKRVI.js} +1 -1
- package/dist/{workspace-onboarding-KLG3GG7S.js → workspace-onboarding-NH4WFJ5N.js} +1 -1
- package/dist/{workspace-registry-summary-M4WMFDQ4.js → workspace-registry-summary-3PXZENLC.js} +1 -1
- package/dist/{workspace-repair-engine-2VGN42QD.js → workspace-repair-engine-ODTFFM6O.js} +1 -1
- package/dist/workspace-run-VDQ6BYLS.js +1 -0
- package/dist/{workspace-verify-PLAKTF3J.js → workspace-verify-UQWAFGNQ.js} +1 -1
- package/dist/{workspace-watch-VNU4KVYN.js → workspace-watch-BKIZQ2SM.js} +1 -1
- package/docs/agent-framework-adapters.md +88 -32
- package/docs/ci-workflows.md +10 -7
- package/docs/commands-reference.md +13 -9
- package/docs/create-planner-capabilities.md +1 -1
- package/docs/creating-workspaces-and-projects.md +24 -20
- package/docs/doctor-command.md +5 -3
- package/docs/model-gateways.md +23 -23
- package/docs/native-kit-baselines.md +2 -2
- package/package.json +4 -1
- package/scripts/enterprise-package-smoke.mjs +50 -0
- package/dist/analyze-TJM66CPF.js +0 -1
- package/dist/autopilot-release-C7Q4OTPY.js +0 -1
- package/dist/chunk-5KXOV7W4.js +0 -1
- package/dist/chunk-IHWS3ALP.js +0 -2
- package/dist/chunk-N7DOKE7V.js +0 -2
- package/dist/chunk-SEZTSMRR.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-67XDXUOT.js +0 -1
- package/dist/workspace-run-5YQR7GEZ.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {l}from'./chunk-IDETNYCF.js';import {a as a$1}from'./chunk-4CXV3PPV.js';import {b}from'./chunk-DWDYLKVW.js';import {j}from'./chunk-SEZTSMRR.js';import {b as b$1}from'./chunk-VN2MKTQO.js';import {a}from'./chunk-AFIFZTOY.js';import {c}from'./chunk-EWZZUQBR.js';import {s,t,p}from'./chunk-ODK4LCEL.js';import Pe from'crypto';import O from'fs';import M from'fs/promises';import f from'path';var fe=s.projectAgentEntry.schemaVersion,L=t.projectAgentEntry,Ce="workspai.agent-bootstrap-receipt.v1",Ve="<!-- WORKSPAI:AGENT-ENTRY:START -->",Be="<!-- WORKSPAI:AGENT-ENTRY:END -->",B=["generic","codex","claude","gemini","qwen","kimi","grok","copilot","cursor","windsurf","amazon-q"],Ue=["CLAUDE.md","GEMINI.md","QWEN.md",".amazonq/rules/workspai-agent-entry.md"];function Se(t){let s=t?.trim().toLowerCase()||"generic";if(s==="orca")return "grok";if(B.includes(s))return s;throw new Error(`Unsupported agent host "${s}". Expected one of: ${B.join(", ")}.`)}function me(t){let s=t.map(c=>c.id).sort(),n=[...B].sort();if(s.length!==n.length||s.some((c,p)=>c!==n[p]))throw new Error("Project agent entry must define each supported host exactly once.")}function U(t){let{integrity:s,...n}=t;return n}function T(t){return c(t)}function Je(t$1){me(t$1.hosts);let s={schemaVersion:fe,generatedAt:t$1.context.generatedAt,project:{name:t$1.context.project.name,relativePath:t$1.context.project.relativePath,...t$1.context.project.runtime?{runtime:t$1.context.project.runtime}:{},...t$1.context.project.framework?{framework:t$1.context.project.framework}:{}},workspace:{name:t$1.context.workspace.name,relationship:t$1.context.workspace.relationship,localBinding:t.projectWorkspaceLink,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},canonical:{projectContext:t.projectContextAgent,projectGrounding:".workspai/PROJECT-GROUNDING.md",projectKnowledgeGraph:t.projectKnowledgeGraphReference,goalIndex:`workspace:${t.goalIndex}`,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json"},protocol:{mode:"canonical-first",bootstrapCommand:"workspai agent bootstrap --for-agent generic --strict --json",verifyCommand:"workspai project agent-entry verify --for-agent all --strict --json",requiredReadOrder:[L,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",t.projectContextAgent,`workspace:${t.goalIndex}`,`workspace:${p.skillsIndex}`,"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json","source:targeted-live-files"],sourcePolicy:{liveSourceAuthority:"exact-implementation",workspaceEvidenceAuthority:"identity-topology-readiness-goals",broadScanBeforeBootstrap:false,sourceMutation:"governed-only",verificationClaims:"cli-evidence-only"},degradedMode:{discloseMissingEvidence:true,allowCompleteArchitectureClaims:false,allowReadOnlySourceInspection:true}},hosts:[...t$1.hosts].sort((c,p)=>c.id.localeCompare(p.id))},n={...s,integrity:{algorithm:"sha256",projectContextHash:t$1.context.integrity.payloadHash,payloadHash:T(s),portable:true,absolutePathsEmitted:false}};if(!A(n))throw new Error("Project agent entry rejected a non-portable local path.");return a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n}function A(t){return typeof t=="string"?!(/^[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])file:\/\//i.test(t)||/(?:^|[\s("'`])\\\\[^\\\s]+[\\]/.test(t)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(t)):Array.isArray(t)?t.every(A):t&&typeof t=="object"?Object.values(t).every(A):true}async function Te(t){let s=f.join(t,L),n=JSON.parse(await M.readFile(s,"utf8"));if(a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n.integrity.payloadHash!==T(U(n)))throw new Error("Project agent entry integrity validation failed.");if(me(n.hosts),!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project agent entry contains a non-portable local path.");return n}async function Re(t$1){let s=f.join(t$1,t.projectContextAgent),n=JSON.parse(await M.readFile(s,"utf8"));a(n,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent");let c=U(n),p=Pe.createHash("sha256").update(JSON.stringify(c)).digest("hex");if(n.integrity.payloadHash!==p)throw new Error("Project context agent integrity validation failed.");if(!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project context agent contains a non-portable local path.");return n}function xe(t){return t.includes("blocked")?"blocked":t.includes("degraded")?"degraded":"ready"}async function Ye(t$1){let s=b({startPath:f.resolve(t$1.startPath??process.cwd()),strict:true,requireProjectMembership:true});if(!s?.projectPath)throw new Error("No canonically bound Workspai project was resolved.");let n=s.projectPath,c$1=s.workspacePath,p$1=await Te(n),o=await Re(n);if(p$1.integrity.projectContextHash!==o.integrity.payloadHash||p$1.project.name!==o.project.name||p$1.workspace.name!==o.workspace.name)throw new Error("Project agent entry is not bound to the current project context.");let J=t$1.forAgent?.trim().toLowerCase()||"generic",Y=J==="all",g=Y?"all":Se(J),D=g,m=Y?p$1.hosts:p$1.hosts.filter(e=>e.id===g),z=p$1.hosts.find(e=>e.id==="generic");if(m.length===0&&z&&m.push(z),m.length===0)throw new Error("Project agent entry does not define generic host coverage.");let y=[],d=(e,r,P,h)=>y.push({id:e,status:r,message:P,...h?{artifact:h}:{}});d("workspace-binding","passed","Canonical workspace membership is resolved."),d("entry-integrity","passed","Project entry manifest integrity is valid.",L),d("project-context-integrity","passed","Project context integrity and manifest binding are valid.",t.projectContextAgent);let $=[...new Set(m.flatMap(e=>e.entryFiles))].sort(),ue=$.filter(e=>!O.existsSync(f.join(n,e))),k=m.some(e=>e.status==="blocked")||ue.length>0?"blocked":m.some(e=>e.status==="degraded")?"degraded":"ready";d("host-discovery",k==="ready"?"passed":k==="degraded"?"warning":"failed",k==="ready"?`${g} has discoverable Workspai entry coverage.`:k==="degraded"?m.find(e=>e.reason)?.reason??`${g} entry coverage is degraded.`:`${g} entry coverage is missing required files.`,$[0]);let Z=[p.agentIndex,p.agentContext,p.skillsIndex,p.model,p.knowledgeGraph],R=Z.filter(e=>!O.existsSync(f.join(c$1,e)));d("canonical-evidence",R.length===0?"passed":"failed",R.length===0?"Required canonical workspace evidence is present.":`Required canonical evidence is missing: ${R.join(", ")}.`);let E=[],x=null,u=null;for(let e of Z)if(!R.includes(e))try{let r=JSON.parse(await M.readFile(f.join(c$1,e),"utf8"));b$1(e,r,e),e===p.model&&(x=r),e===p.knowledgeGraph&&(u=r);}catch{E.push(e);}d("canonical-contracts",E.length===0?"passed":"failed",E.length===0?"Canonical workspace evidence satisfies its published schemas.":`Canonical evidence failed contract validation: ${E.join(", ")}.`);let b$2=t.projectKnowledgeGraphReference,Q=f.join(n,b$2),X="failed",I="The project Knowledge Graph reference is missing.";if(O.existsSync(Q)&&u)try{let e=JSON.parse(await M.readFile(Q,"utf8"));b$1(b$2,e,b$2);let r=j(u,o.project.name),{integrity:P,...h}=e,C=u.source;e.project.name===o.project.name&&e.canonical.sourceHash===C?.hash&&e.canonical.projectionHash===c(r)&&e.integrity.payloadHash===c(h)?(X="passed",I="The project reference integrity-binds the exact current projection of canonical workspace evidence."):I="The project Knowledge Graph reference is stale or does not match the canonical project projection.";}catch{I="The project Knowledge Graph reference failed schema or integrity validation.";}d("project-knowledge-graph",X,I,b$2);let ee=x?.workspace,te=u?.workspace,oe=Array.isArray(u?.entities)?u.entities:[],ne=Array.isArray(x?.projects)?x.projects:[],re=E.length===0&&ee?.name===o.workspace.name&&te?.name===o.workspace.name&&ne.some(e=>e.name===o.project.name)&&oe.some(e=>e.projectId===o.project.name);d("canonical-project-membership",re?"passed":"failed",re?"The project and workspace identities agree across the entry, Model, and Graph.":`The project or workspace identity is missing or inconsistent in canonical evidence (entry workspace=${o.workspace.name}, model workspace=${String(ee?.name??"missing")}, graph workspace=${String(te?.name??"missing")}, entry project=${o.project.name}, model projects=${ne.map(e=>String(e.name??"missing")).join(",")||"missing"}, graph projects=${[...new Set(oe.map(e=>e.projectId).filter(e=>typeof e=="string"))].join(",")||"missing"}).`);let se=!o.intelligence.freshness.graphMatchesModel||["missing","stale"].includes(o.intelligence.freshness.model)||["missing","stale"].includes(o.intelligence.freshness.graph)?"failed":o.intelligence.freshness.model==="unknown"||o.intelligence.freshness.graph==="unknown"?"warning":"passed",j$1=false,G;if(t$1.validateLiveInputs!==false)try{let e=await a$1(c$1);j$1=e.status==="hit";let r=e.status==="hit"?"Live project inputs match the persisted Model and Knowledge Graph snapshot.":`Live project inputs require an intelligence refresh (${e.reason}).`;G={id:"live-inputs",status:j$1?"passed":"failed",message:r};}catch{G={id:"live-inputs",status:"failed",message:"Live project inputs could not be validated against canonical graph evidence."};}else G={id:"live-inputs",status:"warning",message:"Live input validation was skipped; persisted compatibility was checked only."};let K=se==="warning"&&o.intelligence.freshness.model==="unknown"&&o.intelligence.freshness.graph==="fresh"&&o.intelligence.freshness.graphMatchesModel&&j$1?"passed":se;d("persisted-freshness",K,K==="passed"?o.intelligence.freshness.model==="unknown"?"Model and Graph bindings are current; live input validation closes structural freshness while verify-before-use facts remain individually governed.":"Persisted Model and Knowledge Graph bindings are current.":K==="warning"?"Persisted evidence is compatible, but at least one freshness state is unknown.":"Persisted Model or Knowledge Graph evidence is missing, stale, or mismatched."),y.push(G);let i={present:false,appliesToProject:false,status:"none"},_=[],we=f.join(c$1,t.goalIndex);if(O.existsSync(we)){let e=null;try{e=await l({workspacePath:c$1,validateBindings:false});}catch{_.push("workspai goal --list --json"),d("active-goal","failed","The Goal index is present but invalid.");}if(e?.active&&(i={present:true,appliesToProject:e.active.scope.projects.includes(o.project.name),status:"invalid",id:e.active.id,objective:e.active.objective,lifecycle:e.active.lifecycle,goalPack:`workspace:${e.active.goalPack}`,agentHandoff:`workspace:${e.active.agentHandoff}`}),e)try{let r=await l({workspacePath:c$1,validateBindings:true});r.active&&(i={present:true,appliesToProject:r.active.scope.projects.includes(o.project.name),status:"ready",id:r.active.id,objective:r.active.objective,lifecycle:r.active.lifecycle,goalPack:`workspace:${r.active.goalPack}`,agentHandoff:`workspace:${r.active.agentHandoff}`}),d("active-goal","passed",r.active?"The active Goal Pack and agent handoff have valid canonical bindings.":"No active Goal Pack is selected.");}catch(r){let P=r instanceof Error?r.message:String(r),h=i.present&&/\bstale\b|--refresh/i.test(P);if(i.present&&(i.status=h?"stale":"invalid"),h&&i.objective){let w=e.active,ve=w?.scope.kind==="project"&&w.scope.projects.length===1?`project:${w.scope.projects[0]}`:w?.scope.kind==="project-set"&&w.scope.projects.length>1?`projects:${w.scope.projects.join(",")}`:"workspace";_.push(`workspai goal ${JSON.stringify(i.objective)} --scope ${ve} --for-agent generic --refresh --json`);}else _.push("workspai goal --status --json");let C=!i.present||i.appliesToProject;d("active-goal",C?"failed":"warning",h?C?"The selected Goal Pack is present but stale; regenerate it against current canonical evidence before acting.":"The selected Goal Pack is stale, but it does not apply to this project; current project evidence remains usable while the Goal is refreshed for its own scope.":i.present?C?"The selected Goal Pack is present but its canonical binding or handoff is invalid.":"The selected Goal Pack has an invalid canonical binding, but it does not apply to this project; current project evidence remains usable while the Goal is repaired for its own scope.":"The Goal index could not be validated.");}}else d("active-goal","passed","No Goal index is present for this workspace.");let ae=y.filter(e=>e.id!=="active-goal"),W=ae.some(e=>e.status==="failed")?"blocked":ae.some(e=>e.status==="warning")?"degraded":"ready",ye=y.some(e=>e.id==="active-goal"&&e.status==="failed")?"blocked":y.some(e=>e.id==="active-goal"&&e.status==="warning")?"degraded":"ready",N=xe([k,W,ye]),v=o.blockers.some(e=>e.severity==="error")?"blocked":o.blockers.length>0?"degraded":"ready",ke=v==="blocked"?"blocked":v==="degraded"?"degraded":"not-verified",je=`command:workspai agent bootstrap --for-agent ${g} --strict --json`,Ae=p$1.protocol.requiredReadOrder.map(e=>e==="command:workspai agent bootstrap --for-agent generic --strict --json"?je:e),ie={schemaVersion:Ce,generatedAt:(t$1.now??new Date).toISOString(),status:N,statusScope:"agent-grounding",readiness:{agentGrounding:N,architectureEvidence:W,projectEnvironment:v,release:ke},requestedAgent:D,resolvedHost:g,project:{name:o.project.name,relativePath:o.project.relativePath,...o.project.runtime?{runtime:o.project.runtime}:{},...o.project.framework?{framework:o.project.framework}:{}},workspace:{name:o.workspace.name,relationship:o.workspace.relationship,resolved:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},entry:{artifact:L,schemaVersion:fe,hostStatus:k,entryFiles:$},canonicalEvidence:{projectContext:t.projectContextAgent,projectKnowledgeGraph:t.projectKnowledgeGraphReference,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json",modelFreshness:j$1?"fresh":o.intelligence.freshness.model,graphFreshness:j$1?"fresh":o.intelligence.freshness.graph,graphMatchesModel:o.intelligence.freshness.graphMatchesModel,liveInputsValidated:j$1,blockerCount:o.blockers.length},activeGoal:i,requiredReadOrder:Ae,claims:{architecture:W==="ready"?"allowed-with-citations":"prohibited",sourceInspection:"bounded-and-targeted",sourceMutation:"governed-cli-transaction-only",verification:"cli-evidence-only"},checks:y,nextActions:N==="ready"?[...i.present&&i.appliesToProject&&i.agentHandoff?[`read:${i.agentHandoff}`]:[],...v==="blocked"?["workspai doctor project --json","workspai workspace explain release-blocked --json"]:v==="degraded"?["workspai doctor project --json"]:[],`workspai workspace graph search <task-query> --scope project:${o.project.name} --limit 12 --json`,"inspect only the returned proof paths and target source files"]:[..._,"workspai workspace intelligence run --for-agent generic --strict --json",`workspai agent bootstrap --for-agent ${g} --strict --json`]},ce=T(U(p$1)),Ee=T({manifestHash:ce,projectContextHash:o.integrity.payloadHash,requestedAgent:D,status:N,generatedAt:ie.generatedAt}),pe={...ie,receiptId:Ee},F={...pe,integrity:{algorithm:"sha256",manifestHash:ce,projectContextHash:o.integrity.payloadHash,payloadHash:T(pe),portable:true,absolutePathsEmitted:false}};if(!A(F))throw new Error("Agent bootstrap receipt rejected a non-portable local path.");return a(F,"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json","Agent bootstrap receipt"),F}
|
|
1
|
+
import {l}from'./chunk-4H3VNKOJ.js';import {a as a$1}from'./chunk-ETTZXKAS.js';import {b}from'./chunk-DWDYLKVW.js';import {j}from'./chunk-O4TZKLEC.js';import {b as b$1}from'./chunk-VN2MKTQO.js';import {a}from'./chunk-AFIFZTOY.js';import {c}from'./chunk-EWZZUQBR.js';import {s,t,p}from'./chunk-ODK4LCEL.js';import Pe from'crypto';import O from'fs';import M from'fs/promises';import f from'path';var fe=s.projectAgentEntry.schemaVersion,L=t.projectAgentEntry,Ce="workspai.agent-bootstrap-receipt.v1",Ve="<!-- WORKSPAI:AGENT-ENTRY:START -->",Be="<!-- WORKSPAI:AGENT-ENTRY:END -->",B=["generic","codex","claude","gemini","qwen","kimi","grok","copilot","cursor","windsurf","amazon-q"],Ue=["CLAUDE.md","GEMINI.md","QWEN.md",".amazonq/rules/workspai-agent-entry.md"];function Se(t){let s=t?.trim().toLowerCase()||"generic";if(s==="orca")return "grok";if(B.includes(s))return s;throw new Error(`Unsupported agent host "${s}". Expected one of: ${B.join(", ")}.`)}function me(t){let s=t.map(c=>c.id).sort(),n=[...B].sort();if(s.length!==n.length||s.some((c,p)=>c!==n[p]))throw new Error("Project agent entry must define each supported host exactly once.")}function U(t){let{integrity:s,...n}=t;return n}function T(t){return c(t)}function Je(t$1){me(t$1.hosts);let s={schemaVersion:fe,generatedAt:t$1.context.generatedAt,project:{name:t$1.context.project.name,relativePath:t$1.context.project.relativePath,...t$1.context.project.runtime?{runtime:t$1.context.project.runtime}:{},...t$1.context.project.framework?{framework:t$1.context.project.framework}:{}},workspace:{name:t$1.context.workspace.name,relationship:t$1.context.workspace.relationship,localBinding:t.projectWorkspaceLink,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},canonical:{projectContext:t.projectContextAgent,projectGrounding:".workspai/PROJECT-GROUNDING.md",projectKnowledgeGraph:t.projectKnowledgeGraphReference,goalIndex:`workspace:${t.goalIndex}`,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json"},protocol:{mode:"canonical-first",bootstrapCommand:"workspai agent bootstrap --for-agent generic --strict --json",verifyCommand:"workspai project agent-entry verify --for-agent all --strict --json",requiredReadOrder:[L,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",t.projectContextAgent,`workspace:${t.goalIndex}`,`workspace:${p.skillsIndex}`,"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json","source:targeted-live-files"],sourcePolicy:{liveSourceAuthority:"exact-implementation",workspaceEvidenceAuthority:"identity-topology-readiness-goals",broadScanBeforeBootstrap:false,sourceMutation:"governed-only",verificationClaims:"cli-evidence-only"},degradedMode:{discloseMissingEvidence:true,allowCompleteArchitectureClaims:false,allowReadOnlySourceInspection:true}},hosts:[...t$1.hosts].sort((c,p)=>c.id.localeCompare(p.id))},n={...s,integrity:{algorithm:"sha256",projectContextHash:t$1.context.integrity.payloadHash,payloadHash:T(s),portable:true,absolutePathsEmitted:false}};if(!A(n))throw new Error("Project agent entry rejected a non-portable local path.");return a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n}function A(t){return typeof t=="string"?!(/^[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])file:\/\//i.test(t)||/(?:^|[\s("'`])\\\\[^\\\s]+[\\]/.test(t)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(t)):Array.isArray(t)?t.every(A):t&&typeof t=="object"?Object.values(t).every(A):true}async function Te(t){let s=f.join(t,L),n=JSON.parse(await M.readFile(s,"utf8"));if(a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n.integrity.payloadHash!==T(U(n)))throw new Error("Project agent entry integrity validation failed.");if(me(n.hosts),!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project agent entry contains a non-portable local path.");return n}async function Re(t$1){let s=f.join(t$1,t.projectContextAgent),n=JSON.parse(await M.readFile(s,"utf8"));a(n,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent");let c=U(n),p=Pe.createHash("sha256").update(JSON.stringify(c)).digest("hex");if(n.integrity.payloadHash!==p)throw new Error("Project context agent integrity validation failed.");if(!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project context agent contains a non-portable local path.");return n}function xe(t){return t.includes("blocked")?"blocked":t.includes("degraded")?"degraded":"ready"}async function Ye(t$1){let s=b({startPath:f.resolve(t$1.startPath??process.cwd()),strict:true,requireProjectMembership:true});if(!s?.projectPath)throw new Error("No canonically bound Workspai project was resolved.");let n=s.projectPath,c$1=s.workspacePath,p$1=await Te(n),o=await Re(n);if(p$1.integrity.projectContextHash!==o.integrity.payloadHash||p$1.project.name!==o.project.name||p$1.workspace.name!==o.workspace.name)throw new Error("Project agent entry is not bound to the current project context.");let J=t$1.forAgent?.trim().toLowerCase()||"generic",Y=J==="all",g=Y?"all":Se(J),D=g,m=Y?p$1.hosts:p$1.hosts.filter(e=>e.id===g),z=p$1.hosts.find(e=>e.id==="generic");if(m.length===0&&z&&m.push(z),m.length===0)throw new Error("Project agent entry does not define generic host coverage.");let y=[],d=(e,r,P,h)=>y.push({id:e,status:r,message:P,...h?{artifact:h}:{}});d("workspace-binding","passed","Canonical workspace membership is resolved."),d("entry-integrity","passed","Project entry manifest integrity is valid.",L),d("project-context-integrity","passed","Project context integrity and manifest binding are valid.",t.projectContextAgent);let $=[...new Set(m.flatMap(e=>e.entryFiles))].sort(),ue=$.filter(e=>!O.existsSync(f.join(n,e))),k=m.some(e=>e.status==="blocked")||ue.length>0?"blocked":m.some(e=>e.status==="degraded")?"degraded":"ready";d("host-discovery",k==="ready"?"passed":k==="degraded"?"warning":"failed",k==="ready"?`${g} has discoverable Workspai entry coverage.`:k==="degraded"?m.find(e=>e.reason)?.reason??`${g} entry coverage is degraded.`:`${g} entry coverage is missing required files.`,$[0]);let Z=[p.agentIndex,p.agentContext,p.skillsIndex,p.model,p.knowledgeGraph],R=Z.filter(e=>!O.existsSync(f.join(c$1,e)));d("canonical-evidence",R.length===0?"passed":"failed",R.length===0?"Required canonical workspace evidence is present.":`Required canonical evidence is missing: ${R.join(", ")}.`);let E=[],x=null,u=null;for(let e of Z)if(!R.includes(e))try{let r=JSON.parse(await M.readFile(f.join(c$1,e),"utf8"));b$1(e,r,e),e===p.model&&(x=r),e===p.knowledgeGraph&&(u=r);}catch{E.push(e);}d("canonical-contracts",E.length===0?"passed":"failed",E.length===0?"Canonical workspace evidence satisfies its published schemas.":`Canonical evidence failed contract validation: ${E.join(", ")}.`);let b$2=t.projectKnowledgeGraphReference,Q=f.join(n,b$2),X="failed",I="The project Knowledge Graph reference is missing.";if(O.existsSync(Q)&&u)try{let e=JSON.parse(await M.readFile(Q,"utf8"));b$1(b$2,e,b$2);let r=j(u,o.project.name),{integrity:P,...h}=e,C=u.source;e.project.name===o.project.name&&e.canonical.sourceHash===C?.hash&&e.canonical.projectionHash===c(r)&&e.integrity.payloadHash===c(h)?(X="passed",I="The project reference integrity-binds the exact current projection of canonical workspace evidence."):I="The project Knowledge Graph reference is stale or does not match the canonical project projection.";}catch{I="The project Knowledge Graph reference failed schema or integrity validation.";}d("project-knowledge-graph",X,I,b$2);let ee=x?.workspace,te=u?.workspace,oe=Array.isArray(u?.entities)?u.entities:[],ne=Array.isArray(x?.projects)?x.projects:[],re=E.length===0&&ee?.name===o.workspace.name&&te?.name===o.workspace.name&&ne.some(e=>e.name===o.project.name)&&oe.some(e=>e.projectId===o.project.name);d("canonical-project-membership",re?"passed":"failed",re?"The project and workspace identities agree across the entry, Model, and Graph.":`The project or workspace identity is missing or inconsistent in canonical evidence (entry workspace=${o.workspace.name}, model workspace=${String(ee?.name??"missing")}, graph workspace=${String(te?.name??"missing")}, entry project=${o.project.name}, model projects=${ne.map(e=>String(e.name??"missing")).join(",")||"missing"}, graph projects=${[...new Set(oe.map(e=>e.projectId).filter(e=>typeof e=="string"))].join(",")||"missing"}).`);let se=!o.intelligence.freshness.graphMatchesModel||["missing","stale"].includes(o.intelligence.freshness.model)||["missing","stale"].includes(o.intelligence.freshness.graph)?"failed":o.intelligence.freshness.model==="unknown"||o.intelligence.freshness.graph==="unknown"?"warning":"passed",j$1=false,G;if(t$1.validateLiveInputs!==false)try{let e=await a$1(c$1);j$1=e.status==="hit";let r=e.status==="hit"?"Live project inputs match the persisted Model and Knowledge Graph snapshot.":`Live project inputs require an intelligence refresh (${e.reason}).`;G={id:"live-inputs",status:j$1?"passed":"failed",message:r};}catch{G={id:"live-inputs",status:"failed",message:"Live project inputs could not be validated against canonical graph evidence."};}else G={id:"live-inputs",status:"warning",message:"Live input validation was skipped; persisted compatibility was checked only."};let K=se==="warning"&&o.intelligence.freshness.model==="unknown"&&o.intelligence.freshness.graph==="fresh"&&o.intelligence.freshness.graphMatchesModel&&j$1?"passed":se;d("persisted-freshness",K,K==="passed"?o.intelligence.freshness.model==="unknown"?"Model and Graph bindings are current; live input validation closes structural freshness while verify-before-use facts remain individually governed.":"Persisted Model and Knowledge Graph bindings are current.":K==="warning"?"Persisted evidence is compatible, but at least one freshness state is unknown.":"Persisted Model or Knowledge Graph evidence is missing, stale, or mismatched."),y.push(G);let i={present:false,appliesToProject:false,status:"none"},_=[],we=f.join(c$1,t.goalIndex);if(O.existsSync(we)){let e=null;try{e=await l({workspacePath:c$1,validateBindings:false});}catch{_.push("workspai goal --list --json"),d("active-goal","failed","The Goal index is present but invalid.");}if(e?.active&&(i={present:true,appliesToProject:e.active.scope.projects.includes(o.project.name),status:"invalid",id:e.active.id,objective:e.active.objective,lifecycle:e.active.lifecycle,goalPack:`workspace:${e.active.goalPack}`,agentHandoff:`workspace:${e.active.agentHandoff}`}),e)try{let r=await l({workspacePath:c$1,validateBindings:true});r.active&&(i={present:true,appliesToProject:r.active.scope.projects.includes(o.project.name),status:"ready",id:r.active.id,objective:r.active.objective,lifecycle:r.active.lifecycle,goalPack:`workspace:${r.active.goalPack}`,agentHandoff:`workspace:${r.active.agentHandoff}`}),d("active-goal","passed",r.active?"The active Goal Pack and agent handoff have valid canonical bindings.":"No active Goal Pack is selected.");}catch(r){let P=r instanceof Error?r.message:String(r),h=i.present&&/\bstale\b|--refresh/i.test(P);if(i.present&&(i.status=h?"stale":"invalid"),h&&i.objective){let w=e.active,ve=w?.scope.kind==="project"&&w.scope.projects.length===1?`project:${w.scope.projects[0]}`:w?.scope.kind==="project-set"&&w.scope.projects.length>1?`projects:${w.scope.projects.join(",")}`:"workspace";_.push(`workspai goal ${JSON.stringify(i.objective)} --scope ${ve} --for-agent generic --refresh --json`);}else _.push("workspai goal --status --json");let C=!i.present||i.appliesToProject;d("active-goal",C?"failed":"warning",h?C?"The selected Goal Pack is present but stale; regenerate it against current canonical evidence before acting.":"The selected Goal Pack is stale, but it does not apply to this project; current project evidence remains usable while the Goal is refreshed for its own scope.":i.present?C?"The selected Goal Pack is present but its canonical binding or handoff is invalid.":"The selected Goal Pack has an invalid canonical binding, but it does not apply to this project; current project evidence remains usable while the Goal is repaired for its own scope.":"The Goal index could not be validated.");}}else d("active-goal","passed","No Goal index is present for this workspace.");let ae=y.filter(e=>e.id!=="active-goal"),W=ae.some(e=>e.status==="failed")?"blocked":ae.some(e=>e.status==="warning")?"degraded":"ready",ye=y.some(e=>e.id==="active-goal"&&e.status==="failed")?"blocked":y.some(e=>e.id==="active-goal"&&e.status==="warning")?"degraded":"ready",N=xe([k,W,ye]),v=o.blockers.some(e=>e.severity==="error")?"blocked":o.blockers.length>0?"degraded":"ready",ke=v==="blocked"?"blocked":v==="degraded"?"degraded":"not-verified",je=`command:workspai agent bootstrap --for-agent ${g} --strict --json`,Ae=p$1.protocol.requiredReadOrder.map(e=>e==="command:workspai agent bootstrap --for-agent generic --strict --json"?je:e),ie={schemaVersion:Ce,generatedAt:(t$1.now??new Date).toISOString(),status:N,statusScope:"agent-grounding",readiness:{agentGrounding:N,architectureEvidence:W,projectEnvironment:v,release:ke},requestedAgent:D,resolvedHost:g,project:{name:o.project.name,relativePath:o.project.relativePath,...o.project.runtime?{runtime:o.project.runtime}:{},...o.project.framework?{framework:o.project.framework}:{}},workspace:{name:o.workspace.name,relationship:o.workspace.relationship,resolved:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},entry:{artifact:L,schemaVersion:fe,hostStatus:k,entryFiles:$},canonicalEvidence:{projectContext:t.projectContextAgent,projectKnowledgeGraph:t.projectKnowledgeGraphReference,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json",modelFreshness:j$1?"fresh":o.intelligence.freshness.model,graphFreshness:j$1?"fresh":o.intelligence.freshness.graph,graphMatchesModel:o.intelligence.freshness.graphMatchesModel,liveInputsValidated:j$1,blockerCount:o.blockers.length},activeGoal:i,requiredReadOrder:Ae,claims:{architecture:W==="ready"?"allowed-with-citations":"prohibited",sourceInspection:"bounded-and-targeted",sourceMutation:"governed-cli-transaction-only",verification:"cli-evidence-only"},checks:y,nextActions:N==="ready"?[...i.present&&i.appliesToProject&&i.agentHandoff?[`read:${i.agentHandoff}`]:[],...v==="blocked"?["workspai doctor project --json","workspai workspace explain release-blocked --json"]:v==="degraded"?["workspai doctor project --json"]:[],`workspai workspace graph search <task-query> --scope project:${o.project.name} --limit 12 --json`,"inspect only the returned proof paths and target source files"]:[..._,"workspai workspace intelligence run --for-agent generic --strict --json",`workspai agent bootstrap --for-agent ${g} --strict --json`]},ce=T(U(p$1)),Ee=T({manifestHash:ce,projectContextHash:o.integrity.payloadHash,requestedAgent:D,status:N,generatedAt:ie.generatedAt}),pe={...ie,receiptId:Ee},F={...pe,integrity:{algorithm:"sha256",manifestHash:ce,projectContextHash:o.integrity.payloadHash,payloadHash:T(pe),portable:true,absolutePathsEmitted:false}};if(!A(F))throw new Error("Agent bootstrap receipt rejected a non-portable local path.");return a(F,"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json","Agent bootstrap receipt"),F}
|
|
2
2
|
export{fe as a,L as b,Ce as c,Ve as d,Be as e,B as f,Ue as g,Se as h,Je as i,Ye as j};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b as b$1}from'./chunk-B6FJ6RG6.js';import {N,M,k as k$1,q as q$1,G,I,O as O$1}from'./chunk-RRZQPFFR.js';import {c}from'./chunk-7HV4U2OV.js';import {e,f as f$1}from'./chunk-EFHSRPW7.js';import {b}from'./chunk-UJXE4UAX.js';import {m,l}from'./chunk-VQZ5PI5J.js';import {promises}from'fs';import c$1 from'path';import L,{homedir}from'os';import {pathToFileURL}from'url';import p from'process';import ie from'fs-extra';var y={schemaVersion:"workspai.model-gateway-qualification.v1",workspaiReleaseAuthority:"source-ready",attach:"unsupported",adapters:[{adapterId:"openrouter-typescript",status:"source-ready",platforms:[]},{adapterId:"openrouter-python",status:"source-ready",platforms:[]}]};var R=["ubuntu-latest","macos-latest","windows-latest"];function B(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Model gateway qualification document must be an object.");let t=e;if(!Array.isArray(t.adapters)||t.adapters.length===0)throw new Error("Model gateway qualification document contains no adapters.");let r=new Set;for(let a of t.adapters){if(!a||typeof a.adapterId!="string")throw new Error("Model gateway qualification adapter is missing adapterId.");if(r.has(a.adapterId))throw new Error(`Duplicate model gateway qualification adapter: ${a.adapterId}`);r.add(a.adapterId);let n=N(a.adapterId);if(!n)throw new Error(`Qualification adapter ${a.adapterId} is not in the version baseline.`);if(a.status!=="source-ready"&&a.status!=="qualified")throw new Error(`Invalid qualification status for ${a.adapterId}.`);if(!Array.isArray(a.platforms))throw new Error(`Qualification platforms missing for ${a.adapterId}.`);if(a.status==="source-ready"){if(a.platforms.length!==0)throw new Error(`Source-ready adapter ${a.adapterId} must not record platform qualification.`);continue}let s=new Set;for(let o of a.platforms){if(!o||!R.includes(o.os)||o.result!=="pass"||o.skippedRequiredStage!==false||o.sdkVersion!==n.sdkVersion)throw new Error(`Qualified adapter ${a.adapterId} is missing a valid platform record bound to ${n.sdkVersion}.`);if(s.has(o.os))throw new Error(`Duplicate platform ${o.os} for ${a.adapterId}.`);s.add(o.os);}for(let o of R)if(!s.has(o))throw new Error(`Qualified adapter ${a.adapterId} is missing ${o} evidence.`)}for(let a of M)if(!r.has(a.adapterId))throw new Error(`Baseline adapter ${a.adapterId} has no qualification record.`);let i=t.adapters.every(a=>a.status==="qualified");if(i)throw new Error("All adapters are qualified; release authority must match.")}B(y);var f=y,W=Object.freeze({schemaVersion:f.schemaVersion,workspaiReleaseAuthority:f.workspaiReleaseAuthority,attach:f.attach,adapters:Object.freeze(f.adapters.map(e=>Object.freeze({...e,platforms:Object.freeze(e.platforms.map(t=>Object.freeze(t)))})))}),z=W.workspaiReleaseAuthority;function K(e){return `${e} \xB7 ${z}`}var w=["backend","frontend","desktop","agent","gateway","extension","gaming"],J=[{id:"backend",label:"Backend",hint:"APIs and services"},{id:"frontend",label:"Frontend",hint:"Web applications"},{id:"desktop",label:"Desktop",hint:"Native desktop applications"},{id:"agent",label:"AI Agent",hint:"Governed agent runtimes"},{id:"gateway",label:"AI Gateway",hint:"Unified model access and routing"},{id:"extension",label:"Extension",hint:"Editor and platform extensions"},{id:"gaming",label:"Gaming",hint:"Game runtimes and tooling"}];function X(e){let r=e.label.indexOf(" \u2014 ");return r>=0?e.label.slice(r+3).trim():e.label.trim()}function Z(e){return w.includes(e.category)?e.category:null}function T(e){let t=c().flatMap(o=>{let l=Z(o);return l?[{value:o.id,label:`${D(l)} \xB7 ${X(o)}`,hint:`${o.runtime} \xB7 tested baseline`,name:o.label,category:l}]:[]}),r=k$1().map(o=>({value:o.kitId,label:`Frontend \xB7 ${o.displayName}`,hint:"official \xB7 latest stable",name:`${o.displayName} \u2014 ${o.framework}`,category:"frontend"})),i=q$1().map(o=>({value:o.kitId,label:`${D(o.category)} \xB7 ${o.displayName}`,hint:`${o.runtimeCandidates.join(" + ")} \xB7 official latest stable`,name:`${o.displayName} \u2014 ${o.category}`,category:o.category})),a=G().map(o=>({value:o.id,label:`AI Agent \xB7 ${o.label}`,hint:`${o.runtime} \xB7 ${I(o)?"release-admitted baseline":`${o.stability} \xB7 awaiting release admission`}`,name:o.label,category:"agent"})),n=O$1().map(o=>({value:o.id,label:`AI Gateway \xB7 ${o.label}`,hint:K(o.runtime),name:o.label,category:"gateway"})),s=[...t,...r,...i,...a,...n].filter(o=>!e||o.category===e).sort((o,l)=>{let Q=w.indexOf(o.category),V=w.indexOf(l.category);return Q-V||(o.label??"").localeCompare(l.label??"")});return O(s),s}function Ae(){let e=new Set(T().map(t=>t.category));return J.filter(t=>e.has(t.id)).map(t=>({value:t.id,label:t.label,hint:t.hint}))}function D(e){return e.charAt(0).toUpperCase()+e.slice(1)}function O(e){let t=new Set,r=new Set;for(let i of e){let a=i.label??i.name??String(i.value),n=String(i.value);if(t.has(a))throw new Error(`Duplicate kit picker label: ${a}`);if(r.has(n))throw new Error(`Duplicate kit picker value: ${n}`);t.add(a),r.add(n);}}var te=".workspairc.json",oe=".rapidkitrc.json",re=["workspai.config.js","workspai.config.mjs","workspai.config.cjs","rapidkit.config.js","rapidkit.config.mjs","rapidkit.config.cjs"],ae=["workspai.config.json","rapidkit.config.json"];function F(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function k(e,t){let r=t instanceof Error?t.message:String(t),i=e.endsWith(".js")&&/module is not defined in ES module scope/i.test(r)?' CommonJS syntax in a .js config is not valid when the project package uses "type": "module"; rename the file to .cjs or use export default.':"";return `Failed to load Workspai config at ${e}.${i} Cause: ${r}`}async function et(){for(let e$1 of [c$1.join(L.homedir(),te),c$1.join(L.homedir(),oe)])try{let t=await promises.readFile(e$1,"utf-8"),r=JSON.parse(t);return e.debug(`Loaded config from ${e$1}`),r}catch{}return e.debug("No user config found, using defaults"),{}}async function tt(e$1=process.cwd(),t={}){let r=e$1,i=c$1.parse(r).root;for(;r!==i;){for(let a of ae){let n=c$1.join(r,a);try{let s=await promises.readFile(n,"utf-8"),o=JSON.parse(s);if(!o||typeof o!="object"||Array.isArray(o))throw new Error("configuration root must be a JSON object");return e.debug(`Loaded data-only Workspai config from ${a}`),o}catch(s){if(F(s))continue;throw new Error(k(n,s))}}for(let a of re){let n=c$1.join(r,a);try{await promises.access(n);}catch(s){if(F(s))continue;throw new Error(k(n,s))}if(e.debug(`Found config file: ${n}`),!t.trustExecutableConfig)throw new Error(`Refusing to execute Workspai config at ${n} without explicit trust. Use a data-only workspai.config.json file, pass --trust-config, or set WORKSPAI_TRUST_CONFIG=1.`);try{let o=await import(pathToFileURL(n).href),l=o.default||o;return e.debug(`Loaded Workspai config from ${a}`),l}catch(s){throw new Error(k(n,s))}}r=c$1.dirname(r);}return e.debug("No Workspai config file found, using defaults"),{}}function ot(e,t,r){return {author:r.author||t.workspace?.defaultAuthor||e.author,pythonVersion:r.pythonVersion||t.workspace?.pythonVersion||e.pythonVersion,defaultInstallMethod:r.defaultInstallMethod||t.workspace?.installMethod||e.defaultInstallMethod,defaultKit:r.defaultKit||t.projects?.defaultKit||e.defaultKit,skipGit:r.skipGit??t.projects?.skipGit??e.skipGit,license:r.license||e.license,testRapidKitPath:r.testRapidKitPath||e.testRapidKitPath}}function rt(e){return f$1("DEV_PATH")||e.testRapidKitPath||void 0}var C=class extends Error{constructor(r,i){super(["Workspai workspaces cannot be nested.",`Target: ${r}`,`Containing workspace: ${i}`,"Choose Managed home or pass --output <path> with a location outside the current workspace."].join(`
|
|
2
|
+
`));this.targetPath=r;this.containingWorkspacePath=i;this.name="NestedWorkspaceCreationError";}targetPath;containingWorkspacePath;code="WORKSPACE_NESTING_NOT_SUPPORTED"};async function ne(e){try{return !!await ie.stat(e)}catch{return false}}function se(e,t){let r=e.indexOf(t);if(r>=0&&r+1<e.length)return e[r+1];let i=e.find(a=>a.startsWith(`${t}=`));if(i)return i.slice(t.length+1)}function ce(e){return e.includes("--here")}async function U(e){let t=c$1.resolve(e);for(;;){let r=[c$1.join(t,".workspai-workspace"),c$1.join(t,".rapidkit-workspace"),c$1.join(t,".workspai","workspace.json"),c$1.join(t,".rapidkit","workspace.json")];if((await Promise.all(r.map(ne))).some(Boolean))return t;let i=c$1.dirname(t);if(i===t)return;t=i;}}async function ft(e){let t=c$1.resolve(e),r=await U(c$1.dirname(t));if(r)throw new C(t,r)}async function le(e,t=homedir()){let i=[{value:"managed",label:"Managed home",hint:l(t)}];return await U(e)||i.push({value:"here",label:"Current directory",hint:e}),i}function q(e,t=p.cwd()){if(ce(e))return c$1.resolve(t);let r=se(e,"--output");if(r)return c$1.resolve(r)}function gt(e,t=p.cwd()){let r=c$1.resolve(e),i=c$1.resolve(t),a=c$1.relative(i,r);return a.length>0&&!a.startsWith("..")&&!c$1.isAbsolute(a)?`cd ${a}`:`cd ${r}`}function mt(e,t={}){let r=t.argv??[],i=t.outputParent??q(r,p.cwd());return m(e.trim(),{homeDir:t.homeDir,outputDir:i})}function ht(e,t,r={}){return e?c$1.resolve(e)===c$1.resolve(t)?true:r.outputParent===void 0:false}async function yt(e,t={}){let r=t.cwd??p.cwd(),i=t.homeDir??homedir(),a=q(e,r);if(a!==void 0)return a;let n=t.hasYes??(e.includes("--yes")||e.includes("-y"));if(!(t.interactive??(!n&&!!p.stdin.isTTY&&!b())))return;let o=await le(r,i);if(o.length===1)return;let{location:l}=await b$1([{type:"rawlist",name:"location",message:"Where should the workspace be created?",choices:o,default:0}]);if(l==="here")return c$1.resolve(r)}export{T as a,Ae as b,et as c,tt as d,ot as e,rt as f,ft as g,gt as h,mt as i,ht as j,yt as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-SVO2GGTV.js';import {m as m$1}from'./chunk-LUPKDFQ3.js';import {a as a$1}from'./chunk-GR6442P7.js';import {i,h}from'./chunk-BLEIUQL6.js';import {s,t}from'./chunk-ODK4LCEL.js';import {createHash}from'crypto';import l from'path';import {execa}from'execa';import v from'fs-extra';var D=s.projectTestCoverage.schemaVersion,P=t.projectTestCoverage,G=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deps.edn","project.clj","build.sbt","CMakeLists.txt","meson.build","deno.json","deno.jsonc"];function p(t){let e=Number(t);return Number.isFinite(e)&&e>=0?e:0}function m(t,e,o=0){let n=p(t),s=Math.min(p(e),n),r=p(o);return {total:n,covered:s,skipped:r,percent:n>0?Math.round(s/n*1e4)/100:null}}function W(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;return m(e.total,e.covered,e.skipped)}function y(t,e){let o=l.isAbsolute(e)?e:l.resolve(t,e),n=l.relative(t,o);return n&&!n.startsWith("..")?n.split(l.sep).join("/"):e}async function C(t){return createHash("sha256").update(await v.readFile(t)).digest("hex")}async function I(t){let e=l.resolve(t);for(;;){let o=await v.pathExists(l.join(e,".workspai","project.json"))||await v.pathExists(l.join(e,".rapidkit","project.json")),n=(await v.readdir(e).catch(()=>[])).some(r=>r.toLowerCase().endsWith(".gemspec"));if(o||n||(await Promise.all(G.map(r=>v.pathExists(l.join(e,r))))).some(Boolean))return e;let s=l.dirname(e);if(s===e)return l.resolve(t);e=s;}}async function V(t){return m$1(t).runtime}async function U(t,e,o=5){let n=[],s=[{dir:t,depth:0}],r=new Set([".git",".workspai",".rapidkit","node_modules",".venv","vendor","deps"]);for(;s.length>0;){let a=s.shift();if(!a)break;let i=await v.readdir(a.dir,{withFileTypes:true}).catch(()=>[]);for(let c of i){if(r.has(c.name)||a$1(c.name))continue;let u=l.join(a.dir,c.name),g=l.relative(t,u).split(l.sep).join("/");c.isFile()&&e(c.name,g)&&n.push(u),c.isDirectory()&&a.depth<o&&s.push({dir:u,depth:a.depth+1});}}return n}async function L(t,e){let o=await v.readJson(e),n=o.total??o,s={};for(let a of ["lines","branches","functions","statements"]){let i=W(n[a]);i&&(s[a]=i);}let r=[];for(let[a,i]of Object.entries(o)){if(a==="total"||!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u={};for(let g of ["lines","branches","functions","statements"]){let b=W(c[g]);b&&(u[g]=b);}r.push({path:y(t,a),metrics:u});}return {metrics:s,files:r,source:{format:"istanbul-json",path:e,sha256:await C(e)}}}async function z(t,e){let o=await v.readJson(e),n=o.totals??{},s={lines:m(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(s.branches=m(n.num_branches,n.covered_branches));let r=[];for(let[a,i]of Object.entries(o.files??{})){let c=i?.summary??{};r.push({path:y(t,a),metrics:{lines:m(c.num_statements,c.covered_lines),...p(c.num_branches)>0?{branches:m(c.num_branches,c.covered_branches)}:{}}});}return {metrics:s,files:r,source:{format:"coverage-py-json",path:e,sha256:await C(e)}}}function j(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,o=p(e.count),n=p(e.covered);return o>0?m(o,n):void 0}async function B(t,e){let o=await v.readJson(e),n=Array.isArray(o.data)?o.data[0]??{}:o,s=n.totals??{},r={};r.lines=j(s.lines),r.functions=j(s.functions),r.branches=j(s.branches),r.statements=j(s.regions);let a=[];for(let i of Array.isArray(n.files)?n.files:[]){if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u=c.summary??{};a.push({path:y(t,String(c.filename??"unknown")),metrics:{lines:j(u.lines),functions:j(u.functions),branches:j(u.branches),statements:j(u.regions)}});}return {metrics:r,files:a,source:{format:"llvm-cov-json",path:e,sha256:await C(e)}}}async function E(t,e){let o=await v.readFile(e,"utf8"),n=[],s="",r=0,a=0,i=0,c=0,u=0,g=0,b=d=>{s&&(n.push({path:y(t,s),metrics:{lines:m(d.lineTotal,d.lineCovered),functions:m(d.functionTotal,d.functionCovered),branches:m(d.branchTotal,d.branchCovered)}}),r+=d.lineTotal,a+=d.lineCovered,i+=d.functionTotal,c+=d.functionCovered,u+=d.branchTotal,g+=d.branchCovered);},h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0};for(let d of o.split(/\r?\n/))d.startsWith("SF:")?s=d.slice(3):d.startsWith("LF:")?h.lineTotal=p(d.slice(3)):d.startsWith("LH:")?h.lineCovered=p(d.slice(3)):d.startsWith("FNF:")?h.functionTotal=p(d.slice(4)):d.startsWith("FNH:")?h.functionCovered=p(d.slice(4)):d.startsWith("BRF:")?h.branchTotal=p(d.slice(4)):d.startsWith("BRH:")?h.branchCovered=p(d.slice(4)):d==="end_of_record"&&(b(h),s="",h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0});return {metrics:{lines:m(r,a),functions:m(i,c),branches:m(u,g)},files:n,source:{format:"lcov",path:e,sha256:await C(e)}}}async function K(t,e){let o=await v.readFile(e,"utf8"),n=new Map;for(let a of o.split(/\r?\n/).slice(1)){let i=/^(.+?):\d+\.\d+,\d+\.\d+\s+(\d+)\s+(\d+)$/.exec(a.trim());if(!i)continue;let c=n.get(i[1])??{total:0,covered:0},u=p(i[2]);c.total+=u,p(i[3])>0&&(c.covered+=u),n.set(i[1],c);}let s=[...n.entries()].map(([a,i])=>({path:y(t,a),metrics:{statements:m(i.total,i.covered)}})),r=[...n.values()].reduce((a,i)=>({total:a.total+i.total,covered:a.covered+i.covered}),{total:0,covered:0});return {metrics:{statements:m(r.total,r.covered)},files:s,source:{format:"go-coverprofile",path:e,sha256:await C(e)}}}function k(t,e){let n=[...t.matchAll(new RegExp(`<counter\\s+type=["']${e}["']\\s+missed=["'](\\d+)["']\\s+covered=["'](\\d+)["']\\s*\\/?\\s*>`,"gi"))].at(-1);return n?m(Number(n[1])+Number(n[2]),n[2]):void 0}async function x(t,e){let o=await v.readFile(t,"utf8"),n={};if(e==="cobertura-xml"){let s=/<coverage\b([^>]*)>/i.exec(o)?.[1]??"",r=/\bline-rate=["']([\d.]+)["']/i.exec(s)?.[1],a=/\bbranch-rate=["']([\d.]+)["']/i.exec(s)?.[1];r&&(n.lines=m(1e4,Math.round(Number(r)*1e4))),a&&(n.branches=m(1e4,Math.round(Number(a)*1e4)));}if(e==="clover-xml"){let r=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",a=g=>p(new RegExp(`\\b${g}=["'](\\d+)["']`,"i").exec(r)?.[1]),i=a("statements"),c=a("methods"),u=a("conditionals");i>0&&(n.statements=m(i,a("coveredstatements"))),c>0&&(n.functions=m(c,a("coveredmethods"))),u>0&&(n.branches=m(u,a("coveredconditionals")));}return n.lines??=k(o,"LINE"),n.branches??=k(o,"BRANCH"),n.functions??=k(o,"METHOD"),n.statements??=k(o,"INSTRUCTION"),{metrics:n,files:[],source:{format:e,path:t,sha256:await C(t)}}}async function X(t){let e=await v.readFile(t,"utf8"),o=/<scoverage\b([^>]*)>/i.exec(e)?.[1]??"",n=b=>p(new RegExp(`\\b${b}=["']([\\d.]+)["']`,"i").exec(o)?.[1]),s=n("statement-count"),r=n("statements-invoked"),a=n("branch-count"),i=n("branches-invoked"),c=n("statement-rate"),u=n("branch-rate"),g={};return s>0?g.statements=m(s,r):c>0&&(g.statements=m(1e4,Math.round(c*100))),a>0?g.branches=m(a,i):u>0&&(g.branches=m(1e4,Math.round(u*100))),{metrics:g,files:[],source:{format:"scoverage-xml",path:t,sha256:await C(t)}}}async function Q(t,e){let o=await v.readJson(e),n=new Map;for(let a of Object.values(o)){let i=a?.coverage;if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[c,u]of Object.entries(i)){if(!Array.isArray(u))continue;let g=n.get(c)??[];u.forEach((b,h)=>{typeof b=="number"&&(g[h]=Math.max(g[h]??0,b));}),n.set(c,g);}}let s=[...n.entries()].map(([a,i])=>{let c=i.filter(u=>typeof u=="number");return {path:y(t,a),metrics:{lines:m(c.length,c.filter(u=>u>0).length)}}}),r=s.reduce((a,i)=>{let c=i.metrics.lines;return {total:a.total+(c?.total??0),covered:a.covered+(c?.covered??0)}},{total:0,covered:0});return {metrics:{lines:m(r.total,r.covered)},files:s,source:{format:"simplecov-json",path:e,sha256:await C(e)}}}async function q(t,e={}){let o=[{relativePath:"coverage/coverage-summary.json",parser:r=>L(t,r)},{relativePath:"coverage.json",parser:async r=>{let a=await v.readJson(r);return Array.isArray(a.data)?B(t,r):z(t,r)}},{relativePath:"coverage/lcov.info",parser:r=>E(t,r)},{relativePath:"cover/lcov.info",parser:r=>E(t,r)},{relativePath:"lcov.info",parser:r=>E(t,r)},{relativePath:"coverage.out",parser:r=>K(t,r)},{relativePath:"target/site/jacoco/jacoco.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"build/reports/jacoco/test/jacocoTestReport.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"coverage.xml",parser:r=>x(r,"clover-xml")},{relativePath:".resultset.json",parser:r=>Q(t,r)}];for(let r of o){let a=l.join(t,r.relativePath);if(await v.pathExists(a))return r.parser(a)}if(e.recursive===false)return null;let s=(await U(t,(r,a)=>r==="coverage.cobertura.xml"||r==="jacoco.xml"||r==="clover.xml"||r==="scoverage.xml"||a.endsWith("/coverage-summary.json"),7)).sort()[0];return s?s.endsWith("coverage-summary.json")?L(t,s):s.endsWith("jacoco.xml")?x(s,"jacoco-xml"):s.endsWith("coverage.cobertura.xml")?x(s,"cobertura-xml"):s.endsWith("scoverage.xml")?X(s):x(s,"clover-xml"):null}async function Y(t){return v.readJson(l.join(t,"package.json")).catch(()=>null)}async function H(t,e){let o=(n,s)=>({cwd:t,executable:n,args:s});if(e==="node"||e==="bun"){let s=(await Y(t))?.scripts??{},r=["test:coverage","test:cov","coverage"].find(i=>typeof s[i]=="string"),a=e==="bun"?"bun":await v.pathExists(l.join(t,"pnpm-lock.yaml"))?"pnpm":await v.pathExists(l.join(t,"yarn.lock"))?"yarn":"npm";if(r)return {runner:String(s[r]).split(/\s+/)[0]||a,invocations:[o(a,a==="yarn"?[r]:["run",r])],diagnostics:[]};if(typeof s.test=="string"){let i=a==="yarn"?["test","--coverage"]:a==="bun"?["test","--coverage","--coverage-reporter=lcov"]:["test","--","--coverage"];return {runner:String(s.test).split(/\s+/)[0]||a,invocations:[o(a,i)],diagnostics:[]}}return {runner:null,invocations:[],diagnostics:["No project-owned test or coverage script was detected."]}}if(e==="deno")return {runner:"deno",invocations:[o("deno",["test","--coverage=coverage"]),o("deno",["coverage","--lcov","--output=coverage/lcov.info","coverage"])],diagnostics:[]};if(e==="python")return {runner:"pytest-cov",invocations:[o(await v.pathExists(l.join(t,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"))?l.join(".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"):process.platform==="win32"?"python":"python3",["-m","pytest","--cov=.","--cov-report=json:coverage.json"])],diagnostics:[]};if(e==="go")return {runner:"go test",invocations:[o("go",["test","./...","-coverprofile=coverage.out"])],diagnostics:[]};if(e==="java"){let n=await v.pathExists(l.join(t,"gradlew")),s=await v.pathExists(l.join(t,"gradlew.bat")),r=n||s,a=await v.pathExists(l.join(t,"mvnw")),i=await v.pathExists(l.join(t,"mvnw.cmd")),c=r?process.platform==="win32"&&s?".\\gradlew.bat":"./gradlew":await v.pathExists(l.join(t,"pom.xml"))?process.platform==="win32"&&i?".\\mvnw.cmd":a?"./mvnw":"mvn":"gradle";return {runner:r?"jacoco/gradle":"jacoco/maven",invocations:[o(c,r?["test","jacocoTestReport"]:["test","jacoco:report"])],diagnostics:[]}}return e==="dotnet"?{runner:"dotnet coverlet",invocations:[o("dotnet",["test","--collect:XPlat Code Coverage"])],diagnostics:[]}:e==="rust"?{runner:"cargo llvm-cov",invocations:[o("cargo",["llvm-cov","--json","--output-path","coverage.json"])],diagnostics:["cargo-llvm-cov must be available in the project toolchain."]}:e==="php"?{runner:"phpunit",invocations:[o(process.platform==="win32"?"vendor\\bin\\phpunit.bat":"vendor/bin/phpunit",["--coverage-clover","coverage.xml"])],diagnostics:[]}:e==="ruby"?{runner:"simplecov",invocations:[o("bundle",["exec","rspec"])],diagnostics:["The test suite must enable SimpleCov to emit .resultset.json."]}:e==="elixir"?{runner:"mix cover",invocations:[o("mix",["test","--cover"])],diagnostics:["Configure ExCoveralls for JSON or LCOV interchange when machine-readable coverage is required."]}:e==="clojure"?{runner:"cloverage",invocations:[o("clojure",["-M:coverage"])],diagnostics:["The project must declare a coverage alias such as cloverage."]}:e==="scala"?{runner:"sbt-scoverage",invocations:[o("sbt",["clean","coverage","test","coverageReport"])],diagnostics:["The project must declare the scoverage plugin."]}:e==="kotlin"?{runner:"jacoco/gradle",invocations:[o(await v.pathExists(l.join(t,process.platform==="win32"?"gradlew.bat":"gradlew"))?process.platform==="win32"?".\\gradlew.bat":"./gradlew":"gradle",["test","jacocoTestReport"])],diagnostics:["The project must declare the JaCoCo Gradle plugin."]}:e==="c"||e==="cpp"?{runner:"CTest/LLVM coverage",invocations:[o("ctest",["--test-dir","build","--output-on-failure"])],diagnostics:["The native build must be instrumented for coverage and export LCOV, Cobertura, or LLVM JSON evidence."]}:{runner:null,invocations:[],diagnostics:["Project runtime could not be detected."]}}async function ve(t,e){let o=await I(t),n=e??await V(o),s=await H(o,n),r=await q(o,{recursive:false}).catch(()=>null),a=r?.source.path&&r.source.sha256?[{path:l.relative(o,r.source.path).split(l.sep).join("/"),sha256:r.source.sha256}]:[],i=[...s.diagnostics],c=r?"available":s.invocations.length===0||n==="unknown"?"unsupported":i.length>0?"requires-setup":"available";return {runtime:n,runner:s.runner,status:c,existingEvidence:a,invocations:s.invocations,prerequisites:i}}function Z(t,e){let o=t?l.relative(t,e).split(l.sep).join("/"):l.resolve(e),n=l.basename(e).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",s=createHash("sha256").update(o).digest("hex").slice(0,12);return `${n}--${s}`}function ee(t){return t.lines?"lines":t.statements?"statements":t.branches?"branches":"functions"}async function me(t={}){let e=await I(t.projectPath??process.cwd()),o=a(e),n=t.runtime??await V(e),s=Math.max(0,Math.min(100,Math.round(t.target??80))),r=await H(e,n),a$1=[],i$1=Date.now();if(t.run)for(let f of r.invocations){let w=await execa(f.executable,f.args,{cwd:f.cwd,reject:false,timeout:6e5}).catch(()=>({exitCode:1}));if(a$1.push(Number(w.exitCode??1)),Number(w.exitCode??1)!==0)break}let c=await q(e).catch(()=>null),u=c?ee(c.metrics):"lines",g=c?.metrics[u]?.percent??null,b=t.run&&a$1.some(f=>f!==0)?"failed":g===null?"unavailable":g>=s?"passed":"below-target",h$1=Z(o,e),d=l.join(e,P),R=o?`.workspai/reports/projects/${h$1}/project-test-coverage-last-run.json`:null,T={schemaVersion:D,generatedAt:new Date().toISOString(),status:b,project:{id:h$1,name:l.basename(e),path:e,workspacePath:o},runtime:n,runner:r.runner,target:{metric:u,percent:s},metrics:c?.metrics??{},files:c?.files??[],lowCoverageFiles:(c?.files??[]).map(f=>{let w=f.metrics[u]??f.metrics.lines??f.metrics.statements;return {path:f.path,percent:w?.percent??null,uncovered:Math.max(0,(w?.total??0)-(w?.covered??0))}}).filter(f=>f.percent===null||f.percent<s).sort((f,w)=>w.uncovered-f.uncovered||f.path.localeCompare(w.path)),source:c?.source??{format:"unknown",path:null,sha256:null},execution:{requested:t.run===true,invocations:r.invocations,exitCodes:a$1,durationMs:Date.now()-i$1},diagnostics:[...r.diagnostics,...c?[]:["No supported machine-readable coverage artifact was found."]],artifactPaths:{project:d,workspaceLatest:o?l.join(o,P):null,workspaceProject:o&&R?l.join(o,R):null}};return o&&R&&await i(o,P,[{relativePath:P,payload:T},{relativePath:R,payload:T}]),await h(e,P,T),T}export{D as a,P as b,ve as c,me as d};
|
|
1
|
+
import {a}from'./chunk-SVO2GGTV.js';import {m as m$1}from'./chunk-7EMG3C3H.js';import {a as a$1}from'./chunk-GR6442P7.js';import {i,h}from'./chunk-BLEIUQL6.js';import {s,t}from'./chunk-ODK4LCEL.js';import {createHash}from'crypto';import l from'path';import {execa}from'execa';import v from'fs-extra';var D=s.projectTestCoverage.schemaVersion,P=t.projectTestCoverage,G=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deps.edn","project.clj","build.sbt","CMakeLists.txt","meson.build","deno.json","deno.jsonc"];function p(t){let e=Number(t);return Number.isFinite(e)&&e>=0?e:0}function m(t,e,o=0){let n=p(t),s=Math.min(p(e),n),r=p(o);return {total:n,covered:s,skipped:r,percent:n>0?Math.round(s/n*1e4)/100:null}}function W(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;return m(e.total,e.covered,e.skipped)}function y(t,e){let o=l.isAbsolute(e)?e:l.resolve(t,e),n=l.relative(t,o);return n&&!n.startsWith("..")?n.split(l.sep).join("/"):e}async function C(t){return createHash("sha256").update(await v.readFile(t)).digest("hex")}async function I(t){let e=l.resolve(t);for(;;){let o=await v.pathExists(l.join(e,".workspai","project.json"))||await v.pathExists(l.join(e,".rapidkit","project.json")),n=(await v.readdir(e).catch(()=>[])).some(r=>r.toLowerCase().endsWith(".gemspec"));if(o||n||(await Promise.all(G.map(r=>v.pathExists(l.join(e,r))))).some(Boolean))return e;let s=l.dirname(e);if(s===e)return l.resolve(t);e=s;}}async function V(t){return m$1(t).runtime}async function U(t,e,o=5){let n=[],s=[{dir:t,depth:0}],r=new Set([".git",".workspai",".rapidkit","node_modules",".venv","vendor","deps"]);for(;s.length>0;){let a=s.shift();if(!a)break;let i=await v.readdir(a.dir,{withFileTypes:true}).catch(()=>[]);for(let c of i){if(r.has(c.name)||a$1(c.name))continue;let u=l.join(a.dir,c.name),g=l.relative(t,u).split(l.sep).join("/");c.isFile()&&e(c.name,g)&&n.push(u),c.isDirectory()&&a.depth<o&&s.push({dir:u,depth:a.depth+1});}}return n}async function L(t,e){let o=await v.readJson(e),n=o.total??o,s={};for(let a of ["lines","branches","functions","statements"]){let i=W(n[a]);i&&(s[a]=i);}let r=[];for(let[a,i]of Object.entries(o)){if(a==="total"||!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u={};for(let g of ["lines","branches","functions","statements"]){let b=W(c[g]);b&&(u[g]=b);}r.push({path:y(t,a),metrics:u});}return {metrics:s,files:r,source:{format:"istanbul-json",path:e,sha256:await C(e)}}}async function z(t,e){let o=await v.readJson(e),n=o.totals??{},s={lines:m(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(s.branches=m(n.num_branches,n.covered_branches));let r=[];for(let[a,i]of Object.entries(o.files??{})){let c=i?.summary??{};r.push({path:y(t,a),metrics:{lines:m(c.num_statements,c.covered_lines),...p(c.num_branches)>0?{branches:m(c.num_branches,c.covered_branches)}:{}}});}return {metrics:s,files:r,source:{format:"coverage-py-json",path:e,sha256:await C(e)}}}function j(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,o=p(e.count),n=p(e.covered);return o>0?m(o,n):void 0}async function B(t,e){let o=await v.readJson(e),n=Array.isArray(o.data)?o.data[0]??{}:o,s=n.totals??{},r={};r.lines=j(s.lines),r.functions=j(s.functions),r.branches=j(s.branches),r.statements=j(s.regions);let a=[];for(let i of Array.isArray(n.files)?n.files:[]){if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u=c.summary??{};a.push({path:y(t,String(c.filename??"unknown")),metrics:{lines:j(u.lines),functions:j(u.functions),branches:j(u.branches),statements:j(u.regions)}});}return {metrics:r,files:a,source:{format:"llvm-cov-json",path:e,sha256:await C(e)}}}async function E(t,e){let o=await v.readFile(e,"utf8"),n=[],s="",r=0,a=0,i=0,c=0,u=0,g=0,b=d=>{s&&(n.push({path:y(t,s),metrics:{lines:m(d.lineTotal,d.lineCovered),functions:m(d.functionTotal,d.functionCovered),branches:m(d.branchTotal,d.branchCovered)}}),r+=d.lineTotal,a+=d.lineCovered,i+=d.functionTotal,c+=d.functionCovered,u+=d.branchTotal,g+=d.branchCovered);},h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0};for(let d of o.split(/\r?\n/))d.startsWith("SF:")?s=d.slice(3):d.startsWith("LF:")?h.lineTotal=p(d.slice(3)):d.startsWith("LH:")?h.lineCovered=p(d.slice(3)):d.startsWith("FNF:")?h.functionTotal=p(d.slice(4)):d.startsWith("FNH:")?h.functionCovered=p(d.slice(4)):d.startsWith("BRF:")?h.branchTotal=p(d.slice(4)):d.startsWith("BRH:")?h.branchCovered=p(d.slice(4)):d==="end_of_record"&&(b(h),s="",h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0});return {metrics:{lines:m(r,a),functions:m(i,c),branches:m(u,g)},files:n,source:{format:"lcov",path:e,sha256:await C(e)}}}async function K(t,e){let o=await v.readFile(e,"utf8"),n=new Map;for(let a of o.split(/\r?\n/).slice(1)){let i=/^(.+?):\d+\.\d+,\d+\.\d+\s+(\d+)\s+(\d+)$/.exec(a.trim());if(!i)continue;let c=n.get(i[1])??{total:0,covered:0},u=p(i[2]);c.total+=u,p(i[3])>0&&(c.covered+=u),n.set(i[1],c);}let s=[...n.entries()].map(([a,i])=>({path:y(t,a),metrics:{statements:m(i.total,i.covered)}})),r=[...n.values()].reduce((a,i)=>({total:a.total+i.total,covered:a.covered+i.covered}),{total:0,covered:0});return {metrics:{statements:m(r.total,r.covered)},files:s,source:{format:"go-coverprofile",path:e,sha256:await C(e)}}}function k(t,e){let n=[...t.matchAll(new RegExp(`<counter\\s+type=["']${e}["']\\s+missed=["'](\\d+)["']\\s+covered=["'](\\d+)["']\\s*\\/?\\s*>`,"gi"))].at(-1);return n?m(Number(n[1])+Number(n[2]),n[2]):void 0}async function x(t,e){let o=await v.readFile(t,"utf8"),n={};if(e==="cobertura-xml"){let s=/<coverage\b([^>]*)>/i.exec(o)?.[1]??"",r=/\bline-rate=["']([\d.]+)["']/i.exec(s)?.[1],a=/\bbranch-rate=["']([\d.]+)["']/i.exec(s)?.[1];r&&(n.lines=m(1e4,Math.round(Number(r)*1e4))),a&&(n.branches=m(1e4,Math.round(Number(a)*1e4)));}if(e==="clover-xml"){let r=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",a=g=>p(new RegExp(`\\b${g}=["'](\\d+)["']`,"i").exec(r)?.[1]),i=a("statements"),c=a("methods"),u=a("conditionals");i>0&&(n.statements=m(i,a("coveredstatements"))),c>0&&(n.functions=m(c,a("coveredmethods"))),u>0&&(n.branches=m(u,a("coveredconditionals")));}return n.lines??=k(o,"LINE"),n.branches??=k(o,"BRANCH"),n.functions??=k(o,"METHOD"),n.statements??=k(o,"INSTRUCTION"),{metrics:n,files:[],source:{format:e,path:t,sha256:await C(t)}}}async function X(t){let e=await v.readFile(t,"utf8"),o=/<scoverage\b([^>]*)>/i.exec(e)?.[1]??"",n=b=>p(new RegExp(`\\b${b}=["']([\\d.]+)["']`,"i").exec(o)?.[1]),s=n("statement-count"),r=n("statements-invoked"),a=n("branch-count"),i=n("branches-invoked"),c=n("statement-rate"),u=n("branch-rate"),g={};return s>0?g.statements=m(s,r):c>0&&(g.statements=m(1e4,Math.round(c*100))),a>0?g.branches=m(a,i):u>0&&(g.branches=m(1e4,Math.round(u*100))),{metrics:g,files:[],source:{format:"scoverage-xml",path:t,sha256:await C(t)}}}async function Q(t,e){let o=await v.readJson(e),n=new Map;for(let a of Object.values(o)){let i=a?.coverage;if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[c,u]of Object.entries(i)){if(!Array.isArray(u))continue;let g=n.get(c)??[];u.forEach((b,h)=>{typeof b=="number"&&(g[h]=Math.max(g[h]??0,b));}),n.set(c,g);}}let s=[...n.entries()].map(([a,i])=>{let c=i.filter(u=>typeof u=="number");return {path:y(t,a),metrics:{lines:m(c.length,c.filter(u=>u>0).length)}}}),r=s.reduce((a,i)=>{let c=i.metrics.lines;return {total:a.total+(c?.total??0),covered:a.covered+(c?.covered??0)}},{total:0,covered:0});return {metrics:{lines:m(r.total,r.covered)},files:s,source:{format:"simplecov-json",path:e,sha256:await C(e)}}}async function q(t,e={}){let o=[{relativePath:"coverage/coverage-summary.json",parser:r=>L(t,r)},{relativePath:"coverage.json",parser:async r=>{let a=await v.readJson(r);return Array.isArray(a.data)?B(t,r):z(t,r)}},{relativePath:"coverage/lcov.info",parser:r=>E(t,r)},{relativePath:"cover/lcov.info",parser:r=>E(t,r)},{relativePath:"lcov.info",parser:r=>E(t,r)},{relativePath:"coverage.out",parser:r=>K(t,r)},{relativePath:"target/site/jacoco/jacoco.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"build/reports/jacoco/test/jacocoTestReport.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"coverage.xml",parser:r=>x(r,"clover-xml")},{relativePath:".resultset.json",parser:r=>Q(t,r)}];for(let r of o){let a=l.join(t,r.relativePath);if(await v.pathExists(a))return r.parser(a)}if(e.recursive===false)return null;let s=(await U(t,(r,a)=>r==="coverage.cobertura.xml"||r==="jacoco.xml"||r==="clover.xml"||r==="scoverage.xml"||a.endsWith("/coverage-summary.json"),7)).sort()[0];return s?s.endsWith("coverage-summary.json")?L(t,s):s.endsWith("jacoco.xml")?x(s,"jacoco-xml"):s.endsWith("coverage.cobertura.xml")?x(s,"cobertura-xml"):s.endsWith("scoverage.xml")?X(s):x(s,"clover-xml"):null}async function Y(t){return v.readJson(l.join(t,"package.json")).catch(()=>null)}async function H(t,e){let o=(n,s)=>({cwd:t,executable:n,args:s});if(e==="node"||e==="bun"){let s=(await Y(t))?.scripts??{},r=["test:coverage","test:cov","coverage"].find(i=>typeof s[i]=="string"),a=e==="bun"?"bun":await v.pathExists(l.join(t,"pnpm-lock.yaml"))?"pnpm":await v.pathExists(l.join(t,"yarn.lock"))?"yarn":"npm";if(r)return {runner:String(s[r]).split(/\s+/)[0]||a,invocations:[o(a,a==="yarn"?[r]:["run",r])],diagnostics:[]};if(typeof s.test=="string"){let i=a==="yarn"?["test","--coverage"]:a==="bun"?["test","--coverage","--coverage-reporter=lcov"]:["test","--","--coverage"];return {runner:String(s.test).split(/\s+/)[0]||a,invocations:[o(a,i)],diagnostics:[]}}return {runner:null,invocations:[],diagnostics:["No project-owned test or coverage script was detected."]}}if(e==="deno")return {runner:"deno",invocations:[o("deno",["test","--coverage=coverage"]),o("deno",["coverage","--lcov","--output=coverage/lcov.info","coverage"])],diagnostics:[]};if(e==="python")return {runner:"pytest-cov",invocations:[o(await v.pathExists(l.join(t,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"))?l.join(".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"):process.platform==="win32"?"python":"python3",["-m","pytest","--cov=.","--cov-report=json:coverage.json"])],diagnostics:[]};if(e==="go")return {runner:"go test",invocations:[o("go",["test","./...","-coverprofile=coverage.out"])],diagnostics:[]};if(e==="java"){let n=await v.pathExists(l.join(t,"gradlew")),s=await v.pathExists(l.join(t,"gradlew.bat")),r=n||s,a=await v.pathExists(l.join(t,"mvnw")),i=await v.pathExists(l.join(t,"mvnw.cmd")),c=r?process.platform==="win32"&&s?".\\gradlew.bat":"./gradlew":await v.pathExists(l.join(t,"pom.xml"))?process.platform==="win32"&&i?".\\mvnw.cmd":a?"./mvnw":"mvn":"gradle";return {runner:r?"jacoco/gradle":"jacoco/maven",invocations:[o(c,r?["test","jacocoTestReport"]:["test","jacoco:report"])],diagnostics:[]}}return e==="dotnet"?{runner:"dotnet coverlet",invocations:[o("dotnet",["test","--collect:XPlat Code Coverage"])],diagnostics:[]}:e==="rust"?{runner:"cargo llvm-cov",invocations:[o("cargo",["llvm-cov","--json","--output-path","coverage.json"])],diagnostics:["cargo-llvm-cov must be available in the project toolchain."]}:e==="php"?{runner:"phpunit",invocations:[o(process.platform==="win32"?"vendor\\bin\\phpunit.bat":"vendor/bin/phpunit",["--coverage-clover","coverage.xml"])],diagnostics:[]}:e==="ruby"?{runner:"simplecov",invocations:[o("bundle",["exec","rspec"])],diagnostics:["The test suite must enable SimpleCov to emit .resultset.json."]}:e==="elixir"?{runner:"mix cover",invocations:[o("mix",["test","--cover"])],diagnostics:["Configure ExCoveralls for JSON or LCOV interchange when machine-readable coverage is required."]}:e==="clojure"?{runner:"cloverage",invocations:[o("clojure",["-M:coverage"])],diagnostics:["The project must declare a coverage alias such as cloverage."]}:e==="scala"?{runner:"sbt-scoverage",invocations:[o("sbt",["clean","coverage","test","coverageReport"])],diagnostics:["The project must declare the scoverage plugin."]}:e==="kotlin"?{runner:"jacoco/gradle",invocations:[o(await v.pathExists(l.join(t,process.platform==="win32"?"gradlew.bat":"gradlew"))?process.platform==="win32"?".\\gradlew.bat":"./gradlew":"gradle",["test","jacocoTestReport"])],diagnostics:["The project must declare the JaCoCo Gradle plugin."]}:e==="c"||e==="cpp"?{runner:"CTest/LLVM coverage",invocations:[o("ctest",["--test-dir","build","--output-on-failure"])],diagnostics:["The native build must be instrumented for coverage and export LCOV, Cobertura, or LLVM JSON evidence."]}:{runner:null,invocations:[],diagnostics:["Project runtime could not be detected."]}}async function ve(t,e){let o=await I(t),n=e??await V(o),s=await H(o,n),r=await q(o,{recursive:false}).catch(()=>null),a=r?.source.path&&r.source.sha256?[{path:l.relative(o,r.source.path).split(l.sep).join("/"),sha256:r.source.sha256}]:[],i=[...s.diagnostics],c=r?"available":s.invocations.length===0||n==="unknown"?"unsupported":i.length>0?"requires-setup":"available";return {runtime:n,runner:s.runner,status:c,existingEvidence:a,invocations:s.invocations,prerequisites:i}}function Z(t,e){let o=t?l.relative(t,e).split(l.sep).join("/"):l.resolve(e),n=l.basename(e).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",s=createHash("sha256").update(o).digest("hex").slice(0,12);return `${n}--${s}`}function ee(t){return t.lines?"lines":t.statements?"statements":t.branches?"branches":"functions"}async function me(t={}){let e=await I(t.projectPath??process.cwd()),o=a(e),n=t.runtime??await V(e),s=Math.max(0,Math.min(100,Math.round(t.target??80))),r=await H(e,n),a$1=[],i$1=Date.now();if(t.run)for(let f of r.invocations){let w=await execa(f.executable,f.args,{cwd:f.cwd,reject:false,timeout:6e5}).catch(()=>({exitCode:1}));if(a$1.push(Number(w.exitCode??1)),Number(w.exitCode??1)!==0)break}let c=await q(e).catch(()=>null),u=c?ee(c.metrics):"lines",g=c?.metrics[u]?.percent??null,b=t.run&&a$1.some(f=>f!==0)?"failed":g===null?"unavailable":g>=s?"passed":"below-target",h$1=Z(o,e),d=l.join(e,P),R=o?`.workspai/reports/projects/${h$1}/project-test-coverage-last-run.json`:null,T={schemaVersion:D,generatedAt:new Date().toISOString(),status:b,project:{id:h$1,name:l.basename(e),path:e,workspacePath:o},runtime:n,runner:r.runner,target:{metric:u,percent:s},metrics:c?.metrics??{},files:c?.files??[],lowCoverageFiles:(c?.files??[]).map(f=>{let w=f.metrics[u]??f.metrics.lines??f.metrics.statements;return {path:f.path,percent:w?.percent??null,uncovered:Math.max(0,(w?.total??0)-(w?.covered??0))}}).filter(f=>f.percent===null||f.percent<s).sort((f,w)=>w.uncovered-f.uncovered||f.path.localeCompare(w.path)),source:c?.source??{format:"unknown",path:null,sha256:null},execution:{requested:t.run===true,invocations:r.invocations,exitCodes:a$1,durationMs:Date.now()-i$1},diagnostics:[...r.diagnostics,...c?[]:["No supported machine-readable coverage artifact was found."]],artifactPaths:{project:d,workspaceLatest:o?l.join(o,P):null,workspaceProject:o&&R?l.join(o,R):null}};return o&&R&&await i(o,P,[{relativePath:P,payload:T},{relativePath:R,payload:T}]),await h(e,P,T),T}export{D as a,P as b,ve as c,me as d};
|
|
@@ -2,7 +2,7 @@ import {c}from'./chunk-N4B2M44I.js';import {a}from'./chunk-A5FBGRJA.js';import {
|
|
|
2
2
|
`);}async function se(e,r){let t=n.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${e}.${process.pid}.${randomUUID()}.tmp`;try{await promises.writeFile(o,r);let a=await promises.open(o,"r");try{await ae(a);}finally{await a.close();}try{await promises.rename(o,e);}catch(s){let i=s.code;if(i!=="EEXIST"&&i!=="EPERM")throw s;await le.move(o,e,{overwrite:true});}}finally{await promises.rm(o,{force:true}).catch(()=>{});}}async function Z(e){try{return {exists:true,content:await promises.readFile(e)}}catch(r){if(r.code==="ENOENT")return {exists:false};throw r}}async function ee(e,r){if(!r.exists){await promises.rm(e,{force:true});return}await se(e,r.content);}async function we(e,r){let t=n.join(e,"workspaces.json.lock"),o=randomUUID();await promises.mkdir(e,{recursive:true});let a=Date.now(),s;for(;!s;)try{s=await promises.open(t,"wx"),await s.writeFile(`${JSON.stringify({pid:process.pid,lockId:o,createdAt:new Date().toISOString()})}
|
|
3
3
|
`),await ae(s);}catch(i){if(i.code!=="EEXIST")throw i;let c=await promises.stat(t).catch(()=>null);if(c&&Date.now()-c.mtimeMs>de){let d=await promises.readFile(t,"utf8").then(g=>JSON.parse(g)).catch(()=>null),u=Number(d?.pid),f=false;if(Number.isInteger(u)&&u>0)try{process.kill(u,0),f=true;}catch(g){f=g.code==="EPERM";}if(!f){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>me)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(d=>setTimeout(d,25));}try{return await r()}finally{await s.close().catch(()=>{}),await promises.readFile(t,"utf8").then(c=>JSON.parse(c).lockId===o).catch(()=>false)&&await promises.rm(t,{force:true}).catch(()=>{});}}async function S(e){let r=w(),t=n.join(r,"workspaces.json"),o=n.join(x(),"workspaces.json"),a=[...new Set(y())];return we(r,async()=>{let[s,i]=await Promise.all([Z(t),Z(o)]),c=await oe(a);await e(c);let d=I(c);try{await X(t,d),await X(o,d);}catch(u){let g=(await Promise.allSettled([ee(t,s),ee(o,i)])).filter(k=>k.status==="rejected").map(k=>k.reason);throw g.length>0?new AggregateError([u,...g],"Workspace registry transaction failed and could not be fully restored"):u}return d})}async function ie(e,r){let t=a(e);await S(o=>{let a=o.workspaces.find(s=>s.path===t);if(a){a.name=r,a.mode=a.mode||"full",a.projects=Array.isArray(a.projects)?a.projects:[];return}o.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function He(e){let r=a(e),o=(await oe()).workspaces.find(a=>a.path===r);return o?{...o,projects:o.projects.map(a=>({...a}))}:null}async function Ke(e,r){let t=a(e);await S(o=>{let a=o.workspaces.findIndex(i=>i.path===t);if(!r){a>=0&&o.workspaces.splice(a,1);return}let s=G(r);a>=0?o.workspaces[a]=s:o.workspaces.push(s);});}async function qe(e){let r=a(e);await S(t=>{t.workspaces=t.workspaces.filter(o=>o.path!==r);});}async function he(e,r){try{await ie(e,r);}catch{console.warn(p.gray("Note: Could not register workspace in shared registry"));}}async function Qe(e,r=false){let t=a(e),o={workspacePath:t,workspaceFound:false,added:[],skipped:0};try{let a$1=await z(),s=a$1.workspaces.find(k=>k.path===t);if(!s){if(await he(t,n.basename(n.resolve(e))),a$1=await z(),s=a$1.workspaces.find(k=>k.path===t),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),o;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,c=0,d=[],u$1=[],f=[e],g=new Set;for(;f.length>0;){let k=f.shift();if(!k||g.has(k))continue;g.add(k);let w=await promises.readdir(k,{withFileTypes:true});for(let h of w){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let v=n.join(k,h.name),y=a(v);try{let x=false;for(let P of [...u(y,"context.json"),...u(y,"project.json")])try{await promises.access(P),x=true;break}catch{}if(x){let P=n.basename(y),m=s.projects.some($=>$.path===y);u$1.push({name:P,path:y}),m?c++:(s.projects.push({name:P,path:y}),i++,d.push(y),r||console.log(`\u2714 Added: ${n.relative(e,y)}`));continue}}catch{}f.push(v);}}return await S(k=>{let w=k.workspaces.find(y=>y.path===t);if(!w)return;let h=`${t}${n.sep}`,v=(w.projects||[]).filter(y=>y.path!==t&&!y.path.startsWith(h));w.projects=G({...w,projects:[...v,...u$1]}).projects;}),i>0?r||console.log(`
|
|
4
4
|
\u2705 Synced ${i} project(s) to registry`):r||console.log(`
|
|
5
|
-
\u2705 All projects already registered (${c} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:c}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function ye(e,r,t){let o=a(e),a$1=a(t);await S(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let c=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};c>=0?i.projects[c]=d:i.projects.push(d);});}async function Xe(e,r,t){try{await ye(e,r,t);}catch{}}async function Ze(e,r){let t=N("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(n.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(n.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-
|
|
5
|
+
\u2705 All projects already registered (${c} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:c}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function ye(e,r,t){let o=a(e),a$1=a(t);await S(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let c=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};c>=0?i.projects[c]=d:i.projects.push(d);});}async function Xe(e,r,t){try{await ye(e,r,t);}catch{}}async function Ze(e,r){let t=N("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(n.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(n.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-M3TWRHV6.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=$e();await promises.writeFile(n.join(e,"rapidkit"),s),await promises.chmod(n.join(e,"rapidkit"),493);let i=je();await promises.writeFile(n.join(e,"rapidkit.cmd"),i);let c=ve(r.name);await promises.writeFile(n.join(e,"README.md"),c),await promises.writeFile(n.join(e,".gitignore"),`# Workspai workspace
|
|
6
6
|
.env
|
|
7
7
|
.env.*
|
|
8
8
|
!.env.example
|
|
@@ -17,7 +17,7 @@ Thumbs.db
|
|
|
17
17
|
|
|
18
18
|
# Logs
|
|
19
19
|
*.log
|
|
20
|
-
`),await _e(e),t.succeed("Workspace created!"),r.skipGit||await re(e,N(),"Initial commit: Workspai workspace"),await ie(e,r.name);let{publishWorkspaceRegistrySummary:u}=await import('./workspace-registry-summary-
|
|
20
|
+
`),await _e(e),t.succeed("Workspace created!"),r.skipGit||await re(e,N(),"Initial commit: Workspai workspace"),await ie(e,r.name);let{publishWorkspaceRegistrySummary:u}=await import('./workspace-registry-summary-3PXZENLC.js');await u(e),console.log(`
|
|
21
21
|
${p.green("\u2728 Workspai workspace created successfully!")}
|
|
22
22
|
|
|
23
23
|
${p.bold("\u{1F4C2} Workspace structure:")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-A5FBGRJA.js';import {g as g$1,p}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-A5FBGRJA.js';import {g as g$1,p}from'./chunk-WU5M6UP7.js';import {g,h}from'./chunk-BLEIUQL6.js';import {y,w as w$1}from'./chunk-6BO4QHKA.js';import {t as t$1}from'./chunk-VQZ5PI5J.js';import {t,s}from'./chunk-ODK4LCEL.js';import a from'path';import {existsSync}from'fs';import m from'fs-extra';var f=t.workspaceRegistry,w=s.workspaceRegistry.schemaVersion;function E(r){return {slug:r.slug,relativePath:r.relativePath,framework:r.framework,kit:r.kit,source:r.source}}async function b(r){let e=t$1(r,"workspace.json").find(t=>existsSync(t));if(!e)return {exists:false,legacyProjectCount:0};try{let t=await m.readJson(e),c=Array.isArray(t.projects)?t.projects.length:0,o=typeof t.workspace_name=="string"&&t.workspace_name.trim()||typeof t.name=="string"&&t.name.trim()||a.basename(r);return {exists:true,manifestPath:e,workspaceName:o,profile:typeof t.profile=="string"?t.profile:void 0,legacyProjectCount:c}}catch{return {exists:true,manifestPath:e,legacyProjectCount:0,workspaceName:a.basename(r)}}}async function _(r){let e=a$1(r);for(let t of y())if(await m.pathExists(t))try{let o=((await m.readJson(t)).workspaces||[]).find(s=>a$1(s.path)===e);if(o)return {exists:true,projectCount:Array.isArray(o.projects)?o.projects.length:0,registryPath:t}}catch{continue}return {exists:false,projectCount:0,registryPath:a.join(w$1(),"workspaces.json")}}async function T(r,e){let t=a.resolve(r),c=await g(t,g$1),o=await b(t),s=await _(t),i=e?.contract!==void 0||!!c,n=[];if(e?.contract)n=e.contract.projects||[];else if(i)try{let{contract:A}=await p({workspacePath:t});n=A.projects||[];}catch{n=[];}let d={contract:{exists:i,projectCount:n.length,path:g$1},globalRegistry:{exists:s.exists,projectCount:s.projectCount,path:s.registryPath},legacyWorkspaceJson:{exists:o.exists,projectCount:o.legacyProjectCount,path:o.manifestPath?a.relative(t,o.manifestPath):void 0}},p$1="none",u=[],y=0;return i?(p$1="workspace.contract.json",u=n.map(E),y=u.length):s.projectCount>0?(p$1="global-registry",y=s.projectCount):o.legacyProjectCount>0&&(p$1="legacy-workspace.json",y=o.legacyProjectCount),{contractExists:i,summary:{schemaVersion:w,kind:"rapidkit.workspace.registry",workspacePath:t,workspaceName:o.workspaceName||a.basename(t),profile:o.profile,projectCount:y,authority:p$1,contractPath:g$1,projects:u,sources:d}}}async function U(r){let e=await g(r,f);if(!e)return null;try{let t=await m.readJson(e);return t?.schemaVersion!==w?null:t}catch{return null}}async function D(r,e){let t=await M(r,e);return await h(r,f,t),t}async function M(r,e){return {...(await T(r,{contract:e?.contract})).summary,generatedAt:(e?.now??new Date).toISOString(),registrySummaryPath:f}}function F(r,e=""){return r.projectCount>0?r.authority==="workspace.contract.json"?`${r.projectCount} project(s) registered in workspace contract${e}.`:r.authority==="global-registry"?`${r.projectCount} project(s) registered in global workspace registry${e}.`:`${r.projectCount} project(s) registered in legacy workspace manifest${e}.`:`Workspace state exists, but no projects are registered yet${e}.`}export{f as a,w as b,T as c,U as d,D as e,M as f,F as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {H,P as P$1,k,q as q$1,Q,V as V$1}from'./chunk-RRZQPFFR.js';import {b as b$2,c as c$2,a as a$3}from'./chunk-RQXZF7BZ.js';import {a as a$2}from'./chunk-NMXGSVMD.js';import {a as a$6}from'./chunk-HTYMXMQM.js';import {d as d$1,a as a$1,p as p$1,g as g$2,f as f$1,e}from'./chunk-WU5M6UP7.js';import {c,b as b$1,j as j$2,q as q$3,D,f}from'./chunk-7HV4U2OV.js';import {d,b as b$3}from'./chunk-ROOPODG6.js';import {j as j$3,m,l}from'./chunk-7EMG3C3H.js';import {a as a$5}from'./chunk-GR6442P7.js';import {j as j$1,g as g$1,a as a$4,h}from'./chunk-BLEIUQL6.js';import {a}from'./chunk-252EKOR6.js';import {d as d$2,c as c$1}from'./chunk-EWZZUQBR.js';import {t}from'./chunk-VQZ5PI5J.js';import {q as q$2,p,t as t$1,s}from'./chunk-ODK4LCEL.js';import g from'path';import C from'fs-extra';import $t from'crypto';import {execFile}from'child_process';import {promisify}from'util';import {createRequire}from'module';var Tt=new Set([...c().map(e=>e.id),...H().map(e=>e.id),...P$1().flatMap(e=>[e.id,...e.aliases])]),Nt=[...k().map(e=>({id:e.kitId,aliases:[...e.aliases],ecosystem:e.framework,plannerFramework:e.id,runtime:"node",runtimeCandidates:["node"],workspacePythonEngine:"none",status:"available",canExecuteCreate:true,versionPolicy:e.versionPolicy,officialCommands:[e.commandDisplay("<name>",{skipGit:false,skipInstall:false})],adoptAfterCreate:true,...e.minNodeVersion?{runtimeRequirements:{node:`>=${e.minNodeVersion}`}}:e.minNodeMajor?{runtimeRequirements:{node:`>=${e.minNodeMajor}`}}:{}})),...q$1().map(e=>({id:e.kitId,aliases:[...e.aliases],ecosystem:e.framework,plannerFramework:e.framework,runtime:e.runtime,runtimeCandidates:[...e.runtimeCandidates],workspacePythonEngine:"none",status:"available",canExecuteCreate:true,versionPolicy:e.versionPolicy,officialCommands:[e.commandDisplay("<name>",{skipGit:false,skipInstall:false})],adoptAfterCreate:true,...e.nodeSupport?{runtimeRequirements:{node:e.nodeSupport.requirement}}:{}})),{id:"wordpress-site",aliases:["wordpress","wordpress-site","wp","wp-site"],ecosystem:"wordpress",plannerFramework:"wordpress",runtime:"php",runtimeCandidates:["php"],workspacePythonEngine:"none",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["wp core download","wp config create","wp db create","wp core install"],adoptAfterCreate:true},{id:"wordpress-block",aliases:["wordpress-block","wp-block","gutenberg-block"],ecosystem:"wordpress",plannerFramework:"wordpress",runtime:"node",runtimeCandidates:["node","php"],workspacePythonEngine:"none",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["npx @wordpress/create-block@latest <slug>"],adoptAfterCreate:true},{id:"symfony",aliases:["symfony","php-symfony"],ecosystem:"php",plannerFramework:"symfony",runtime:"php",runtimeCandidates:["php"],workspacePythonEngine:"none",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["composer create-project symfony/skeleton <name>"],adoptAfterCreate:true},{id:"rails",aliases:["rails","ruby-on-rails","ruby-rails"],ecosystem:"ruby",plannerFramework:"rails",runtime:"ruby",runtimeCandidates:["ruby"],workspacePythonEngine:"none",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["rails new <name>"],adoptAfterCreate:true}],L=new Map;for(let e of Nt){L.set(e.id,e);for(let t of e.aliases)L.set(t,e);}var Kt=new Set(["php","ruby","rust","elixir","clojure","scala","kotlin","unknown"]);function V(e){return e?.trim().toLowerCase()||void 0}function dt(e){let t=V(e.kitId)??V(e.framework)??V(e.runtime)??"unknown";if(e.projectExists)return {lane:"existing",status:"available",canExecuteCreate:false,requested:t,reason:"Existing projects enter Workspace Intelligence through adopt/import."};let r=Q(e.kitId)??Q(e.framework);if(r)return {lane:"native",status:"available",canExecuteCreate:true,requested:t,resolved:r.id,reason:"Workspai owns the create contract, project marker, registry, doctor, and workspace model path."};let o=e.kitId?b$1(e.kitId):void 0;if(o&&Tt.has(o))return {lane:"native",status:"available",canExecuteCreate:true,requested:t,resolved:o,reason:"Workspai owns the create contract, project marker, registry, doctor, and workspace model path."};let s=L.get(t)??L.get(V(e.framework)??"")??L.get(V(e.runtime)??"");if(s)return {lane:"official",status:s.status,canExecuteCreate:s.canExecuteCreate,requested:t,resolved:s.id,officialCommands:s.officialCommands,fallbackLane:s.canExecuteCreate?void 0:"existing",reason:s.status==="available"?"Workspai runs the official ecosystem generator, then registers the project in Workspace Intelligence.":"Official generator support is planned but not enabled; use adopt/import until Workspai owns the post-create contract."};let n=V(e.runtime);return n&&Kt.has(n)?{lane:"existing",status:"available",canExecuteCreate:false,requested:t,resolved:n,reason:"Runtime can be governed through Workspace Intelligence, but native create is not supported."}:{lane:"existing",status:"available",canExecuteCreate:false,requested:t,reason:"No native create contract is available; use adopt/import to enter Workspace Intelligence."}}function Zr(e){return !e.canExecuteCreate&&(e.lane==="official"||e.lane==="existing"&&e.resolved!==void 0)}var nn="rapidkit-freshness-metadata-v1";function ke(e){if(Array.isArray(e))return e.map(t=>ke(t));if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=ke(e[r]);return t}return e}function Vt(e){return JSON.stringify(ke(e))}function _(e){return $t.createHash("sha256").update(Vt(e)).digest("hex")}var lt=".workspai/workspace-graph.overrides.json",Ht=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),Bt=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),ut=600,ft=5,Lt=256*1024,pt={inferred:1,contract:2,manual:3};function Ut(e){return e.split(g.sep).join("/")}function ee(e,t){return Ut(g.relative(e,t)||".")}function mt(e){let t=new Map;for(let r of e.projects)t.has(r.name)||t.set(r.name,{id:r.name,path:r.path,...r.runtime?{runtime:r.runtime}:{},...r.framework?{framework:r.framework}:{},...r.kind?{kind:r.kind}:{}});return [...t.values()].sort((r,o)=>r.id.localeCompare(o.id))}function gt(e,t){let r=new Map,o=new Map;for(let n of t.projects){if(r.has(n.name))continue;let i=d(e,n.path,{...n.absolutePath?{absolutePath:n.absolutePath}:{}});r.set(n.name,i),o.has(i)||o.set(i,n.name);}let s=[...o.entries()].map(([n,i])=>({dir:n,id:i})).sort((n,i)=>i.dir.length-n.dir.length||n.dir.localeCompare(i.dir));return {idToDir:r,dirToId:o,sortedDirs:s}}function te(e,t){let r=g.resolve(t);for(let{dir:o,id:s}of e.sortedDirs)if(r===o||r.startsWith(`${o}${g.sep}`))return s;return null}function ve(e,t){let r=g.relative(e,t);return r.length>0&&!r.startsWith("..")&&!g.isAbsolute(r)}function je(e,t,r){let o=e.idToDir.get(t),s=e.idToDir.get(r);return !o||!s?false:ve(o,s)||ve(s,o)}async function be(e){try{if(!await C.pathExists(e))return null;let t=await C.readJSON(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function Ce(e){try{return await C.pathExists(e)?await C.readFile(e,"utf8"):null}catch{return null}}async function ht(e,t){let r=[],o=new Map;for(let[s,n]of t.idToDir.entries()){let i=await be(g.join(n,"package.json")),a=typeof i?.name=="string"?i.name.trim():"";a&&!o.has(a)&&o.set(a,s);}for(let[s,n]of t.idToDir.entries()){let i=await be(g.join(n,"package.json"));if(i){let a=["dependencies","devDependencies","peerDependencies","optionalDependencies"],c=new Set;for(let l of a){let u=i[l];if(!(!u||typeof u!="object"||Array.isArray(u)))for(let p of Object.keys(u)){let d=o.get(p);!d||d===s||c.has(d)||(c.add(d),r.push({from:s,to:d,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ee(e,g.join(n,"package.json")),detail:`declares dependency ${p}`}]}));}}}r.push(...await zt(e,t,s,n)),r.push(...await qt(e,t,s,n));}return r}async function zt(e,t,r,o){let s=await Ce(g.join(o,"pyproject.toml"));if(!s)return [];let n=[],i=new Set,a=/path\s*=\s*["']([^"']+)["']/g,c;for(;(c=a.exec(s))!==null;){let l=te(t,g.resolve(o,c[1]));!l||l===r||je(t,r,l)||i.has(l)||(i.add(l),n.push({from:r,to:l,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ee(e,g.join(o,"pyproject.toml")),detail:`path dependency ${c[1]}`}]}));}return n}async function qt(e,t,r,o){let s=await Ce(g.join(o,"go.mod"));if(!s)return [];let n=[],i=new Set,a=/replace\s+\S+\s+=>\s+(\.[^\s]+)/g,c;for(;(c=a.exec(s))!==null;){let l=te(t,g.resolve(o,c[1]));!l||l===r||je(t,r,l)||i.has(l)||(i.add(l),n.push({from:r,to:l,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ee(e,g.join(o,"go.mod")),detail:`go.mod replace ${c[1]}`}]}));}return n}async function Jt(e,t,r=new Set){let o=[],s=[e];for(;s.length>0&&o.length<t;){let n=s.shift();if(!n)continue;let i=[];try{i=await C.readdir(n,{withFileTypes:true});}catch{continue}let a=[],c=[];for(let l of i)if(l.isDirectory()){let u=g.resolve(n,l.name);if(r.has(u)||Bt.has(l.name)||a$5(l.name)||l.name.startsWith("."))continue;a.push(g.join(n,l.name));}else l.isFile()&&Ht.has(g.extname(l.name))&&c.push(g.join(n,l.name));c.sort((l,u)=>l.localeCompare(u)),a.sort((l,u)=>l.localeCompare(u));for(let l of c){if(o.length>=t)break;o.push(l);}s.push(...a);}return o}var Xt=[/\bfrom\s+["']([^"']+)["']/g,/\bimport\s+["']([^"']+)["']/g,/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g];function Yt(e){let t=new Set;for(let r of Xt){r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){let s=o[1];s.startsWith(".")&&t.add(s);}}return [...t]}async function Pe(e,t,r,o){let s=new Map;for(let[n,i]of t.idToDir.entries()){if(o&&!o.has(n))continue;let a=new Set([...t.idToDir.entries()].filter(([l,u])=>l!==n&&ve(i,u)).map(([,l])=>g.resolve(l))),c=await Jt(i,r,a);for(let l of c){let u=await C.stat(l).catch(()=>null);if(!u||u.size>Lt)continue;let p=await Ce(l);if(p)for(let d of Yt(p)){let f=g.resolve(g.dirname(l),d),h=te(t,f);if(!h||h===n||je(t,n,h))continue;let m=`${n}\0${h}`,v=s.get(m);v||(v={from:n,to:h,evidence:[]},s.set(m,v)),v.evidence.length<ft&&v.evidence.push({file:ee(e,l),detail:`imports ${d}`});}}}return [...s.values()].map(n=>({from:n.from,to:n.to,kind:"code-import",source:"inferred",confidence:"medium",evidence:n.evidence}))}function Qt(e,t,r){let o=new Map;for(let s of r.projects){let n=Zt(e,t,s);n&&o.set(s.slug,n);}return o}function Zt(e,t,r){let o=[r.relativePath,r.externalPath].filter(s=>typeof s=="string"&&s.length>0);for(let s of o){let n=g.resolve(e,s),i=t.dirToId.get(n)??te(t,n);if(i)return i}return t.idToDir.has(r.slug)?r.slug:null}function kt(e,t,r){let o=[],s=Qt(e,t,r),n=g$2,i=new Map,a=new Map;for(let c of r.projects){let l=s.get(c.slug);if(!l)continue;let u=c.contracts??{publishes:[],consumes:[],dependsOn:[]};for(let p of u.dependsOn??[]){let d=s.get(p);!d||d===l||o.push({from:l,to:d,kind:"service-dependsOn",source:"contract",confidence:"high",evidence:[{file:n,detail:`dependsOn ${p}`}]});}for(let p of u.publishes??[])i.has(p)||i.set(p,new Set),i.get(p)?.add(l);for(let p of u.consumes??[])a.has(p)||a.set(p,new Set),a.get(p)?.add(l);}for(let[c,l]of i.entries()){let u=a.get(c);if(u)for(let p of u)for(let d of l)p!==d&&o.push({from:p,to:d,kind:"event-pub-sub",source:"contract",confidence:"high",evidence:[{file:n,detail:`consumes event ${c}`}]});}return o.push(...er(r,s)),o}function ye(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function er(e,t){let r=[],o=e.projects.map(s=>({project:s,id:t.get(s.slug)})).filter(s=>!!s.id).filter(s=>ye(s.project.slug).length>=3);for(let s of e.projects){let n=t.get(s.slug);if(!n)continue;let i=s.contracts?.env??[];if(i.length===0)continue;let a=new Set;for(let c of i){let l=ye(c);for(let u of o)u.id===n||a.has(u.id)||!(l.includes(ye(u.project.slug))&&(u.project.ports?.length??0)>0)||(a.add(u.id),r.push({from:n,to:u.id,kind:"shared-resource",source:"inferred",confidence:"low",evidence:[{file:g$2,detail:`env ${c} references ${u.project.slug}`}]}));}}return r}async function yt(e,t){let r=await be(g.join(e,lt)),o=Array.isArray(r?.edges)?r?.edges:[],s=[],n=new Set(f$1);for(let i of o){if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,c=typeof a.from=="string"?a.from:"",l=typeof a.to=="string"?a.to:"",u=typeof a.kind=="string"?a.kind:"";if(!t.has(c)||!t.has(l)||c===l||!n.has(u))continue;let p=Array.isArray(a.evidence)?a.evidence.map(d=>d&&typeof d=="object"&&typeof d.file=="string"?{file:d.file,...typeof d.detail=="string"?{detail:d.detail}:{}}:null).filter(d=>!!d):[];s.push({from:c,to:l,kind:u,source:"manual",confidence:"high",evidence:p.length>0?p:[{file:lt,detail:"manual edge"}]});}return s}function tr(e){return `${e.from}\0${e.to}\0${e.kind}`}function rr(e){let t=new Set,r=[];for(let o of e){let s=`${o.file}\0${o.detail??""}`;t.has(s)||(t.add(s),r.push(o));}return r.sort((o,s)=>o.file.localeCompare(s.file)||(o.detail??"").localeCompare(s.detail??"")).slice(0,ft)}function nr(e){let t=new Map;for(let r of e){let o=tr(r),s=t.get(o);if(!s){t.set(o,{...r,evidence:[...r.evidence]});continue}let n=pt[s.source],i=pt[r.source];i>n?t.set(o,{...r,evidence:[...r.evidence,...s.evidence]}):i===n&&s.evidence.push(...r.evidence);}return [...t.values()].map(r=>({from:r.from,to:r.to,kind:r.kind,source:r.source,confidence:r.confidence,evidence:rr(r.evidence)})).sort((r,o)=>r.from.localeCompare(o.from)||r.to.localeCompare(o.to)||r.kind.localeCompare(o.kind)||r.source.localeCompare(o.source))}function we(e){return Math.round(e*1e3)/1e3}function or(e){return Math.max(0,Math.min(100,Math.round(e)))}function sr(e){return e>=75?"critical":e>=50?"high":e>=20?"medium":"low"}function ar(e){return e==="critical"||e==="high"?"strict":e==="medium"?"elevated":"normal"}function ir(e,t){let r=a$6({nodes:e,edges:t}),o=new Map;for(let s of e){let n=r.byId.get(s.id)??{fanIn:0,fanOut:0,reach:0,betweenness:0,isHotspot:false},i=t.filter(f=>f.from===s.id||f.to===s.id),a=i.filter(f=>f.source==="contract"||f.source==="manual").length,c=i.filter(f=>f.confidence==="low").length,l=[],u=n.reach*20+n.fanIn*14+n.fanOut*8+Math.min(20,n.betweenness*4)+a*8;n.isHotspot&&(u+=24,l.push("Critical-path hotspot in dependency graph")),n.reach>0&&l.push(`Change reaches ${n.reach} dependent project(s)`),n.fanIn>0&&l.push(`${n.fanIn} direct dependent project(s)`),n.fanOut>0&&l.push(`${n.fanOut} direct dependency project(s)`),a>0&&l.push(`${a} contract/manual edge(s)`),c>0&&l.push(`${c} low-confidence inferred edge(s) need review`),i.length===0&&l.push(e.length===1?"Single-project workspace; inter-project dependency edges are not applicable":"No dependency evidence connected to this project yet");let p=or(u),d=sr(p);o.set(s.id,{weight:d,score:p,verificationPriority:ar(d),reasons:l.slice(0,5),centrality:{fanIn:n.fanIn,fanOut:n.fanOut,reach:n.reach,betweenness:n.betweenness,isHotspot:n.isHotspot}});}return o}function cr(e,t){let r=ir(e,t);return e.map(o=>({...o,operationalProfile:r.get(o.id)}))}function dr(e,t){let r=new Set;for(let c of t)r.add(c.from),r.add(c.to);let o=e.length,s=t.length,n=e.filter(c=>r.has(c.id)).length,i=Math.max(0,o-n),a=a$6({nodes:e,edges:t});return {nodeCount:o,edgeCount:s,inferredEdges:t.filter(c=>c.source==="inferred").length,contractEdges:t.filter(c=>c.source==="contract").length,manualEdges:t.filter(c=>c.source==="manual").length,authoritativeEdges:t.filter(c=>c.source==="contract"||c.source==="manual").length,lowConfidenceEdges:t.filter(c=>c.confidence==="low").length,orphanCount:i,connectedNodeCount:n,density:we(o>1?s/(o*(o-1)):0),edgeCoverageRatio:we(o>0?n/o:1),evidenceCoverageRatio:we(s>0?t.filter(c=>c.evidence.length>0).length/s:1),hotspotCount:a.hotspots.length,hasCycle:pr(e,t)}}function lr(e,t,r){let o=[],s=e.filter(n=>!t.some(i=>i.from===n.id||i.to===n.id)).map(n=>n.id).sort((n,i)=>n.localeCompare(i));return r.nodeCount===0&&o.push({code:"graph.empty",severity:"info",message:"Workspace model has no projects, so dependency reasoning is unavailable.",recommendation:"Import, scaffold, or register projects before relying on graph-aware impact."}),r.nodeCount>1&&r.edgeCount===0?o.push({code:"graph.edges.missing",severity:"warning",message:"Projects were detected, but no inter-project dependency edges were found.",recommendation:"Run graph explain, add workspace contract relationships, or define manual graph overrides for operational dependencies that code imports cannot reveal.",nodeIds:s}):r.nodeCount>1&&r.orphanCount>0&&o.push({code:"graph.orphans.detected",severity:"warning",message:`${r.orphanCount} project(s) have no dependency evidence connected to the graph.`,recommendation:"Review isolated projects and add package, contract, or manual edges when they participate in release-critical flows.",nodeIds:s.slice(0,12)}),r.lowConfidenceEdges>0&&o.push({code:"graph.low_confidence_edges",severity:"info",message:`${r.lowConfidenceEdges} inferred edge(s) are low confidence.`,recommendation:"Promote important low-confidence relationships to workspace contract or manual overrides."}),r.edgeCount>0&&r.evidenceCoverageRatio<1&&o.push({code:"graph.evidence.partial",severity:"warning",message:"Some dependency edges do not include file-level evidence.",recommendation:"Attach evidence to manual overrides so agents can audit why a relationship exists."}),r.hasCycle&&o.push({code:"graph.cycle.detected",severity:"error",message:"The dependency graph contains at least one directed cycle.",recommendation:"Break the cycle or document the relationship explicitly before using graph-aware release gates."}),o.sort((n,i)=>{let a={error:0,warning:1,info:2};return a[n.severity]-a[i.severity]||n.code.localeCompare(i.code)})}function pr(e,t){let r=new Map;for(let c of e)r.set(c.id,[]);for(let c of t)r.has(c.from)||r.set(c.from,[]),r.get(c.from)?.push(c.to);let o=0,s=1,n=2,i=new Map;for(let c of r.keys())i.set(c,o);let a=c=>{let l=[{id:c,index:0}];for(i.set(c,s);l.length>0;){let u=l[l.length-1],p=r.get(u.id)??[];if(u.index>=p.length){i.set(u.id,n),l.pop();continue}let d=p[u.index];u.index+=1;let f=i.get(d)??o;if(f===s)return true;f===o&&(i.set(d,s),l.push({id:d,index:0}));}return false};for(let c of [...r.keys()].sort())if(i.get(c)===o&&a(c))return true;return false}function wt(e$1,t,r,o){let s=nr(r.filter(c=>t.has(c.from)&&t.has(c.to))),n=cr(e$1,s),i=dr(e$1,s),a=lr(e$1,s,i);return {schemaVersion:e,generatedAt:(o??new Date).toISOString(),nodes:n,edges:s,stats:i,...a.length>0?{diagnostics:a}:{}}}async function vt(e){let t=g.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ut,o=mt(e.model),s=new Set(o.map(a=>a.id)),n=gt(t,e.model),i=[];return i.push(...await ht(t,n)),i.push(...await Pe(t,n,r)),e.contract&&i.push(...kt(t,n,e.contract)),i.push(...await yt(t,s)),wt(o,s,i,e.now)}async function bt(e){let t=g.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ut,o=mt(e.model),s=new Set(o.map(a=>a.id)),n=gt(t,e.model),i=[];if(i.push(...await ht(t,n)),e.structuralChange)i.push(...await Pe(t,n,r));else {i.push(...await Pe(t,n,r,e.changedProjectIds));for(let a of e.previousGraph.edges)a.kind==="code-import"&&a.source==="inferred"&&!e.changedProjectIds.has(a.from)&&s.has(a.from)&&s.has(a.to)&&i.push({from:a.from,to:a.to,kind:"code-import",source:"inferred",confidence:a.confidence,evidence:a.evidence});}return e.contract&&i.push(...kt(t,n,e.contract)),i.push(...await yt(t,s)),wt(o,s,i,e.now)}var re="workspace-model-producer.v3";var Ee=s.workspaceModelCache.schemaVersion,Se=t$1.workspaceModelCache,hr=["package.json","pyproject.toml","setup.py","requirements.txt","requirements.in","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","Gemfile.lock","mix.exs","mix.lock","deno.json","deno.jsonc","deno.lock","bun.lock","bun.lockb","bunfig.toml",".bunfig.toml","deps.edn","project.clj","build.sbt","CMakeLists.txt","meson.build","workspai.project.json",".workspai/project.json",".workspai/context.json","rapidkit.project.json",".rapidkit/project.json",".rapidkit/context.json"],kr=[".csproj",".fsproj",".vbproj",".sln",".slnx",".gemspec"],Pt=[t$1.workspaceContract,".workspai/workspace.json","workspai.workspace.json",".workspai/policies.yml",".workspai/policies.yaml",".rapidkit/workspace.contract.json",".rapidkit/workspace.json","rapidkit.workspace.json",".rapidkit/policies.yml",".rapidkit/policies.yaml"],jt=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".vue",".svelte",".rb",".go",".py",".java",".kt",".kts",".rs",".cs",".php",".ex",".exs",".clj",".cljs",".scala",".c",".cc",".cpp",".cxx",".h",".hh",".hpp",".hxx",".proto",".graphql",".gql",".sql",".sh"]),yr=new Set([".git",".workspai",".rapidkit","node_modules","dist","build","out","target","coverage",".next",".turbo",".cache",".venv"]),wr=1500,ne=promisify(execFile);function vr(e){return jt.has(g.extname(e).toLowerCase())}async function br(e){try{let{stdout:t}=await ne("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",timeout:1e4,maxBuffer:1048576}),r=t.trim();if(!r)return null;let o=g.relative(r,e).split(g.sep).join("/");if(o===".."||o.startsWith("../"))return null;let s=o||".",n=o?`HEAD:${o}`:"HEAD^{tree}",{stdout:i}=await ne("git",["-C",r,"rev-parse",n],{encoding:"utf8",timeout:1e4,maxBuffer:1024*1024}),[a,c]=await Promise.all([ne("git",["-C",r,"diff","--name-only","-z","HEAD","--",s],{encoding:"buffer",timeout:2e4,maxBuffer:64*1024*1024}),ne("git",["-C",r,"ls-files","--others","--exclude-standard","-z","--",s],{encoding:"buffer",timeout:2e4,maxBuffer:64*1024*1024})]),l=new Set([a.stdout,c.stdout].flatMap(p=>p.toString("utf8").split("\0")).filter(Boolean)),u=[`git-tree:${i.trim()}`];for(let p of [...l].sort((d,f)=>d.localeCompare(f))){let d=g.resolve(r,p),f=g.relative(e,d).split(g.sep).join("/");f===".."||f.startsWith("../")||!vr(f)||u.push(`${f}:${await z(d)??"<deleted>"}`);}return u}catch{return null}}var U=null;function We(){if(U)return U;try{U=createRequire(import.meta.url)("../package.json")?.version??"0.0.0";}catch{U="0.0.0";}return U}async function z(e){try{let t=await C.readFile(e);return $t.createHash("sha256").update(t).digest("hex")}catch{return null}}async function Ct(e){let t={};for(let o of hr){let s=await z(g.join(e,o));s&&(t[o]=s);}let r=await C.readdir(e).catch(()=>[]);for(let o of r.sort((s,n)=>s.localeCompare(n))){if(!kr.some(n=>o.toLowerCase().endsWith(n)))continue;let s=await z(g.join(e,o));s&&(t[o]=s);}return t}async function Pr(e){let t=await Ct(e),r=await br(e),o=r??[];if(r)return _({manifests:t,source:o});let s=[e];for(;s.length>0&&o.length<wr;){let n=s.shift();if(!n)continue;let i=[];try{i=await C.readdir(n,{withFileTypes:true});}catch{continue}let a=[];for(let c of i)if(c.isDirectory()){if(yr.has(c.name)||a$5(c.name)||c.name.startsWith("."))continue;a.push(g.join(n,c.name));}else if(c.isFile()&&jt.has(g.extname(c.name))){let l=g.join(n,c.name),u=await C.stat(l).catch(()=>null);if(u){let p=g.relative(e,l).split(g.sep).join("/");o.push(`${p}:${u.size}:${Math.round(u.mtimeMs)}`);}}a.sort((c,l)=>c.localeCompare(l)),s.push(...a);}return o.sort((n,i)=>n.localeCompare(i)),_({manifests:t,source:o})}async function oe(e,t){let r=g.resolve(e),o={},s=[...new Set(t.map(n=>g.relative(r,g.resolve(n)).split(g.sep).join("/")))].sort((n,i)=>n.localeCompare(i));for(let n of s)o[n]=await Pr(g.join(r,n));return o}async function se(e){let t=g.resolve(e),r={};for(let o of Pt){let s=await z(g.join(t,o));s&&(r[o]=s);}return r}async function ae(e){let t=g.resolve(e.workspacePath),r=[...new Set(e.projectPaths.map(n=>g.relative(t,g.resolve(n)).split(g.sep).join("/")))].sort((n,i)=>n.localeCompare(i)),o=[];for(let n of r){let i=await Ct(g.join(t,n));o.push({project:n,manifests:i});}let s={};for(let n of Pt){let i=await z(g.join(t,n));i&&(s[n]=i);}return _({cacheSchema:Ee,cliVersion:e.cliVersion,flags:e.flags,workspaceJson:e.workspaceJson??null,marker:e.marker??null,projects:o,workspaceFiles:s})}async function Re(e){let t=await g$1(e,Se)??a$4(e,Se);try{if(!await C.pathExists(t))return null;let r=await C.readJson(t);return !r||r.schemaVersion!==Ee||r.producerRevision!==re||typeof r.inputsHash!="string"||typeof r.cliVersion!="string"||!r.model?null:r}catch{return null}}async function ie(e,t){let r={schemaVersion:Ee,producerRevision:re,...t};return h(e,Se,r)}var St="rapidkit-fact-freshness-v1",q={durable:720*60*60,derived:10080*60,evidenceBacked:1440*60,live:300,verifyBeforeUse:1440*60};function jr(e){switch(e){case "durable":return q.durable;case "derived":return q.derived;case "evidence-backed":return q.evidenceBacked;case "live":return q.live;case "verify-before-use":return q.verifyBeforeUse}}function Cr(e){if(e.status)return e.status;if(e.ttlSeconds===null)return "unknown";let t=Date.parse(e.generatedAt);if(!Number.isFinite(t))return "unknown";let r=t+e.ttlSeconds*1e3;return e.now.getTime()>r?"stale":"fresh"}function Sr(e){let t=e.now??new Date,r=e.generatedAt??t.toISOString(),o=Date.parse(r),s=Number.isFinite(o),n=s?r:t.toISOString(),i=e.ttlSeconds===void 0?jr(e.kind):e.ttlSeconds,a=Cr({generatedAt:n,ttlSeconds:i,status:e.status??(s?void 0:"unknown"),now:t}),c=Date.parse(n),l=i===null||!Number.isFinite(c)?void 0:new Date(c+i*1e3),u=e.verifyBeforeUse??(e.kind==="live"||e.kind==="verify-before-use"||e.category!=="structure"||a!=="fresh");return {schemaVersion:St,kind:e.kind,category:e.category,generatedAt:n,ttlSeconds:i,...l?{expiresAt:l.toISOString()}:{},status:a,verifyBeforeUse:u,...e.sourceArtifact?{sourceArtifact:e.sourceArtifact}:{},...e.sourcePath?{sourcePath:e.sourcePath}:{},inputsHash:e.inputsHash??_(e.value??null),reason:e.reason}}function b(e){return {id:e.id,label:e.label,scope:e.scope,value:e.value,...e.project?{project:e.project}:{},freshness:Sr({...e.freshness,value:e.value})}}function Et(e){let t=e.generatedAt??(e.now??new Date).toISOString(),r={durable:0,derived:0,"evidence-backed":0,live:0,"verify-before-use":0},o={structure:0,verification:0,state:0},s=0,n=0,i=0,a=0;for(let c of e.facts)r[c.freshness.kind]+=1,o[c.freshness.category]+=1,c.freshness.status==="stale"&&(s+=1),c.freshness.status==="unknown"&&(n+=1),c.freshness.kind==="live"&&(i+=1),c.freshness.verifyBeforeUse&&(a+=1);return {schemaVersion:St,generatedAt:t,status:s>0?"stale":n>0?"unknown":"fresh",totalFacts:e.facts.length,staleFacts:s,unknownFacts:n,liveFacts:i,verifyBeforeUseFacts:a,byKind:r,byCategory:o}}function J(e,t){let r=[...new Set(e)],o=r.filter(s=>t.has(s)).length;return {eligibleCount:r.length,boundCount:o,unknownCount:r.length-o,coverageRatio:r.length===0?null:o/r.length}}function Wt(e,t){let r=e.filter(d=>d.kind==="project").map(d=>d.id),o=e.filter(d=>d.kind==="endpoint").map(d=>d.id),s=new Set(o),n=e.filter(d=>d.kind==="api"&&!!d.projectId&&d.attributes.runtimeRegistrationRequired===true).map(d=>d.id),i=new Set(n),a=new Map(e.map(d=>[d.id,d.kind])),c=new Set(t.filter(d=>d.kind==="implements"||d.kind==="defines"&&a.get(d.from)==="file"&&a.get(d.to)==="endpoint").flatMap(d=>s.has(d.from)?[d.from]:s.has(d.to)?[d.to]:[])),l=new Set(t.filter(d=>d.kind==="implements"&&(a.get(d.from)==="runtime-unit"||a.get(d.to)==="runtime-unit")).flatMap(d=>i.has(d.from)?[d.from]:i.has(d.to)?[d.to]:[])),u=new Set(r),p=d=>new Set(t.filter(f=>f.kind===d).flatMap(f=>[f.from,f.to]).filter(f=>u.has(f)));return {apiImplementation:J(o,c),apiRuntimeRegistration:J(n,l),projectTests:J(r,p("tests")),projectDeployment:J(r,p("deploys")),projectOwnership:J(r,p("owns"))}}function Rt(e,t){return e.filter(o=>o.code.includes("unknown")||o.code.includes("unresolved")||o.code.includes("limit_reached")||o.code.endsWith(".empty_result")).reduce((o,s)=>o+Math.max(s.entityIds?.length??0,s.relationIds?.length??0,1),0)+Object.values(t).reduce((o,s)=>o+s.unknownCount,0)}function xe(e,t){return t===0?1:e/t}function Er(e,t,r,o){return e.entityIds?.some(s=>t.has(s))||e.relationIds?.some(s=>r.has(s))?true:e.entityIds?.length||e.relationIds?.length?false:!/\bproject\b/i.test(e.message)||e.message.includes(o)}function Wr(e,t,r,o,s){let n=new Set(s.filter(a=>a.provider===e.id).map(a=>a.id)),i=e.inputCoverage?.filter(a=>a.scope==="workspace"||a.scope==="project"&&a.scopeId===t);return {...e,discoveredEntities:r.filter(a=>a.proofIds.some(c=>n.has(c))).length,discoveredRelations:o.filter(a=>a.proofIds.some(c=>n.has(c))).length,proofCount:n.size,...i?{inputCoverage:i}:{}}}function Rr(e,t){let r=new Set(e.entities.filter(m=>m.projectId===t).map(m=>m.id)),o=e.relations.filter(m=>r.has(m.from)||r.has(m.to)),s=new Set(r);for(let m of o)s.add(m.from),s.add(m.to);let n=e.entities.filter(m=>s.has(m.id)),i=new Set([...n,...o].flatMap(m=>m.proofIds)),a=e.proofs.filter(m=>i.has(m.id)),c=new Set(o.map(m=>m.id)),l=e.diagnostics.filter(m=>Er(m,s,c,t)),u=e.providers.map(m=>Wr(m,t,n,o,a)),p=e.source.inputs?.scopes.filter(m=>m.kind==="workspace"||m.kind==="project"&&m.id===t)??[],d=p.filter(m=>!m.truncated).length,f=u.reduce((m,v)=>(v.status==="failed"?m.failed+=1:v.status==="skipped"||v.inputCoverage?.every(W=>W.status==="not-applicable")?m.notApplicable+=1:v.status==="partial"||v.inputCoverage?.some(W=>W.status==="bounded")?m.bounded+=1:m.complete+=1,m),{complete:0,bounded:0,notApplicable:0,failed:0}),h=Wt(n,o);return {...e,entities:n,relations:o,proofs:a,providers:u,quality:{entityCount:n.length,relationCount:o.length,proofCount:a.length,entityProofCoverageRatio:xe(n.filter(m=>m.proofIds.length>0).length,n.length),relationProofCoverageRatio:xe(o.filter(m=>m.proofIds.length>0).length,o.length),providerSuccessRatio:xe(u.filter(m=>m.status!=="failed").length,u.length),conflictCount:l.filter(m=>m.code.includes("conflict")).length,unknownCount:Rt(l,h),bindingCoverage:h,...e.quality.completeness?{completeness:{status:p.some(m=>m.truncated)||f.bounded>0||f.failed>0?"bounded":"complete",inventory:{scopeCount:p.length,completeScopes:d,boundedScopes:p.length-d,eligibleFiles:p.reduce((m,v)=>m+(v.eligibleFileCount??v.fileCount),0),indexedFiles:p.reduce((m,v)=>m+v.fileCount,0),eligibleFileCountExact:p.every(m=>m.eligibleFileCountExact!==false)},providers:f}}:{},portable:true,secretValuesEmitted:false},diagnostics:l}}var xr=s.projectKnowledgeGraphReference.schemaVersion;function xt(e,t){let r=Rr(e,t),o={schemaVersion:xr,generatedAt:e.generatedAt,project:{name:t},canonical:{graph:"workspace:.workspai/reports/workspace-knowledge-graph.json",boundedQuery:`workspai workspace graph search <task-query> --scope project:${t} --limit 12 --json`,sourceHash:e.source.hash,projectionHash:c$1(r)},summary:{entityCount:r.entities.length,relationCount:r.relations.length,proofCount:r.proofs.length}};return {...o,integrity:{algorithm:"sha256",payloadHash:c$1(o),portable:true,absolutePathsEmitted:false}}}function At(e,t){return d(e,t.path,{...t.absolutePath?{absolutePath:t.absolutePath}:{}})}var Ar=q$2.model,de=p.model;function Ae(e){return e.projectTopology??e.graph}function It(e){return !!(e.projectTopology&&e.graph&&c$1(e.projectTopology)===c$1(e.graph))}function ko(e){let t=e.engineStatus==="hit"||e.engineStatus==="unchanged"?"reused":e.engineStatus==="incremental"?"partially-reused":"rebuilt";return {schemaVersion:"workspace-model-build.v1",mode:e.mode,outcome:t,engineStatus:e.engineStatus}}var Mr=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","bun.lock","bun.lockb","bunfig.toml",".bunfig.toml","deps.edn","project.clj","build.sbt","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","terraform.tf"],Ir=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next",".turbo"]);function Fr(e,t){return (g.relative(e,t)||".").split(g.sep).join("/")}function ce(e,t){return Fr(e,d(e,t.path,{...t.absolutePath?{absolutePath:t.absolutePath}:{}}))}async function Ft(e){try{if(!await C.pathExists(e))return null;let t=await C.readJSON(e);return t&&typeof t=="object"?t:null}catch{return null}}async function Dr(e,t){for(let r of t)if(await C.pathExists(g.join(e,r)))return true;return false}function Me(e){let t=Number.parseInt(process.env.RAPIDKIT_WORKSPACE_MODEL_SCAN_DEPTH??"",10),r=typeof e=="number"&&Number.isFinite(e)?e:Number.isFinite(t)?t:4;return Math.min(12,Math.max(1,Math.trunc(r)))}async function Or(e,t){let r=g.resolve(e),o=[{dirPath:r,depth:0}],s=new Set,n=new Set;for(;o.length>0;){let i=o.shift();if(!i)continue;let a=g.resolve(i.dirPath);if(n.has(a))continue;if(n.add(a),a!==r&&await Dr(a,Mr)){s.add(a);continue}if(i.depth>=t)continue;let c=[];try{c=await C.readdir(a,{withFileTypes:true});}catch{continue}for(let l of c)!l.isDirectory()||Ir.has(l.name)||a$5(l.name)||l.name.startsWith(".")&&l.name!==".config"||o.push({dirPath:g.join(a,l.name),depth:i.depth+1});}return Array.from(s).sort((i,a)=>i.localeCompare(a))}function Gr(e){let t=new Set,r=[];for(let o of e){let s=g.resolve(o);t.has(s)||(t.add(s),r.push(s));}return r.sort((o,s)=>o.localeCompare(s))}function Mt(e,t){let r=e?.[t];return typeof r=="string"&&r.trim()?r.trim():void 0}function _r(e,t){return e?.[t]===true}function Tr(e,t,r){let o=e?.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,s=Mt(o,"generator"),n=Mt(o,"command_display"),i=typeof t=="string"&&t.startsWith("frontend.");if(!(!s&&!i))return {...s?{id:s}:{},...t?{kit:t}:{},displayName:r,source:_r(o,"official_generator")?"official-generator":"metadata",...n?{commandDisplay:n}:{}}}async function Nr(e){let t=[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json","package.json","product.json","tsconfig.json","pnpm-workspace.yaml","bunfig.toml",".bunfig.toml","nx.json","turbo.json","pyproject.toml","requirements.txt","go.mod","go.work","go.work.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","rust-toolchain.toml","rust-toolchain","CMakeLists.txt","meson.build","Makefile","WORKSPACE","WORKSPACE.bazel","MODULE.bazel","BUILD","BUILD.bazel",".bazelrc","composer.json","Gemfile","mix.exs","deno.json","setup.py","setup.cfg","Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","README.md"],r=[];for(let s of t)await C.pathExists(g.join(e,s))&&r.push(s);let o=new Set(["package.json","pyproject.toml","go.mod","go.work","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","CMakeLists.txt","meson.build","composer.json","Gemfile","mix.exs","deno.json"]);if(!r.some(s=>o.has(s))){let s=[],n=new Set([".git",".workspai",".rapidkit",".venv","build","dist","node_modules","target","third_party","vendor"]),i=(p,d)=>{let f=p.toLowerCase();return ["package.json","pyproject.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","cargo.toml","cmakelists.txt","meson.build","composer.json","gemfile","mix.exs","deno.json"].includes(f)||f.endsWith(".gemspec")||f==="description"&&d.toLowerCase()==="r"},a=async(p,d)=>{if(d>3||s.length>=512)return;let f=await C.readdir(p,{withFileTypes:true}).catch(()=>[]);for(let h of f.sort((m,v)=>m.name.localeCompare(v.name))){if(s.length>=512)return;h.isFile()&&i(h.name,g.basename(p))?s.push(g.relative(e,g.join(p,h.name)).split(g.sep).join("/")):h.isDirectory()&&!n.has(h.name)&&await a(g.join(p,h.name),d+1);}};await a(e,0);let c=new Map;for(let p of s){let d=p.split("/")[0],f=c.get(d)??[];f.push(p),c.set(d,f);}for(let p of c.values())p.sort((d,f)=>d.split("/").length-f.split("/").length||d.localeCompare(f));let l=[],u=[...c.keys()].sort();for(let p=0;l.length<16&&u.some(d=>p<(c.get(d)?.length??0));p+=1)for(let d of u){let f=c.get(d)?.[p];f&&l.length<16&&l.push(f);}r.push(...l.filter(p=>!r.includes(p)));}return r}async function A(e,t,r,o=t){let s=await g$1(e,t),n=s!==null,i={path:o.split(g.sep).join("/"),exists:n};if(s&&r){let a=await Ft(s);typeof a?.generatedAt=="string"&&(i.generatedAt=a.generatedAt);let c=a?.status??a?.result??a?.verdict;typeof c=="string"&&(i.status=c);}return i}async function Kr(e,t,r,o){let s=".workspai/reports",n=c=>A(t,`${s}/${c}`,r,`${o}/${s}/${c}`),i=await n("doctor-project-last-run.json");return {doctor:i?.exists===true?i:await n("doctor-last-run.json"),remediationPlan:await n("doctor-remediation-plan-last-run.json"),fixResult:await n("doctor-fix-result-last-run.json"),analyze:await n("analyze-last-run.json"),readiness:await n("release-readiness-last-run.json")}}async function $r(e,t,r){let o=j$2(t,{searchParents:false}),s=q$3(t),n=s&&!j$3(o)?s.detection:m(t,o),i=D(t),a=f(n.runtime),c=await b$2(t,o,{runtime:n.runtime,framework:n.key}),l$1=r.contractProject?.slug?r.contractProject.slug:typeof o?.name=="string"&&o.name.trim()?o.name.trim():g.basename(t),u=j$3(o)?`adopted.${n.key}`:typeof o?.kit_name=="string"?o.kit_name:typeof o?.kit=="string"?o.kit:r.contractProject?.kit,p=typeof o?.engine=="string"?o.engine:i.engine!=="unknown"?i.engine:void 0,d=Tr(o,u,n.displayName),f$1=dt({kitId:u,framework:n.key,runtime:n.runtime}),h=l(t),m$1=[n.runtime,...h.filter(T=>T!==n.runtime)],v=await c$2({projectPath:t,declaration:r.contractProject?.governance}),W=b$3({workspacePath:e,projectPath:t,projectName:l$1,declaredRelativePath:r.contractProject?.relativePath});return {name:l$1,path:W,...r.includeAbsolutePaths?{absolutePath:t}:{},kind:c,category:a$3(c),runtime:n.runtime,runtimeCandidates:m$1,framework:n.key,frameworkDisplayName:n.displayName,confidence:n.confidence,detectionSource:n.source,supportTier:n.supportTier,runtimeSupportTier:a.tier,runtimeDoctorSupport:a.doctorSupport,moduleSupport:i.moduleSupport,...u?{kit:u}:{},...p?{engine:p}:{},...d?{generator:d}:{},createCapability:f$1,commands:{supported:i.supportedCommands,unsupported:i.unsupportedCommands,global:i.globalCommands,fleetStages:i.fleetStages,localOnly:i.localOnlyCommands,map:i.commandMap},importantFiles:await Nr(t),governance:v,evidence:await Kr(e,t,r.includeEvidence,W),provenance:{path:r.contractProject?"workspace contract declaration reconciled with filesystem discovery":"filesystem discovery",runtime:n.source,framework:n.source,commands:"project command capability matrix",createCapability:"create planner capability contract",governance:r.contractProject?.governance!==void 0?"workspace contract declaration reconciled with repository evidence":"repository and documented external governance discovery",evidence:"project .workspai/reports"}}}async function Vr(e){for(let t$1 of t(e,"workspace.json")){let r=await Ft(t$1);if(r)return r}return null}function Hr(e){if(e.length===0)return "empty-workspace";let t=new Set(e.map(r=>r.category));return t.size>1?"polyglot-product-workspace":t.has("frontend")&&e.length>1?"full-stack-workspace":t.has("frontend")?"frontend-workspace":t.has("desktop")?"desktop-application-workspace":t.has("extension")?"extension-workspace":t.has("agent")?e.length>1?"agent-platform-workspace":"agent-workspace":t.has("platform")?"platform-workspace":t.has("library")?"library-workspace":e.length>1?"backend-platform":"backend-workspace"}function Br(e){let t=new Set;for(let r of e){let o=`${r.name} ${r.path}`.toLowerCase();for(let s of ["auth","billing","payment","notification","order","admin","report","search","analytics"])o.includes(s)&&t.add(s);}return Array.from(t).sort()}function j(e,t,r,o){return {severity:e,code:t,message:r,target:o}}function Dt(e){let t=[];if(e.workspace.name.trim()||t.push(j("error","workspace.name.missing","Workspace name could not be resolved.","workspace")),e.workspace.type==="observed-workspace"&&t.push(j("warning","workspace.marker.missing","Workspace marker is missing; model is based on filesystem observation.","workspace.marker")),e.summary.projectCount===0&&t.push(j("warning","workspace.projects.empty","No project roots were detected in this workspace.","projects")),e.workspace.profile){let n=V$1({profile:e.workspace.profile,runtimes:e.summary.runtimes});n.ok||t.push(j("warning","workspace.profile.mismatch",[n.message,n.recommendedCommand?`Keep the current profile and run ${n.recommendedCommand} when you want the recommended profile.`:void 0].filter(Boolean).join(" "),"workspace.profile"));}e.contracts.exists||t.push(j("warning","workspace.contract.missing","Workspace contract is missing; dependency and API edges may be incomplete.",e.contracts.workspaceContractPath));let r=new Map;for(let n of e.projects){let i=n.name.toLowerCase(),a=r.get(i)??[];a.push(n),r.set(i,a),n.importantFiles.length||t.push(j("warning","project.markers.missing",`Project ${n.name} has no important manifest files recorded.`,n.path));let c=d(e.workspace.root,n.path,{...n.absolutePath?{absolutePath:n.absolutePath}:{}});C.existsSync(c)||t.push(j("warning","project.path.missing",`Registered project ${n.name} is not available at its declared path.`,n.path)),n.runtime==="unknown"&&t.push(j("warning","project.runtime.unknown",`Project ${n.name} runtime could not be confidently detected.`,n.path));let l=["test","build"];for(let d of l)n.commands.supported.includes(d)&&n.commands.unsupported.includes(d)&&t.push(j("error","project.commands.conflict",`Project ${n.name} marks ${d} as both supported and unsupported.`,n.path));let u=new Set(n.commands.fleetStages),p=new Set(n.commands.localOnly);for(let d of n.commands.fleetStages){p.has(d)&&t.push(j("error","project.commands.scope-conflict",`Project ${n.name} marks ${d} as both fleet and local-only.`,n.path));let f=n.commands.map[d];(!f||f.fleetEligible!==true||f.executionScope!=="fleet")&&t.push(j("error","project.commands.fleet-stage-invalid",`Project ${n.name} advertises ${d} as a fleet stage without a supported fleet capability.`,n.path));}for(let d of n.commands.localOnly){let f=n.commands.map[d];(!f||f.status!=="supported"||f.executionScope!=="local-only"||f.fleetEligible===true)&&t.push(j("error","project.commands.local-only-invalid",`Project ${n.name} advertises ${d} as local-only without a matching local-only capability.`,n.path));}for(let d of Object.values(n.commands.map))d.status==="supported"&&(d.fleetEligible===true&&!u.has(d.command)&&t.push(j("error","project.commands.fleet-stage-missing",`Project ${n.name} capability ${d.command} is fleet-eligible but missing from fleetStages.`,n.path)),d.executionScope==="local-only"&&d.fleetEligible!==true&&!p.has(d.command)&&t.push(j("error","project.commands.local-only-missing",`Project ${n.name} capability ${d.command} is local-only but missing from localOnly commands.`,n.path)));}for(let[n,i]of r.entries())i.length>1&&t.push(j("error","project.name.duplicate",`Project name "${n}" is ambiguous across ${i.length} project roots.`,i.map(a=>a.path).join(", ")));e.projectTopology&&e.graph&&c$1({...e.projectTopology,generatedAt:"<ignored>"})!==c$1({...e.graph,generatedAt:"<ignored>"})&&t.push(j("error","workspace.project-topology.alias-mismatch","Deprecated model.graph must remain structurally identical to canonical model.projectTopology during the v1 migration window.","projectTopology"));let o=t.filter(n=>n.severity==="error").length,s=t.filter(n=>n.severity==="warning").length;return {status:o>0?"failed":s>0?"warning":"passed",errors:o,warnings:s,issues:t}}function yo(e){return Dt(e)}function P(e){return e.join(".")}function Lr(e,t){let r=de,o=e.generatedAt,s=[b({id:"workspace.name",label:"Workspace name",scope:"workspace",value:e.workspace.name,freshness:{kind:"durable",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:P(["workspace","name"]),reason:"Workspace identity is structural metadata and changes through workspace setup."}}),b({id:"workspace.type",label:"Workspace type",scope:"workspace",value:e.identity.workspaceType,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:P(["identity","workspaceType"]),reason:"Workspace type is derived from the current project inventory."}}),b({id:"workspace.projectCount",label:"Project count",scope:"workspace",value:e.summary.projectCount,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:P(["summary","projectCount"]),reason:"Project count is derived from workspace discovery and should be refreshed after structural changes."}}),b({id:"workspace.runtimeFamilies",label:"Runtime families",scope:"workspace",value:e.identity.runtimeFamilies,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:P(["identity","runtimeFamilies"]),reason:"Runtime coverage is inferred from project surfaces."}}),b({id:"workspace.policyMode",label:"Workspace policy mode",scope:"policy",value:e.policies.mode,freshness:{kind:"durable",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:P(["policies","mode"]),reason:"Policy mode is configuration, not runtime state."}}),b({id:"workspace.contract.exists",label:"Workspace contract presence",scope:"contract",value:e.contracts.exists,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:P(["contracts","exists"]),reason:"Contract presence is derived from workspace files and should be refreshed before release gating."}})],n=Ae(e);n&&s.push(b({id:"graph.edgeCount",label:"Dependency graph edge count",scope:"graph",value:n.stats.edgeCount,freshness:{kind:"derived",category:"structure",generatedAt:n.generatedAt??o,now:t,sourceArtifact:r,sourcePath:P(["projectTopology","stats","edgeCount"]),reason:"Graph topology is derived from manifests, imports, and workspace contracts."}}),b({id:"graph.evidenceCoverageRatio",label:"Dependency graph evidence coverage",scope:"graph",value:n.stats.evidenceCoverageRatio,freshness:{kind:"derived",category:"structure",generatedAt:n.generatedAt??o,now:t,sourceArtifact:r,sourcePath:P(["projectTopology","stats","evidenceCoverageRatio"]),reason:"Graph evidence coverage changes when dependency evidence or contract edges change."}}));for(let[i,a]of e.projects.entries()){let c=`projects[${i}]`,l={kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,reason:"Project facts are derived from workspace discovery, project metadata, and framework probes."};s.push(b({id:`project.${a.name}.kind`,label:`${a.name} kind`,scope:"project",project:a.name,value:a.kind,freshness:{...l,sourcePath:P([c,"kind"])}}),b({id:`project.${a.name}.category`,label:`${a.name} category`,scope:"project",project:a.name,value:a.category,freshness:{...l,sourcePath:P([c,"category"])}}),b({id:`project.${a.name}.runtime`,label:`${a.name} runtime`,scope:"project",project:a.name,value:a.runtime,freshness:{...l,sourcePath:P([c,"runtime"])}}),b({id:`project.${a.name}.framework`,label:`${a.name} framework`,scope:"project",project:a.name,value:a.frameworkDisplayName,freshness:{...l,sourcePath:P([c,"frameworkDisplayName"])}}),b({id:`project.${a.name}.supportTier`,label:`${a.name} support tier`,scope:"project",project:a.name,value:a.supportTier,freshness:{...l,sourcePath:P([c,"supportTier"])}}),b({id:`project.${a.name}.safeFleetStages`,label:`${a.name} safe fleet stages`,scope:"command",project:a.name,value:a.commands.fleetStages,freshness:{...l,sourcePath:P([c,"commands","fleetStages"]),reason:"Safe command availability is derived from package and project command surfaces."}}),...["ci","release","ownership"].map(u=>b({id:`project.${a.name}.governance.${u}`,label:`${a.name} ${u} governance`,scope:"policy",project:a.name,value:a.governance?.[u]??{status:"unknown",provider:null,evidence:[],reference:null},freshness:{...l,sourcePath:P([c,"governance",u]),reason:"Governance truth is reconciled from repository surfaces and explicit workspace contract declarations."}})));for(let[u,p]of Object.entries(a.evidence))s.push(b({id:`project.${a.name}.evidence.${u}`,label:`${a.name} ${u} evidence`,scope:"evidence",project:a.name,value:p?{path:p.path,exists:p.exists,status:p.status??null}:{exists:false},freshness:{kind:p?.exists?"evidence-backed":"verify-before-use",category:"verification",generatedAt:p?.generatedAt??o,now:t,status:p?.exists?void 0:"unknown",sourceArtifact:p?.path??r,sourcePath:P([c,"evidence",u]),verifyBeforeUse:true,reason:p?.exists?"Evidence reports can expire or become stale after source changes.":"Missing evidence must be generated before this fact is used for verification."}}));}for(let[i,a]of Object.entries(e.evidence))s.push(b({id:`workspace.evidence.${i}`,label:`Workspace ${i} evidence`,scope:"evidence",value:a?{path:a.path,exists:a.exists,status:a.status??null}:null,freshness:{kind:a?.exists?"evidence-backed":"verify-before-use",category:"verification",generatedAt:a?.generatedAt??o,now:t,status:a?.exists?void 0:"unknown",sourceArtifact:a?.path??r,sourcePath:P(["evidence",i]),verifyBeforeUse:true,reason:a?.exists?"Workspace evidence can expire or become stale after project, dependency, or policy changes.":"Missing workspace evidence must be generated before release or repair decisions."}}));return s}async function Ie(e,t){let[r,o,s,n,i,a$3]=await Promise.all([a(e),Vr(e),Fe(e),a$1(e),a$2(e,{descendIntoMatchedProjects:false}),Or(e,t)]),c=new Map;for(let u of s?.projects??[]){let p=d(e,u.relativePath,u.externalPath?{absolutePath:u.externalPath}:{});c.set(p,u);}let l=Gr([...i,...a$3.filter(u=>!i.some(p=>{let d=g.relative(p,u);return d!==""&&d!==".."&&!d.startsWith(`..${g.sep}`)&&!g.isAbsolute(d)})),...c.keys(),...n.map(u=>d(e,u.relativePath||u.name,u.path?{absolutePath:u.path}:{}))]);return {marker:r,workspaceJson:o,workspaceContract:s,contractProjectPaths:c,projectPaths:l}}async function le(e){let t$2=g.resolve(e.workspacePath),r=e.includeAbsolutePaths===true,o=e.includeEvidence===true,s=Me(e.observableScanDepth),n=e.now??new Date,{marker:i,workspaceJson:a,workspaceContract:c,contractProjectPaths:l,projectPaths:u}=await Ie(t$2,s),p$1=e.reuseProjectModels,d=await Promise.all(u.map(w=>{if(p$1){let _t=g.relative(t$2,g.resolve(w)).split(g.sep).join("/"),De=p$1.get(_t);if(De)return Promise.resolve(De)}return $r(t$2,w,{includeAbsolutePaths:r,includeEvidence:o,contractProject:l.get(g.resolve(w))})})),f=typeof a?.workspace_name=="string"?a.workspace_name:typeof a?.name=="string"?a.name:i?.name||c?.workspace.name||g.basename(t$2),h=typeof a?.profile=="string"?a.profile:typeof a?.mode=="string"?a.mode:c?.workspace.profile,m=Array.from(new Set(d.map(w=>w.kind))).sort(),v=Array.from(new Set(d.map(w=>w.category))).sort(),W=Array.from(new Set(d.flatMap(w=>w.runtimeCandidates.length>0?w.runtimeCandidates:[w.runtime]))).sort(),T=Array.from(new Set(d.map(w=>w.framework))).sort(),N=[".workspai/policies.yml",".workspai/policies.yaml",".rapidkit/policies.yml",".rapidkit/policies.yaml"].find(w=>C.existsSync(g.join(t$2,w))),X=t(t$2,"workspace.contract.json").map(w=>g.relative(t$2,w).split(g.sep).join("/")).find(w=>C.existsSync(g.join(t$2,w)))??t$1.workspaceContract,O=await C.pathExists(g.join(t$2,X)),Y={schemaVersion:Ar,generatedAt:n.toISOString(),workspace:{name:f,root:t$2,...h?{profile:h}:{},type:i?"rapidkit-workspace":"observed-workspace",...i?{marker:{createdBy:i.createdBy,version:i.version,createdAt:i.createdAt}}:{}},identity:{workspaceType:Hr(d),surfaces:m,categories:v,runtimeFamilies:W,businessCapabilities:Br(d)},discovery:{observableScanDepth:s},projects:d,policies:{mode:typeof a?.policy_mode=="string"?a.policy_mode:typeof a?.policyMode=="string"?a.policyMode:"warn",source:N??null,exists:!!N},contracts:{workspaceContractPath:X,exists:O,status:O?"known":"missing"},evidence:{doctor:await A(t$2,p.doctor,o),projectDoctor:await A(t$2,t$1.doctorProject,o),doctorRemediationPlan:await A(t$2,t$1.doctorRemediationPlan,o),artifactRemediationPlan:await A(t$2,t$1.artifactRemediationPlan,o),doctorFixResult:await A(t$2,t$1.doctorFixResult,o),analyze:await A(t$2,p.analyze,o),readiness:await A(t$2,p.readiness,o),pipeline:await A(t$2,t$1.pipelineLastRun,o)},summary:{projectCount:d.length,runtimes:W,frameworks:T,firstClassProjects:d.filter(w=>w.supportTier==="first-class").length,extendedProjects:d.filter(w=>w.supportTier==="extended").length,observedProjects:d.filter(w=>w.supportTier==="observed").length}},S=await Ot(t$2,Y,{contractExists:O,now:n,incrementalGraph:e.incrementalGraph}),E={...Y,projectTopology:S,graph:S},G=Dt(E),K=Lr({...E},n),Gt=Et({facts:K,generatedAt:n.toISOString(),now:n});return {...E,facts:K,factFreshness:Gt,validation:G}}async function wo(e){if(e.cache!==true)return {model:await le(e),cache:"disabled"};let t=g.resolve(e.workspacePath),r=Me(e.observableScanDepth),o=We(),{marker:s,workspaceJson:n,projectPaths:i}=await Ie(t,r),a=await ae({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:i,workspaceJson:n,marker:s}),c=await Re(t);if(c&&c.cliVersion===o&&c.inputsHash===a&&It(c.model))return {model:c.model,cache:"hit"};let l=await le({...e}),[u,p]=await Promise.all([oe(t,i),se(t)]);return await ie(t,{cliVersion:o,inputsHash:a,generatedAt:(e.now??new Date).toISOString(),model:l,projectSignatures:u,workspaceFileSignatures:p}),{model:l,cache:"miss"}}function Ur(e,t){let r=new Set,o=new Set,s=new Set;for(let[n,i]of Object.entries(t))n in e?e[n]!==i&&r.add(n):o.add(n);for(let n of Object.keys(e))n in t||s.add(n);return {changed:r,added:o,removed:s}}function zr(e={},t={}){let r=new Set([...Object.keys(e),...Object.keys(t)]);for(let o of r)if(e[o]!==t[o])return false;return true}async function vo(e){let t=g.resolve(e.workspacePath),r=Me(e.observableScanDepth),o=We(),s=e.now??new Date,{marker:n,workspaceJson:i,projectPaths:a}=await Ie(t,r),c=await Re(t),l=async()=>{let S=await le({...e}),E=await ae({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:a,workspaceJson:i,marker:n}),[G,K]=await Promise.all([oe(t,a),se(t)]);return await ie(t,{cliVersion:o,inputsHash:E,generatedAt:s.toISOString(),model:S,projectSignatures:G,workspaceFileSignatures:K}),{model:S,mode:"full"}},u=c?Ae(c.model):void 0;if(!c||c.cliVersion!==o||!c.projectSignatures||!u||!It(c.model))return l();let p=await se(t);if(!zr(c.workspaceFileSignatures,p))return l();let d=await oe(t,a),{changed:f,added:h,removed:m}=Ur(c.projectSignatures,d);if(f.size===0&&h.size===0&&m.size===0)return {model:c.model,mode:"unchanged"};let v=new Set([...f,...h]),W=new Map;for(let S of c.model.projects){let E=ce(t,S);!v.has(E)&&!m.has(E)&&W.set(E,S);}let T=new Set,N=false;for(let S of c.model.projects){let E=ce(t,S);f.has(E)&&T.add(S.name);}let X=h.size>0||m.size>0,O=await le({...e,reuseProjectModels:W,incrementalGraph:{previousGraph:u,changedProjectIds:T,structuralChange:X||N}});for(let S of c.model.projects){let E=ce(t,S);if(!f.has(E))continue;let G=O.projects.find(K=>ce(t,K)===E);if(G&&G.name!==S.name){N=true;break}}if(N)return l();let Y=await ae({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:a,workspaceJson:i,marker:n});return await ie(t,{cliVersion:o,inputsHash:Y,generatedAt:s.toISOString(),model:O,projectSignatures:d,workspaceFileSignatures:p}),{model:O,mode:"incremental"}}async function Fe(e){try{let{contract:t}=await p$1({workspacePath:e});return t&&typeof t=="object"?t:null}catch{return null}}async function Ot(e,t,r){let o=r.contractExists?await Fe(e):null;try{return r.incrementalGraph?await bt({workspacePath:e,model:t,contract:o,now:r.now,previousGraph:r.incrementalGraph.previousGraph,changedProjectIds:r.incrementalGraph.changedProjectIds,structuralChange:r.incrementalGraph.structuralChange}):await vt({workspacePath:e,model:t,contract:o,now:r.now})}catch{let s=t.projects.map(n=>({id:n.name,path:n.path}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:r.now.toISOString(),nodes:s,edges:[],stats:{nodeCount:s.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:s.length,connectedNodeCount:0,density:0,edgeCoverageRatio:s.length>0?0:1,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:s.length>1?[{code:"graph.inference.failed",severity:"warning",message:"Dependency graph inference failed; model contains projects but no dependency edges.",recommendation:"Run workspace model again after fixing graph inputs, or add workspace contract/manual graph overrides.",nodeIds:s.map(n=>n.id).sort((n,i)=>n.localeCompare(i))}]:void 0}}}async function bo(e,t,r={}){let o=e.contracts.exists?await Fe(t):null,{buildWorkspaceKnowledgeGraph:s}=await import('./workspace-knowledge-graph-4RSZTEFJ.js'),n=d$1(e),i=r.refreshKnowledgeGraph?null:await C.readJson(g.join(t,p.knowledgeGraph)).then(p=>p).catch(()=>null),a=await s({workspacePath:t,workspace:{name:e.workspace.name,...e.workspace.profile?{profile:e.workspace.profile}:{}},projects:e.projects.map(p=>({id:p.name,path:p.path,...p.absolutePath?{absolutePath:p.absolutePath}:{},runtime:p.runtime,runtimeCandidates:p.runtimeCandidates,framework:p.framework,kind:p.kind,category:p.category,...p.governance?{governance:p.governance}:{},...p.kit?{kit:p.kit}:{}})),projectTopology:Ae(e)??await Ot(t,e,{contractExists:e.contracts.exists,now:new Date(e.generatedAt)}),contract:o,now:new Date(e.generatedAt),source:{kind:"workspace-model",artifact:de,hashAlgorithm:"sha256",hash:d$2(n)},previousGraph:i}),c=[],l=new Map;for(let p of e.projects){let d=At(t,p);if(!(await C.stat(d).catch(()=>null))?.isDirectory())continue;let h=await C.realpath(d),m=l.get(h);if(m)throw new Error(`Projects ${m} and ${p.name} resolve to the same graph artifact root: ${d}`);l.set(h,p.name),c.push({rootPath:d,relativePath:t$1.projectKnowledgeGraphReference,payload:xt(a,p.name)});}let u=await j$1(t,de,[{rootPath:t,relativePath:p.knowledgeGraph,payload:a},{rootPath:t,relativePath:de,payload:n},...c]);for(let p$1 of c){let d=g.join(p$1.rootPath,p.knowledgeGraph);(await C.readJson(d).catch(()=>null))?.schemaVersion===q$2.knowledgeGraph&&await C.remove(d).catch(()=>{});}return u[1]}export{dt as a,Zr as b,nn as c,_ as d,St as e,b as f,Et as g,Wt as h,Rt as i,Rr as j,At as k,Ar as l,de as m,Ae as n,ko as o,yo as p,Lr as q,le as r,wo as s,vo as t,bo as u};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a}from'./chunk-HCFOVANQ.js';import {n,h,i}from'./chunk-SEZTSMRR.js';import {B}from'./chunk-O3TVVQ6X.js';import {d as d$1}from'./chunk-ROOPODG6.js';import {a as a$1}from'./chunk-GR6442P7.js';import {d,c}from'./chunk-EWZZUQBR.js';import {p,t}from'./chunk-ODK4LCEL.js';import u from'path';import {createHash}from'crypto';import {createReadStream}from'fs';import {execFile}from'child_process';import {promisify}from'util';import _ from'fs-extra';import {parseAllDocuments}from'yaml';var Bs=p.knowledgeGraph;function Ls(e,t){if(e.source.kind!=="workspace-model")throw new Error(`Workspace knowledge graph is not bound to the canonical workspace model (source: ${e.source.kind}).`);if(e.source.artifact!==p.model)throw new Error(`Workspace knowledge graph source artifact is ${e.source.artifact}; expected ${p.model}.`);if(e.source.hashAlgorithm!=="sha256")throw new Error(`Workspace knowledge graph source hash algorithm is ${e.source.hashAlgorithm}; expected sha256.`);let s=d(t);if(e.source.hash!==s)throw new Error("Workspace knowledge graph is stale: its source hash does not match the canonical workspace model.");if(e.workspace.name!==t.workspace.name||(e.workspace.profile??void 0)!==(t.workspace.profile??void 0))throw new Error("Workspace knowledge graph identity does not match the canonical workspace model.");let o=n(t);if(!o)throw new Error("Canonical workspace model has no project topology for the workspace knowledge graph.");let i=n=>({...n,generatedAt:"<ignored>"});if(c(i(e.projectTopology))!==c(i(o)))throw new Error("Workspace knowledge graph project topology does not match the canonical workspace model.")}function jt(e){return {path:e.path,...e.runtime!==void 0?{runtime:e.runtime}:{},...e.runtimeCandidates!==void 0?{runtimeCandidates:e.runtimeCandidates}:{},...e.framework!==void 0?{framework:e.framework}:{},...e.kit!==void 0?{kit:e.kit}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.category!==void 0?{category:e.category}:{},...e.governance?{governanceCiStatus:e.governance.ci.status,governanceReleaseStatus:e.governance.release.status,governanceOwnershipStatus:e.governance.ownership.status,governanceProviders:[e.governance.ci.provider,e.governance.release.provider,e.governance.ownership.provider].filter(t=>!!t)}:{}}}var Dt=5e5,qt=2e6;function ke(e,t){if(e!==void 0&&Number.isFinite(e)&&e>0)return Math.floor(e);let s=process.env[t];if(!s)return;let o=Number.parseInt(s,10);return Number.isFinite(o)&&o>0?o:void 0}var It=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"]),Et=new Set(["AGENTS.md","CLAUDE.md","GEMINI.md","QWEN.md"]),Ct=new Set([".workspai-workspace"]),Zt=[/(?:^|\/)\.agents\/skills\/workspai-[^/]+\//u,/(?:^|\/)\.amazonq\/rules\/workspai-[^/]+\.md$/u,/(?:^|\/)\.claude\/(?:rules|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.cursor\/(?:rules|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.grok\/(?:rules|skills)\/workspai-[^/]+(?:\/|$)/u,/(?:^|\/)\.github\/agents\/workspai-[^/]+\.agent\.md$/u,/(?:^|\/)\.github\/(?:instructions|prompts|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.github\/copilot-instructions\.md$/u,/(?:^|\/)\.windsurf\/rules\/workspai-[^/]+\.md$/u,/(?:^|\/)\.windsurfrules$/u,/(?:^|\/)\.vscode\/(?:workspai|rapidkit)-agent-hooks\.json$/u];function Ke(e,t){let s=D(u.relative(e,t));return Et.has(u.posix.basename(s))||Ct.has(u.posix.basename(s))||Zt.some(o=>o.test(s))}var Ht=new Set(["test","tests","spec","specs","e2e","integration","integration-tests","integration_tests","__tests__","fixture","fixtures","__fixtures__","testdata"]),Ut=new Set(["examples","samples","worked"]);function Ge(e,t){let s=u.relative(e,t).split(u.sep).map(i=>i.toLowerCase()),o=u.basename(t).toLowerCase();return s.some(i=>Ht.has(i))||/(?:\.test|\.spec|_test)\.[a-z0-9]+$/i.test(o)||/^test_.+\.[a-z0-9]+$/i.test(o)||/(?:tests?|specs?)\.(?:cs|fs|vb|java|kt|kts)$/i.test(o)}function De(e,t){return u.relative(e,t).split(u.sep).map(s=>s.toLowerCase()).some(s=>Ut.has(s))}function ee(e,t){return Ge(e,t)||De(e,t)}function he(e,t){return u.relative(e,t).split(u.sep).some(s=>s.toLowerCase()==="generated")}var Le=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"]),Jt=new Set([...Le,"go.work","go.work.sum"]),Vt=new Set(["get","put","post","delete","options","head","patch","trace"]),te=new Set([".c",".cc",".cpp",".cs",".dart",".ex",".exs",".go",".h",".hpp",".java",".cjs",".cts",".js",".jsx",".kt",".kts",".mjs",".mts",".php",".py",".r",".rb",".rs",".scala",".svelte",".swift",".ts",".tsx",".vue",".clj",".cljs",".fs",".fsx",".lua",".vb"]),nt=new Set([...te,".adb",".ads",".asm",".bash",".bat",".cl",".cob",".cu",".cuh",".erl",".f",".f03",".f08",".f77",".f90",".f95",".fish",".for",".gql",".graphql",".groovy",".hip",".hrl",".hs",".hlsl",".jl",".ll",".m",".metal",".mir",".mlir",".mm",".nim",".pas",".pl",".pm",".proto",".ps1",".s",".sh",".sol",".sql",".sv",".td",".thrift",".v",".vhd",".vhdl",".zig",".zsh"]);function J(e,t){let s=u.extname(e).toLowerCase();return s===".h"&&t==="cpp"?"cpp":{".c":"c",".adb":"ada",".ads":"ada",".asm":"assembly",".bash":"shell",".bat":"batch",".cc":"cpp",".cl":"opencl",".cob":"cobol",".cpp":"cpp",".cs":"csharp",".cu":"cuda",".cuh":"cuda",".dart":"dart",".erl":"erlang",".ex":"elixir",".exs":"elixir",".f":"fortran",".f03":"fortran",".f08":"fortran",".f77":"fortran",".f90":"fortran",".f95":"fortran",".fish":"shell",".for":"fortran",".gql":"graphql",".go":"go",".graphql":"graphql",".groovy":"groovy",".h":"c",".hip":"hip",".hpp":"cpp",".hrl":"erlang",".hs":"haskell",".hlsl":"hlsl",".java":"java",".jl":"julia",".cjs":"javascript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".kt":"kotlin",".kts":"kotlin",".mjs":"javascript",".mts":"typescript",".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",".ll":"llvm-ir",".m":"objective-c",".metal":"metal",".mir":"llvm-mir",".mlir":"mlir",".mm":"objective-cpp",".nim":"nim",".pas":"pascal",".pl":"perl",".pm":"perl",".proto":"protobuf",".ps1":"powershell",".s":"assembly",".sh":"shell",".sol":"solidity",".sql":"sql",".sv":"systemverilog",".td":"tablegen",".thrift":"thrift",".v":"verilog",".vb":"visual-basic",".vhd":"vhdl",".vhdl":"vhdl",".zig":"zig",".zsh":"shell"}[s]??s.slice(1)}var Yt=new Set(["external","third_party","third-party","vendor","vendors","vendored"]),Qt=new Set(["app","apps","cli","cmd","core","extensions","internal","lib","packages","services","src"]);function at(e,t){let o=D(u.relative(t,e)).split("/").filter(Boolean),i=o[0]?.toLowerCase()??"";return (o.some(l=>Yt.has(l.toLowerCase()))?1e3:0)+(Qt.has(i)?-100:0)+Math.min(o.length,20)}function Xt(e,t,s){if(e.length<=t)return [...e];let o=[...e].sort((c,r)=>at(c,s)-at(r,s)||c.localeCompare(r)),i=new Map;for(let c of o){let r=J(c),d=i.get(r)??[];d.push(c),i.set(r,d);}let n=new Set,l=Math.max(1,Math.min(25,Math.floor(t/Math.max(i.size,1))));for(let c of [...i.values()])for(let r of c.slice(0,l))n.add(r);for(let c of o){if(n.size>=t)break;n.add(c);}return [...n].sort((c,r)=>c.localeCompare(r))}function eo(e,t){let s=D(u.relative(t,e)).split("/").filter(Boolean);if(s.length===0)return "<root>";let o=s[0].toLowerCase();return ["app","apps","cmd","components","crates","modules","packages","plugins","services"].includes(o)&&s[1]?`${o}/${s[1].toLowerCase()}`:o}function $e(e,t,s){let o=[...new Set(e)].sort((d,a)=>d.localeCompare(a));if(o.length<=t)return o;let i=new Set,n=o.filter(d=>Jt.has(u.basename(d))).sort((d,a)=>D(u.relative(s,d)).split("/").length-D(u.relative(s,a)).split("/").length||d.localeCompare(a));for(let d of n){if(i.size>=t)break;i.add(d);}let l=new Map;for(let d of o){if(i.has(d))continue;let a=`${eo(d,s)}\0${J(d)}`,p=l.get(a)??[];p.push(d),l.set(a,p);}let c=[...l.entries()].sort(([d],[a])=>d.localeCompare(a)),r=0;for(;i.size<t;){let d=false;for(let[,a]of c){let p=a[r];if(p&&(i.add(p),d=true,i.size>=t))break}if(!d)break;r+=1;}return [...i].sort((d,a)=>d.localeCompare(a))}function to(e){let t=Math.max(0,e.eligibleFiles),s=Math.min(25e3,Math.max(5e3,Math.ceil(t*.2))),o=Math.max(100,Math.min(e.deepOverride??s,Math.max(t,100),1e5)),i=Math.min(1e5,Math.max(25e3,o*4,Math.ceil(t*.6))),n=Math.max(o,Math.min(e.semanticOverride??i,Math.max(t,o),25e4)),l=Math.min(2e4,Math.max(2e3,Math.ceil(Math.min(t,o)*.25))),c=Math.max(100,Math.min(e.sourceOverride??l,o,5e4));return {semanticFileBudget:n,deepFileBudget:o,sourceExtractionFileBudget:c}}function Oe(e,t,s){let o=[],i=e.split(/\r?\n/);for(let n=0;n<i.length&&o.length<s;n+=1)for(let l of t){let r=i[n].match(l.pattern)?.[1]?.trim();if(r){o.push({name:r,line:n+1,detail:l.detail});break}}return o}var oo=[{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"}],Rt=[{pattern:/^\s*import(?:.+?from\s*)?["']([^"']+)["']/,detail:"import"},{pattern:/require\(["']([^"']+)["']\)/,detail:"require"}],St=[{pattern:/^\s*from\s+([A-Za-z0-9_.]+)\s+import\s+/,detail:"import"},{pattern:/^\s*import\s+([A-Za-z0-9_.]+)(?:\s|$)/,detail:"import"}],so=[{pattern:/^\s*#\s*include\s*["<]([^">]+)[">]/,detail:"include"}],io=[{pattern:/^\s*use\s+([A-Za-z0-9_:*.-]+)/,detail:"use"}],ro=[{pattern:/^\s*import\s+(?:static\s+)?([A-Za-z0-9_.*]+)\s*;?/,detail:"import"}],no=[{pattern:/^\s*(?:global\s+)?using\s+([A-Za-z0-9_.]+)/,detail:"using"}],ao=[{pattern:/^\s*import\s+(?:[A-Za-z0-9_.]+\s+)?["']([^"']+)["']/,detail:"import"}],At=[{pattern:/^\s*require(?:_relative)?\s+["']([^"']+)["']/,detail:"require"}],co=[{pattern:/^\s*use\s+([A-Za-z0-9_\\]+)/,detail:"use"}],lo=[{pattern:/^\s*(?:alias|import|require|use)\s+([A-Za-z0-9_.]+)/,detail:"import"}],po=[{pattern:/^\s*import\s+["']([^"']+)["']/,detail:"import"}],uo=[{pattern:/\brequire\s*\(?\s*["']([^"']+)["']/,detail:"require"}],fo=[{pattern:/^\s*(?:library|require)\s*\(\s*["']?([^"')\s]+)["']?/,detail:"import"}],go=[...Rt,...St,{pattern:/^\s*(?:import|using|use)\s+([A-Za-z0-9_:.*\\/.-]+)/,detail:"import"},...At];function mo(e){let t=u.extname(e).toLowerCase();return [".cjs",".cts",".js",".jsx",".mjs",".mts",".ts",".tsx",".vue",".svelte"].includes(t)?Rt:t===".py"?St:[".c",".cc",".cpp",".h",".hpp"].includes(t)?so:t===".rs"?io:[".java",".kt",".kts",".scala"].includes(t)?ro:[".cs",".fs",".fsx",".vb"].includes(t)?no:t===".go"?ao:t===".rb"?At:t===".php"?co:[".ex",".exs"].includes(t)?lo:t===".dart"?po:t===".lua"?uo:t===".r"?fo:go}function ho(e,t,s,o,i){let n=u.extname(e).toLowerCase()===".py",l=[];if(n){let r=t.match(/^\.+/)?.[0].length??0,d=r>0?u.dirname(e):u.resolve(o??"");for(let p=1;p<r;p+=1)d=u.dirname(d);let a=t.slice(r).replace(/\./g,u.sep);l.push(a?u.join(d,a):d);}else if(t.startsWith("."))l.push(u.resolve(u.dirname(e),t));else if(i==="include")l.push(u.resolve(u.dirname(e),t)),o&&l.push(u.resolve(o,t));else return null;let c=new Set;for(let r of l){c.add(r);let d=u.extname(r).toLowerCase(),a=te.has(d);if(n&&(c.add(`${r}.py`),c.add(u.join(r,"__init__.py"))),a){let p=r.slice(0,-d.length);if([".js",".jsx",".mjs"].includes(d))for(let f of [".ts",".tsx",".js",".jsx",".mjs"])c.add(`${p}${f}`);}else for(let p of te)c.add(`${r}${p}`),c.add(u.join(r,`index${p}`));}return [...c].find(r=>s.has(u.resolve(r)))??null}function vo(e,t){let s=t.trimStart(),o=u.extname(e).toLowerCase();return [".py",".rb",".sh",".bash",".zsh"].includes(o)?s.startsWith("#"):[".sql",".lua",".hs"].includes(o)?s.startsWith("--"):s.startsWith("//")||s.startsWith("/*")||s.startsWith("*")}function yo(e,t){if(u.extname(e).toLowerCase()!==".py")return t;let s=null;return t.split(/\r?\n/).map(o=>{let i=0,n="";for(;i<o.length;){if(s){let a=o.indexOf(s,i);if(a<0)return n;i=a+3,s=null;continue}let l=o.indexOf("'''",i),c=o.indexOf('"""',i),r=o.indexOf("#",i),d=l<0?c:c<0?l:Math.min(l,c);if(r>=0&&(d<0||r<d)){n+=o.slice(i,r);break}if(d<0){n+=o.slice(i);break}n+=o.slice(i,d),s=o.startsWith("'''",d)?"'''":'"""',i=d+3;}return n}).join(`
|
|
1
|
+
import {a}from'./chunk-HCFOVANQ.js';import {n,h,i}from'./chunk-O4TZKLEC.js';import {B}from'./chunk-7HV4U2OV.js';import {d as d$1}from'./chunk-ROOPODG6.js';import {a as a$1}from'./chunk-GR6442P7.js';import {d,c}from'./chunk-EWZZUQBR.js';import {p,t}from'./chunk-ODK4LCEL.js';import u from'path';import {createHash}from'crypto';import {createReadStream}from'fs';import {execFile}from'child_process';import {promisify}from'util';import _ from'fs-extra';import {parseAllDocuments}from'yaml';var Bs=p.knowledgeGraph;function Ls(e,t){if(e.source.kind!=="workspace-model")throw new Error(`Workspace knowledge graph is not bound to the canonical workspace model (source: ${e.source.kind}).`);if(e.source.artifact!==p.model)throw new Error(`Workspace knowledge graph source artifact is ${e.source.artifact}; expected ${p.model}.`);if(e.source.hashAlgorithm!=="sha256")throw new Error(`Workspace knowledge graph source hash algorithm is ${e.source.hashAlgorithm}; expected sha256.`);let s=d(t);if(e.source.hash!==s)throw new Error("Workspace knowledge graph is stale: its source hash does not match the canonical workspace model.");if(e.workspace.name!==t.workspace.name||(e.workspace.profile??void 0)!==(t.workspace.profile??void 0))throw new Error("Workspace knowledge graph identity does not match the canonical workspace model.");let o=n(t);if(!o)throw new Error("Canonical workspace model has no project topology for the workspace knowledge graph.");let i=n=>({...n,generatedAt:"<ignored>"});if(c(i(e.projectTopology))!==c(i(o)))throw new Error("Workspace knowledge graph project topology does not match the canonical workspace model.")}function jt(e){return {path:e.path,...e.runtime!==void 0?{runtime:e.runtime}:{},...e.runtimeCandidates!==void 0?{runtimeCandidates:e.runtimeCandidates}:{},...e.framework!==void 0?{framework:e.framework}:{},...e.kit!==void 0?{kit:e.kit}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.category!==void 0?{category:e.category}:{},...e.governance?{governanceCiStatus:e.governance.ci.status,governanceReleaseStatus:e.governance.release.status,governanceOwnershipStatus:e.governance.ownership.status,governanceProviders:[e.governance.ci.provider,e.governance.release.provider,e.governance.ownership.provider].filter(t=>!!t)}:{}}}var Dt=5e5,qt=2e6;function ke(e,t){if(e!==void 0&&Number.isFinite(e)&&e>0)return Math.floor(e);let s=process.env[t];if(!s)return;let o=Number.parseInt(s,10);return Number.isFinite(o)&&o>0?o:void 0}var It=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"]),Et=new Set(["AGENTS.md","CLAUDE.md","GEMINI.md","QWEN.md"]),Ct=new Set([".workspai-workspace"]),Zt=[/(?:^|\/)\.agents\/skills\/workspai-[^/]+\//u,/(?:^|\/)\.amazonq\/rules\/workspai-[^/]+\.md$/u,/(?:^|\/)\.claude\/(?:rules|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.cursor\/(?:rules|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.grok\/(?:rules|skills)\/workspai-[^/]+(?:\/|$)/u,/(?:^|\/)\.github\/agents\/workspai-[^/]+\.agent\.md$/u,/(?:^|\/)\.github\/(?:instructions|prompts|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.github\/copilot-instructions\.md$/u,/(?:^|\/)\.windsurf\/rules\/workspai-[^/]+\.md$/u,/(?:^|\/)\.windsurfrules$/u,/(?:^|\/)\.vscode\/(?:workspai|rapidkit)-agent-hooks\.json$/u];function Ke(e,t){let s=D(u.relative(e,t));return Et.has(u.posix.basename(s))||Ct.has(u.posix.basename(s))||Zt.some(o=>o.test(s))}var Ht=new Set(["test","tests","spec","specs","e2e","integration","integration-tests","integration_tests","__tests__","fixture","fixtures","__fixtures__","testdata"]),Ut=new Set(["examples","samples","worked"]);function Ge(e,t){let s=u.relative(e,t).split(u.sep).map(i=>i.toLowerCase()),o=u.basename(t).toLowerCase();return s.some(i=>Ht.has(i))||/(?:\.test|\.spec|_test)\.[a-z0-9]+$/i.test(o)||/^test_.+\.[a-z0-9]+$/i.test(o)||/(?:tests?|specs?)\.(?:cs|fs|vb|java|kt|kts)$/i.test(o)}function De(e,t){return u.relative(e,t).split(u.sep).map(s=>s.toLowerCase()).some(s=>Ut.has(s))}function ee(e,t){return Ge(e,t)||De(e,t)}function he(e,t){return u.relative(e,t).split(u.sep).some(s=>s.toLowerCase()==="generated")}var Le=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"]),Jt=new Set([...Le,"go.work","go.work.sum"]),Vt=new Set(["get","put","post","delete","options","head","patch","trace"]),te=new Set([".c",".cc",".cpp",".cs",".dart",".ex",".exs",".go",".h",".hpp",".java",".cjs",".cts",".js",".jsx",".kt",".kts",".mjs",".mts",".php",".py",".r",".rb",".rs",".scala",".svelte",".swift",".ts",".tsx",".vue",".clj",".cljs",".fs",".fsx",".lua",".vb"]),nt=new Set([...te,".adb",".ads",".asm",".bash",".bat",".cl",".cob",".cu",".cuh",".erl",".f",".f03",".f08",".f77",".f90",".f95",".fish",".for",".gql",".graphql",".groovy",".hip",".hrl",".hs",".hlsl",".jl",".ll",".m",".metal",".mir",".mlir",".mm",".nim",".pas",".pl",".pm",".proto",".ps1",".s",".sh",".sol",".sql",".sv",".td",".thrift",".v",".vhd",".vhdl",".zig",".zsh"]);function J(e,t){let s=u.extname(e).toLowerCase();return s===".h"&&t==="cpp"?"cpp":{".c":"c",".adb":"ada",".ads":"ada",".asm":"assembly",".bash":"shell",".bat":"batch",".cc":"cpp",".cl":"opencl",".cob":"cobol",".cpp":"cpp",".cs":"csharp",".cu":"cuda",".cuh":"cuda",".dart":"dart",".erl":"erlang",".ex":"elixir",".exs":"elixir",".f":"fortran",".f03":"fortran",".f08":"fortran",".f77":"fortran",".f90":"fortran",".f95":"fortran",".fish":"shell",".for":"fortran",".gql":"graphql",".go":"go",".graphql":"graphql",".groovy":"groovy",".h":"c",".hip":"hip",".hpp":"cpp",".hrl":"erlang",".hs":"haskell",".hlsl":"hlsl",".java":"java",".jl":"julia",".cjs":"javascript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".kt":"kotlin",".kts":"kotlin",".mjs":"javascript",".mts":"typescript",".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",".ll":"llvm-ir",".m":"objective-c",".metal":"metal",".mir":"llvm-mir",".mlir":"mlir",".mm":"objective-cpp",".nim":"nim",".pas":"pascal",".pl":"perl",".pm":"perl",".proto":"protobuf",".ps1":"powershell",".s":"assembly",".sh":"shell",".sol":"solidity",".sql":"sql",".sv":"systemverilog",".td":"tablegen",".thrift":"thrift",".v":"verilog",".vb":"visual-basic",".vhd":"vhdl",".vhdl":"vhdl",".zig":"zig",".zsh":"shell"}[s]??s.slice(1)}var Yt=new Set(["external","third_party","third-party","vendor","vendors","vendored"]),Qt=new Set(["app","apps","cli","cmd","core","extensions","internal","lib","packages","services","src"]);function at(e,t){let o=D(u.relative(t,e)).split("/").filter(Boolean),i=o[0]?.toLowerCase()??"";return (o.some(l=>Yt.has(l.toLowerCase()))?1e3:0)+(Qt.has(i)?-100:0)+Math.min(o.length,20)}function Xt(e,t,s){if(e.length<=t)return [...e];let o=[...e].sort((c,r)=>at(c,s)-at(r,s)||c.localeCompare(r)),i=new Map;for(let c of o){let r=J(c),d=i.get(r)??[];d.push(c),i.set(r,d);}let n=new Set,l=Math.max(1,Math.min(25,Math.floor(t/Math.max(i.size,1))));for(let c of [...i.values()])for(let r of c.slice(0,l))n.add(r);for(let c of o){if(n.size>=t)break;n.add(c);}return [...n].sort((c,r)=>c.localeCompare(r))}function eo(e,t){let s=D(u.relative(t,e)).split("/").filter(Boolean);if(s.length===0)return "<root>";let o=s[0].toLowerCase();return ["app","apps","cmd","components","crates","modules","packages","plugins","services"].includes(o)&&s[1]?`${o}/${s[1].toLowerCase()}`:o}function $e(e,t,s){let o=[...new Set(e)].sort((d,a)=>d.localeCompare(a));if(o.length<=t)return o;let i=new Set,n=o.filter(d=>Jt.has(u.basename(d))).sort((d,a)=>D(u.relative(s,d)).split("/").length-D(u.relative(s,a)).split("/").length||d.localeCompare(a));for(let d of n){if(i.size>=t)break;i.add(d);}let l=new Map;for(let d of o){if(i.has(d))continue;let a=`${eo(d,s)}\0${J(d)}`,p=l.get(a)??[];p.push(d),l.set(a,p);}let c=[...l.entries()].sort(([d],[a])=>d.localeCompare(a)),r=0;for(;i.size<t;){let d=false;for(let[,a]of c){let p=a[r];if(p&&(i.add(p),d=true,i.size>=t))break}if(!d)break;r+=1;}return [...i].sort((d,a)=>d.localeCompare(a))}function to(e){let t=Math.max(0,e.eligibleFiles),s=Math.min(25e3,Math.max(5e3,Math.ceil(t*.2))),o=Math.max(100,Math.min(e.deepOverride??s,Math.max(t,100),1e5)),i=Math.min(1e5,Math.max(25e3,o*4,Math.ceil(t*.6))),n=Math.max(o,Math.min(e.semanticOverride??i,Math.max(t,o),25e4)),l=Math.min(2e4,Math.max(2e3,Math.ceil(Math.min(t,o)*.25))),c=Math.max(100,Math.min(e.sourceOverride??l,o,5e4));return {semanticFileBudget:n,deepFileBudget:o,sourceExtractionFileBudget:c}}function Oe(e,t,s){let o=[],i=e.split(/\r?\n/);for(let n=0;n<i.length&&o.length<s;n+=1)for(let l of t){let r=i[n].match(l.pattern)?.[1]?.trim();if(r){o.push({name:r,line:n+1,detail:l.detail});break}}return o}var oo=[{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"}],Rt=[{pattern:/^\s*import(?:.+?from\s*)?["']([^"']+)["']/,detail:"import"},{pattern:/require\(["']([^"']+)["']\)/,detail:"require"}],St=[{pattern:/^\s*from\s+([A-Za-z0-9_.]+)\s+import\s+/,detail:"import"},{pattern:/^\s*import\s+([A-Za-z0-9_.]+)(?:\s|$)/,detail:"import"}],so=[{pattern:/^\s*#\s*include\s*["<]([^">]+)[">]/,detail:"include"}],io=[{pattern:/^\s*use\s+([A-Za-z0-9_:*.-]+)/,detail:"use"}],ro=[{pattern:/^\s*import\s+(?:static\s+)?([A-Za-z0-9_.*]+)\s*;?/,detail:"import"}],no=[{pattern:/^\s*(?:global\s+)?using\s+([A-Za-z0-9_.]+)/,detail:"using"}],ao=[{pattern:/^\s*import\s+(?:[A-Za-z0-9_.]+\s+)?["']([^"']+)["']/,detail:"import"}],At=[{pattern:/^\s*require(?:_relative)?\s+["']([^"']+)["']/,detail:"require"}],co=[{pattern:/^\s*use\s+([A-Za-z0-9_\\]+)/,detail:"use"}],lo=[{pattern:/^\s*(?:alias|import|require|use)\s+([A-Za-z0-9_.]+)/,detail:"import"}],po=[{pattern:/^\s*import\s+["']([^"']+)["']/,detail:"import"}],uo=[{pattern:/\brequire\s*\(?\s*["']([^"']+)["']/,detail:"require"}],fo=[{pattern:/^\s*(?:library|require)\s*\(\s*["']?([^"')\s]+)["']?/,detail:"import"}],go=[...Rt,...St,{pattern:/^\s*(?:import|using|use)\s+([A-Za-z0-9_:.*\\/.-]+)/,detail:"import"},...At];function mo(e){let t=u.extname(e).toLowerCase();return [".cjs",".cts",".js",".jsx",".mjs",".mts",".ts",".tsx",".vue",".svelte"].includes(t)?Rt:t===".py"?St:[".c",".cc",".cpp",".h",".hpp"].includes(t)?so:t===".rs"?io:[".java",".kt",".kts",".scala"].includes(t)?ro:[".cs",".fs",".fsx",".vb"].includes(t)?no:t===".go"?ao:t===".rb"?At:t===".php"?co:[".ex",".exs"].includes(t)?lo:t===".dart"?po:t===".lua"?uo:t===".r"?fo:go}function ho(e,t,s,o,i){let n=u.extname(e).toLowerCase()===".py",l=[];if(n){let r=t.match(/^\.+/)?.[0].length??0,d=r>0?u.dirname(e):u.resolve(o??"");for(let p=1;p<r;p+=1)d=u.dirname(d);let a=t.slice(r).replace(/\./g,u.sep);l.push(a?u.join(d,a):d);}else if(t.startsWith("."))l.push(u.resolve(u.dirname(e),t));else if(i==="include")l.push(u.resolve(u.dirname(e),t)),o&&l.push(u.resolve(o,t));else return null;let c=new Set;for(let r of l){c.add(r);let d=u.extname(r).toLowerCase(),a=te.has(d);if(n&&(c.add(`${r}.py`),c.add(u.join(r,"__init__.py"))),a){let p=r.slice(0,-d.length);if([".js",".jsx",".mjs"].includes(d))for(let f of [".ts",".tsx",".js",".jsx",".mjs"])c.add(`${p}${f}`);}else for(let p of te)c.add(`${r}${p}`),c.add(u.join(r,`index${p}`));}return [...c].find(r=>s.has(u.resolve(r)))??null}function vo(e,t){let s=t.trimStart(),o=u.extname(e).toLowerCase();return [".py",".rb",".sh",".bash",".zsh"].includes(o)?s.startsWith("#"):[".sql",".lua",".hs"].includes(o)?s.startsWith("--"):s.startsWith("//")||s.startsWith("/*")||s.startsWith("*")}function yo(e,t){if(u.extname(e).toLowerCase()!==".py")return t;let s=null;return t.split(/\r?\n/).map(o=>{let i=0,n="";for(;i<o.length;){if(s){let a=o.indexOf(s,i);if(a<0)return n;i=a+3,s=null;continue}let l=o.indexOf("'''",i),c=o.indexOf('"""',i),r=o.indexOf("#",i),d=l<0?c:c<0?l:Math.min(l,c);if(r>=0&&(d<0||r<d)){n+=o.slice(i,r);break}if(d<0){n+=o.slice(i);break}n+=o.slice(i,d),s=o.startsWith("'''",d)?"'''":'"""',i=d+3;}return n}).join(`
|
|
2
2
|
`)}function bo(e,t){if(![".js",".jsx",".mjs",".ts",".tsx"].includes(u.extname(e).toLowerCase()))return t;let s=false,o=false;return t.split(/\r?\n/).map(i=>{let n="",l=null,c=false;for(let r=0;r<i.length;r+=1){let d=i[r],a=i[r+1];if(s){n+=" ",d==="*"&&a==="/"&&(n+=" ",r+=1,s=false);continue}if(o){n+=" ",d==="`"&&!c&&(o=false),c=d==="\\"&&!c,d!=="\\"&&(c=false);continue}if(l){n+=d,d===l&&!c&&(l=null),c=d==="\\"&&!c,d!=="\\"&&(c=false);continue}if(d==="/"&&a==="/")return n.padEnd(i.length," ");if(d==="/"&&a==="*"){n+=" ",r+=1,s=true;continue}if(d==="`"){n+=" ",o=true,c=false;continue}(d==="'"||d==='"')&&(l=d),n+=d;}return n}).join(`
|
|
3
3
|
`)}function Ft(e,t){return bo(e,yo(e,t))}var we=[{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"}],ko=[{pattern:/@Router\s+([^\s]+)\s+\[(?:get|post|put|delete|patch|options|head)\]/i,detail:"swagger route"},{pattern:/\b[A-Za-z_]\w*\.(?:GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD)\s*\(\s*["']([^"']+)["']/,detail:"go router route"}],wo=[{pattern:/\.route\s*\(\s*["']([^"']+)["']\s*,\s*(?:routing::)?(?:get|post|put|delete|patch|options|head)\s*\(/i,detail:"rust router route"}],Po=[{pattern:/\b[A-Za-z_]\w*\.Map(?:Get|Post|Put|Delete|Patch|Methods)\s*\(\s*["']([^"']+)["']/i,detail:"dotnet route"},{pattern:/\b[A-Za-z_]\w*\.MapHealthChecks\s*\(\s*["']([^"']+)["']/i,detail:"dotnet health route"}];function $o(e){let t=u.extname(e).toLowerCase();return t===".go"?[...we,...ko]:t===".rs"?[...we,...wo]:t===".cs"?[...we,...Po]:we}function jo(e,t){return t==="swagger route"?e.match(/\[(get|post|put|delete|patch|options|head)\]/i)?.[1]?.toUpperCase()??"HTTP":t==="rust router route"?e.match(/,\s*(?:routing::)?(get|post|put|delete|patch|options|head)\s*\(/i)?.[1]?.toUpperCase()??"HTTP":t==="dotnet health route"?"GET":t==="dotnet route"?e.match(/\.Map(Get|Post|Put|Delete|Patch|Methods)\s*\(/i)?.[1]?.toUpperCase()??"HTTP":e.match(/(?:@|\.|\[|^\s*)(get|post|put|delete|patch|options|head)/i)?.[1]?.toUpperCase()??"HTTP"}function je(e){return createHash("sha256").update(e).digest("hex")}function R(e,t){return `wkg:${e}:${je(`${e}\0${t}`).slice(0,20)}`}function D(e){return e.replace(/\\/g,"/")}function me(e){let t=D(e).replace(/^\.\//,"");return !t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")?"unknown":t}function C(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function P(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function H(e){if(Array.isArray(e))return e.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).sort();let t=C(e);return t?Object.keys(t).map(s=>s.trim()).filter(Boolean).sort():[]}function Io(e){if(Array.isArray(e))return e.map(s=>typeof s=="string"?s.split("=",1)[0]?.trim():"").filter(s=>!!s).sort();let t=C(e);return t?Object.keys(t).sort():[]}function Eo(e){return Object.fromEntries(Object.entries(e).filter(t=>t[1]!==void 0).sort(([t],[s])=>t.localeCompare(s)))}async function Co(e,t,s=[]){let o=[],i=[e],n=s.map(r=>u.resolve(r)),l=r=>{let d=u.resolve(r);return n.some(a=>d===a||d.startsWith(`${a}${u.sep}`))},c=0;for(;c<i.length&&o.length<t;){let r=i[c++],d;try{d=await _.readdir(r,{withFileTypes:true});}catch{continue}d.sort((a,p)=>a.name.localeCompare(p.name));for(let a of d){if(o.length>=t)break;if(a.isSymbolicLink())continue;let p=u.join(r,a.name);l(p)||(a.isDirectory()?!It.has(a.name)&&!a$1(a.name)&&i.push(p):a.isFile()&&(Ke(e,p)||o.push(p)));}}return o.sort((r,d)=>r.localeCompare(d))}function ve(e,t,s){let o=s?.projects.find(i=>i.relativePath===t.path||t.id!==void 0&&(i.slug===t.id||i.relativePath===`external/${t.id}`));return d$1(e,t.path,{...t.absolutePath||o?.externalPath?{absolutePath:t.absolutePath??o?.externalPath}:{}})}async function qe(e){return new Promise(t=>{let s=createHash("sha256"),o=createReadStream(e);o.on("data",i=>s.update(i)),o.on("error",i=>{t(`unreadable:${i.code??"unknown"}`);}),o.on("end",()=>t(s.digest("hex")));})}var Ro=promisify(execFile);async function Z(e,t){let s=await Ro("git",t,{cwd:e,encoding:"buffer",maxBuffer:268435456,windowsHide:true});return Buffer.isBuffer(s.stdout)?s.stdout:Buffer.from(s.stdout)}function Ze(){return [".",...[...It].sort((e,t)=>e.localeCompare(t)).map(e=>`:(exclude,glob)**/${e}/**`),...[...Et].sort((e,t)=>e.localeCompare(t)).map(e=>`:(exclude,glob)**/${e}`),...[...Ct].sort((e,t)=>e.localeCompare(t)).map(e=>`:(exclude,glob)**/${e}`),":(exclude,glob)**/.agents/skills/workspai-*/**",":(exclude,glob)**/.amazonq/rules/workspai-*.md",":(exclude,glob)**/.claude/rules/workspai-*.md",":(exclude,glob)**/.claude/rules/rapidkit-*.md",":(exclude,glob)**/.claude/skills/workspai-*/**",":(exclude,glob)**/.cursor/rules/workspai-*.*",":(exclude,glob)**/.cursor/rules/rapidkit-*.*",":(exclude,glob)**/.cursor/skills/workspai-*/**",":(exclude,glob)**/.grok/rules/workspai-*.md",":(exclude,glob)**/.grok/skills/workspai-*/**",":(exclude,glob)**/.github/agents/workspai-*.agent.md",":(exclude,glob)**/.github/copilot-instructions.md",":(exclude,glob)**/.github/instructions/workspai-*.md",":(exclude,glob)**/.github/instructions/rapidkit-*.md",":(exclude,glob)**/.github/prompts/workspai-*.md",":(exclude,glob)**/.github/prompts/rapidkit-*.md",":(exclude,glob)**/.github/skills/workspai-*/**",":(exclude,glob)**/.github/skills/rapidkit-*/**",":(exclude,glob)**/.windsurf/rules/workspai-*.md",":(exclude,glob)**/.windsurfrules",":(exclude,glob)**/.vscode/workspai-agent-hooks.json",":(exclude,glob)**/.vscode/rapidkit-agent-hooks.json"]}function We(e){return e.toString("utf8").split("\0").filter(Boolean).map(t=>t.replace(/\\/gu,"/"))}async function So(e,t,s=[]){try{await Z(e,["rev-parse","--show-toplevel"]);let o=Ze(),[i,n,l]=await Promise.all([Z(e,["ls-files","--stage","-z","--",...o]),Z(e,["ls-files","--deleted","-z","--",...o]),Z(e,["ls-files","--others","--exclude-standard","-z","--",...o])]),c=new Set(We(n)),r=i.toString("utf8").split("\0").filter(Boolean).flatMap(v=>{let m=v.match(/^(\d{6}) [0-9a-f]+ \d\t([\s\S]+)$/u);if(!m)return [];let[,h,y]=m,b=y.replace(/\\/gu,"/");return h==="120000"||h==="160000"||c.has(b)?[]:[b]}),p=(await Ce([...new Set([...r,...We(l)])],64,async v=>{let m=u.normalize(v);if(u.isAbsolute(m)||m===".."||m.startsWith(`..${u.sep}`))return null;let h=u.resolve(e,m);try{let y=await _.lstat(h);return y.isFile()&&!y.isSymbolicLink()?v:null}catch{return null}})).filter(v=>v!==null).map(v=>u.resolve(e,...v.split("/").filter(Boolean))).filter(v=>!Ke(e,v)).filter(v=>!s.some(m=>v===u.resolve(m)||v.startsWith(`${u.resolve(m)}${u.sep}`))).sort((v,m)=>v.localeCompare(m)),f=p.length>t;return {files:f?$e(p,t,e):p,eligibleFileCount:p.length,eligibleFileCountExact:true,truncated:f,fileLimit:t,strategy:"git-index-worktree-v1"}}catch{return null}}async function ye(e,t,s=[]){let o=await So(e,t,s);if(o)return o;let i=await Co(e,t+1,s),n=i.length>t;return {files:n?$e(i,t,e):i,eligibleFileCount:i.length,eligibleFileCountExact:!n,truncated:n,fileLimit:t,strategy:"filesystem-bfs-v1"}}async function Ao(e){try{let t=(await Z(e.root,["rev-parse","--show-prefix"])).toString("utf8").trim().replace(/\\/gu,"/"),s=t?`${t.replace(/^\/+|\/+$/gu,"")}/`:"";if(u.posix.isAbsolute(s)||s==="../"||s.startsWith("../")||s.includes("/../"))return null;let o=Ze(),[i,n,l,c,r,d]=await Promise.all([Z(e.root,["ls-files","--full-name","-s","--",...o]),Z(e.root,["diff","--no-ext-diff","--no-textconv","--binary","HEAD","--",...o]),Z(e.root,["ls-files","--full-name","--others","--exclude-standard","-z","--",...o]),Z(e.root,["ls-files","--full-name","--others","--ignored","--exclude-standard","-z","--",...o]),Z(e.root,["ls-files","-v","--",...o]),Z(e.root,["ls-files","--full-name","-s","--",...o])]);if(r.toString("utf8").split(/\r?\n/u).some(y=>/^[a-z] /u.test(y)))return null;let a=e.files.map(y=>{let b=D(u.relative(e.root,y));return `${s}${b}`});if(d.toString("utf8").split(/\r?\n/u).filter(y=>y.startsWith("160000 ")).map(y=>y.split(" ",2)[1]).filter(y=>!!y).map(y=>y.replace(/\\/gu,"/").replace(/\/$/u,"")).some(y=>a.some(b=>b.startsWith(`${y}/`))))return null;let f=new Set(a),v=Buffer.concat([l,c]).toString("utf8").split("\0").filter(Boolean).map(y=>y.replace(/\\/gu,"/")).filter(y=>f.has(y)),m=await Ce([...new Set(v)].sort((y,b)=>y.localeCompare(b)),16,async y=>{let b=s?y.slice(s.length):y;return {path:b,hash:await qe(u.resolve(e.root,...b.split("/").filter(Boolean)))}}),h=createHash("sha256");h.update(`git-worktree-v2\0${e.kind}\0${e.id}\0${e.fileLimit}\0`),h.update(i),h.update(createHash("sha256").update(n).digest());for(let y of m)h.update(`${y.path}\0${y.hash}\0`);return {kind:e.kind,id:e.id,strategy:"git-worktree-v2",hash:h.digest("hex"),fileCount:e.files.length,fileLimit:e.fileLimit,truncated:e.files.length>=e.fileLimit}}catch{return null}}async function Fo(e){try{let t=(await Z(e.root,["rev-parse","--show-prefix"])).toString("utf8").trim().replace(/\\/gu,"/"),s=t?`${t.replace(/^\/+|\/+$/gu,"")}/`:"";if(u.posix.isAbsolute(s)||s==="../"||s.startsWith("../")||s.includes("/../"))return null;let o=Ze(),[i,n,l,c]=await Promise.all([Z(e.root,["ls-files","--full-name","-s","--",...o]),Z(e.root,["diff","--no-ext-diff","--no-textconv","--binary","HEAD","--",...o]),Z(e.root,["ls-files","--full-name","--others","--exclude-standard","-z","--",...o]),Z(e.root,["ls-files","-v","--",...o])]);if(c.toString("utf8").split(/\r?\n/u).some(p=>/^[a-z] /u.test(p)))return null;let r=(e.excludedRoots??[]).map(p=>u.resolve(p)),d=(await Ce([...new Set(We(l))].sort((p,f)=>p.localeCompare(f)),16,async p=>{if(s&&!p.startsWith(s))return null;let f=s?p.slice(s.length):p,v=u.normalize(f);if(!f||u.isAbsolute(v)||v===".."||v.startsWith(`..${u.sep}`))return null;let m=u.resolve(e.root,v);if(r.some(h=>m===h||m.startsWith(`${h}${u.sep}`))||Ke(e.root,m))return null;try{let h=await _.lstat(m);if(!h.isFile()||h.isSymbolicLink())return null}catch{return null}return {path:f,hash:await qe(m)}})).filter(p=>p!==null),a=createHash("sha256");a.update(`git-worktree-v2\0${e.kind}\0${e.id}\0${e.fileLimit}\0`),a.update(i),a.update(createHash("sha256").update(n).digest());for(let p of d)a.update(`${p.path}\0${p.hash}\0`);return a.digest("hex")===e.expectedHash}catch{return null}}async function Ce(e,t,s){let o=new Array(e.length),i=0,n=Array.from({length:Math.min(t,Math.max(e.length,1))},async()=>{for(;i<e.length;){let l=i++;o[l]=await s(e[l]);}});return await Promise.all(n),o}async function xe(e){let t=[...new Set(e.files)].sort((d,a)=>d.localeCompare(a)),s=e.eligibleFileCount??t.length,o=s>e.fileLimit||t.length>e.fileLimit,i=t.slice(0,e.fileLimit),n=await Ao({...e,files:i}),l={eligibleFileCount:s,eligibleFileCountExact:e.eligibleFileCountExact??!o,inventoryMode:o?"emergency-bounded":"complete",...e.inventoryStrategy?{inventoryStrategy:e.inventoryStrategy}:{},...e.selection?{selection:e.selection}:{}};if(n)return {...n,fileCount:i.length,truncated:o,...l};let c=await Ce(i,16,async d=>({path:D(u.relative(e.root,d)),hash:await qe(d)}));c.sort((d,a)=>d.path.localeCompare(a.path));let r=createHash("sha256");r.update(`content-merkle-v1\0${e.kind}\0${e.id}\0${e.fileLimit}\0`);for(let d of c)r.update(`${d.path}\0${d.hash}\0`);return {kind:e.kind,id:e.id,strategy:"content-merkle-v1",hash:r.digest("hex"),fileCount:c.length,fileLimit:e.fileLimit,truncated:o,...l}}async function _o(e){let t=u.resolve(e.workspacePath),s=[...e.projects].sort((r,d)=>r.id.localeCompare(d.id)),o=s.map(r=>ve(t,r)),i=e.inventories?.workspaceInventory??(e.inventories?.workspaceFiles?{files:[...e.inventories.workspaceFiles],eligibleFileCount:e.inventories.workspaceFiles.length,eligibleFileCountExact:e.inventories.workspaceFiles.length<=e.workspaceFileLimit,truncated:e.inventories.workspaceFiles.length>e.workspaceFileLimit,fileLimit:e.workspaceFileLimit,strategy:"filesystem-bfs-v1"}:await ye(t,e.workspaceFileLimit,o)),n=i.files.filter(r=>!o.some(d=>r===d||r.startsWith(`${d}${u.sep}`))),l={...i,files:n,eligibleFileCount:i.eligibleFileCountExact&&!i.truncated?n.length:i.eligibleFileCount},c=await Promise.all([xe({kind:"workspace",id:"workspace",root:t,files:l.files,fileLimit:e.workspaceFileLimit,eligibleFileCount:l.eligibleFileCount,eligibleFileCountExact:l.eligibleFileCountExact,inventoryStrategy:l.strategy}),...s.map(async r=>{let d=ve(t,r),a=e.inventories?.projectFiles?.get(r.id),p=e.inventories?.projectInventories?.get(r.id)??(a?{files:[...a],eligibleFileCount:a.length,eligibleFileCountExact:a.length<=e.projectFileLimit,strategy:"filesystem-bfs-v1"}:await ye(d,e.projectFileLimit)),f=e.inventories?.scanBudgetsByProject?.get(r.id);return xe({kind:"project",id:r.id,root:d,files:p.files,fileLimit:e.projectFileLimit,eligibleFileCount:p.eligibleFileCount,eligibleFileCountExact:p.eligibleFileCountExact,inventoryStrategy:p.strategy,...f?{selection:{strategy:"component-language-round-robin-v1",semanticFileCount:Math.min(p.files.length,f.semanticFileBudget),semanticFileBudget:f.semanticFileBudget,deepFileCount:Math.min(p.files.length,f.deepFileBudget),deepFileBudget:f.deepFileBudget,sourceExtractionFileBudget:f.sourceExtractionFileBudget}}:{}})})]);return c.sort((r,d)=>r.kind.localeCompare(d.kind)||r.id.localeCompare(d.id)),_t(c)}function _t(e){let t=[...e].sort((o,i)=>o.kind.localeCompare(i.kind)||o.id.localeCompare(i.id)),s=createHash("sha256");s.update("workspace-knowledge-graph-inputs.v1\0hybrid-git-content-v2\0");for(let o of t)s.update(`${o.kind}\0${o.id}\0${o.hash}\0${o.fileCount}\0${o.fileLimit}\0${o.truncated}\0${o.eligibleFileCount??o.fileCount}\0${o.eligibleFileCountExact??!o.truncated}\0${o.inventoryMode??(o.truncated?"emergency-bounded":"complete")}\0${o.inventoryStrategy??"unknown"}\0${o.selection?c(o.selection):""}\0`);return {schemaVersion:"workspace-knowledge-graph-inputs.v1",strategy:"hybrid-git-content-v2",hashAlgorithm:"sha256",hash:s.digest("hex"),scopes:t}}async function Ws(e){if(_t(e.expected.scopes).hash!==e.expected.hash)return false;let t=u.resolve(e.workspacePath),s=[...e.projects].sort((n,l)=>n.id.localeCompare(l.id)),o=s.map(n=>ve(t,n)),i=new Map(s.map(n=>[n.id,n]));for(let n of e.expected.scopes){let l=n.kind==="project"?i.get(n.id):void 0;if(n.kind==="project"&&!l)return false;let c$1=l?ve(t,l):t;if(n.strategy==="git-worktree-v2"){let v=await Fo({kind:n.kind,id:n.id,root:c$1,fileLimit:n.fileLimit,expectedHash:n.hash,...n.kind==="workspace"?{excludedRoots:o}:{}});if(v!==null){if(!v)return false;continue}}let r=await ye(c$1,n.fileLimit,n.kind==="workspace"?o:[]),d=n.kind==="workspace"?r.files.filter(v=>!o.some(m=>v===m||v.startsWith(`${m}${u.sep}`))):r.files,a={...r,files:d,eligibleFileCount:r.eligibleFileCountExact&&!r.truncated?d.length:r.eligibleFileCount},p=n.selection?{strategy:"component-language-round-robin-v1",semanticFileCount:Math.min(a.files.length,n.selection.semanticFileBudget),semanticFileBudget:n.selection.semanticFileBudget,deepFileCount:Math.min(a.files.length,n.selection.deepFileBudget),deepFileBudget:n.selection.deepFileBudget,sourceExtractionFileBudget:n.selection.sourceExtractionFileBudget}:void 0,f=await xe({kind:n.kind,id:n.id,root:c$1,files:a.files,fileLimit:n.fileLimit,eligibleFileCount:a.eligibleFileCount,eligibleFileCountExact:a.eligibleFileCountExact,inventoryStrategy:a.strategy,...p?{selection:p}:{}});if(c(f)!==c(n))return false}return true}async function ae(e){let t=await _.readFile(e,"utf8");if(e.toLowerCase().endsWith(".json")){let s=JSON.parse(t),o=C(s);return o?[o]:[]}return parseAllDocuments(t,{logLevel:"silent"}).map(s=>C(s.toJSON())).filter(s=>s!==null)}function ue(e){return [...new Set([...e.workspaceFiles,...e.projects.flatMap(t=>e.filesByProject.get(t.id)??[])])].sort((t,s)=>t.localeCompare(s))}function Ie(e){return /^(?:openapi|swagger)(?:\.[^.]+)?\.(?:json|ya?ml)$/i.test(u.basename(e))}function ct(e){let t=u.basename(e).toLowerCase();return /\.(?:graphql|gql|proto)$/.test(t)||/^asyncapi(?:\.[^.]+)?\.(?:json|ya?ml)$/.test(t)}function dt(e){let t=u.basename(e),s=D(e);return !/(?:^|\/)\.devcontainer(?:\/|$)/i.test(s)&&/^Dockerfile(?:\..+)?$/i.test(t)||/\.tf$/i.test(t)||t==="Chart.yaml"}function lt(e){return /(?:^|[\\/])(?:README|ARCHITECTURE|CONTRIBUTING|SECURITY)\.md$/i.test(e)}function To(e,t){let s=D(u.relative(e,t));return /^\.github\/workflows\/.+\.ya?ml$/i.test(s)||/^(?:\.gitlab-ci\.ya?ml|azure-pipelines\.ya?ml|Jenkinsfile|bitbucket-pipelines\.ya?ml|\.woodpecker\.ya?ml|\.drone\.ya?ml|\.travis\.ya?ml|appveyor\.ya?ml)$/i.test(s)||/^\.circleci\/config\.ya?ml$/i.test(s)||/^\.buildkite\/pipeline\.ya?ml$/i.test(s)||/^\.tekton\/.+\.ya?ml$/i.test(s)||/^prow\/[^/]+\.(?:sh|py)$/i.test(s)}function pt(e,t){let s=D(u.relative(e,t));return /(?:^|\/)(?:adr|adrs|decisions)(?:\/).+\.md$/i.test(s)||/(?:^|\/)ADR[-_0-9].+\.md$/i.test(s)}async function ut(e){let t=new Set;for(let s of [e.workspacePath,...e.projects.map(o=>o.root)])for(let o of ["compose.yml","compose.yaml","docker-compose.yml","docker-compose.yaml"]){let i=u.join(s,o);await _.pathExists(i)&&t.add(i);}for(let s of ue(e))/^(?:docker-)?compose(?:\.[a-z0-9_-]+)*\.ya?ml$/i.test(u.basename(s))&&t.add(s);return [...t].sort((s,o)=>s.localeCompare(o))}async function ft(e){let s=[e.workspacePath,...e.projects.map(i=>i.root)].flatMap(i=>[u.join(i,"CODEOWNERS"),u.join(i,".github","CODEOWNERS"),u.join(i,".gitlab","CODEOWNERS"),u.join(i,"docs","CODEOWNERS")]);for(let i of ue(e))u.basename(i)==="OWNERS"&&s.push(i);let o=await Promise.all(s.map(async i=>await _.pathExists(i)?i:null));return [...new Set(o.filter(i=>!!i))].sort((i,n)=>i.localeCompare(n))}function gt(e){let t=[{root:e.workspacePath,files:e.workspaceFiles},...e.projects.map(s=>({root:s.root,files:e.filesByProject.get(s.id)??[]}))];return [...new Set(t.flatMap(s=>s.files.filter(o=>To(s.root,o))))].sort((s,o)=>s.localeCompare(o))}async function mt(e){let t=[];for(let s of ue(e))if(/\.ya?ml$/i.test(s))try{(await ae(s)).some(i=>{let n=C(i.metadata);return !!(P(i.apiVersion)&&P(i.kind)&&P(n?.name))})&&t.push(s);}catch{}return t.sort((s,o)=>s.localeCompare(o))}function ie(e,t){let s=u.resolve(t);return e.filter(o=>s===o.root||s.startsWith(`${o.root}${u.sep}`)).sort((o,i)=>i.root.length-o.root.length)[0]??null}var ze=class{constructor(t,s,o){this.workspacePath=t;this.now=s;this.workspaceName=o;}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,s){if(s){let o=D(u.relative(s.root,t));return me(u.posix.join(s.artifactPrefix,o))}return me(u.relative(this.workspacePath,t))}async addProof(t){let s;if(t.absolutePath){if(!this.contentHashes.has(t.absolutePath))try{this.contentHashes.set(t.absolutePath,je(await _.readFile(t.absolutePath)));}catch{this.contentHashes.set(t.absolutePath,null);}s=this.contentHashes.get(t.absolutePath)??void 0;}let o=me(t.artifact),i=R("proof",[t.provider,o,t.pointer??"",t.line??"",t.detail??""].join("\0"));return this.proofs.has(i)||this.proofs.set(i,{id:i,provider:t.provider,artifact:o,...t.pointer?{pointer:t.pointer}:{},...t.line?{line:t.line}:{},...t.column?{column:t.column}:{},...s?{contentHash:s}:{},observedAt:this.now.toISOString(),derivation:t.derivation??"extracted",trust:t.trust??"observed",confidence:t.confidence??"high",freshness:"fresh",...t.detail?{detail:t.detail}:{}}),i}addEntity(t){let s=R(t.kind,t.key),o=Eo(t.attributes??{}),i=this.entities.get(s),n=t.label.trim(),l=n||i?.label||t.key.trim()||t.kind;!n&&!this.emptyLabelDiagnostics.has(s)&&(this.emptyLabelDiagnostics.add(s),this.diagnostics.push({code:"graph.knowledge.empty_label_normalized",severity:"warning",message:`An empty ${t.kind} label was normalized to ${l}.`,entityIds:[s],recommendation:"Inspect the provider proof and preserve a non-empty source identifier before publishing the entity."}));let c={...i?.attributes??{}};for(let[a,p]of Object.entries(o)){if(a in c&&JSON.stringify(c[a])!==JSON.stringify(p)){if(t.mergeArrayAttributes?.includes(a)&&Array.isArray(c[a])&&Array.isArray(p)){c[a]=p;continue}let f=`${s}\0${a}`;this.attributeConflicts.has(f)||(this.attributeConflicts.add(f),this.diagnostics.push({code:"graph.knowledge.attribute_conflict",severity:"warning",message:`Conflicting ${a} values were observed for ${t.kind} ${l}.`,entityIds:[s],recommendation:"Inspect the entity proof paths and make the authoritative source explicit."}));continue}c[a]=p;}let r=[...new Set([...i?.identity.aliases??[],...t.aliases??[]].map(a=>a.trim()).filter(Boolean))].sort(),d=[...new Set([...i?.proofIds??[],...t.proofIds??[]])].sort();return this.entities.set(s,{id:s,kind:t.kind,label:l,...t.projectId?{projectId:t.projectId}:{},identity:{key:t.key,scope:t.projectId?"project":"workspace",aliases:r,fingerprint:je(JSON.stringify({kind:t.kind,key:t.key,attributes:c}))},attributes:c,proofIds:d}),s}addRelation(t){let s=R("relation",`${t.from}\0${t.kind}\0${t.to}`),o=this.relations.get(s),i=[...new Set([...o?.proofIds??[],...t.proofIds])].sort(),n=new Set(i.map(r=>this.proofs.get(r)?.provider).filter(Boolean)).size,l=t.trust??o?.trust??"observed",c=n>=2&&l!=="ambiguous"?"corroborated":l;return this.relations.set(s,{id:s,from:t.from,to:t.to,kind:t.kind,derivation:t.derivation??o?.derivation??"extracted",trust:c,confidence:c==="corroborated"?"high":t.confidence??o?.confidence??"high",proofIds:i}),s}};function pe(e){let t=[],s=null;for(let o of e.split(/\r?\n/)){let i=o.match(/^\s*\[\[([^\]]+)\]\]\s*(?:#.*)?$/)?.[1]?.trim()??o.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/)?.[1]?.trim();if(i){s&&t.push({name:s.name,body:s.lines.join(`
|
|
4
4
|
`)}),s={name:i,lines:[]};continue}s?.lines.push(o);}return s&&t.push({name:s.name,body:s.lines.join(`
|