workspai 0.59.1 → 0.60.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +4 -0
- package/contracts/extension-cli-compatibility.v1.json +1 -1
- package/contracts/workspace-intelligence/goal-agent-handoff.v1.json +89 -8
- package/contracts/workspace-intelligence/goal-index.v1.json +100 -7
- package/contracts/workspace-intelligence/goal-lifecycle-result.v1.json +74 -6
- package/contracts/workspace-intelligence/goal-pack.v1.json +182 -19
- package/contracts/workspace-intelligence/verified-goal.v1.json +44 -3
- package/dist/analyze-FYNMI5KT.js +1 -0
- package/dist/autopilot-release-IRXB2VOH.js +1 -0
- package/dist/{chunk-DGGTTRYE.js → chunk-7ITSLGPZ.js} +1 -1
- package/dist/{chunk-5NIZNXRS.js → chunk-A4BK7C7M.js} +1 -1
- package/dist/{chunk-FLTIFYTJ.js → chunk-AJ535F22.js} +1 -1
- package/dist/{chunk-KVSYBHUR.js → chunk-B6FJ6RG6.js} +1 -1
- package/dist/{chunk-5PSKBJKJ.js → chunk-DIJGQUEV.js} +1 -1
- package/dist/{chunk-QMPFNXI7.js → chunk-E4LJ3PQD.js} +1 -1
- package/dist/{chunk-6FBNSTUS.js → chunk-GPGEJVVO.js} +1 -1
- package/dist/{chunk-U3MGJN7A.js → chunk-HQWDW2BV.js} +1 -1
- package/dist/chunk-I2O6AC2Z.js +2 -0
- package/dist/chunk-ILIBOMYL.js +1 -0
- package/dist/chunk-J7G3YL4O.js +1 -0
- package/dist/{chunk-NOZ4JCH7.js → chunk-KCJ3VS6R.js} +1 -1
- package/dist/{chunk-SP5EHSWG.js → chunk-KG3TUTXU.js} +1 -1
- package/dist/chunk-KNTPDRZB.js +1 -0
- package/dist/{chunk-QPE6VCDW.js → chunk-KTW4EN47.js} +19 -19
- package/dist/{chunk-RVKMGKYL.js → chunk-MDF2FBLS.js} +1 -1
- package/dist/{chunk-WSRUPDZN.js → chunk-NA2NXX5P.js} +1 -1
- package/dist/{chunk-OFWSZYUX.js → chunk-NBJ6AP7K.js} +1 -1
- package/dist/{chunk-RTDEFUTL.js → chunk-NRVSDL4J.js} +1 -1
- package/dist/{chunk-7WUT5ZSO.js → chunk-NVQUBUTY.js} +1 -1
- package/dist/{chunk-YEEAWZWI.js → chunk-O6R7SE6Y.js} +1 -1
- package/dist/{chunk-7SFXADXO.js → chunk-OU7DF6MP.js} +1 -1
- package/dist/{chunk-WJVB6SSD.js → chunk-PTNLVI62.js} +5 -5
- package/dist/{chunk-WP3CXMVA.js → chunk-SCP5LJNO.js} +1 -1
- package/dist/{chunk-QFBVQUKV.js → chunk-TFOOSYGO.js} +6 -6
- package/dist/{chunk-3CGR6435.js → chunk-TYQMO36U.js} +1 -1
- package/dist/chunk-UJXE4UAX.js +1 -0
- package/dist/{chunk-ENKGGWRX.js → chunk-VDFHUYAQ.js} +8 -8
- package/dist/chunk-VR6XMUF3.js +2 -0
- package/dist/{chunk-Y4B55J5S.js → chunk-VV55EAWO.js} +1 -1
- package/dist/{chunk-ZJCM37KX.js → chunk-WLFJHRB3.js} +1 -1
- package/dist/{chunk-P2WH7W2H.js → chunk-WUB6QGC7.js} +6 -6
- package/dist/chunk-X6TNBARH.js +6 -0
- package/dist/{create-HUEDWYDM.js → create-ZLDOBXG4.js} +1 -1
- package/dist/demo-kit-QHIDCSBI.js +149 -0
- package/dist/{doctor-NAZEKMGU.js → doctor-MAPZ2ZCD.js} +1 -1
- package/dist/{dotnet-webapi-clean-VXEF4SHM.js → dotnet-webapi-clean-AVHPJG7Y.js} +5 -5
- package/dist/goal-command-contract-43E22XQD.js +1 -0
- package/dist/goal-interactive-selection-6YJOK4WC.js +1 -0
- package/dist/goal-lifecycle-OV6NZDD6.js +1 -0
- package/dist/goal-pack-Q3O2Z7R5.js +1 -0
- package/dist/{gofiber-standard-AQGSC7ON.js → gofiber-standard-47S2GYAO.js} +2 -2
- package/dist/{gogin-standard-7DU3OCBX.js → gogin-standard-EWB4XNOI.js} +3 -3
- package/dist/index.js +122 -122
- package/dist/{pipeline-62A2SDLC.js → pipeline-NICVJLZF.js} +1 -1
- package/dist/{project-agent-entry-7SYHRY7J.js → project-agent-entry-DVPKQST7.js} +1 -1
- package/dist/{project-intelligence-lens-BSG5LK6N.js → project-intelligence-lens-RLYSPJB2.js} +1 -1
- package/dist/{project-test-coverage-HP37HUV2.js → project-test-coverage-E2Q4QL44.js} +1 -1
- package/dist/{rust-axum-4HXDICIB.js → rust-axum-M5X4ZC4Z.js} +4 -4
- package/dist/{springboot-standard-EK6GYN5T.js → springboot-standard-Y5ADLZMQ.js} +7 -7
- package/dist/verified-goal-2BRQZQBL.js +1 -0
- package/dist/{workspace-BNRSBWSL.js → workspace-LQ77WAHC.js} +1 -1
- package/dist/{workspace-agent-sync-ANBHBZ2H.js → workspace-agent-sync-YLP75OWF.js} +1 -1
- package/dist/{workspace-context-RAO62QVU.js → workspace-context-YAK5XX27.js} +1 -1
- package/dist/{workspace-contract-ACSIHJIO.js → workspace-contract-3BWIRSVQ.js} +1 -1
- package/dist/{workspace-explain-RH27OQB4.js → workspace-explain-QH4FXQW5.js} +1 -1
- package/dist/{workspace-foundation-EWYJPPT6.js → workspace-foundation-G4KPT5CN.js} +1 -1
- package/dist/{workspace-graph-stream-ZZZEQQTE.js → workspace-graph-stream-XTSDKRLM.js} +1 -1
- package/dist/{workspace-intelligence-3YERTBA3.js → workspace-intelligence-625UN27X.js} +1 -1
- package/dist/{workspace-intelligence-runner-QLLBUD6G.js → workspace-intelligence-runner-T6CVJIQQ.js} +1 -1
- package/dist/{workspace-knowledge-graph-HZZP6ZRB.js → workspace-knowledge-graph-3ZBPSAS7.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-ZI4W735H.js +1 -0
- package/dist/{workspace-mcp-serve-5TTAN243.js → workspace-mcp-serve-ALIZV72K.js} +1 -1
- package/dist/{workspace-model-EIQSKDX7.js → workspace-model-ETCLINRB.js} +1 -1
- package/dist/{workspace-onboarding-UW3CSURE.js → workspace-onboarding-46BE3EQD.js} +1 -1
- package/dist/{workspace-registry-summary-OV5KX3WC.js → workspace-registry-summary-VSOBKAJG.js} +1 -1
- package/dist/workspace-repair-engine-SZZKV3JF.js +3 -0
- package/dist/workspace-run-JTEFCQYQ.js +1 -0
- package/dist/{workspace-verify-W4P6LBIH.js → workspace-verify-7ENGIY4S.js} +1 -1
- package/dist/{workspace-watch-EZ4D4VCF.js → workspace-watch-2YFSB2WL.js} +1 -1
- package/docs/ci-workflows.md +1 -1
- package/docs/commands-reference.md +12 -2
- package/docs/goal-packs.md +51 -11
- package/package.json +1 -1
- package/dist/analyze-52TEGLDR.js +0 -1
- package/dist/autopilot-release-NFLAKBA3.js +0 -1
- package/dist/chunk-DQ6VXTDE.js +0 -1
- package/dist/chunk-MZKKRAAJ.js +0 -2
- package/dist/chunk-RO73VVHW.js +0 -2
- package/dist/chunk-T3GJ7YVG.js +0 -1
- package/dist/chunk-VRW6KXNK.js +0 -6
- package/dist/demo-kit-KHH63TNA.js +0 -149
- package/dist/goal-command-contract-CHE7U6YY.js +0 -1
- package/dist/goal-lifecycle-NUKWVUAL.js +0 -1
- package/dist/goal-pack-TWOXHXN6.js +0 -1
- package/dist/verified-goal-B6HQOZWA.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-7DWHMEM2.js +0 -1
- package/dist/workspace-repair-engine-DHH2UUJN.js +0 -3
- package/dist/workspace-run-BLHRXT2N.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-QJCCZLOF.js';import {a as a$1}from'./chunk-GR6442P7.js';import {f,e}from'./chunk-CCDGHPEJ.js';import {h,i}from'./chunk-NZ3WZYD5.js';import {createHash}from'crypto';import c from'path';import {execa}from'execa';import u from'fs-extra';var D=h.projectTestCoverage.schemaVersion,E=i.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(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function g(e,t,o=0){let n=p(e),a=Math.min(p(t),n),r=p(o);return {total:n,covered:a,skipped:r,percent:n>0?Math.round(a/n*1e4)/100:null}}function W(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;return g(t.total,t.covered,t.skipped)}function y(e,t){let o=c.isAbsolute(t)?t:c.resolve(e,t),n=c.relative(e,o);return n&&!n.startsWith("..")?n.split(c.sep).join("/"):t}async function x(e){return createHash("sha256").update(await u.readFile(e)).digest("hex")}async function I(e){let t=c.resolve(e);for(;;){if(await u.pathExists(c.join(t,".workspai","project.json"))||await u.pathExists(c.join(t,".rapidkit","project.json"))||(await Promise.all(G.map(a=>u.pathExists(c.join(t,a))))).some(Boolean))return t;let n=c.dirname(t);if(n===t)return c.resolve(e);t=n;}}async function V(e){if(await u.pathExists(c.join(e,"deno.json"))||await u.pathExists(c.join(e,"deno.jsonc")))return "deno";if(await u.pathExists(c.join(e,"bun.lock"))||await u.pathExists(c.join(e,"bun.lockb")))return "bun";if(await u.pathExists(c.join(e,"package.json")))return "node";if(await u.pathExists(c.join(e,"pyproject.toml"))||await u.pathExists(c.join(e,"requirements.txt")))return "python";if(await u.pathExists(c.join(e,"go.mod")))return "go";let t=await u.pathExists(c.join(e,"pom.xml"))||await u.pathExists(c.join(e,"build.gradle"))||await u.pathExists(c.join(e,"build.gradle.kts"));return t&&(await P(e,o=>o.endsWith(".kt")||o.endsWith(".kts")&&o!=="build.gradle.kts"&&o!=="settings.gradle.kts",4)).length>0?"kotlin":t?"java":await u.pathExists(c.join(e,"Cargo.toml"))?"rust":await u.pathExists(c.join(e,"composer.json"))?"php":await u.pathExists(c.join(e,"Gemfile"))?"ruby":await u.pathExists(c.join(e,"mix.exs"))?"elixir":await u.pathExists(c.join(e,"deps.edn"))||await u.pathExists(c.join(e,"project.clj"))?"clojure":await u.pathExists(c.join(e,"build.sbt"))?"scala":await u.pathExists(c.join(e,"CMakeLists.txt"))?(await P(e,n=>/\.(c|cc|cpp|cxx)$/.test(n),3)).some(n=>/\.(cc|cpp|cxx)$/.test(n))?"cpp":"c":(await P(e,o=>/\.(sln|csproj)$/.test(o),2)).length>0?"dotnet":"unknown"}async function P(e,t,o=5){let n=[],a=[{dir:e,depth:0}],r=new Set([".git",".workspai",".rapidkit","node_modules",".venv","vendor","deps"]);for(;a.length>0;){let s=a.shift();if(!s)break;let i=await u.readdir(s.dir,{withFileTypes:true}).catch(()=>[]);for(let l of i){if(r.has(l.name)||a$1(l.name))continue;let d=c.join(s.dir,l.name),m=c.relative(e,d).split(c.sep).join("/");l.isFile()&&t(l.name,m)&&n.push(d),l.isDirectory()&&s.depth<o&&a.push({dir:d,depth:s.depth+1});}}return n}async function L(e,t){let o=await u.readJson(t),n=o.total??o,a={};for(let s of ["lines","branches","functions","statements"]){let i=W(n[s]);i&&(a[s]=i);}let r=[];for(let[s,i]of Object.entries(o)){if(s==="total"||!i||typeof i!="object"||Array.isArray(i))continue;let l=i,d={};for(let m of ["lines","branches","functions","statements"]){let b=W(l[m]);b&&(d[m]=b);}r.push({path:y(e,s),metrics:d});}return {metrics:a,files:r,source:{format:"istanbul-json",path:t,sha256:await x(t)}}}async function U(e,t){let o=await u.readJson(t),n=o.totals??{},a={lines:g(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(a.branches=g(n.num_branches,n.covered_branches));let r=[];for(let[s,i]of Object.entries(o.files??{})){let l=i?.summary??{};r.push({path:y(e,s),metrics:{lines:g(l.num_statements,l.covered_lines),...p(l.num_branches)>0?{branches:g(l.num_branches,l.covered_branches)}:{}}});}return {metrics:a,files:r,source:{format:"coverage-py-json",path:t,sha256:await x(t)}}}function j(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,o=p(t.count),n=p(t.covered);return o>0?g(o,n):void 0}async function z(e,t){let o=await u.readJson(t),n=Array.isArray(o.data)?o.data[0]??{}:o,a=n.totals??{},r={};r.lines=j(a.lines),r.functions=j(a.functions),r.branches=j(a.branches),r.statements=j(a.regions);let s=[];for(let i of Array.isArray(n.files)?n.files:[]){if(!i||typeof i!="object"||Array.isArray(i))continue;let l=i,d=l.summary??{};s.push({path:y(e,String(l.filename??"unknown")),metrics:{lines:j(d.lines),functions:j(d.functions),branches:j(d.branches),statements:j(d.regions)}});}return {metrics:r,files:s,source:{format:"llvm-cov-json",path:t,sha256:await x(t)}}}async function A(e,t){let o=await u.readFile(t,"utf8"),n=[],a="",r=0,s=0,i=0,l=0,d=0,m=0,b=v=>{a&&(n.push({path:y(e,a),metrics:{lines:g(v.lineTotal,v.lineCovered),functions:g(v.functionTotal,v.functionCovered),branches:g(v.branchTotal,v.branchCovered)}}),r+=v.lineTotal,s+=v.lineCovered,i+=v.functionTotal,l+=v.functionCovered,d+=v.branchTotal,m+=v.branchCovered);},h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0};for(let v of o.split(/\r?\n/))v.startsWith("SF:")?a=v.slice(3):v.startsWith("LF:")?h.lineTotal=p(v.slice(3)):v.startsWith("LH:")?h.lineCovered=p(v.slice(3)):v.startsWith("FNF:")?h.functionTotal=p(v.slice(4)):v.startsWith("FNH:")?h.functionCovered=p(v.slice(4)):v.startsWith("BRF:")?h.branchTotal=p(v.slice(4)):v.startsWith("BRH:")?h.branchCovered=p(v.slice(4)):v==="end_of_record"&&(b(h),a="",h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0});return {metrics:{lines:g(r,s),functions:g(i,l),branches:g(d,m)},files:n,source:{format:"lcov",path:t,sha256:await x(t)}}}async function B(e,t){let o=await u.readFile(t,"utf8"),n=new Map;for(let s of o.split(/\r?\n/).slice(1)){let i=/^(.+?):\d+\.\d+,\d+\.\d+\s+(\d+)\s+(\d+)$/.exec(s.trim());if(!i)continue;let l=n.get(i[1])??{total:0,covered:0},d=p(i[2]);l.total+=d,p(i[3])>0&&(l.covered+=d),n.set(i[1],l);}let a=[...n.entries()].map(([s,i])=>({path:y(e,s),metrics:{statements:g(i.total,i.covered)}})),r=[...n.values()].reduce((s,i)=>({total:s.total+i.total,covered:s.covered+i.covered}),{total:0,covered:0});return {metrics:{statements:g(r.total,r.covered)},files:a,source:{format:"go-coverprofile",path:t,sha256:await x(t)}}}function T(e,t){let n=[...e.matchAll(new RegExp(`<counter\\s+type=["']${t}["']\\s+missed=["'](\\d+)["']\\s+covered=["'](\\d+)["']\\s*\\/?\\s*>`,"gi"))].at(-1);return n?g(Number(n[1])+Number(n[2]),n[2]):void 0}async function C(e,t){let o=await u.readFile(e,"utf8"),n={};if(t==="cobertura-xml"){let a=/<coverage\b([^>]*)>/i.exec(o)?.[1]??"",r=/\bline-rate=["']([\d.]+)["']/i.exec(a)?.[1],s=/\bbranch-rate=["']([\d.]+)["']/i.exec(a)?.[1];r&&(n.lines=g(1e4,Math.round(Number(r)*1e4))),s&&(n.branches=g(1e4,Math.round(Number(s)*1e4)));}if(t==="clover-xml"){let r=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",s=m=>p(new RegExp(`\\b${m}=["'](\\d+)["']`,"i").exec(r)?.[1]),i=s("statements"),l=s("methods"),d=s("conditionals");i>0&&(n.statements=g(i,s("coveredstatements"))),l>0&&(n.functions=g(l,s("coveredmethods"))),d>0&&(n.branches=g(d,s("coveredconditionals")));}return n.lines??=T(o,"LINE"),n.branches??=T(o,"BRANCH"),n.functions??=T(o,"METHOD"),n.statements??=T(o,"INSTRUCTION"),{metrics:n,files:[],source:{format:t,path:e,sha256:await x(e)}}}async function K(e){let t=await u.readFile(e,"utf8"),o=/<scoverage\b([^>]*)>/i.exec(t)?.[1]??"",n=b=>p(new RegExp(`\\b${b}=["']([\\d.]+)["']`,"i").exec(o)?.[1]),a=n("statement-count"),r=n("statements-invoked"),s=n("branch-count"),i=n("branches-invoked"),l=n("statement-rate"),d=n("branch-rate"),m={};return a>0?m.statements=g(a,r):l>0&&(m.statements=g(1e4,Math.round(l*100))),s>0?m.branches=g(s,i):d>0&&(m.branches=g(1e4,Math.round(d*100))),{metrics:m,files:[],source:{format:"scoverage-xml",path:e,sha256:await x(e)}}}async function X(e,t){let o=await u.readJson(t),n=new Map;for(let s of Object.values(o)){let i=s?.coverage;if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[l,d]of Object.entries(i)){if(!Array.isArray(d))continue;let m=n.get(l)??[];d.forEach((b,h)=>{typeof b=="number"&&(m[h]=Math.max(m[h]??0,b));}),n.set(l,m);}}let a=[...n.entries()].map(([s,i])=>{let l=i.filter(d=>typeof d=="number");return {path:y(e,s),metrics:{lines:g(l.length,l.filter(d=>d>0).length)}}}),r=a.reduce((s,i)=>{let l=i.metrics.lines;return {total:s.total+(l?.total??0),covered:s.covered+(l?.covered??0)}},{total:0,covered:0});return {metrics:{lines:g(r.total,r.covered)},files:a,source:{format:"simplecov-json",path:t,sha256:await x(t)}}}async function $(e,t={}){let o=[{relativePath:"coverage/coverage-summary.json",parser:r=>L(e,r)},{relativePath:"coverage.json",parser:async r=>{let s=await u.readJson(r);return Array.isArray(s.data)?z(e,r):U(e,r)}},{relativePath:"coverage/lcov.info",parser:r=>A(e,r)},{relativePath:"cover/lcov.info",parser:r=>A(e,r)},{relativePath:"lcov.info",parser:r=>A(e,r)},{relativePath:"coverage.out",parser:r=>B(e,r)},{relativePath:"target/site/jacoco/jacoco.xml",parser:r=>C(r,"jacoco-xml")},{relativePath:"build/reports/jacoco/test/jacocoTestReport.xml",parser:r=>C(r,"jacoco-xml")},{relativePath:"coverage.xml",parser:r=>C(r,"clover-xml")},{relativePath:".resultset.json",parser:r=>X(e,r)}];for(let r of o){let s=c.join(e,r.relativePath);if(await u.pathExists(s))return r.parser(s)}if(t.recursive===false)return null;let a=(await P(e,(r,s)=>r==="coverage.cobertura.xml"||r==="jacoco.xml"||r==="clover.xml"||r==="scoverage.xml"||s.endsWith("/coverage-summary.json"),7)).sort()[0];return a?a.endsWith("coverage-summary.json")?L(e,a):a.endsWith("jacoco.xml")?C(a,"jacoco-xml"):a.endsWith("coverage.cobertura.xml")?C(a,"cobertura-xml"):a.endsWith("scoverage.xml")?K(a):C(a,"clover-xml"):null}async function Q(e){return u.readJson(c.join(e,"package.json")).catch(()=>null)}async function q(e,t){let o=(n,a)=>({cwd:e,executable:n,args:a});if(t==="node"||t==="bun"){let a=(await Q(e))?.scripts??{},r=["test:coverage","test:cov","coverage"].find(i=>typeof a[i]=="string"),s=t==="bun"?"bun":await u.pathExists(c.join(e,"pnpm-lock.yaml"))?"pnpm":await u.pathExists(c.join(e,"yarn.lock"))?"yarn":"npm";if(r)return {runner:String(a[r]).split(/\s+/)[0]||s,invocations:[o(s,s==="yarn"?[r]:["run",r])],diagnostics:[]};if(typeof a.test=="string"){let i=s==="yarn"?["test","--coverage"]:s==="bun"?["test","--coverage","--coverage-reporter=lcov"]:["test","--","--coverage"];return {runner:String(a.test).split(/\s+/)[0]||s,invocations:[o(s,i)],diagnostics:[]}}return {runner:null,invocations:[],diagnostics:["No project-owned test or coverage script was detected."]}}if(t==="deno")return {runner:"deno",invocations:[o("deno",["test","--coverage=coverage"]),o("deno",["coverage","--lcov","--output=coverage/lcov.info","coverage"])],diagnostics:[]};if(t==="python")return {runner:"pytest-cov",invocations:[o(await u.pathExists(c.join(e,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"))?c.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(t==="go")return {runner:"go test",invocations:[o("go",["test","./...","-coverprofile=coverage.out"])],diagnostics:[]};if(t==="java"){let n=await u.pathExists(c.join(e,"gradlew")),a=await u.pathExists(c.join(e,"gradlew.bat")),r=n||a,s=await u.pathExists(c.join(e,"mvnw")),i=await u.pathExists(c.join(e,"mvnw.cmd")),l=r?process.platform==="win32"&&a?".\\gradlew.bat":"./gradlew":await u.pathExists(c.join(e,"pom.xml"))?process.platform==="win32"&&i?".\\mvnw.cmd":s?"./mvnw":"mvn":"gradle";return {runner:r?"jacoco/gradle":"jacoco/maven",invocations:[o(l,r?["test","jacocoTestReport"]:["test","jacoco:report"])],diagnostics:[]}}return t==="dotnet"?{runner:"dotnet coverlet",invocations:[o("dotnet",["test","--collect:XPlat Code Coverage"])],diagnostics:[]}:t==="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."]}:t==="php"?{runner:"phpunit",invocations:[o(process.platform==="win32"?"vendor\\bin\\phpunit.bat":"vendor/bin/phpunit",["--coverage-clover","coverage.xml"])],diagnostics:[]}:t==="ruby"?{runner:"simplecov",invocations:[o("bundle",["exec","rspec"])],diagnostics:["The test suite must enable SimpleCov to emit .resultset.json."]}:t==="elixir"?{runner:"mix cover",invocations:[o("mix",["test","--cover"])],diagnostics:["Configure ExCoveralls for JSON or LCOV interchange when machine-readable coverage is required."]}:t==="clojure"?{runner:"cloverage",invocations:[o("clojure",["-M:coverage"])],diagnostics:["The project must declare a coverage alias such as cloverage."]}:t==="scala"?{runner:"sbt-scoverage",invocations:[o("sbt",["clean","coverage","test","coverageReport"])],diagnostics:["The project must declare the scoverage plugin."]}:t==="kotlin"?{runner:"jacoco/gradle",invocations:[o(await u.pathExists(c.join(e,process.platform==="win32"?"gradlew.bat":"gradlew"))?process.platform==="win32"?".\\gradlew.bat":"./gradlew":"gradle",["test","jacocoTestReport"])],diagnostics:["The project must declare the JaCoCo Gradle plugin."]}:t==="c"||t==="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 ue(e,t){let o=await I(e),n=t??await V(o),a=await q(o,n),r=await $(o,{recursive:false}).catch(()=>null),s=r?.source.path&&r.source.sha256?[{path:c.relative(o,r.source.path).split(c.sep).join("/"),sha256:r.source.sha256}]:[],i=[...a.diagnostics],l=r?"available":a.invocations.length===0||n==="unknown"?"unsupported":i.length>0?"requires-setup":"available";return {runtime:n,runner:a.runner,status:l,existingEvidence:s,invocations:a.invocations,prerequisites:i}}function Y(e,t){let o=e?c.relative(e,t).split(c.sep).join("/"):c.resolve(t),n=c.basename(t).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",a=createHash("sha256").update(o).digest("hex").slice(0,12);return `${n}--${a}`}function Z(e){return e.lines?"lines":e.statements?"statements":e.branches?"branches":"functions"}async function de(e$1={}){let t=await I(e$1.projectPath??process.cwd()),o=a(t),n=await V(t),a$1=Math.max(0,Math.min(100,Math.round(e$1.target??80))),r=await q(t,n),s=[],i=Date.now();if(e$1.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(s.push(Number(w.exitCode??1)),Number(w.exitCode??1)!==0)break}let l=await $(t).catch(()=>null),d=l?Z(l.metrics):"lines",m=l?.metrics[d]?.percent??null,b=e$1.run&&s.some(f=>f!==0)?"failed":m===null?"unavailable":m>=a$1?"passed":"below-target",h=Y(o,t),v=c.join(t,E),k=o?`.workspai/reports/projects/${h}/project-test-coverage-last-run.json`:null,R={schemaVersion:D,generatedAt:new Date().toISOString(),status:b,project:{id:h,name:c.basename(t),path:t,workspacePath:o},runtime:n,runner:r.runner,target:{metric:d,percent:a$1},metrics:l?.metrics??{},files:l?.files??[],lowCoverageFiles:(l?.files??[]).map(f=>{let w=f.metrics[d]??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<a$1).sort((f,w)=>w.uncovered-f.uncovered||f.path.localeCompare(w.path)),source:l?.source??{format:"unknown",path:null,sha256:null},execution:{requested:e$1.run===true,invocations:r.invocations,exitCodes:s,durationMs:Date.now()-i},diagnostics:[...r.diagnostics,...l?[]:["No supported machine-readable coverage artifact was found."]],artifactPaths:{project:v,workspaceLatest:o?c.join(o,E):null,workspaceProject:o&&k?c.join(o,k):null}};return o&&k&&await f(o,E,[{relativePath:E,payload:R},{relativePath:k,payload:R}]),await e(t,E,R),R}export{D as a,E as b,ue as c,de as d};
|
|
1
|
+
import {a}from'./chunk-QJCCZLOF.js';import {a as a$1}from'./chunk-GR6442P7.js';import {f,e}from'./chunk-CCDGHPEJ.js';import {h,i}from'./chunk-NZ3WZYD5.js';import {createHash}from'crypto';import c from'path';import {execa}from'execa';import u from'fs-extra';var D=h.projectTestCoverage.schemaVersion,E=i.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(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function g(e,t,o=0){let n=p(e),a=Math.min(p(t),n),r=p(o);return {total:n,covered:a,skipped:r,percent:n>0?Math.round(a/n*1e4)/100:null}}function W(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;return g(t.total,t.covered,t.skipped)}function y(e,t){let o=c.isAbsolute(t)?t:c.resolve(e,t),n=c.relative(e,o);return n&&!n.startsWith("..")?n.split(c.sep).join("/"):t}async function x(e){return createHash("sha256").update(await u.readFile(e)).digest("hex")}async function I(e){let t=c.resolve(e);for(;;){if(await u.pathExists(c.join(t,".workspai","project.json"))||await u.pathExists(c.join(t,".rapidkit","project.json"))||(await Promise.all(G.map(a=>u.pathExists(c.join(t,a))))).some(Boolean))return t;let n=c.dirname(t);if(n===t)return c.resolve(e);t=n;}}async function V(e){if(await u.pathExists(c.join(e,"deno.json"))||await u.pathExists(c.join(e,"deno.jsonc")))return "deno";if(await u.pathExists(c.join(e,"bun.lock"))||await u.pathExists(c.join(e,"bun.lockb")))return "bun";if(await u.pathExists(c.join(e,"package.json")))return "node";if(await u.pathExists(c.join(e,"pyproject.toml"))||await u.pathExists(c.join(e,"requirements.txt")))return "python";if(await u.pathExists(c.join(e,"go.mod")))return "go";let t=await u.pathExists(c.join(e,"pom.xml"))||await u.pathExists(c.join(e,"build.gradle"))||await u.pathExists(c.join(e,"build.gradle.kts"));return t&&(await P(e,o=>o.endsWith(".kt")||o.endsWith(".kts")&&o!=="build.gradle.kts"&&o!=="settings.gradle.kts",4)).length>0?"kotlin":t?"java":await u.pathExists(c.join(e,"Cargo.toml"))?"rust":await u.pathExists(c.join(e,"composer.json"))?"php":await u.pathExists(c.join(e,"Gemfile"))?"ruby":await u.pathExists(c.join(e,"mix.exs"))?"elixir":await u.pathExists(c.join(e,"deps.edn"))||await u.pathExists(c.join(e,"project.clj"))?"clojure":await u.pathExists(c.join(e,"build.sbt"))?"scala":await u.pathExists(c.join(e,"CMakeLists.txt"))?(await P(e,n=>/\.(c|cc|cpp|cxx)$/.test(n),3)).some(n=>/\.(cc|cpp|cxx)$/.test(n))?"cpp":"c":(await P(e,o=>/\.(sln|csproj)$/.test(o),2)).length>0?"dotnet":"unknown"}async function P(e,t,o=5){let n=[],a=[{dir:e,depth:0}],r=new Set([".git",".workspai",".rapidkit","node_modules",".venv","vendor","deps"]);for(;a.length>0;){let s=a.shift();if(!s)break;let i=await u.readdir(s.dir,{withFileTypes:true}).catch(()=>[]);for(let l of i){if(r.has(l.name)||a$1(l.name))continue;let d=c.join(s.dir,l.name),m=c.relative(e,d).split(c.sep).join("/");l.isFile()&&t(l.name,m)&&n.push(d),l.isDirectory()&&s.depth<o&&a.push({dir:d,depth:s.depth+1});}}return n}async function L(e,t){let o=await u.readJson(t),n=o.total??o,a={};for(let s of ["lines","branches","functions","statements"]){let i=W(n[s]);i&&(a[s]=i);}let r=[];for(let[s,i]of Object.entries(o)){if(s==="total"||!i||typeof i!="object"||Array.isArray(i))continue;let l=i,d={};for(let m of ["lines","branches","functions","statements"]){let b=W(l[m]);b&&(d[m]=b);}r.push({path:y(e,s),metrics:d});}return {metrics:a,files:r,source:{format:"istanbul-json",path:t,sha256:await x(t)}}}async function U(e,t){let o=await u.readJson(t),n=o.totals??{},a={lines:g(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(a.branches=g(n.num_branches,n.covered_branches));let r=[];for(let[s,i]of Object.entries(o.files??{})){let l=i?.summary??{};r.push({path:y(e,s),metrics:{lines:g(l.num_statements,l.covered_lines),...p(l.num_branches)>0?{branches:g(l.num_branches,l.covered_branches)}:{}}});}return {metrics:a,files:r,source:{format:"coverage-py-json",path:t,sha256:await x(t)}}}function j(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,o=p(t.count),n=p(t.covered);return o>0?g(o,n):void 0}async function z(e,t){let o=await u.readJson(t),n=Array.isArray(o.data)?o.data[0]??{}:o,a=n.totals??{},r={};r.lines=j(a.lines),r.functions=j(a.functions),r.branches=j(a.branches),r.statements=j(a.regions);let s=[];for(let i of Array.isArray(n.files)?n.files:[]){if(!i||typeof i!="object"||Array.isArray(i))continue;let l=i,d=l.summary??{};s.push({path:y(e,String(l.filename??"unknown")),metrics:{lines:j(d.lines),functions:j(d.functions),branches:j(d.branches),statements:j(d.regions)}});}return {metrics:r,files:s,source:{format:"llvm-cov-json",path:t,sha256:await x(t)}}}async function A(e,t){let o=await u.readFile(t,"utf8"),n=[],a="",r=0,s=0,i=0,l=0,d=0,m=0,b=v=>{a&&(n.push({path:y(e,a),metrics:{lines:g(v.lineTotal,v.lineCovered),functions:g(v.functionTotal,v.functionCovered),branches:g(v.branchTotal,v.branchCovered)}}),r+=v.lineTotal,s+=v.lineCovered,i+=v.functionTotal,l+=v.functionCovered,d+=v.branchTotal,m+=v.branchCovered);},h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0};for(let v of o.split(/\r?\n/))v.startsWith("SF:")?a=v.slice(3):v.startsWith("LF:")?h.lineTotal=p(v.slice(3)):v.startsWith("LH:")?h.lineCovered=p(v.slice(3)):v.startsWith("FNF:")?h.functionTotal=p(v.slice(4)):v.startsWith("FNH:")?h.functionCovered=p(v.slice(4)):v.startsWith("BRF:")?h.branchTotal=p(v.slice(4)):v.startsWith("BRH:")?h.branchCovered=p(v.slice(4)):v==="end_of_record"&&(b(h),a="",h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0});return {metrics:{lines:g(r,s),functions:g(i,l),branches:g(d,m)},files:n,source:{format:"lcov",path:t,sha256:await x(t)}}}async function B(e,t){let o=await u.readFile(t,"utf8"),n=new Map;for(let s of o.split(/\r?\n/).slice(1)){let i=/^(.+?):\d+\.\d+,\d+\.\d+\s+(\d+)\s+(\d+)$/.exec(s.trim());if(!i)continue;let l=n.get(i[1])??{total:0,covered:0},d=p(i[2]);l.total+=d,p(i[3])>0&&(l.covered+=d),n.set(i[1],l);}let a=[...n.entries()].map(([s,i])=>({path:y(e,s),metrics:{statements:g(i.total,i.covered)}})),r=[...n.values()].reduce((s,i)=>({total:s.total+i.total,covered:s.covered+i.covered}),{total:0,covered:0});return {metrics:{statements:g(r.total,r.covered)},files:a,source:{format:"go-coverprofile",path:t,sha256:await x(t)}}}function T(e,t){let n=[...e.matchAll(new RegExp(`<counter\\s+type=["']${t}["']\\s+missed=["'](\\d+)["']\\s+covered=["'](\\d+)["']\\s*\\/?\\s*>`,"gi"))].at(-1);return n?g(Number(n[1])+Number(n[2]),n[2]):void 0}async function C(e,t){let o=await u.readFile(e,"utf8"),n={};if(t==="cobertura-xml"){let a=/<coverage\b([^>]*)>/i.exec(o)?.[1]??"",r=/\bline-rate=["']([\d.]+)["']/i.exec(a)?.[1],s=/\bbranch-rate=["']([\d.]+)["']/i.exec(a)?.[1];r&&(n.lines=g(1e4,Math.round(Number(r)*1e4))),s&&(n.branches=g(1e4,Math.round(Number(s)*1e4)));}if(t==="clover-xml"){let r=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",s=m=>p(new RegExp(`\\b${m}=["'](\\d+)["']`,"i").exec(r)?.[1]),i=s("statements"),l=s("methods"),d=s("conditionals");i>0&&(n.statements=g(i,s("coveredstatements"))),l>0&&(n.functions=g(l,s("coveredmethods"))),d>0&&(n.branches=g(d,s("coveredconditionals")));}return n.lines??=T(o,"LINE"),n.branches??=T(o,"BRANCH"),n.functions??=T(o,"METHOD"),n.statements??=T(o,"INSTRUCTION"),{metrics:n,files:[],source:{format:t,path:e,sha256:await x(e)}}}async function K(e){let t=await u.readFile(e,"utf8"),o=/<scoverage\b([^>]*)>/i.exec(t)?.[1]??"",n=b=>p(new RegExp(`\\b${b}=["']([\\d.]+)["']`,"i").exec(o)?.[1]),a=n("statement-count"),r=n("statements-invoked"),s=n("branch-count"),i=n("branches-invoked"),l=n("statement-rate"),d=n("branch-rate"),m={};return a>0?m.statements=g(a,r):l>0&&(m.statements=g(1e4,Math.round(l*100))),s>0?m.branches=g(s,i):d>0&&(m.branches=g(1e4,Math.round(d*100))),{metrics:m,files:[],source:{format:"scoverage-xml",path:e,sha256:await x(e)}}}async function X(e,t){let o=await u.readJson(t),n=new Map;for(let s of Object.values(o)){let i=s?.coverage;if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[l,d]of Object.entries(i)){if(!Array.isArray(d))continue;let m=n.get(l)??[];d.forEach((b,h)=>{typeof b=="number"&&(m[h]=Math.max(m[h]??0,b));}),n.set(l,m);}}let a=[...n.entries()].map(([s,i])=>{let l=i.filter(d=>typeof d=="number");return {path:y(e,s),metrics:{lines:g(l.length,l.filter(d=>d>0).length)}}}),r=a.reduce((s,i)=>{let l=i.metrics.lines;return {total:s.total+(l?.total??0),covered:s.covered+(l?.covered??0)}},{total:0,covered:0});return {metrics:{lines:g(r.total,r.covered)},files:a,source:{format:"simplecov-json",path:t,sha256:await x(t)}}}async function $(e,t={}){let o=[{relativePath:"coverage/coverage-summary.json",parser:r=>L(e,r)},{relativePath:"coverage.json",parser:async r=>{let s=await u.readJson(r);return Array.isArray(s.data)?z(e,r):U(e,r)}},{relativePath:"coverage/lcov.info",parser:r=>A(e,r)},{relativePath:"cover/lcov.info",parser:r=>A(e,r)},{relativePath:"lcov.info",parser:r=>A(e,r)},{relativePath:"coverage.out",parser:r=>B(e,r)},{relativePath:"target/site/jacoco/jacoco.xml",parser:r=>C(r,"jacoco-xml")},{relativePath:"build/reports/jacoco/test/jacocoTestReport.xml",parser:r=>C(r,"jacoco-xml")},{relativePath:"coverage.xml",parser:r=>C(r,"clover-xml")},{relativePath:".resultset.json",parser:r=>X(e,r)}];for(let r of o){let s=c.join(e,r.relativePath);if(await u.pathExists(s))return r.parser(s)}if(t.recursive===false)return null;let a=(await P(e,(r,s)=>r==="coverage.cobertura.xml"||r==="jacoco.xml"||r==="clover.xml"||r==="scoverage.xml"||s.endsWith("/coverage-summary.json"),7)).sort()[0];return a?a.endsWith("coverage-summary.json")?L(e,a):a.endsWith("jacoco.xml")?C(a,"jacoco-xml"):a.endsWith("coverage.cobertura.xml")?C(a,"cobertura-xml"):a.endsWith("scoverage.xml")?K(a):C(a,"clover-xml"):null}async function Q(e){return u.readJson(c.join(e,"package.json")).catch(()=>null)}async function q(e,t){let o=(n,a)=>({cwd:e,executable:n,args:a});if(t==="node"||t==="bun"){let a=(await Q(e))?.scripts??{},r=["test:coverage","test:cov","coverage"].find(i=>typeof a[i]=="string"),s=t==="bun"?"bun":await u.pathExists(c.join(e,"pnpm-lock.yaml"))?"pnpm":await u.pathExists(c.join(e,"yarn.lock"))?"yarn":"npm";if(r)return {runner:String(a[r]).split(/\s+/)[0]||s,invocations:[o(s,s==="yarn"?[r]:["run",r])],diagnostics:[]};if(typeof a.test=="string"){let i=s==="yarn"?["test","--coverage"]:s==="bun"?["test","--coverage","--coverage-reporter=lcov"]:["test","--","--coverage"];return {runner:String(a.test).split(/\s+/)[0]||s,invocations:[o(s,i)],diagnostics:[]}}return {runner:null,invocations:[],diagnostics:["No project-owned test or coverage script was detected."]}}if(t==="deno")return {runner:"deno",invocations:[o("deno",["test","--coverage=coverage"]),o("deno",["coverage","--lcov","--output=coverage/lcov.info","coverage"])],diagnostics:[]};if(t==="python")return {runner:"pytest-cov",invocations:[o(await u.pathExists(c.join(e,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"))?c.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(t==="go")return {runner:"go test",invocations:[o("go",["test","./...","-coverprofile=coverage.out"])],diagnostics:[]};if(t==="java"){let n=await u.pathExists(c.join(e,"gradlew")),a=await u.pathExists(c.join(e,"gradlew.bat")),r=n||a,s=await u.pathExists(c.join(e,"mvnw")),i=await u.pathExists(c.join(e,"mvnw.cmd")),l=r?process.platform==="win32"&&a?".\\gradlew.bat":"./gradlew":await u.pathExists(c.join(e,"pom.xml"))?process.platform==="win32"&&i?".\\mvnw.cmd":s?"./mvnw":"mvn":"gradle";return {runner:r?"jacoco/gradle":"jacoco/maven",invocations:[o(l,r?["test","jacocoTestReport"]:["test","jacoco:report"])],diagnostics:[]}}return t==="dotnet"?{runner:"dotnet coverlet",invocations:[o("dotnet",["test","--collect:XPlat Code Coverage"])],diagnostics:[]}:t==="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."]}:t==="php"?{runner:"phpunit",invocations:[o(process.platform==="win32"?"vendor\\bin\\phpunit.bat":"vendor/bin/phpunit",["--coverage-clover","coverage.xml"])],diagnostics:[]}:t==="ruby"?{runner:"simplecov",invocations:[o("bundle",["exec","rspec"])],diagnostics:["The test suite must enable SimpleCov to emit .resultset.json."]}:t==="elixir"?{runner:"mix cover",invocations:[o("mix",["test","--cover"])],diagnostics:["Configure ExCoveralls for JSON or LCOV interchange when machine-readable coverage is required."]}:t==="clojure"?{runner:"cloverage",invocations:[o("clojure",["-M:coverage"])],diagnostics:["The project must declare a coverage alias such as cloverage."]}:t==="scala"?{runner:"sbt-scoverage",invocations:[o("sbt",["clean","coverage","test","coverageReport"])],diagnostics:["The project must declare the scoverage plugin."]}:t==="kotlin"?{runner:"jacoco/gradle",invocations:[o(await u.pathExists(c.join(e,process.platform==="win32"?"gradlew.bat":"gradlew"))?process.platform==="win32"?".\\gradlew.bat":"./gradlew":"gradle",["test","jacocoTestReport"])],diagnostics:["The project must declare the JaCoCo Gradle plugin."]}:t==="c"||t==="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 ue(e,t){let o=await I(e),n=t??await V(o),a=await q(o,n),r=await $(o,{recursive:false}).catch(()=>null),s=r?.source.path&&r.source.sha256?[{path:c.relative(o,r.source.path).split(c.sep).join("/"),sha256:r.source.sha256}]:[],i=[...a.diagnostics],l=r?"available":a.invocations.length===0||n==="unknown"?"unsupported":i.length>0?"requires-setup":"available";return {runtime:n,runner:a.runner,status:l,existingEvidence:s,invocations:a.invocations,prerequisites:i}}function Y(e,t){let o=e?c.relative(e,t).split(c.sep).join("/"):c.resolve(t),n=c.basename(t).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",a=createHash("sha256").update(o).digest("hex").slice(0,12);return `${n}--${a}`}function Z(e){return e.lines?"lines":e.statements?"statements":e.branches?"branches":"functions"}async function de(e$1={}){let t=await I(e$1.projectPath??process.cwd()),o=a(t),n=e$1.runtime??await V(t),a$1=Math.max(0,Math.min(100,Math.round(e$1.target??80))),r=await q(t,n),s=[],i=Date.now();if(e$1.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(s.push(Number(w.exitCode??1)),Number(w.exitCode??1)!==0)break}let l=await $(t).catch(()=>null),d=l?Z(l.metrics):"lines",m=l?.metrics[d]?.percent??null,b=e$1.run&&s.some(f=>f!==0)?"failed":m===null?"unavailable":m>=a$1?"passed":"below-target",h=Y(o,t),v=c.join(t,E),R=o?`.workspai/reports/projects/${h}/project-test-coverage-last-run.json`:null,k={schemaVersion:D,generatedAt:new Date().toISOString(),status:b,project:{id:h,name:c.basename(t),path:t,workspacePath:o},runtime:n,runner:r.runner,target:{metric:d,percent:a$1},metrics:l?.metrics??{},files:l?.files??[],lowCoverageFiles:(l?.files??[]).map(f=>{let w=f.metrics[d]??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<a$1).sort((f,w)=>w.uncovered-f.uncovered||f.path.localeCompare(w.path)),source:l?.source??{format:"unknown",path:null,sha256:null},execution:{requested:e$1.run===true,invocations:r.invocations,exitCodes:s,durationMs:Date.now()-i},diagnostics:[...r.diagnostics,...l?[]:["No supported machine-readable coverage artifact was found."]],artifactPaths:{project:v,workspaceLatest:o?c.join(o,E):null,workspaceProject:o&&R?c.join(o,R):null}};return o&&R&&await f(o,E,[{relativePath:E,payload:k},{relativePath:R,payload:k}]),await e(t,E,k),k}export{D as a,E as b,ue as c,de as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {f,l}from'./chunk-
|
|
1
|
+
import {f,l}from'./chunk-NA2NXX5P.js';import {a,b}from'./chunk-S5KTATOU.js';function u(r){let s=new Map;for(let n of r.projects)s.has(n.name)||s.set(n.name,f(n));return s}function w(r){let s=u(r),n=l(r)??{nodes:r.projects.map(t=>({id:t.name,path:t.path})),edges:[]},a$1=a(n),o=new Map;for(let t of n.nodes){let e=s.get(t.id)??f({missing:t.id}),l=[...b(a$1,[t.id],{direction:"dependencies"}).keys()].filter(c=>c!==t.id).sort((c,f)=>c.localeCompare(f)).map(c=>({id:c,hash:s.get(c)??"<unknown>"}));o.set(t.id,{id:t.id,ownHash:e,transitiveInputsHash:f({own:e,dependencies:l})});}return o}function y(r,s){if(!s||Object.keys(s).length===0)return {verdict:"unknown",baseline:"none",changed:[],added:[],removed:[]};let n=[],a=[];for(let[e,i]of r.entries())e in s?s[e]!==i.transitiveInputsHash&&n.push(e):a.push(e);let o=[];for(let e of Object.keys(s))r.has(e)||o.push(e);return n.sort((e,i)=>e.localeCompare(i)),a.sort((e,i)=>e.localeCompare(i)),o.sort((e,i)=>e.localeCompare(i)),{verdict:n.length>0||a.length>0||o.length>0?"stale":"fresh",baseline:"recorded",changed:n,added:a,removed:o}}function M(r){let s={};for(let[n,a]of [...r.entries()].sort((o,t)=>o[0].localeCompare(t[0])))s[n]=a.transitiveInputsHash;return s}export{u as a,w as b,y as c,M as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {f,e}from'./chunk-T3GJ7YVG.js';import {a,b}from'./chunk-QJCCZLOF.js';import {a as a$1,b as b$2}from'./chunk-X7FYEKLI.js';import {c as c$1,d}from'./chunk-HCFWT42C.js';import {i,j as j$1,l,k,n}from'./chunk-WP3CXMVA.js';import {a as a$2,e as e$2}from'./chunk-CCDGHPEJ.js';import {b as b$1}from'./chunk-D65FCQIO.js';import {f as f$1,e as e$1}from'./chunk-NZ3WZYD5.js';import {s}from'./chunk-MOSXTVPU.js';import u from'chalk';import c from'fs';import y from'path';var H=e$1.readiness,K=f$1.readiness;function U(n,e){let t=y.resolve(n);if(!b(t))return t;let a=M(e,"workspace.contract.json");if(c.existsSync(a))try{let o=JSON.parse(c.readFileSync(a,"utf-8")),s=Array.isArray(o.projects)?o.projects:[];for(let i of s){let l=m(i),p=typeof l.relativePath=="string"?l.relativePath.trim():"";if(p)return y.join(e,p)}}catch{}let r=T(e),d=Array.isArray(r.payload?.projects)?r.payload.projects:[];for(let o of d){let s=m(o),i=typeof s.path=="string"?s.path.trim():"";if(i)return y.resolve(i)}return t}function z(n$1){let e=i(n$1);return j$1(e,n$1)?"go":l(e,n$1)?"java":k(e,n$1)?"node":n(e,n$1)?"python":"unknown"}function _(n,e){if(!c.existsSync(n))return null;let t=c.readdirSync(n).filter(a=>a.endsWith(".json")&&e.some(r=>r.test(a))).map(a=>y.join(n,a));return t.length===0?null:(t.sort((a,r)=>c.statSync(r).mtimeMs-c.statSync(a).mtimeMs),t[0])}function m(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function J(n){for(let e of n)if(c.existsSync(e))return e;return null}function M(n,...e){let t=s(n,...e);return J(t)??t[0]}function j(n,e){let t=a$2(n,`.workspai/reports/${e}`);return J([t,y.join(n,".rapidkit","reports",e)])??t}async function B(n){let{readWorkspaceRegistrySummary:e,resolveWorkspaceRegisteredProjects:t}=await import('./workspace-registry-summary-OV5KX3WC.js'),a=await e(n);return a?a.projectCount:(await t(n)).summary.projectCount}function Q(n,e,t){let a=M(n,"toolchain.lock");if(!c.existsSync(a))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run workspai bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:a};try{let r=JSON.parse(c.readFileSync(a,"utf-8")),d=m(r.runtime),s=["python","node","go","java"].filter(p=>{let f=m(d[p]);return typeof f.version=="string"&&f.version.trim().length>0});if(s.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via workspai setup <runtime> and re-run bootstrap."],evidencePath:a};let l=[...new Set((Array.isArray(e)?e:[e]).filter(p=>p!=="unknown"))].filter(p=>{let f=m(d[p]);return typeof f.version!="string"||f.version.trim().length===0});return l.length>0?{gate:"env",status:"fail",summary:`${t?.hasRegisteredProjects?"Project runtime":"Workspace"}${l.length===1?"":"s"} (${l.join(", ")}) ${l.length===1?"is":"are"} not pinned in toolchain.lock`,details:l.map(f=>`Run workspai setup ${f} and workspai bootstrap to lock ${f} for this workspace.`),evidencePath:a}:{gate:"env",status:"pass",summary:`Pinned runtimes: ${s.join(", ")}`,details:[],evidencePath:a}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with workspai bootstrap."],evidencePath:a}}}function T(n){let e=j(n,"doctor-last-run.json");if(!c.existsSync(e))return {payload:null,path:e};try{let t=JSON.parse(c.readFileSync(e,"utf-8"));return c$1(t,"workspace")?(d(t),{payload:t,path:e}):{payload:null,path:e}}catch{return {payload:null,path:e}}}function X(n){let e=T(n);if(!e.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run workspai doctor workspace --json before release readiness checks."],evidencePath:e.path},payload:null};let t=a$1(e.payload);if(t.hasSystemErrors)return {gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:e.path},payload:e.payload};if(t.blockingFindings>0)return {gate:{gate:"doctor",status:"fail",summary:`Doctor reported ${t.blockingFindings} blocking finding(s)`,details:["Resolve the canonical Doctor findings and regenerate fresh Doctor evidence."],evidencePath:e.path},payload:e.payload};let a=[...t.advisoryFindings>0?[`${t.advisoryFindings} advisory finding(s)`]:[],...t.unknownFindings>0?[`${t.unknownFindings} unknown finding(s)`]:[],...t.contradictionCount>0?[`${t.contradictionCount} evidence contradiction(s)`]:[],...t.missingDiagnosisProjects>0?[`${t.missingDiagnosisProjects} project(s) without canonical diagnosis`]:[],...t.staleEvidence?["stale Doctor evidence"]:[],...t.unknownFreshness?["unknown Doctor evidence freshness"]:[],...t.minimumDiagnosisCompleteness<100?[`diagnosis completeness ${t.minimumDiagnosisCompleteness}%`]:[]];return a.length>0?{gate:{gate:"doctor",status:"warn",summary:"Doctor evidence requires attention",details:a,evidencePath:e.path},payload:e.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:e.path},payload:e.payload}}function Y(n){let e=j(n,"analyze-last-run.json");if(!c.existsSync(e))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run workspai analyze --json before release readiness checks."],evidencePath:e};try{let t=JSON.parse(c.readFileSync(e,"utf-8"));b$1(e$1.analyze,t,e);let a=m(t.summary),r=String(a.verdict??"").toLowerCase(),d=Number(a.score??0),o=m(a.findings),s=Number(o.fail??0);return r==="blocked"||s>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${d}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:e}:r==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${d}/100)`,details:["Review analyze warnings before release."],evidencePath:e}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${d}/100)`,details:[],evidencePath:e}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid or violates its contract",details:["Re-run workspai analyze --json to regenerate evidence."],evidencePath:e}}}function Z(n){try{let e=JSON.parse(c.readFileSync(n,"utf-8")),t=String(e.status??"").toLowerCase(),a=m(e.summary),r=Number(a.failedChecks??0);return t==="fail"||r>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:n}:t==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:n}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:n}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:n}}}async function ee(n,e){if(e.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let t=[a$2(n,".workspai/reports"),y.join(n,".rapidkit","reports")],a=t[0],r=t.map(s=>_(s,[/verify-pack-contract/i,/^verify.*\.json$/i])).find(s=>typeof s=="string")??null;if(r)return Z(r);let d=a$2(n,e$1.contractVerify),o=t.map(s=>_(s,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i])).find(s=>typeof s=="string")??null;if(o)try{let s=JSON.parse(c.readFileSync(o,"utf-8")),i=String(s.status??"").toLowerCase();if(i==="passed"||i==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(i==="failed"||i==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(s.violations)?s.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:s}=await import('./workspace-contract-ACSIHJIO.js'),i=await s({workspacePath:n}),l={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:i.status,contractPath:i.contractPath,projectCount:i.projectCount,checks:i.checks,violations:i.violations};return await e$2(n,e$1.contractVerify,l),i.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:i.violations.slice(0,5),evidencePath:d}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:d}}catch(s){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run workspai workspace contract verify --json or export verify-pack contract from CI.",s instanceof Error?s.message:String(s)],evidencePath:y.join(a,"*verify*.json")}}}function te(n,e){let t=j(e,"doctor-last-run.json");if(!n)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run workspai doctor workspace --json to include dependency findings."],evidencePath:t};let a=b$2(n);return a.blockingFindings>0||a.vulnerableDependencies>0?{gate:"dependency",status:"fail",summary:`${Math.max(a.blockingFindings,a.vulnerableDependencies)} blocking dependency/security vulnerability finding(s) reported`,details:["Resolve the typed dependency/security findings and regenerate focused audit evidence."],evidencePath:t}:a.auditFailed>0?{gate:"dependency",status:"fail",summary:`${a.auditFailed} dependency audit(s) failed`,details:["Repair the audit runner or dependency environment; failed audits are not clean."],evidencePath:t}:a.missingDependencies>0||a.auditUnavailable>0||a.unknownFindings>0||a.advisoryFindings>0?{gate:"dependency",status:"warn",summary:"Dependency evidence is incomplete or requires attention",details:[...a.missingDependencies>0?[`${a.missingDependencies} project(s) have no materialized dependency tree.`]:[],...a.auditUnavailable>0?[`${a.auditUnavailable} audit provider(s) are unavailable or unsupported.`]:[],...a.unknownFindings>0?[`${a.unknownFindings} dependency/security finding(s) remain unknown.`]:[],...a.advisoryFindings>0?[`${a.advisoryFindings} dependency/security advisory finding(s) remain.`]:[]],evidencePath:t}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:t}}function ne(n){return n.some(e=>e.status==="fail")?"fail":n.some(e=>e.status==="warn")?"warn":"pass"}async function ae(n,e){return e$2(n,H,e)}async function se(n={}){let e$1=y.resolve(n.startPath??process.cwd()),t=a(e$1)??e$1,a$1=await B(t)>0,r=a$1&&b(e$1)?t:U(e$1,t),d=r===t?"unknown":z(r),o=a$1?d:"unknown";if(a$1&&r===t){let{resolveWorkspaceRegisteredProjects:g}=await import('./workspace-registry-summary-OV5KX3WC.js');o=(await g(t)).summary.projects.map(q=>z(y.resolve(t,q.relativePath)));}let s=Q(t,o,{hasRegisteredProjects:a$1}),i=X(t),l=Y(t),p=await ee(t,{skipVerify:n.skipVerify}),f$1=te(i.payload,t),w=[s,i.gate,l,p,f$1],k=ne(w),v={schemaVersion:K,generatedAt:new Date().toISOString(),workspacePath:t,projectPath:r,action:n.action,overallStatus:k,blocking:k==="fail",blockingReasons:w.filter(g=>g.status==="fail").map(g=>`${g.gate}: ${g.summary}`),gates:w};if(n.writeReport!==false){let g=f(v,{commandId:"workspaceReadiness",exitCode:k==="fail"?2:k==="warn"?1:0,generatedAt:v.generatedAt,blockers:v.blockingReasons,runId:e()});v.evidencePath=await ae(t,g);}return v}function re(n){return n==="pass"?u.green("PASS"):n==="warn"?u.yellow("WARN"):u.red("FAIL")}function ie(n){return n==="pass"?u.green("PASS"):n==="warn"?u.yellow("WARN"):u.red("FAIL")}async function Pe(n){let e=await se({startPath:n.workspace,writeReport:true,skipVerify:n.skipVerify===true});if(n.json)console.log(JSON.stringify(e,null,2));else {console.log(u.bold.cyan(`
|
|
1
|
+
import {f,e}from'./chunk-ILIBOMYL.js';import {a,b}from'./chunk-QJCCZLOF.js';import {a as a$1,b as b$2}from'./chunk-X7FYEKLI.js';import {c as c$1,d}from'./chunk-HCFWT42C.js';import {i,j as j$1,l,k,n}from'./chunk-SCP5LJNO.js';import {a as a$2,e as e$2}from'./chunk-CCDGHPEJ.js';import {b as b$1}from'./chunk-D65FCQIO.js';import {f as f$1,e as e$1}from'./chunk-NZ3WZYD5.js';import {s}from'./chunk-MOSXTVPU.js';import u from'chalk';import c from'fs';import y from'path';var H=e$1.readiness,K=f$1.readiness;function U(n,e){let t=y.resolve(n);if(!b(t))return t;let a=M(e,"workspace.contract.json");if(c.existsSync(a))try{let o=JSON.parse(c.readFileSync(a,"utf-8")),s=Array.isArray(o.projects)?o.projects:[];for(let i of s){let l=m(i),p=typeof l.relativePath=="string"?l.relativePath.trim():"";if(p)return y.join(e,p)}}catch{}let r=T(e),d=Array.isArray(r.payload?.projects)?r.payload.projects:[];for(let o of d){let s=m(o),i=typeof s.path=="string"?s.path.trim():"";if(i)return y.resolve(i)}return t}function z(n$1){let e=i(n$1);return j$1(e,n$1)?"go":l(e,n$1)?"java":k(e,n$1)?"node":n(e,n$1)?"python":"unknown"}function _(n,e){if(!c.existsSync(n))return null;let t=c.readdirSync(n).filter(a=>a.endsWith(".json")&&e.some(r=>r.test(a))).map(a=>y.join(n,a));return t.length===0?null:(t.sort((a,r)=>c.statSync(r).mtimeMs-c.statSync(a).mtimeMs),t[0])}function m(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function J(n){for(let e of n)if(c.existsSync(e))return e;return null}function M(n,...e){let t=s(n,...e);return J(t)??t[0]}function j(n,e){let t=a$2(n,`.workspai/reports/${e}`);return J([t,y.join(n,".rapidkit","reports",e)])??t}async function B(n){let{readWorkspaceRegistrySummary:e,resolveWorkspaceRegisteredProjects:t}=await import('./workspace-registry-summary-VSOBKAJG.js'),a=await e(n);return a?a.projectCount:(await t(n)).summary.projectCount}function Q(n,e,t){let a=M(n,"toolchain.lock");if(!c.existsSync(a))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run workspai bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:a};try{let r=JSON.parse(c.readFileSync(a,"utf-8")),d=m(r.runtime),s=["python","node","go","java"].filter(p=>{let f=m(d[p]);return typeof f.version=="string"&&f.version.trim().length>0});if(s.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via workspai setup <runtime> and re-run bootstrap."],evidencePath:a};let l=[...new Set((Array.isArray(e)?e:[e]).filter(p=>p!=="unknown"))].filter(p=>{let f=m(d[p]);return typeof f.version!="string"||f.version.trim().length===0});return l.length>0?{gate:"env",status:"fail",summary:`${t?.hasRegisteredProjects?"Project runtime":"Workspace"}${l.length===1?"":"s"} (${l.join(", ")}) ${l.length===1?"is":"are"} not pinned in toolchain.lock`,details:l.map(f=>`Run workspai setup ${f} and workspai bootstrap to lock ${f} for this workspace.`),evidencePath:a}:{gate:"env",status:"pass",summary:`Pinned runtimes: ${s.join(", ")}`,details:[],evidencePath:a}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with workspai bootstrap."],evidencePath:a}}}function T(n){let e=j(n,"doctor-last-run.json");if(!c.existsSync(e))return {payload:null,path:e};try{let t=JSON.parse(c.readFileSync(e,"utf-8"));return c$1(t,"workspace")?(d(t),{payload:t,path:e}):{payload:null,path:e}}catch{return {payload:null,path:e}}}function X(n){let e=T(n);if(!e.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run workspai doctor workspace --json before release readiness checks."],evidencePath:e.path},payload:null};let t=a$1(e.payload);if(t.hasSystemErrors)return {gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:e.path},payload:e.payload};if(t.blockingFindings>0)return {gate:{gate:"doctor",status:"fail",summary:`Doctor reported ${t.blockingFindings} blocking finding(s)`,details:["Resolve the canonical Doctor findings and regenerate fresh Doctor evidence."],evidencePath:e.path},payload:e.payload};let a=[...t.advisoryFindings>0?[`${t.advisoryFindings} advisory finding(s)`]:[],...t.unknownFindings>0?[`${t.unknownFindings} unknown finding(s)`]:[],...t.contradictionCount>0?[`${t.contradictionCount} evidence contradiction(s)`]:[],...t.missingDiagnosisProjects>0?[`${t.missingDiagnosisProjects} project(s) without canonical diagnosis`]:[],...t.staleEvidence?["stale Doctor evidence"]:[],...t.unknownFreshness?["unknown Doctor evidence freshness"]:[],...t.minimumDiagnosisCompleteness<100?[`diagnosis completeness ${t.minimumDiagnosisCompleteness}%`]:[]];return a.length>0?{gate:{gate:"doctor",status:"warn",summary:"Doctor evidence requires attention",details:a,evidencePath:e.path},payload:e.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:e.path},payload:e.payload}}function Y(n){let e=j(n,"analyze-last-run.json");if(!c.existsSync(e))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run workspai analyze --json before release readiness checks."],evidencePath:e};try{let t=JSON.parse(c.readFileSync(e,"utf-8"));b$1(e$1.analyze,t,e);let a=m(t.summary),r=String(a.verdict??"").toLowerCase(),d=Number(a.score??0),o=m(a.findings),s=Number(o.fail??0);return r==="blocked"||s>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${d}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:e}:r==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${d}/100)`,details:["Review analyze warnings before release."],evidencePath:e}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${d}/100)`,details:[],evidencePath:e}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid or violates its contract",details:["Re-run workspai analyze --json to regenerate evidence."],evidencePath:e}}}function Z(n){try{let e=JSON.parse(c.readFileSync(n,"utf-8")),t=String(e.status??"").toLowerCase(),a=m(e.summary),r=Number(a.failedChecks??0);return t==="fail"||r>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:n}:t==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:n}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:n}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:n}}}async function ee(n,e){if(e.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let t=[a$2(n,".workspai/reports"),y.join(n,".rapidkit","reports")],a=t[0],r=t.map(s=>_(s,[/verify-pack-contract/i,/^verify.*\.json$/i])).find(s=>typeof s=="string")??null;if(r)return Z(r);let d=a$2(n,e$1.contractVerify),o=t.map(s=>_(s,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i])).find(s=>typeof s=="string")??null;if(o)try{let s=JSON.parse(c.readFileSync(o,"utf-8")),i=String(s.status??"").toLowerCase();if(i==="passed"||i==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(i==="failed"||i==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(s.violations)?s.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:s}=await import('./workspace-contract-3BWIRSVQ.js'),i=await s({workspacePath:n}),l={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:i.status,contractPath:i.contractPath,projectCount:i.projectCount,checks:i.checks,violations:i.violations};return await e$2(n,e$1.contractVerify,l),i.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:i.violations.slice(0,5),evidencePath:d}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:d}}catch(s){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run workspai workspace contract verify --json or export verify-pack contract from CI.",s instanceof Error?s.message:String(s)],evidencePath:y.join(a,"*verify*.json")}}}function te(n,e){let t=j(e,"doctor-last-run.json");if(!n)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run workspai doctor workspace --json to include dependency findings."],evidencePath:t};let a=b$2(n);return a.blockingFindings>0||a.vulnerableDependencies>0?{gate:"dependency",status:"fail",summary:`${Math.max(a.blockingFindings,a.vulnerableDependencies)} blocking dependency/security vulnerability finding(s) reported`,details:["Resolve the typed dependency/security findings and regenerate focused audit evidence."],evidencePath:t}:a.auditFailed>0?{gate:"dependency",status:"fail",summary:`${a.auditFailed} dependency audit(s) failed`,details:["Repair the audit runner or dependency environment; failed audits are not clean."],evidencePath:t}:a.missingDependencies>0||a.auditUnavailable>0||a.unknownFindings>0||a.advisoryFindings>0?{gate:"dependency",status:"warn",summary:"Dependency evidence is incomplete or requires attention",details:[...a.missingDependencies>0?[`${a.missingDependencies} project(s) have no materialized dependency tree.`]:[],...a.auditUnavailable>0?[`${a.auditUnavailable} audit provider(s) are unavailable or unsupported.`]:[],...a.unknownFindings>0?[`${a.unknownFindings} dependency/security finding(s) remain unknown.`]:[],...a.advisoryFindings>0?[`${a.advisoryFindings} dependency/security advisory finding(s) remain.`]:[]],evidencePath:t}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:t}}function ne(n){return n.some(e=>e.status==="fail")?"fail":n.some(e=>e.status==="warn")?"warn":"pass"}async function ae(n,e){return e$2(n,H,e)}async function se(n={}){let e$1=y.resolve(n.startPath??process.cwd()),t=a(e$1)??e$1,a$1=await B(t)>0,r=a$1&&b(e$1)?t:U(e$1,t),d=r===t?"unknown":z(r),o=a$1?d:"unknown";if(a$1&&r===t){let{resolveWorkspaceRegisteredProjects:g}=await import('./workspace-registry-summary-VSOBKAJG.js');o=(await g(t)).summary.projects.map(q=>z(y.resolve(t,q.relativePath)));}let s=Q(t,o,{hasRegisteredProjects:a$1}),i=X(t),l=Y(t),p=await ee(t,{skipVerify:n.skipVerify}),f$1=te(i.payload,t),w=[s,i.gate,l,p,f$1],k=ne(w),v={schemaVersion:K,generatedAt:new Date().toISOString(),workspacePath:t,projectPath:r,action:n.action,overallStatus:k,blocking:k==="fail",blockingReasons:w.filter(g=>g.status==="fail").map(g=>`${g.gate}: ${g.summary}`),gates:w};if(n.writeReport!==false){let g=f(v,{commandId:"workspaceReadiness",exitCode:k==="fail"?2:k==="warn"?1:0,generatedAt:v.generatedAt,blockers:v.blockingReasons,runId:e()});v.evidencePath=await ae(t,g);}return v}function re(n){return n==="pass"?u.green("PASS"):n==="warn"?u.yellow("WARN"):u.red("FAIL")}function ie(n){return n==="pass"?u.green("PASS"):n==="warn"?u.yellow("WARN"):u.red("FAIL")}async function Pe(n){let e=await se({startPath:n.workspace,writeReport:true,skipVerify:n.skipVerify===true});if(n.json)console.log(JSON.stringify(e,null,2));else {console.log(u.bold.cyan(`
|
|
2
2
|
\u{1F6A6} Workspai Release Readiness
|
|
3
3
|
`)),console.log(u.bold(`Workspace: ${u.cyan(y.basename(e.workspacePath))}`)),console.log(u.gray(`Path: ${e.workspacePath}`)),console.log(`Overall: ${ie(e.overallStatus)}`);for(let t of e.gates){console.log(` - ${t.gate}: ${re(t.status)} ${t.summary}`);for(let a of t.details)console.log(u.gray(` ${a}`));t.evidencePath&&console.log(u.gray(` evidence: ${t.evidencePath}`));}e.evidencePath&&console.log(u.gray(`
|
|
4
4
|
Evidence saved: ${e.evidencePath}`));}n.strict&&e.overallStatus!=="pass"&&process.exit(1);}export{se as a,Pe as b};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {d,b,e}from'./chunk-W6FHVXNL.js';import {a}from'./chunk-2647BYBC.js';import {a as a$1}from'./chunk-27UR373Z.js';import {d as d$2}from'./chunk-S5KTATOU.js';import {p as p$1,w,t as t$1}from'./chunk-WP3CXMVA.js';import {h,j,f,e as e$2}from'./chunk-ZCPT6KC3.js';import {d as d$1}from'./chunk-CCDGHPEJ.js';import {e as e$1,i}from'./chunk-NZ3WZYD5.js';import {a as a$2}from'./chunk-TQEMLBAG.js';import {t,p,s}from'./chunk-MOSXTVPU.js';import {e as e$3,g}from'./chunk-RJIYCDVC.js';import U from'fs';import k from'path';import T from'chalk';import {execa}from'execa';function Le(e){return U.existsSync(k.join(e,"bun.lock"))||U.existsSync(k.join(e,"bunfig.toml"))?"bun":U.existsSync(k.join(e,"pnpm-lock.yaml"))?"pnpm":U.existsSync(k.join(e,"yarn.lock"))?"yarn":(U.existsSync(k.join(e,"package-lock.json")),"npm")}function Ge(e,r,t=Le(e)){return t==="npm"?`npm run ${r}`:`${t} run ${r}`}function Be(e,r=Le(e)){return `${r} install`}var ct={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},dt={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],c:["cmake -S . -B build"],cpp:["cmake -S . -B build"],elixir:["mix deps.get"],ruby:["bundle install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],c:["ctest --test-dir build --output-on-failure"],cpp:["ctest --test-dir build --output-on-failure"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],c:["cmake --build build"],cpp:["cmake --build build"],elixir:["mix compile"],ruby:["gem build *.gemspec"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],c:[],cpp:[],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function te(e,r){if(r){let t=r.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=e$2(r),s=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:t==="fiber"?"fiber":t==="aspnetcore"||t==="asp-net-core"?"aspnetcore":t}`;return ct[s]}}function He(e,r,t){if(r){let n=te(e,r);if(n&&n.commands[t])return n.commands[t]}if(["init","test","build","start"].includes(t)){let n=dt[t]?.[e]??[];return n.length>0?n[0]:void 0}}var lt={test:"test",build:"build",start:"start"};function ge(e){if(e.stage==="init")return e.runtime==="node"?Be(e.projectPath):He(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let r=lt[e.stage];if(r){let t=t$1(e.projectPath,r,{framework:e.framework});if(t)return Ge(e.projectPath,t.scriptName)}}return He(e.runtime,e.framework,e.stage)}function mt(e){let r=h(e).map(t=>t==="python"?"python":t==="node"||t==="bun"?"node":t==="go"?"go":t==="java"?"java":t==="php"?"php":t==="rust"?"rust":t==="dotnet"?"dotnet":t==="elixir"?"elixir":t==="ruby"?"ruby":t==="clojure"||t==="scala"||t==="kotlin"?"jvm-generic":null).filter(t=>t!==null).filter((t,n,o)=>o.indexOf(t)===n);return {primary:r.length>0?r[0]:"unknown",secondary:r.slice(1)}}function ze(e){return mt(e).primary}function ye(e,r){if(!e)return "unknown";r||(r={setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[t,n]of Object.entries(r))for(let o of n)if(new RegExp(o,"i").test(e))return t;return "unknown"}async function re(e){let r=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(r))return {valid:true};try{let n=process.platform==="win32"?"where":"which";if((await execa(n,[r],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${r}' not found or not executable`}}function Je(e,r,t){if(!r)return e;let n=typeof r=="object"&&!Array.isArray(r)&&("dev"in r||"staging"in r||"prod"in r||"default"in r)&&!Object.keys(r).some(o=>["init","test","build","start"].includes(o))?r:{};return t&&typeof n[t]=="string"?n[t]:typeof n.default=="string"?n.default:e}async function qe(e,r){if(!e)return {healthy:true};switch(e.type){case "port":{let t=e.value;try{let n=await import('net');return new Promise(o=>{let s=new n.Socket,u=5e3;s.setTimeout(u),s.on("connect",()=>{s.destroy(),o({healthy:true,reason:`Port ${t} is listening`});}),s.on("timeout",()=>{s.destroy(),o({healthy:false,reason:`Port ${t} timeout after ${u}ms`});}),s.on("error",c=>{s.destroy(),o({healthy:false,reason:`Port ${t} error: ${String(c)}`});}),s.connect(t,"localhost");})}catch(n){return {healthy:false,reason:`Port check error: ${n instanceof Error?n.message:String(n)}`}}}case "http":{let t=e.value,n;try{let o=new AbortController;n=setTimeout(()=>o.abort(),5e3);let s=await fetch(t,{method:"GET",signal:o.signal});return {healthy:s.status===200,reason:`HTTP ${s.status}`,metadata:{status:s.status}}}catch(o){return {healthy:false,reason:`HTTP check error: ${o instanceof Error?o.message:String(o)}`}}finally{n&&clearTimeout(n);}}case "log":{let t=e.value;if(!r)return {healthy:true};try{let n=[k.join(r,".workspai","last-run.log"),k.join(r,".rapidkit","last-run.log")].find(o=>U.existsSync(o));if(n){let o=U.readFileSync(n,"utf-8"),s=new RegExp(t,"i");return {healthy:s.test(o),reason:s.test(o)?"Log pattern found":"Log pattern not found"}}return {healthy:true,reason:"No log file to check"}}catch(n){return {healthy:false,reason:`Log check error: ${n instanceof Error?n.message:String(n)}`}}}case "command":{let t=e.value;try{let n=await execa(t,[],{cwd:r,reject:false,shell:true});return {healthy:n.exitCode===0,reason:n.exitCode===0?"Health check passed":"Health check failed",metadata:{exitCode:n.exitCode}}}catch(n){return {healthy:false,reason:`Command check error: ${n instanceof Error?n.message:String(n)}`}}}default:return {healthy:true}}}var Ye={init:"init",test:"test",build:"build",start:"start"};function pt(e){return e in Ye?Ye[e]:null}function ft(e,r){let n=p$1(e)?.contextJson?.commands;if(!n||typeof n!="object"||Array.isArray(n))return;let o=n[r];if(typeof o=="string"&&o.trim().length>0)return o.trim();if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,u=s.default??s.dev;if(typeof u=="string"&&u.trim().length>0)return u.trim()}}function Qe(e,r,t=w(e)){let n=pt(r);if(!n)return ft(e,r)?{supported:true}:{supported:false,reason:`Workspace stage "${r}" is not part of the Workspai fleet contract.`};if(!t.projectRoot)return {supported:false,reason:"No Workspai project metadata was detected for this target."};let o=t.commandMap[n];if(!o||o.status!=="supported"){let s=t.runtimeSupportTier==="observed"||t.frameworkSupportTier==="observed";return {supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!s}}return {supported:true}}var gt=new Set(["init","test","build","start"]),yt=new Set([".git","node_modules",".workspai",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function B(e){try{return await U.promises.access(e,U.constants.F_OK),true}catch{return false}}async function ht(e){for(let r of e)if(await B(r))return true;return false}async function kt(e,r,t){if(r==="python"){let o=[k.join(e,".workspai","cli.py"),k.join(e,".rapidkit","cli.py")];for(let s of o)if(await B(s))return {valid:true};return {valid:false,reason:"Project-local .workspai/cli.py is missing. Run `workspai init` in this project first."}}let n=t.trim().split(/\s+/)[0];if(n&&["npm","npx","pnpm","yarn"].includes(n)){let o=e$3(n);if((await execa(o.command,[...o.prefixArgs,"--version"],{reject:false,env:g()})).exitCode===0)return {valid:true}}return re(t)}async function ne(e){let r=await U.promises.readFile(e,"utf-8");return JSON.parse(r)}function D(e){return e.replace(/\\/g,"/")}function bt(e){let r=e?.trim();return r?r.startsWith("project:")?r.slice(8).trim()||null:r:null}async function wt(e){let r=k.join(e,e$1.model);if(await B(r))try{let n=((await ne(r)).projects??[]).map(o=>typeof o.path=="string"?k.resolve(e,o.path):null).filter(o=>!!o).filter((o,s,u)=>u.indexOf(o)===s).filter(o=>U.existsSync(o));if(n.length>0)return n.sort()}catch{}return a$1(e,{skipDirs:yt,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t$1,n)=>await ht([...t(t$1,"context.json"),...t(t$1,"project.json")])?true:k.resolve(t$1)===k.resolve(n)?false:h(t$1).length>0})}async function xt(e){for(let r of [k.join(".workspai","project.json"),k.join(".workspai","context.json"),k.join(".rapidkit","project.json"),k.join(".rapidkit","context.json")]){let t=k.join(e,r);if(await B(t))try{let n=await ne(t),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function vt(e,r,t){let n=bt(t);if(!n)return {projects:r,normalizedScope:null};let o=D(n).toLowerCase(),s=[];for(let u of r){let c=D(k.relative(e,u)),m=k.basename(u),p=await xt(u);[c,m,p].filter(i=>typeof i=="string"&&i.length>0).map(i=>D(i).toLowerCase()).includes(o)&&s.push(u);}if(s.length===0)throw new Error(`Workspace run scope did not match any project: ${t}`);return {projects:s,normalizedScope:n}}async function Rt(e,r,t){let n=await execa("git",["diff","--name-only",`${t}...HEAD`],{cwd:e,reject:false,env:a$2()});if(n.exitCode!==0)return new Set(r);let o=n.stdout.split(/\r?\n/).map(u=>u.trim()).filter(u=>u.length>0).map(u=>D(u));if(o.length===0)return new Set;let s=new Set;for(let u of r){let c=D(k.relative(e,u));if(!c||c===".")continue;let m=`${c}/`;o.some(p=>p===c||p.startsWith(m))&&s.add(u);}return s}async function St(e,r,t){let n=await d$1(e,i.workspaceContract)??p(e,"workspace.contract.json");if(await B(n))try{let d=await Ct(e,r,t,n);if(d.graphStatus!=="missing")return d}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let o=await d$1(e,".workspai/workspace-dependency-graph.json")??p(e,"workspace-dependency-graph.json");if(!await B(o))return {expanded:t,graphStatus:"missing",expansionDepth:0};let s;try{s=await ne(o);}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let u=new Set(r.map(d=>k.resolve(d))),c=new Map;if(!s||typeof s!="object"||Array.isArray(s))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let m=Array.isArray(s.projects)?s.projects:[];for(let d of m){if(!d||typeof d!="object"||Array.isArray(d))continue;let i=d,l=typeof i.path=="string"?i.path:"",y=k.resolve(e,l);if(!u.has(y))continue;let b=Array.isArray(i.dependsOn)?i.dependsOn.filter(S=>typeof S=="string"):[];for(let S of b){let g=k.resolve(e,S);u.has(g)&&(c.has(g)||c.set(g,new Set),c.get(g)?.add(y));}}let p$1=d$2(c,t);return {expanded:p$1.reached,graphStatus:"loaded",expansionDepth:p$1.added}}async function Ct(e,r,t,n){let o=await ne(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let s=o,u=Array.isArray(s.projects)?s.projects:null;if(!u)return {expanded:t,graphStatus:"invalid",expansionDepth:0};let c=new Map,m=new Map;for(let y of r){let b=D(k.relative(e,y));m.set(b,k.resolve(y));}let p=new Map,d=new Map,i=new Map;for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=typeof b.relativePath=="string"?D(b.relativePath):S,v=m.get(g);!S||!v||c.set(S,v);}for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=c.get(S);if(!g)continue;let v=b.contracts&&typeof b.contracts=="object"&&!Array.isArray(b.contracts)?b.contracts:{},E=Array.isArray(v.dependsOn)?v.dependsOn.filter(R=>typeof R=="string"):[],W=Array.isArray(v.publishes)?v.publishes.filter(R=>typeof R=="string"):[],_=Array.isArray(v.consumes)?v.consumes.filter(R=>typeof R=="string"):[];for(let R of E){let j=c.get(R);j&&(i.has(j)||i.set(j,new Set),i.get(j)?.add(g));}for(let R of W)p.has(R)||p.set(R,new Set),p.get(R)?.add(g);for(let R of _)d.has(R)||d.set(R,new Set),d.get(R)?.add(g);}for(let[y,b]of p.entries()){let S=d.get(y);if(S)for(let g of b){i.has(g)||i.set(g,new Set);for(let v of S)v!==g&&i.get(g)?.add(v);}}let l=d$2(i,t);return {expanded:l.reached,graphStatus:"loaded",expansionDepth:l.added}}async function Et(e,r){if(typeof r=="boolean")return r;let t=s(e,"policies.yml").find(s=>U.existsSync(s))??p(e,"policies.yml");if(!await B(t))return true;let n="";try{n=await U.promises.readFile(t,"utf-8");}catch{return true}let o=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o?o[1]==="true":true}function jt(e){let r=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(r){let t=Number.parseInt(r,10);if(Number.isFinite(t)&&t>0)return t}return e==="init"?12e4:9e4}function Xe(e,r){let t=Number.parseInt(process.env[e]??"",10);return Number.isFinite(t)&&t>0?t:r}function he(e){return new Promise(r=>setTimeout(r,e))}async function Pt(e){let r=process.argv[1];if(e.useRapidkitWrapper&&!r)return {exitCode:1,stdout:"",stderr:"Workspai entrypoint is unavailable for startup verification.",healthStatus:{healthy:false,reason:"Workspai entrypoint is unavailable."}};let t=e.useRapidkitWrapper&&r?execa(process.execPath,[r,"start"],{cwd:e.projectPath,reject:false,timeout:e.timeoutMs,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}}):execa(e.finalCommand,[],{cwd:e.projectPath,reject:false,shell:true,timeout:e.timeoutMs}),n=Promise.resolve(t).then(d=>({kind:"exit",result:d}),d=>({kind:"error",error:d})),o=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_GRACE_MS",2e3),s=await Promise.race([n,he(o).then(()=>({kind:"alive"}))]);if(s.kind==="error"){let d=typeof s.error=="object"&&s.error!==null&&"timedOut"in s.error&&!!s.error.timedOut;return {exitCode:d?124:1,stdout:"",stderr:s.error instanceof Error?s.error.message:String(s.error),timedOut:d,healthStatus:{healthy:false,reason:"The start command failed before readiness."}}}if(s.kind==="exit"){let d=Number(s.result.exitCode??0);return {exitCode:d,stdout:String(s.result.stdout??""),stderr:String(s.result.stderr??""),healthStatus:{healthy:d===0,reason:d===0?"The start command completed successfully.":`The start command exited with code ${d} before readiness.`}}}let u=te(e.runtime,e.framework)?.healthCheck,c=u?{healthy:false,reason:"The configured health check has not passed yet."}:{healthy:true,reason:`The service remained alive for ${o}ms (bounded startup smoke).`};if(u){let d=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_HEALTH_TIMEOUT_MS",15e3),i=Date.now()+d;for(;Date.now()<i;){let l=await qe(u,e.projectPath);if(c={healthy:l.healthy,reason:l.reason},l.healthy)break;if((await Promise.race([n,he(350).then(()=>({kind:"alive"}))])).kind!=="alive"){c={healthy:false,reason:"The service exited before its configured health check passed."};break}}}try{t.kill?.("SIGTERM",{forceKillAfterDelay:1e3});}catch{try{t.kill?.();}catch{}}let m=await Promise.race([n,he(2e3).then(()=>({kind:"alive"}))]),p=m.kind==="exit"?m.result:void 0;return {exitCode:c.healthy?0:1,stdout:String(p?.stdout??""),stderr:String(p?.stderr??""),healthStatus:c}}async function ke(e,r,t){let n=process.argv[1];if(!n)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};try{let o=await execa(process.execPath,[n,...e],{cwd:r,reject:false,timeout:t,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr}}catch(o){return {exitCode:typeof o=="object"&&o!==null&&"timedOut"in o&&!!o.timedOut?124:1,stdout:typeof o=="object"&&o!==null&&"stdout"in o?String(o.stdout??""):"",stderr:typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr??""):o instanceof Error?o.message:String(o)}}}function At(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"||e==="rust"||e==="php"}function Ft(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}function Ot(e,r=8){if(e.length<=r)return e.join(`
|
|
1
|
+
import {d,b,e}from'./chunk-W6FHVXNL.js';import {a}from'./chunk-2647BYBC.js';import {a as a$1}from'./chunk-27UR373Z.js';import {d as d$2}from'./chunk-S5KTATOU.js';import {p as p$1,w,t as t$1}from'./chunk-SCP5LJNO.js';import {h,j,f,e as e$2}from'./chunk-ZCPT6KC3.js';import {d as d$1}from'./chunk-CCDGHPEJ.js';import {e as e$1,i}from'./chunk-NZ3WZYD5.js';import {a as a$2}from'./chunk-TQEMLBAG.js';import {t,p,s}from'./chunk-MOSXTVPU.js';import {e as e$3,g}from'./chunk-RJIYCDVC.js';import U from'fs';import k from'path';import T from'chalk';import {execa}from'execa';function Le(e){return U.existsSync(k.join(e,"bun.lock"))||U.existsSync(k.join(e,"bunfig.toml"))?"bun":U.existsSync(k.join(e,"pnpm-lock.yaml"))?"pnpm":U.existsSync(k.join(e,"yarn.lock"))?"yarn":(U.existsSync(k.join(e,"package-lock.json")),"npm")}function Ge(e,r,t=Le(e)){return t==="npm"?`npm run ${r}`:`${t} run ${r}`}function Be(e,r=Le(e)){return `${r} install`}var ct={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},dt={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],c:["cmake -S . -B build"],cpp:["cmake -S . -B build"],elixir:["mix deps.get"],ruby:["bundle install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],c:["ctest --test-dir build --output-on-failure"],cpp:["ctest --test-dir build --output-on-failure"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],c:["cmake --build build"],cpp:["cmake --build build"],elixir:["mix compile"],ruby:["gem build *.gemspec"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],c:[],cpp:[],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function te(e,r){if(r){let t=r.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=e$2(r),s=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:t==="fiber"?"fiber":t==="aspnetcore"||t==="asp-net-core"?"aspnetcore":t}`;return ct[s]}}function He(e,r,t){if(r){let n=te(e,r);if(n&&n.commands[t])return n.commands[t]}if(["init","test","build","start"].includes(t)){let n=dt[t]?.[e]??[];return n.length>0?n[0]:void 0}}var lt={test:"test",build:"build",start:"start"};function ge(e){if(e.stage==="init")return e.runtime==="node"?Be(e.projectPath):He(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let r=lt[e.stage];if(r){let t=t$1(e.projectPath,r,{framework:e.framework});if(t)return Ge(e.projectPath,t.scriptName)}}return He(e.runtime,e.framework,e.stage)}function mt(e){let r=h(e).map(t=>t==="python"?"python":t==="node"||t==="bun"?"node":t==="go"?"go":t==="java"?"java":t==="php"?"php":t==="rust"?"rust":t==="dotnet"?"dotnet":t==="elixir"?"elixir":t==="ruby"?"ruby":t==="clojure"||t==="scala"||t==="kotlin"?"jvm-generic":null).filter(t=>t!==null).filter((t,n,o)=>o.indexOf(t)===n);return {primary:r.length>0?r[0]:"unknown",secondary:r.slice(1)}}function ze(e){return mt(e).primary}function ye(e,r){if(!e)return "unknown";r||(r={setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[t,n]of Object.entries(r))for(let o of n)if(new RegExp(o,"i").test(e))return t;return "unknown"}async function re(e){let r=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(r))return {valid:true};try{let n=process.platform==="win32"?"where":"which";if((await execa(n,[r],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${r}' not found or not executable`}}function Je(e,r,t){if(!r)return e;let n=typeof r=="object"&&!Array.isArray(r)&&("dev"in r||"staging"in r||"prod"in r||"default"in r)&&!Object.keys(r).some(o=>["init","test","build","start"].includes(o))?r:{};return t&&typeof n[t]=="string"?n[t]:typeof n.default=="string"?n.default:e}async function qe(e,r){if(!e)return {healthy:true};switch(e.type){case "port":{let t=e.value;try{let n=await import('net');return new Promise(o=>{let s=new n.Socket,u=5e3;s.setTimeout(u),s.on("connect",()=>{s.destroy(),o({healthy:true,reason:`Port ${t} is listening`});}),s.on("timeout",()=>{s.destroy(),o({healthy:false,reason:`Port ${t} timeout after ${u}ms`});}),s.on("error",c=>{s.destroy(),o({healthy:false,reason:`Port ${t} error: ${String(c)}`});}),s.connect(t,"localhost");})}catch(n){return {healthy:false,reason:`Port check error: ${n instanceof Error?n.message:String(n)}`}}}case "http":{let t=e.value,n;try{let o=new AbortController;n=setTimeout(()=>o.abort(),5e3);let s=await fetch(t,{method:"GET",signal:o.signal});return {healthy:s.status===200,reason:`HTTP ${s.status}`,metadata:{status:s.status}}}catch(o){return {healthy:false,reason:`HTTP check error: ${o instanceof Error?o.message:String(o)}`}}finally{n&&clearTimeout(n);}}case "log":{let t=e.value;if(!r)return {healthy:true};try{let n=[k.join(r,".workspai","last-run.log"),k.join(r,".rapidkit","last-run.log")].find(o=>U.existsSync(o));if(n){let o=U.readFileSync(n,"utf-8"),s=new RegExp(t,"i");return {healthy:s.test(o),reason:s.test(o)?"Log pattern found":"Log pattern not found"}}return {healthy:true,reason:"No log file to check"}}catch(n){return {healthy:false,reason:`Log check error: ${n instanceof Error?n.message:String(n)}`}}}case "command":{let t=e.value;try{let n=await execa(t,[],{cwd:r,reject:false,shell:true});return {healthy:n.exitCode===0,reason:n.exitCode===0?"Health check passed":"Health check failed",metadata:{exitCode:n.exitCode}}}catch(n){return {healthy:false,reason:`Command check error: ${n instanceof Error?n.message:String(n)}`}}}default:return {healthy:true}}}var Ye={init:"init",test:"test",build:"build",start:"start"};function pt(e){return e in Ye?Ye[e]:null}function ft(e,r){let n=p$1(e)?.contextJson?.commands;if(!n||typeof n!="object"||Array.isArray(n))return;let o=n[r];if(typeof o=="string"&&o.trim().length>0)return o.trim();if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,u=s.default??s.dev;if(typeof u=="string"&&u.trim().length>0)return u.trim()}}function Qe(e,r,t=w(e)){let n=pt(r);if(!n)return ft(e,r)?{supported:true}:{supported:false,reason:`Workspace stage "${r}" is not part of the Workspai fleet contract.`};if(!t.projectRoot)return {supported:false,reason:"No Workspai project metadata was detected for this target."};let o=t.commandMap[n];if(!o||o.status!=="supported"){let s=t.runtimeSupportTier==="observed"||t.frameworkSupportTier==="observed";return {supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!s}}return {supported:true}}var gt=new Set(["init","test","build","start"]),yt=new Set([".git","node_modules",".workspai",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function B(e){try{return await U.promises.access(e,U.constants.F_OK),true}catch{return false}}async function ht(e){for(let r of e)if(await B(r))return true;return false}async function kt(e,r,t){if(r==="python"){let o=[k.join(e,".workspai","cli.py"),k.join(e,".rapidkit","cli.py")];for(let s of o)if(await B(s))return {valid:true};return {valid:false,reason:"Project-local .workspai/cli.py is missing. Run `workspai init` in this project first."}}let n=t.trim().split(/\s+/)[0];if(n&&["npm","npx","pnpm","yarn"].includes(n)){let o=e$3(n);if((await execa(o.command,[...o.prefixArgs,"--version"],{reject:false,env:g()})).exitCode===0)return {valid:true}}return re(t)}async function ne(e){let r=await U.promises.readFile(e,"utf-8");return JSON.parse(r)}function D(e){return e.replace(/\\/g,"/")}function bt(e){let r=e?.trim();return r?r.startsWith("project:")?r.slice(8).trim()||null:r:null}async function wt(e){let r=k.join(e,e$1.model);if(await B(r))try{let n=((await ne(r)).projects??[]).map(o=>typeof o.path=="string"?k.resolve(e,o.path):null).filter(o=>!!o).filter((o,s,u)=>u.indexOf(o)===s).filter(o=>U.existsSync(o));if(n.length>0)return n.sort()}catch{}return a$1(e,{skipDirs:yt,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t$1,n)=>await ht([...t(t$1,"context.json"),...t(t$1,"project.json")])?true:k.resolve(t$1)===k.resolve(n)?false:h(t$1).length>0})}async function xt(e){for(let r of [k.join(".workspai","project.json"),k.join(".workspai","context.json"),k.join(".rapidkit","project.json"),k.join(".rapidkit","context.json")]){let t=k.join(e,r);if(await B(t))try{let n=await ne(t),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function vt(e,r,t){let n=bt(t);if(!n)return {projects:r,normalizedScope:null};let o=D(n).toLowerCase(),s=[];for(let u of r){let c=D(k.relative(e,u)),m=k.basename(u),p=await xt(u);[c,m,p].filter(i=>typeof i=="string"&&i.length>0).map(i=>D(i).toLowerCase()).includes(o)&&s.push(u);}if(s.length===0)throw new Error(`Workspace run scope did not match any project: ${t}`);return {projects:s,normalizedScope:n}}async function Rt(e,r,t){let n=await execa("git",["diff","--name-only",`${t}...HEAD`],{cwd:e,reject:false,env:a$2()});if(n.exitCode!==0)return new Set(r);let o=n.stdout.split(/\r?\n/).map(u=>u.trim()).filter(u=>u.length>0).map(u=>D(u));if(o.length===0)return new Set;let s=new Set;for(let u of r){let c=D(k.relative(e,u));if(!c||c===".")continue;let m=`${c}/`;o.some(p=>p===c||p.startsWith(m))&&s.add(u);}return s}async function St(e,r,t){let n=await d$1(e,i.workspaceContract)??p(e,"workspace.contract.json");if(await B(n))try{let d=await Ct(e,r,t,n);if(d.graphStatus!=="missing")return d}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let o=await d$1(e,".workspai/workspace-dependency-graph.json")??p(e,"workspace-dependency-graph.json");if(!await B(o))return {expanded:t,graphStatus:"missing",expansionDepth:0};let s;try{s=await ne(o);}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let u=new Set(r.map(d=>k.resolve(d))),c=new Map;if(!s||typeof s!="object"||Array.isArray(s))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let m=Array.isArray(s.projects)?s.projects:[];for(let d of m){if(!d||typeof d!="object"||Array.isArray(d))continue;let i=d,l=typeof i.path=="string"?i.path:"",y=k.resolve(e,l);if(!u.has(y))continue;let b=Array.isArray(i.dependsOn)?i.dependsOn.filter(S=>typeof S=="string"):[];for(let S of b){let g=k.resolve(e,S);u.has(g)&&(c.has(g)||c.set(g,new Set),c.get(g)?.add(y));}}let p$1=d$2(c,t);return {expanded:p$1.reached,graphStatus:"loaded",expansionDepth:p$1.added}}async function Ct(e,r,t,n){let o=await ne(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let s=o,u=Array.isArray(s.projects)?s.projects:null;if(!u)return {expanded:t,graphStatus:"invalid",expansionDepth:0};let c=new Map,m=new Map;for(let y of r){let b=D(k.relative(e,y));m.set(b,k.resolve(y));}let p=new Map,d=new Map,i=new Map;for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=typeof b.relativePath=="string"?D(b.relativePath):S,v=m.get(g);!S||!v||c.set(S,v);}for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=c.get(S);if(!g)continue;let v=b.contracts&&typeof b.contracts=="object"&&!Array.isArray(b.contracts)?b.contracts:{},E=Array.isArray(v.dependsOn)?v.dependsOn.filter(R=>typeof R=="string"):[],W=Array.isArray(v.publishes)?v.publishes.filter(R=>typeof R=="string"):[],_=Array.isArray(v.consumes)?v.consumes.filter(R=>typeof R=="string"):[];for(let R of E){let j=c.get(R);j&&(i.has(j)||i.set(j,new Set),i.get(j)?.add(g));}for(let R of W)p.has(R)||p.set(R,new Set),p.get(R)?.add(g);for(let R of _)d.has(R)||d.set(R,new Set),d.get(R)?.add(g);}for(let[y,b]of p.entries()){let S=d.get(y);if(S)for(let g of b){i.has(g)||i.set(g,new Set);for(let v of S)v!==g&&i.get(g)?.add(v);}}let l=d$2(i,t);return {expanded:l.reached,graphStatus:"loaded",expansionDepth:l.added}}async function Et(e,r){if(typeof r=="boolean")return r;let t=s(e,"policies.yml").find(s=>U.existsSync(s))??p(e,"policies.yml");if(!await B(t))return true;let n="";try{n=await U.promises.readFile(t,"utf-8");}catch{return true}let o=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o?o[1]==="true":true}function jt(e){let r=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(r){let t=Number.parseInt(r,10);if(Number.isFinite(t)&&t>0)return t}return e==="init"?12e4:9e4}function Xe(e,r){let t=Number.parseInt(process.env[e]??"",10);return Number.isFinite(t)&&t>0?t:r}function he(e){return new Promise(r=>setTimeout(r,e))}async function Pt(e){let r=process.argv[1];if(e.useRapidkitWrapper&&!r)return {exitCode:1,stdout:"",stderr:"Workspai entrypoint is unavailable for startup verification.",healthStatus:{healthy:false,reason:"Workspai entrypoint is unavailable."}};let t=e.useRapidkitWrapper&&r?execa(process.execPath,[r,"start"],{cwd:e.projectPath,reject:false,timeout:e.timeoutMs,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}}):execa(e.finalCommand,[],{cwd:e.projectPath,reject:false,shell:true,timeout:e.timeoutMs}),n=Promise.resolve(t).then(d=>({kind:"exit",result:d}),d=>({kind:"error",error:d})),o=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_GRACE_MS",2e3),s=await Promise.race([n,he(o).then(()=>({kind:"alive"}))]);if(s.kind==="error"){let d=typeof s.error=="object"&&s.error!==null&&"timedOut"in s.error&&!!s.error.timedOut;return {exitCode:d?124:1,stdout:"",stderr:s.error instanceof Error?s.error.message:String(s.error),timedOut:d,healthStatus:{healthy:false,reason:"The start command failed before readiness."}}}if(s.kind==="exit"){let d=Number(s.result.exitCode??0);return {exitCode:d,stdout:String(s.result.stdout??""),stderr:String(s.result.stderr??""),healthStatus:{healthy:d===0,reason:d===0?"The start command completed successfully.":`The start command exited with code ${d} before readiness.`}}}let u=te(e.runtime,e.framework)?.healthCheck,c=u?{healthy:false,reason:"The configured health check has not passed yet."}:{healthy:true,reason:`The service remained alive for ${o}ms (bounded startup smoke).`};if(u){let d=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_HEALTH_TIMEOUT_MS",15e3),i=Date.now()+d;for(;Date.now()<i;){let l=await qe(u,e.projectPath);if(c={healthy:l.healthy,reason:l.reason},l.healthy)break;if((await Promise.race([n,he(350).then(()=>({kind:"alive"}))])).kind!=="alive"){c={healthy:false,reason:"The service exited before its configured health check passed."};break}}}try{t.kill?.("SIGTERM",{forceKillAfterDelay:1e3});}catch{try{t.kill?.();}catch{}}let m=await Promise.race([n,he(2e3).then(()=>({kind:"alive"}))]),p=m.kind==="exit"?m.result:void 0;return {exitCode:c.healthy?0:1,stdout:String(p?.stdout??""),stderr:String(p?.stderr??""),healthStatus:c}}async function ke(e,r,t){let n=process.argv[1];if(!n)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};try{let o=await execa(process.execPath,[n,...e],{cwd:r,reject:false,timeout:t,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr}}catch(o){return {exitCode:typeof o=="object"&&o!==null&&"timedOut"in o&&!!o.timedOut?124:1,stdout:typeof o=="object"&&o!==null&&"stdout"in o?String(o.stdout??""):"",stderr:typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr??""):o instanceof Error?o.message:String(o)}}}function At(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"||e==="rust"||e==="php"}function Ft(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}function Ot(e,r=8){if(e.length<=r)return e.join(`
|
|
2
2
|
`);let t=3;return [...e.slice(0,t),...e.slice(-(r-t))].join(`
|
|
3
3
|
`)}function Tt(e){let r=/(?:\bnot found\b|\bno such\b|\bmissing\b|\bfailed\b|\berror\b|\bexception\b|\bcannot\b|\bdenied\b|\btimeout\b|\btimed out\b|\benoent\b|\beacces\b|\beperm\b)/i;return [...e].reverse().find(t=>r.test(t))??e.at(-1)}async function Mt(e){let r=process.cwd();try{process.chdir(e);let{handleInitCommand:t}=await import('./index.js');return {exitCode:await t(["init"]),stdout:"",stderr:""}}finally{process.chdir(r);}}async function Ze(e){let r=i=>{let l=f(i);return l==="node"||l==="bun"?"node":l==="python"?"python":l==="go"?"go":l==="java"?"java":l==="php"?"php":l==="ruby"?"ruby":l==="rust"?"rust":l==="dotnet"?"dotnet":l==="elixir"?"elixir":l==="clojure"||l==="scala"||l==="kotlin"?"jvm-generic":ze(e)},t=i=>{if(!i)return;let l=e$2(i);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(l))return l},n=p$1(e),o=n?.detection??j(e,n?.projectJson??null),s=n?.contextJson,u=r(o.runtime),c=t(o.key),m={},p=new Set(["init","test","build","start"]);if(s?.commands&&typeof s.commands=="object")for(let[i,l]of Object.entries(s.commands))typeof l=="string"&&p.has(i)&&(m[i]=l);let d;if(s?.commandEnvironments&&typeof s.commandEnvironments=="object"){let i=s.commandEnvironments;d={dev:typeof i.dev=="string"?i.dev:void 0,staging:typeof i.staging=="string"?i.staging:void 0,prod:typeof i.prod=="string"?i.prod:void 0,default:typeof i.default=="string"?i.default:void 0};}return {runtime:u,framework:c,commandOverrides:Object.keys(m).length>0?m:void 0,environmentCommandVariants:d,environment:typeof s?.environment=="string"?s.environment:void 0}}async function et(e,r,t,n,o,s,u){let c=!o?.[r]&&At(t),m;if(o&&o[r]?m=o[r]:c?m=`rapidkit ${r}`:m=ge({projectPath:e,runtime:t,framework:n,stage:r}),!m)return {exitCode:127,command:`<stage not supported for ${t}>`,message:`No stage command found for runtime '${t}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let p=Je(m,s,u);if(!p)return {exitCode:127,command:m,message:"Failed to resolve stage command",errorCategory:"runtime"};let d=ge({projectPath:e,runtime:t,framework:n,stage:r});if(c){if(d){let x=c?await kt(e,t,d):await re(d);if(!x.valid)return {exitCode:127,command:p,message:x.reason||"Command not available",errorCategory:"setup"}}}else {let x=await re(p);if(!x.valid)return {exitCode:127,command:p,message:x.reason||"Command not available",errorCategory:"setup"}}let i=0,l="",y="",b,S,g=jt(r),v=Date.now();try{let x=r==="start"?await Pt({projectPath:e,finalCommand:p,useRapidkitWrapper:c,runtime:t,framework:n,timeoutMs:g}):c?r==="init"&&Ft()?await Mt(e):await ke([r],e,g):await execa(p,[],{cwd:e,reject:false,shell:true,timeout:g});if(i=Number(x.exitCode??0),l=x.stdout,y=x.stderr,S=r==="start"?x.healthStatus:void 0,i!==0){let I=`${l}
|
|
4
4
|
${y}`,V=Date.now()-v;b=i===124||ye(I)==="timeout"||i===143&&V>=Math.floor(g*.8)?"timeout":ye(I);}}catch(x){let I=typeof x=="object"&&x!==null&&"timedOut"in x&&!!x.timedOut;return {exitCode:I?124:1,command:p,message:I?`Stage timed out after ${g}ms`:x instanceof Error?x.message:"Command execution failed",errorCategory:I?"timeout":"runtime"}}let E=`${l}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {l}from'./chunk-KNTPDRZB.js';import {b}from'./chunk-GPOZILMY.js';import {a as a$1}from'./chunk-A4BK7C7M.js';import {c}from'./chunk-EWZZUQBR.js';import {b as b$1}from'./chunk-D65FCQIO.js';import {a}from'./chunk-AFIFZTOY.js';import {h,i,e}from'./chunk-NZ3WZYD5.js';import he from'crypto';import G from'fs';import M from'fs/promises';import f from'path';var te=h.projectAgentEntry.schemaVersion,I=i.projectAgentEntry,fe="workspai.agent-bootstrap-receipt.v1",_e="<!-- WORKSPAI:AGENT-ENTRY:START -->",Ne="<!-- WORKSPAI:AGENT-ENTRY:END -->",O=["generic","codex","claude","gemini","qwen","kimi","grok","copilot","cursor","windsurf","amazon-q"],He=["CLAUDE.md","GEMINI.md","QWEN.md",".amazonq/rules/workspai-agent-entry.md"];function me(t){let s=t?.trim().toLowerCase()||"generic";if(s==="orca")return "grok";if(O.includes(s))return s;throw new Error(`Unsupported agent host "${s}". Expected one of: ${O.join(", ")}.`)}function oe(t){let s=t.map(i=>i.id).sort(),n=[...O].sort();if(s.length!==n.length||s.some((i,c)=>i!==n[c]))throw new Error("Project agent entry must define each supported host exactly once.")}function L(t){let{integrity:s,...n}=t;return n}function j(t){return c(t)}function Ge(t){oe(t.hosts);let s={schemaVersion:te,generatedAt:t.context.generatedAt,project:{name:t.context.project.name,relativePath:t.context.project.relativePath,...t.context.project.runtime?{runtime:t.context.project.runtime}:{},...t.context.project.framework?{framework:t.context.project.framework}:{}},workspace:{name:t.context.workspace.name,relationship:t.context.workspace.relationship,localBinding:i.projectWorkspaceLink,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},canonical:{projectContext:i.projectContextAgent,projectGrounding:".workspai/PROJECT-GROUNDING.md",goalIndex:`workspace:${i.goalIndex}`,workspaceIndex:`workspace:${e.agentIndex}`,workspaceContext:`workspace:${e.agentContext}`,workspaceModel:`workspace:${e.model}`,knowledgeGraph:`workspace:${e.knowledgeGraph}`},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:[I,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",i.projectContextAgent,`workspace:${i.goalIndex}`,`workspace:${e.agentIndex}`,`workspace:${e.agentContext}`,`workspace:${e.model}`,`workspace:${e.knowledgeGraph}`,"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.hosts].sort((i,c)=>i.id.localeCompare(c.id))},n={...s,integrity:{algorithm:"sha256",projectContextHash:t.context.integrity.payloadHash,payloadHash:j(s),portable:true,absolutePathsEmitted:false}};if(!w(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 w(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(w):t&&typeof t=="object"?Object.values(t).every(w):true}async function ue(t){let s=f.join(t,I),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!==j(L(n)))throw new Error("Project agent entry integrity validation failed.");if(oe(n.hosts),!w(n)||n.integrity.absolutePathsEmitted)throw new Error("Project agent entry contains a non-portable local path.");return n}async function ye(t){let s=f.join(t,i.projectContextAgent),n=JSON.parse(await M.readFile(s,"utf8"));a(n,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent");let i$1=L(n),c=he.createHash("sha256").update(JSON.stringify(i$1)).digest("hex");if(n.integrity.payloadHash!==c)throw new Error("Project context agent integrity validation failed.");if(!w(n)||n.integrity.absolutePathsEmitted)throw new Error("Project context agent contains a non-portable local path.");return n}function we(t){return t.includes("blocked")?"blocked":t.includes("degraded")?"degraded":"ready"}async function Oe(t){let s=b({startPath:f.resolve(t.startPath??process.cwd()),strict:true,requireProjectMembership:true});if(!s?.projectPath)throw new Error("No canonically bound Workspai project was resolved.");let n=s.projectPath,i$1=s.workspacePath,c=await ue(n),o=await ye(n);if(c.integrity.projectContextHash!==o.integrity.payloadHash||c.project.name!==o.project.name||c.workspace.name!==o.workspace.name)throw new Error("Project agent entry is not bound to the current project context.");let $=t.forAgent?.trim().toLowerCase()||"generic",F=$==="all",g=F?"all":me($),W=g,h=F?c.hosts:c.hosts.filter(e=>e.id===g),K=c.hosts.find(e=>e.id==="generic");if(h.length===0&&K&&h.push(K),h.length===0)throw new Error("Project agent entry does not define generic host coverage.");let k=[],p=(e,r,R,u)=>k.push({id:e,status:r,message:R,...u?{artifact:u}:{}});p("workspace-binding","passed","Canonical workspace membership is resolved."),p("entry-integrity","passed","Project entry manifest integrity is valid.",I),p("project-context-integrity","passed","Project context integrity and manifest binding are valid.",i.projectContextAgent);let b$2=[...new Set(h.flatMap(e=>e.entryFiles))].sort(),ne=b$2.filter(e=>!G.existsSync(f.join(n,e))),m=h.some(e=>e.status==="blocked")||ne.length>0?"blocked":h.some(e=>e.status==="degraded")?"degraded":"ready";p("host-discovery",m==="ready"?"passed":m==="degraded"?"warning":"failed",m==="ready"?`${g} has discoverable Workspai entry coverage.`:m==="degraded"?h.find(e=>e.reason)?.reason??`${g} entry coverage is degraded.`:`${g} entry coverage is missing required files.`,b$2[0]);let V=[e.agentIndex,e.agentContext,e.model,e.knowledgeGraph],v=V.filter(e=>!G.existsSync(f.join(i$1,e)));p("canonical-evidence",v.length===0?"passed":"failed",v.length===0?"Required canonical workspace evidence is present.":`Required canonical evidence is missing: ${v.join(", ")}.`);let A=[],P=null,q=null;for(let e$1 of V)if(!v.includes(e$1))try{let r=JSON.parse(await M.readFile(f.join(i$1,e$1),"utf8"));b$1(e$1,r,e$1),e$1===e.model&&(P=r),e$1===e.knowledgeGraph&&(q=r);}catch{A.push(e$1);}p("canonical-contracts",A.length===0?"passed":"failed",A.length===0?"Canonical workspace evidence satisfies its published schemas.":`Canonical evidence failed contract validation: ${A.join(", ")}.`);let re=P?.workspace,se=q?.workspace,ae=Array.isArray(P?.projects)?P.projects:[],B=A.length===0&&re?.name===o.workspace.name&&se?.name===o.workspace.name&&ae.some(e=>e.name===o.project.name);p("canonical-project-membership",B?"passed":"failed",B?"The project and workspace identities agree across the entry, Model, and Graph.":"The project or workspace identity is missing or inconsistent in canonical evidence.");let J=!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",C=false,T;if(t.validateLiveInputs!==false)try{let e=await a$1(i$1);C=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}).`;T={id:"live-inputs",status:C?"passed":"failed",message:r};}catch{T={id:"live-inputs",status:"failed",message:"Live project inputs could not be validated against canonical graph evidence."};}else T={id:"live-inputs",status:"warning",message:"Live input validation was skipped; persisted compatibility was checked only."};let _=J==="warning"&&o.intelligence.freshness.model==="unknown"&&o.intelligence.freshness.graph==="fresh"&&o.intelligence.freshness.graphMatchesModel&&C?"passed":J;p("persisted-freshness",_,_==="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.":_==="warning"?"Persisted evidence is compatible, but at least one freshness state is unknown.":"Persisted Model or Knowledge Graph evidence is missing, stale, or mismatched."),k.push(T);let l$1={present:false,appliesToProject:false,status:"none"},x=[],ie=f.join(i$1,i.goalIndex);if(G.existsSync(ie)){let e=null;try{e=await l({workspacePath:i$1,validateBindings:false});}catch{x.push("workspai goal --list --json"),p("active-goal","failed","The Goal index is present but invalid.");}if(e?.active&&(l$1={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:i$1,validateBindings:true});r.active&&(l$1={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}`}),p("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 R=r instanceof Error?r.message:String(r),u=l$1.present&&/\bstale\b|--refresh/i.test(R);if(l$1.present&&(l$1.status=u?"stale":"invalid"),u&&l$1.objective){let y=e.active,ge=y?.scope.kind==="project"&&y.scope.projects.length===1?`project:${y.scope.projects[0]}`:y?.scope.kind==="project-set"&&y.scope.projects.length>1?`projects:${y.scope.projects.join(",")}`:"workspace";x.push(`workspai goal ${JSON.stringify(l$1.objective)} --scope ${ge} --for-agent generic --refresh --json`);}else x.push("workspai goal --status --json");p("active-goal","failed",u?"The selected Goal Pack is present but stale; regenerate it against current canonical evidence before acting.":l$1.present?"The selected Goal Pack is present but its canonical binding or handoff is invalid.":"The Goal index could not be validated.");}}else p("active-goal","passed","No Goal index is present for this workspace.");let ce=k.some(e=>e.status==="failed")?"blocked":k.some(e=>e.status==="warning")?"degraded":"ready",S=we([m,ce]),le=`command:workspai agent bootstrap --for-agent ${g} --strict --json`,pe=c.protocol.requiredReadOrder.map(e=>e==="command:workspai agent bootstrap --for-agent generic --strict --json"?le:e),U={schemaVersion:fe,generatedAt:(t.now??new Date).toISOString(),status:S,requestedAgent:W,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:I,schemaVersion:te,hostStatus:m,entryFiles:b$2},canonicalEvidence:{projectContext:i.projectContextAgent,workspaceIndex:`workspace:${e.agentIndex}`,workspaceContext:`workspace:${e.agentContext}`,workspaceModel:`workspace:${e.model}`,knowledgeGraph:`workspace:${e.knowledgeGraph}`,modelFreshness:o.intelligence.freshness.model,graphFreshness:o.intelligence.freshness.graph,graphMatchesModel:o.intelligence.freshness.graphMatchesModel,liveInputsValidated:C,blockerCount:o.blockers.length},activeGoal:l$1,requiredReadOrder:pe,claims:{architecture:S==="ready"?"allowed-with-citations":"prohibited",sourceInspection:"bounded-and-targeted",sourceMutation:"governed-cli-transaction-only",verification:"cli-evidence-only"},checks:k,nextActions:S==="ready"?[...l$1.present&&l$1.appliesToProject&&l$1.agentHandoff?[`read:${l$1.agentHandoff}`]:[],`workspai workspace graph search <task-query> --scope project:${o.project.name} --limit 12 --json`,"inspect only the returned proof paths and target source files"]:[...x,"workspai workspace intelligence run --for-agent generic --strict --json",`workspai agent bootstrap --for-agent ${g} --strict --json`]},Y=j(L(c)),de=j({manifestHash:Y,projectContextHash:o.integrity.payloadHash,requestedAgent:W,status:S,generatedAt:U.generatedAt}),D={...U,receiptId:de},N={...D,integrity:{algorithm:"sha256",manifestHash:Y,projectContextHash:o.integrity.payloadHash,payloadHash:j(D),portable:true,absolutePathsEmitted:false}};if(!w(N))throw new Error("Agent bootstrap receipt rejected a non-portable local path.");return a(N,"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json","Agent bootstrap receipt"),N}
|
|
2
|
+
export{te as a,I as b,fe as c,_e as d,Ne as e,O as f,He as g,me as h,Ge as i,Oe as j};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b,e,a as a$1}from'./chunk-VR6XMUF3.js';import {b as b$1,a}from'./chunk-UJXE4UAX.js';import {randomUUID}from'crypto';var i=null;function f(){return i}function V(t){let r=t.argv??process.argv,n=m(r.slice(2)),e$1={runId:randomUUID(),startedAt:new Date().toISOString(),command:n,cwd:t.cwd??process.cwd(),rapidkitVersion:t.rapidkitVersion,finalized:false};return i=e$1,b(e$1.runId),b$1(r)&&e(l(e$1,"run.started","info","CLI run started")),e$1}function A(t,r){if(!(!i||i.finalized)){if(i.finalized=true,!b$1()){i=null;return}t===0?e(l(i,"run.completed","info",r??"CLI run completed",{exitCode:t})):e(l(i,"run.failed","error",r??"CLI run failed",{exitCode:t})),i=null;}}function w(t=process.argv){a(t)==="json"&&(process.env.WORKSPAI_LOG_FORMAT="json",process.env.RAPIDKIT_LOG_FORMAT="json");let r=t.slice(0,2),n=m(t.slice(2));n.length!==t.length-2&&(process.argv=[...r,...n]);}function m(t){let r=[];for(let n=0;n<t.length;n+=1){let e=t[n];if(e!=="--log-json"){if(e==="--log-format"){n+=1;continue}e.startsWith("--log-format=")||r.push(e);}}return r}function l(t,r,n,e,o){return {schemaVersion:a$1,runId:t.runId,timestamp:new Date().toISOString(),level:n,event:r,component:"cli",message:e,command:t.command,metadata:{cwd:t.cwd,rapidkitVersion:t.rapidkitVersion,startedAt:t.startedAt,...o}}}var g=false;function L(t){if(g||!t?.force&&(process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"))return;g=true;let r=process.exit.bind(process);process.exit=(n=>{let e=typeof n=="number"?n:typeof n=="string"?Number.parseInt(n,10):0,o=Number.isFinite(e)?e:1;return A(o),r(n)});}function h(){return f()?.runId}function y(t,r){let{blockers:n,stderrTail:e,runId:o,generatedAt:p,...C}=r,x=p||(typeof t.generatedAt=="string"?t.generatedAt:void 0)||(typeof t.timestamp=="string"?t.timestamp:void 0)||new Date().toISOString();return {...t,...C,generatedAt:x,...n&&n.length>0?{blockers:n}:{},...e&&e.trim()?{stderrTail:e.trim()}:{},...o?{runId:o}:{}}}export{V as a,A as b,w as c,L as d,h as e,y as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import t from'picocolors';var e={brand:r=>t.cyan(r),accent:r=>t.magenta(r),value:r=>t.cyan(r),dim:r=>t.gray(r),muted:r=>t.dim(r),success:r=>t.green(r),warn:r=>t.yellow(r),error:r=>t.red(r),white:r=>t.white(r),bold:r=>t.bold(r)};export{e as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-A5FBGRJA.js';import {d as d$1,m}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-A5FBGRJA.js';import {d as d$1,m}from'./chunk-KG3TUTXU.js';import {d,e}from'./chunk-CCDGHPEJ.js';import {i,h}from'./chunk-NZ3WZYD5.js';import {s}from'./chunk-MOSXTVPU.js';import {s as s$1,q}from'./chunk-RJIYCDVC.js';import a from'path';import {existsSync}from'fs';import m$1 from'fs-extra';var f=i.workspaceRegistry,w=h.workspaceRegistry.schemaVersion;function E(r){return {slug:r.slug,relativePath:r.relativePath,framework:r.framework,kit:r.kit,source:r.source}}async function b(r){let e=s(r,"workspace.json").find(t=>existsSync(t));if(!e)return {exists:false,legacyProjectCount:0};try{let t=await m$1.readJson(e),c=Array.isArray(t.projects)?t.projects.length:0,o=typeof t.workspace_name=="string"&&t.workspace_name.trim()||typeof t.name=="string"&&t.name.trim()||a.basename(r);return {exists:true,manifestPath:e,workspaceName:o,profile:typeof t.profile=="string"?t.profile:void 0,legacyProjectCount:c}}catch{return {exists:true,manifestPath:e,legacyProjectCount:0,workspaceName:a.basename(r)}}}async function _(r){let e=a$1(r);for(let t of s$1())if(await m$1.pathExists(t))try{let o=((await m$1.readJson(t)).workspaces||[]).find(s=>a$1(s.path)===e);if(o)return {exists:true,projectCount:Array.isArray(o.projects)?o.projects.length:0,registryPath:t}}catch{continue}return {exists:false,projectCount:0,registryPath:a.join(q(),"workspaces.json")}}async function T(r,e){let t=a.resolve(r),c=await d(t,d$1),o=await b(t),s=await _(t),i=e?.contract!==void 0||!!c,n=[];if(e?.contract)n=e.contract.projects||[];else if(i)try{let{contract:A}=await m({workspacePath:t});n=A.projects||[];}catch{n=[];}let d$2={contract:{exists:i,projectCount:n.length,path:d$1},globalRegistry:{exists:s.exists,projectCount:s.projectCount,path:s.registryPath},legacyWorkspaceJson:{exists:o.exists,projectCount:o.legacyProjectCount,path:o.manifestPath?a.relative(t,o.manifestPath):void 0}},p="none",u=[],y=0;return i?(p="workspace.contract.json",u=n.map(E),y=u.length):s.projectCount>0?(p="global-registry",y=s.projectCount):o.legacyProjectCount>0&&(p="legacy-workspace.json",y=o.legacyProjectCount),{contractExists:i,summary:{schemaVersion:w,kind:"rapidkit.workspace.registry",workspacePath:t,workspaceName:o.workspaceName||a.basename(t),profile:o.profile,projectCount:y,authority:p,contractPath:d$1,projects:u,sources:d$2}}}async function U(r){let e=await d(r,f);if(!e)return null;try{let t=await m$1.readJson(e);return t?.schemaVersion!==w?null:t}catch{return null}}async function D(r,e$1){let t=await M(r,e$1);return await e(r,f,t),t}async function M(r,e){return {...(await T(r,{contract:e?.contract})).summary,generatedAt:(e?.now??new Date).toISOString(),registrySummaryPath:f}}function F(r,e=""){return r.projectCount>0?r.authority==="workspace.contract.json"?`${r.projectCount} project(s) registered in workspace contract${e}.`:r.authority==="global-registry"?`${r.projectCount} project(s) registered in global workspace registry${e}.`:`${r.projectCount} project(s) registered in legacy workspace manifest${e}.`:`Workspace state exists, but no projects are registered yet${e}.`}export{f as a,w as b,T as c,U as d,D as e,M as f,F as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {w}from'./chunk-WP3CXMVA.js';import {a as a$1}from'./chunk-T5YRFRJV.js';import {a}from'./chunk-GR6442P7.js';import {a as a$2,d,c,e as e$2}from'./chunk-CCDGHPEJ.js';import {b}from'./chunk-D65FCQIO.js';import {i,e,h,f}from'./chunk-NZ3WZYD5.js';import {l}from'./chunk-OCGZNSOE.js';import {e as e$1}from'./chunk-RO73VVHW.js';import {t,s}from'./chunk-MOSXTVPU.js';import g from'path';import h$1 from'fs-extra';var ue="unknown-run";function Z(e){let t=e$1();return !t||t===ue?e:{...e,runId:t}}var xe="workspace-dependency-graph.v1",Q=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],X=["inferred","contract","manual"];var E=i.workspaceContract,me=e.contractVerify,S=h.workspaceContract.schemaVersion,ge=f.contractVerify,x=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function ne(e){return e.replace(/\\/g,"/")}function V(e){let t=ne(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function ee(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function fe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function te(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(p=>{if(!p||typeof p!="object"||Array.isArray(p))return null;let c=p,m=Number(c.port);if(!Number.isInteger(m)||m<1||m>65535)return null;let d=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:m,protocol:d}}).filter(p=>p!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,a=Number(e.port??o?.default_port);return Number.isInteger(a)&&a>=1&&a<=65535?[{name:"http",port:a,protocol:"http"}]:[]}async function he(e){let t=g.join(e,"Dockerfile");if(!await h$1.pathExists(t))return [];try{let r=await h$1.readFile(t,"utf8"),o=new Map;for(let a of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let p of a[1].split(/\s+/)){let c=p.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),m=Number(c?.[1]);if(!c||!Number.isInteger(m)||m<1||m>65535)continue;let d=c[2]?.toLowerCase();o.set(m,{name:"http",port:m,protocol:d==="udp"?"udp":"http"});}return [...o.values()].sort((a,p)=>a.port-p.port)}catch{return []}}async function G(e){for(let t of e)if(await h$1.pathExists(t))return t;return null}async function ke(e){for(let t of s(e,"workspace.json"))try{let r=await h$1.readJson(t);return {name:typeof r.workspace_name=="string"&&r.workspace_name.trim()||typeof r.name=="string"&&r.name.trim()||g.basename(e),profile:typeof r.profile=="string"?r.profile:void 0}}catch{}return {name:g.basename(e)}}async function we(e){let t$1=[],r=[e],o=new Set,a$1=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let p=r.shift();if(!p||o.has(p))continue;o.add(p);let c=await G(t(p,"project.json")),m=await G(t(p,"context.json"));if(c||m){t$1.push(c??m??"");continue}let d;try{d=await h$1.readdir(p,{withFileTypes:true});}catch{continue}for(let l of d)!l.isDirectory()||a$1.has(l.name)||a(l.name)||r.push(g.join(p,l.name));}return t$1.sort()}function Pe(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function Ce(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("vscode-extension")?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function I(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function T(e,t,r){let o=e!==void 0&&e.source===void 0,a=Ce(t.kit,t.runtime),p=e?.ports||[],c=t.ports||[],m=(t.kit||"").toLowerCase().includes("vscode-extension"),d=t.source==="adopted-local"&&e?.source==="adopted-local",l=d,i=(m&&c.length===0?[]:d?c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]:p.length>0?p:c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]).map(P=>({...P,port:I(P.port,r)}));for(let P of i)r.add(P.port);let k={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&V(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:l?t.runtime:e?.runtime||t.runtime,framework:l?t.framework:e?.framework||t.framework,kit:l?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:i,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},f=JSON.stringify(e||null)!==JSON.stringify(k);return {project:k,changed:f}}async function ae(e){let t$1=g.resolve(e.workspacePath),r=await ke(t$1),o=await we(t$1),a=await a$1(t$1),p=[];for(let l of a){let s=g.resolve(l.path),i=await G(t(s,"project.json"))??await G(t(s,"context.json"));!i||o.some(k=>g.resolve(k)===g.resolve(i))||p.push({projectJsonPath:i,registryEntry:l});}let c=[],m=[...o.map(l=>({projectJsonPath:l})),...p];for(let{projectJsonPath:l,registryEntry:s}of m){let i=g.dirname(g.dirname(l)),k=ne(g.relative(t$1,i)),f=s!==void 0&&!V(k),P=ee(s?.name||g.basename(i),g.basename(i)),C=f?`external/${P}`:k||P,w=await h$1.readJson(l),j=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,n=typeof w.framework=="string"&&w.framework||Pe(j);c.push({slug:s?.name||C||g.basename(i),relativePath:C,source:s?.source??"workspace",relationship:s?.relationship,externalPath:f?i:void 0,runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:n,kit:j,modules:fe(w.modules),ports:te(w).length>0?te(w):await he(i),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let d=new Map;for(let l of c){let s=ee(l.slug,l.relativePath),i=d.get(s);(!i||i.source!=="workspace"&&l.source==="workspace")&&d.set(s,l);}return {schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function Ue(e){let t=g.resolve(e.outputPath||a$2(e.workspacePath,E));if(await h$1.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await ae({workspacePath:e.workspacePath,now:e.now}),o=new Set,a={...r,projects:r.projects.map(c=>T(void 0,c,o).project)},p=await ie({workspacePath:e.workspacePath,contractPath:t,contract:a});if(e.strict&&p.status==="failed")throw new x(p);return await se({workspacePath:e.workspacePath,contractPath:t,contract:a,now:e.now}),{contractPath:t,contract:a}}async function ze(e){let t=g.resolve(e.workspacePath),r=a$2(t,E),o=await d(t,E)??r,a=await ae({workspacePath:t,now:e.now}),p=await h$1.pathExists(o)?await h$1.readJson(o):null,c=new Map((p?.projects||[]).map(f=>[f.slug,f])),m=new Set,d$1=[],l=[],s=[];for(let f of a.projects){let P=c.get(f.slug),C=T(P,f,m);P?C.changed&&l.push(f.slug):d$1.push(f.slug),s.push(C.project),c.delete(f.slug);}for(let f of c.values()){if(f.source)continue;let P=T(f,f,m);s.push(P.project);}let i={schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...p?.workspace||{},...a.workspace,name:a.workspace.name||p?.workspace?.name||g.basename(t)},projects:s.sort((f,P)=>f.slug.localeCompare(P.slug))},k=await ie({workspacePath:t,contractPath:r,contract:i});if(e.strict&&k.status==="failed")throw new x(k);return await se({workspacePath:t,contractPath:r,contract:i,now:e.now}),{contractPath:r,contract:i,addedProjects:d$1,updatedProjects:l,verification:k}}async function re(e){return await h$1.pathExists(e)?{exists:true,contents:await h$1.readFile(e)}:{exists:false}}async function oe(e,t){if(!t.exists){await h$1.remove(e);return}await h$1.outputFile(e,t.contents);}async function se(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-OV5KX3WC.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),a=a$2(e.workspacePath,r),p=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:m,...d}=c;return JSON.stringify(d)};if(await h$1.pathExists(e.contractPath)&&await h$1.pathExists(a)){let[c,m]=await Promise.all([h$1.readJson(e.contractPath),h$1.readJson(a)]);if(p(c)===p(e.contract)&&p(m)===p(o))return}b(E,e.contract),b(r,o),await c(e.workspacePath,E,async()=>{let[c,m]=await Promise.all([re(e.contractPath),re(a)]);try{if(e.contractPath===a$2(e.workspacePath,E)?await e$2(e.workspacePath,E,e.contract):(await h$1.ensureDir(g.dirname(e.contractPath)),await h$1.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await e$2(e.workspacePath,r,o);}catch(d){let s=(await Promise.allSettled([oe(e.contractPath,c),oe(a,m)])).filter(i=>i.status==="rejected");throw s.length>0?new AggregateError([d,...s.map(i=>i.reason)],"Workspace contract publication failed and rollback was incomplete."):d}});}async function ce(e){let t=e.contractPath??(await d(e.workspacePath,E)||a$2(e.workspacePath,E)),r=await h$1.readJson(t);return {contractPath:t,contract:r}}var ye={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function Ee(e,t){return t.externalPath?g.resolve(t.externalPath):g.resolve(e,t.relativePath)}async function be(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(ye))for(let a of o)await h$1.pathExists(g.join(e,a))&&t[r].push(a);try{let r=await h$1.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,a)=>o.localeCompare(a));return t}function A(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function We(e){try{let t=await h$1.readJson(g.join(e,"package.json")),r={runtime:A(t.dependencies),development:A(t.devDependencies),peer:A(t.peerDependencies),optional:A(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:A(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function ve(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await h$1.readFile(g.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,a)=>o.localeCompare(a))}catch{}return []}function Ae(e,t){try{let r=w(e);if(r.engine!=="unknown")return r;let o=h$1.pathExistsSync(g.join(e,"package.json"))?"npm":h$1.pathExistsSync(g.join(e,"pyproject.toml"))?"python":h$1.pathExistsSync(g.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Se(e,t,r){let o=e.projects.map(a=>({id:a.slug,path:a.relativePath,runtime:a.runtime,framework:a.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function Ye(e$1){let{contractPath:t,contract:r}=await ce(e$1),o=e$1.now??new Date,a=o.toISOString(),{buildWorkspaceModel:p,workspaceModelProjectTopology:c}=await import('./workspace-model-EIQSKDX7.js'),{hashWorkspaceModel:m}=await import('./workspace-model-hash-ZXYPIGCW.js'),d=await p({workspacePath:e$1.workspacePath,includeEvidence:false,now:o}),l=c(d)??Se(r,a,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(l.nodes.map(n=>[n.id,n.operationalProfile])),{buildWorkspaceKnowledgeGraph:i}=await import('./workspace-knowledge-graph-HZZP6ZRB.js'),k=await i({workspacePath:e$1.workspacePath,workspace:{name:d.workspace.name,...d.workspace.profile?{profile:d.workspace.profile}:{}},contract:r,projectTopology:l,now:o,projects:d.projects.map(n=>({id:n.name,path:n.path,...n.absolutePath?{absolutePath:n.absolutePath}:{},runtime:n.runtime,runtimeCandidates:n.runtimeCandidates,framework:n.framework,...n.kit?{kit:n.kit}:{}})),source:{kind:"workspace-model",artifact:e.model,hashAlgorithm:"sha256",hash:m(d)}}),f=await Promise.all(r.projects.map(async n=>{let u=Ee(e$1.workspacePath,n),[R,W,pe]=await Promise.all([be(u),We(u),ve(u)]),y=Ae(u,n);return {id:n.slug,label:n.slug,relativePath:n.relativePath,source:n.source,relationship:n.relationship,externalPath:n.externalPath,runtime:n.runtime??y.runtime,framework:n.framework??y.framework,kit:n.kit,modules:n.modules,ports:n.ports,apis:n.contracts.apis,owns:n.contracts.owns,env:[...new Set([...n.contracts.env,...pe])].sort((le,de)=>le.localeCompare(de)),contracts:{owns:[...n.contracts.owns],apis:[...n.contracts.apis],publishes:[...n.contracts.publishes],consumes:[...n.contracts.consumes],dependsOn:[...n.contracts.dependsOn],env:[...n.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:R,...W?{package:W}:{},...s.get(n.slug)?{operationalProfile:s.get(n.slug)}:{}}})),P=new Set(f.map(n=>n.id)),C=new Map,w=[];for(let n of r.projects){for(let u of n.contracts.dependsOn||[])P.has(u)&&w.push({from:u,to:n.slug,type:"dependency",label:"dependsOn"});for(let u of n.contracts.publishes||[])C.has(u)||C.set(u,new Set),C.get(u)?.add(n.slug);}for(let n of r.projects)for(let u of n.contracts.consumes||[]){let R=C.get(u);if(R)for(let W of R)W!==n.slug&&w.push({from:W,to:n.slug,type:"event",label:u});}let j={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:a,nodes:f.sort((n,u)=>n.id.localeCompare(u.id)),edges:w.sort((n,u)=>`${n.from}:${n.to}:${n.type}:${n.label}`.localeCompare(`${u.from}:${u.to}:${u.type}:${u.label}`)),dependencyGraph:l,knowledgeGraph:k,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:f.length,dependencyEdges:w.filter(n=>n.type==="dependency").length,eventEdges:w.filter(n=>n.type==="event").length,portCount:f.reduce((n,u)=>n+u.ports.length,0),apiCount:f.reduce((n,u)=>n+u.apis.length,0),relationshipEdges:l.stats.edgeCount,inferredEdges:l.stats.inferredEdges,authoritativeEdges:l.stats.authoritativeEdges,orphanProjects:l.stats.orphanCount,hotspotProjects:l.stats.hotspotCount,evidenceCoverageRatio:l.stats.evidenceCoverageRatio,edgeCoverageRatio:l.stats.edgeCoverageRatio,connectedProjects:l.stats.connectedNodeCount,lowConfidenceEdges:l.stats.lowConfidenceEdges,hasCycle:l.stats.hasCycle,manifestCount:f.reduce((n,u)=>n+u.files.manifests.length,0),entrypointCount:f.reduce((n,u)=>n+u.files.entrypoints.length,0),diagnostics:l.diagnostics?.length??0,relationshipKinds:Object.fromEntries(Q.map(n=>[n,l.edges.filter(u=>u.kind===n).length])),relationshipSources:Object.fromEntries(X.map(n=>[n,l.edges.filter(u=>u.source===n).length])),entityCount:k.quality.entityCount,knowledgeRelations:k.quality.relationCount,proofCount:k.quality.proofCount,providerCount:k.providers.length,knowledgeUnknowns:k.quality.unknownCount}};return {contractPath:t,graph:j}}async function ie(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,E),contract:e.contract}:await ce(e),{contractPath:r,contract:o}=t,a=[],p=[];o.kind!=="rapidkit.workspace.contract"&&a.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==S&&a.push(`Contract schemaVersion must be ${S}.`),o.workspace?.name||a.push("Contract workspace.name is required."),Array.isArray(o.projects)||a.push("Contract projects must be an array.");let c=new Set,m=new Map;for(let s of o.projects||[]){if(!s.slug){a.push("Every project must declare slug.");continue}c.has(s.slug)&&a.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?V(s.relativePath)||a.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):a.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||a.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),g.isAbsolute(s.externalPath)||a.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let i of s.ports||[]){(!Number.isInteger(i.port)||i.port<1||i.port>65535)&&a.push(`Project ${s.slug} declares invalid port: ${i.port}.`);let k=m.get(i.port);k&&a.push(`Port ${i.port} is claimed by both ${k} and ${s.slug}.`),m.set(i.port,s.slug);}for(let i of s.contracts?.apis||[])(!i.name?.trim()||!i.basePath?.startsWith("/"))&&a.push(`Project ${s.slug} declares invalid API contract.`);for(let i of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])i.trim()||a.push(`Project ${s.slug} declares an empty event contract.`);for(let i of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(i)||a.push(`Project ${s.slug} declares invalid env contract: ${i}.`);for(let i of s.contracts?.dependsOn||[])c.has(i);}for(let s of o.projects||[])for(let i of s.contracts?.dependsOn||[])c.has(i)||a.push(`Project ${s.slug} depends on unknown project: ${i}.`);p.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===S?"passed":"failed",message:"Contract schema and kind are valid."}),p.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),p.push({id:"ports",status:a.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),p.push({id:"dependencies",status:a.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),p.push({id:"contracts",status:a.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let d=await l(e.workspacePath);if(d.moduleCount>0){for(let s of d.issues)a.push(`${g.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);p.push({id:"module-paths",status:d.status,message:d.status==="passed"?`All ${d.moduleCount} registered module(s) resolve under canonical paths.`:`${d.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&p.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:a.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:p,violations:a}}async function qe(e){let t=g.resolve(e.workspacePath),r={schemaVersion:ge,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return e$2(t,me,Z(r))}
|
|
1
|
+
import {w}from'./chunk-SCP5LJNO.js';import {a as a$1}from'./chunk-T5YRFRJV.js';import {a}from'./chunk-GR6442P7.js';import {a as a$2,d,c as c$1,e as e$1}from'./chunk-CCDGHPEJ.js';import {b}from'./chunk-D65FCQIO.js';import {i,e,h,f}from'./chunk-NZ3WZYD5.js';import {l}from'./chunk-OCGZNSOE.js';import {c}from'./chunk-VR6XMUF3.js';import {t,s}from'./chunk-MOSXTVPU.js';import g from'path';import h$1 from'fs-extra';var ue="unknown-run";function Z(e){let t=c();return !t||t===ue?e:{...e,runId:t}}var xe="workspace-dependency-graph.v1",Q=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],X=["inferred","contract","manual"];var E=i.workspaceContract,me=e.contractVerify,S=h.workspaceContract.schemaVersion,ge=f.contractVerify,x=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function ne(e){return e.replace(/\\/g,"/")}function V(e){let t=ne(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function ee(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function fe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function te(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(p=>{if(!p||typeof p!="object"||Array.isArray(p))return null;let c=p,m=Number(c.port);if(!Number.isInteger(m)||m<1||m>65535)return null;let d=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:m,protocol:d}}).filter(p=>p!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,a=Number(e.port??o?.default_port);return Number.isInteger(a)&&a>=1&&a<=65535?[{name:"http",port:a,protocol:"http"}]:[]}async function he(e){let t=g.join(e,"Dockerfile");if(!await h$1.pathExists(t))return [];try{let r=await h$1.readFile(t,"utf8"),o=new Map;for(let a of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let p of a[1].split(/\s+/)){let c=p.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),m=Number(c?.[1]);if(!c||!Number.isInteger(m)||m<1||m>65535)continue;let d=c[2]?.toLowerCase();o.set(m,{name:"http",port:m,protocol:d==="udp"?"udp":"http"});}return [...o.values()].sort((a,p)=>a.port-p.port)}catch{return []}}async function G(e){for(let t of e)if(await h$1.pathExists(t))return t;return null}async function ke(e){for(let t of s(e,"workspace.json"))try{let r=await h$1.readJson(t);return {name:typeof r.workspace_name=="string"&&r.workspace_name.trim()||typeof r.name=="string"&&r.name.trim()||g.basename(e),profile:typeof r.profile=="string"?r.profile:void 0}}catch{}return {name:g.basename(e)}}async function we(e){let t$1=[],r=[e],o=new Set,a$1=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let p=r.shift();if(!p||o.has(p))continue;o.add(p);let c=await G(t(p,"project.json")),m=await G(t(p,"context.json"));if(c||m){t$1.push(c??m??"");continue}let d;try{d=await h$1.readdir(p,{withFileTypes:true});}catch{continue}for(let l of d)!l.isDirectory()||a$1.has(l.name)||a(l.name)||r.push(g.join(p,l.name));}return t$1.sort()}function Pe(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function Ce(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("vscode-extension")?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function I(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function T(e,t,r){let o=e!==void 0&&e.source===void 0,a=Ce(t.kit,t.runtime),p=e?.ports||[],c=t.ports||[],m=(t.kit||"").toLowerCase().includes("vscode-extension"),d=t.source==="adopted-local"&&e?.source==="adopted-local",l=d,i=(m&&c.length===0?[]:d?c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]:p.length>0?p:c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]).map(P=>({...P,port:I(P.port,r)}));for(let P of i)r.add(P.port);let k={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&V(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:l?t.runtime:e?.runtime||t.runtime,framework:l?t.framework:e?.framework||t.framework,kit:l?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:i,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},f=JSON.stringify(e||null)!==JSON.stringify(k);return {project:k,changed:f}}async function ae(e){let t$1=g.resolve(e.workspacePath),r=await ke(t$1),o=await we(t$1),a=await a$1(t$1),p=[];for(let l of a){let s=g.resolve(l.path),i=await G(t(s,"project.json"))??await G(t(s,"context.json"));!i||o.some(k=>g.resolve(k)===g.resolve(i))||p.push({projectJsonPath:i,registryEntry:l});}let c=[],m=[...o.map(l=>({projectJsonPath:l})),...p];for(let{projectJsonPath:l,registryEntry:s}of m){let i=g.dirname(g.dirname(l)),k=ne(g.relative(t$1,i)),f=s!==void 0&&!V(k),P=ee(s?.name||g.basename(i),g.basename(i)),C=f?`external/${P}`:k||P,w=await h$1.readJson(l),j=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,n=typeof w.framework=="string"&&w.framework||Pe(j);c.push({slug:s?.name||C||g.basename(i),relativePath:C,source:s?.source??"workspace",relationship:s?.relationship,externalPath:f?i:void 0,runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:n,kit:j,modules:fe(w.modules),ports:te(w).length>0?te(w):await he(i),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let d=new Map;for(let l of c){let s=ee(l.slug,l.relativePath),i=d.get(s);(!i||i.source!=="workspace"&&l.source==="workspace")&&d.set(s,l);}return {schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function Ue(e){let t=g.resolve(e.outputPath||a$2(e.workspacePath,E));if(await h$1.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await ae({workspacePath:e.workspacePath,now:e.now}),o=new Set,a={...r,projects:r.projects.map(c=>T(void 0,c,o).project)},p=await ie({workspacePath:e.workspacePath,contractPath:t,contract:a});if(e.strict&&p.status==="failed")throw new x(p);return await se({workspacePath:e.workspacePath,contractPath:t,contract:a,now:e.now}),{contractPath:t,contract:a}}async function ze(e){let t=g.resolve(e.workspacePath),r=a$2(t,E),o=await d(t,E)??r,a=await ae({workspacePath:t,now:e.now}),p=await h$1.pathExists(o)?await h$1.readJson(o):null,c=new Map((p?.projects||[]).map(f=>[f.slug,f])),m=new Set,d$1=[],l=[],s=[];for(let f of a.projects){let P=c.get(f.slug),C=T(P,f,m);P?C.changed&&l.push(f.slug):d$1.push(f.slug),s.push(C.project),c.delete(f.slug);}for(let f of c.values()){if(f.source)continue;let P=T(f,f,m);s.push(P.project);}let i={schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...p?.workspace||{},...a.workspace,name:a.workspace.name||p?.workspace?.name||g.basename(t)},projects:s.sort((f,P)=>f.slug.localeCompare(P.slug))},k=await ie({workspacePath:t,contractPath:r,contract:i});if(e.strict&&k.status==="failed")throw new x(k);return await se({workspacePath:t,contractPath:r,contract:i,now:e.now}),{contractPath:r,contract:i,addedProjects:d$1,updatedProjects:l,verification:k}}async function re(e){return await h$1.pathExists(e)?{exists:true,contents:await h$1.readFile(e)}:{exists:false}}async function oe(e,t){if(!t.exists){await h$1.remove(e);return}await h$1.outputFile(e,t.contents);}async function se(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-VSOBKAJG.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),a=a$2(e.workspacePath,r),p=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:m,...d}=c;return JSON.stringify(d)};if(await h$1.pathExists(e.contractPath)&&await h$1.pathExists(a)){let[c,m]=await Promise.all([h$1.readJson(e.contractPath),h$1.readJson(a)]);if(p(c)===p(e.contract)&&p(m)===p(o))return}b(E,e.contract),b(r,o),await c$1(e.workspacePath,E,async()=>{let[c,m]=await Promise.all([re(e.contractPath),re(a)]);try{if(e.contractPath===a$2(e.workspacePath,E)?await e$1(e.workspacePath,E,e.contract):(await h$1.ensureDir(g.dirname(e.contractPath)),await h$1.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await e$1(e.workspacePath,r,o);}catch(d){let s=(await Promise.allSettled([oe(e.contractPath,c),oe(a,m)])).filter(i=>i.status==="rejected");throw s.length>0?new AggregateError([d,...s.map(i=>i.reason)],"Workspace contract publication failed and rollback was incomplete."):d}});}async function ce(e){let t=e.contractPath??(await d(e.workspacePath,E)||a$2(e.workspacePath,E)),r=await h$1.readJson(t);return {contractPath:t,contract:r}}var ye={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function Ee(e,t){return t.externalPath?g.resolve(t.externalPath):g.resolve(e,t.relativePath)}async function be(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(ye))for(let a of o)await h$1.pathExists(g.join(e,a))&&t[r].push(a);try{let r=await h$1.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,a)=>o.localeCompare(a));return t}function A(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function We(e){try{let t=await h$1.readJson(g.join(e,"package.json")),r={runtime:A(t.dependencies),development:A(t.devDependencies),peer:A(t.peerDependencies),optional:A(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:A(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function ve(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await h$1.readFile(g.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,a)=>o.localeCompare(a))}catch{}return []}function Ae(e,t){try{let r=w(e);if(r.engine!=="unknown")return r;let o=h$1.pathExistsSync(g.join(e,"package.json"))?"npm":h$1.pathExistsSync(g.join(e,"pyproject.toml"))?"python":h$1.pathExistsSync(g.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Se(e,t,r){let o=e.projects.map(a=>({id:a.slug,path:a.relativePath,runtime:a.runtime,framework:a.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function Ye(e$1){let{contractPath:t,contract:r}=await ce(e$1),o=e$1.now??new Date,a=o.toISOString(),{buildWorkspaceModel:p,workspaceModelProjectTopology:c}=await import('./workspace-model-ETCLINRB.js'),{hashWorkspaceModel:m}=await import('./workspace-model-hash-ZXYPIGCW.js'),d=await p({workspacePath:e$1.workspacePath,includeEvidence:false,now:o}),l=c(d)??Se(r,a,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(l.nodes.map(n=>[n.id,n.operationalProfile])),{buildWorkspaceKnowledgeGraph:i}=await import('./workspace-knowledge-graph-3ZBPSAS7.js'),k=await i({workspacePath:e$1.workspacePath,workspace:{name:d.workspace.name,...d.workspace.profile?{profile:d.workspace.profile}:{}},contract:r,projectTopology:l,now:o,projects:d.projects.map(n=>({id:n.name,path:n.path,...n.absolutePath?{absolutePath:n.absolutePath}:{},runtime:n.runtime,runtimeCandidates:n.runtimeCandidates,framework:n.framework,...n.kit?{kit:n.kit}:{}})),source:{kind:"workspace-model",artifact:e.model,hashAlgorithm:"sha256",hash:m(d)}}),f=await Promise.all(r.projects.map(async n=>{let u=Ee(e$1.workspacePath,n),[R,W,pe]=await Promise.all([be(u),We(u),ve(u)]),y=Ae(u,n);return {id:n.slug,label:n.slug,relativePath:n.relativePath,source:n.source,relationship:n.relationship,externalPath:n.externalPath,runtime:n.runtime??y.runtime,framework:n.framework??y.framework,kit:n.kit,modules:n.modules,ports:n.ports,apis:n.contracts.apis,owns:n.contracts.owns,env:[...new Set([...n.contracts.env,...pe])].sort((le,de)=>le.localeCompare(de)),contracts:{owns:[...n.contracts.owns],apis:[...n.contracts.apis],publishes:[...n.contracts.publishes],consumes:[...n.contracts.consumes],dependsOn:[...n.contracts.dependsOn],env:[...n.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:R,...W?{package:W}:{},...s.get(n.slug)?{operationalProfile:s.get(n.slug)}:{}}})),P=new Set(f.map(n=>n.id)),C=new Map,w=[];for(let n of r.projects){for(let u of n.contracts.dependsOn||[])P.has(u)&&w.push({from:u,to:n.slug,type:"dependency",label:"dependsOn"});for(let u of n.contracts.publishes||[])C.has(u)||C.set(u,new Set),C.get(u)?.add(n.slug);}for(let n of r.projects)for(let u of n.contracts.consumes||[]){let R=C.get(u);if(R)for(let W of R)W!==n.slug&&w.push({from:W,to:n.slug,type:"event",label:u});}let j={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:a,nodes:f.sort((n,u)=>n.id.localeCompare(u.id)),edges:w.sort((n,u)=>`${n.from}:${n.to}:${n.type}:${n.label}`.localeCompare(`${u.from}:${u.to}:${u.type}:${u.label}`)),dependencyGraph:l,knowledgeGraph:k,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:f.length,dependencyEdges:w.filter(n=>n.type==="dependency").length,eventEdges:w.filter(n=>n.type==="event").length,portCount:f.reduce((n,u)=>n+u.ports.length,0),apiCount:f.reduce((n,u)=>n+u.apis.length,0),relationshipEdges:l.stats.edgeCount,inferredEdges:l.stats.inferredEdges,authoritativeEdges:l.stats.authoritativeEdges,orphanProjects:l.stats.orphanCount,hotspotProjects:l.stats.hotspotCount,evidenceCoverageRatio:l.stats.evidenceCoverageRatio,edgeCoverageRatio:l.stats.edgeCoverageRatio,connectedProjects:l.stats.connectedNodeCount,lowConfidenceEdges:l.stats.lowConfidenceEdges,hasCycle:l.stats.hasCycle,manifestCount:f.reduce((n,u)=>n+u.files.manifests.length,0),entrypointCount:f.reduce((n,u)=>n+u.files.entrypoints.length,0),diagnostics:l.diagnostics?.length??0,relationshipKinds:Object.fromEntries(Q.map(n=>[n,l.edges.filter(u=>u.kind===n).length])),relationshipSources:Object.fromEntries(X.map(n=>[n,l.edges.filter(u=>u.source===n).length])),entityCount:k.quality.entityCount,knowledgeRelations:k.quality.relationCount,proofCount:k.quality.proofCount,providerCount:k.providers.length,knowledgeUnknowns:k.quality.unknownCount}};return {contractPath:t,graph:j}}async function ie(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,E),contract:e.contract}:await ce(e),{contractPath:r,contract:o}=t,a=[],p=[];o.kind!=="rapidkit.workspace.contract"&&a.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==S&&a.push(`Contract schemaVersion must be ${S}.`),o.workspace?.name||a.push("Contract workspace.name is required."),Array.isArray(o.projects)||a.push("Contract projects must be an array.");let c=new Set,m=new Map;for(let s of o.projects||[]){if(!s.slug){a.push("Every project must declare slug.");continue}c.has(s.slug)&&a.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?V(s.relativePath)||a.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):a.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||a.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),g.isAbsolute(s.externalPath)||a.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let i of s.ports||[]){(!Number.isInteger(i.port)||i.port<1||i.port>65535)&&a.push(`Project ${s.slug} declares invalid port: ${i.port}.`);let k=m.get(i.port);k&&a.push(`Port ${i.port} is claimed by both ${k} and ${s.slug}.`),m.set(i.port,s.slug);}for(let i of s.contracts?.apis||[])(!i.name?.trim()||!i.basePath?.startsWith("/"))&&a.push(`Project ${s.slug} declares invalid API contract.`);for(let i of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])i.trim()||a.push(`Project ${s.slug} declares an empty event contract.`);for(let i of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(i)||a.push(`Project ${s.slug} declares invalid env contract: ${i}.`);for(let i of s.contracts?.dependsOn||[])c.has(i);}for(let s of o.projects||[])for(let i of s.contracts?.dependsOn||[])c.has(i)||a.push(`Project ${s.slug} depends on unknown project: ${i}.`);p.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===S?"passed":"failed",message:"Contract schema and kind are valid."}),p.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),p.push({id:"ports",status:a.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),p.push({id:"dependencies",status:a.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),p.push({id:"contracts",status:a.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let d=await l(e.workspacePath);if(d.moduleCount>0){for(let s of d.issues)a.push(`${g.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);p.push({id:"module-paths",status:d.status,message:d.status==="passed"?`All ${d.moduleCount} registered module(s) resolve under canonical paths.`:`${d.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&p.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:a.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:p,violations:a}}async function qe(e){let t=g.resolve(e.workspacePath),r={schemaVersion:ge,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return e$1(t,me,Z(r))}
|
|
2
2
|
export{Z as a,xe as b,Q as c,E as d,me as e,S as f,ge as g,x as h,we as i,ae as j,Ue as k,ze as l,ce as m,Ye as n,ie as o,qe as p};
|