workspai 0.75.2 → 0.77.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +2 -2
  2. package/contracts/agent-framework-capabilities.v1.json +2 -2
  3. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +12 -0
  4. package/contracts/create-planner-capabilities.v1.json +48 -0
  5. package/contracts/extension-cli-compatibility.v1.json +4 -2
  6. package/contracts/published-contract-catalog.v1.json +10 -0
  7. package/contracts/runtime-command-surface.v1.json +5 -1
  8. package/contracts/workspace-intelligence/agent-framework-admission-candidate.v2.json +217 -0
  9. package/contracts/workspace-intelligence/agent-framework-conformance-report.v2.json +274 -0
  10. package/contracts/workspace-intelligence/workspace-model.v1.json +4 -0
  11. package/contracts/workspace-intelligence-architecture.v1.json +7 -3
  12. package/dist/analyze-TJM66CPF.js +1 -0
  13. package/dist/autopilot-release-C7Q4OTPY.js +1 -0
  14. package/dist/capabilities-command-TIBIKWPK.js +1 -0
  15. package/dist/{chunk-K52IQX3J.js → chunk-223SWPTL.js} +1 -1
  16. package/dist/chunk-3EMAC3MF.js +4 -0
  17. package/dist/{chunk-GDOO2YZW.js → chunk-3EPR3D5Q.js} +1 -1
  18. package/dist/chunk-3SQIV3F4.js +1 -0
  19. package/dist/{chunk-ZI54C2AO.js → chunk-475GQJ2D.js} +1 -1
  20. package/dist/{chunk-P36TACKN.js → chunk-47UR6ZH4.js} +1 -1
  21. package/dist/{chunk-VHMDWRDG.js → chunk-4BPZJR4Z.js} +4 -4
  22. package/dist/{chunk-VWBWDDU2.js → chunk-4CXV3PPV.js} +1 -1
  23. package/dist/chunk-4ZUBPFSO.js +6 -0
  24. package/dist/chunk-5KXOV7W4.js +1 -0
  25. package/dist/chunk-6BO4QHKA.js +1 -0
  26. package/dist/{chunk-OA2YJN22.js → chunk-DWDYLKVW.js} +1 -1
  27. package/dist/{chunk-KDVNRNDU.js → chunk-DWKCFHHL.js} +1 -1
  28. package/dist/{chunk-EP7SUMAX.js → chunk-E7WJ2QX7.js} +1 -1
  29. package/dist/{chunk-FNVWDXK2.js → chunk-GLBFY7AB.js} +5 -5
  30. package/dist/{chunk-ZGVODK5C.js → chunk-HRVHQBTA.js} +1 -1
  31. package/dist/{chunk-WHBKKJ7L.js → chunk-IAXRGH4Q.js} +1 -1
  32. package/dist/chunk-IDETNYCF.js +1 -0
  33. package/dist/chunk-IHWS3ALP.js +2 -0
  34. package/dist/{chunk-FZWLWFR4.js → chunk-J2MPBSQJ.js} +1 -1
  35. package/dist/{chunk-PFAGXI3G.js → chunk-JVZA35OL.js} +1 -1
  36. package/dist/chunk-LUPKDFQ3.js +7 -0
  37. package/dist/chunk-N7DOKE7V.js +2 -0
  38. package/dist/chunk-O3TVVQ6X.js +6 -0
  39. package/dist/chunk-P5LI5DL3.js +1 -0
  40. package/dist/{chunk-4JXJRIJM.js → chunk-QCX6BO2M.js} +1 -1
  41. package/dist/chunk-SC43A6LH.js +97 -0
  42. package/dist/chunk-SEZTSMRR.js +1 -0
  43. package/dist/{chunk-COOVCORC.js → chunk-SVO2GGTV.js} +1 -1
  44. package/dist/{chunk-5K4O3TAW.js → chunk-TGNPMOM6.js} +1 -1
  45. package/dist/chunk-UNEK3VVR.js +2684 -0
  46. package/dist/{chunk-IKBE3HOH.js → chunk-UP3UWAJV.js} +1 -1
  47. package/dist/{chunk-LFY7KTPD.js → chunk-UTIK3K3M.js} +1 -1
  48. package/dist/{chunk-WXUCAVFT.js → chunk-V6HVDVKJ.js} +8 -8
  49. package/dist/chunk-WC2K5QFI.js +10 -0
  50. package/dist/{chunk-DTNOF3MP.js → chunk-X5XFT5UZ.js} +1 -1
  51. package/dist/{chunk-ADHX7D3F.js → chunk-ZIWWE4BQ.js} +1 -1
  52. package/dist/{create-ZFSFWAW3.js → create-YPAZJYCE.js} +1 -1
  53. package/dist/{doctor-4KL4XUCS.js → doctor-W5PXJ5FL.js} +1 -1
  54. package/dist/{goal-lifecycle-EXQZD7IA.js → goal-lifecycle-5R55CA7H.js} +1 -1
  55. package/dist/{goal-pack-DKJU2DEP.js → goal-pack-IS6GGJPH.js} +1 -1
  56. package/dist/index.d.ts +12 -6
  57. package/dist/index.js +181 -171
  58. package/dist/{pipeline-4GVAOCEN.js → pipeline-LW3SW2WT.js} +1 -1
  59. package/dist/platform-capabilities-RWOWND5Q.js +1 -0
  60. package/dist/{project-agent-entry-7QKNEEXP.js → project-agent-entry-5TYKK5IV.js} +1 -1
  61. package/dist/{project-intelligence-lens-IHRYCLNU.js → project-intelligence-lens-TEOSTKNU.js} +1 -1
  62. package/dist/{project-test-coverage-3P5FH6E5.js → project-test-coverage-T4TIWGKN.js} +1 -1
  63. package/dist/proof-carrying-change-2TKRADCW.js +1 -0
  64. package/dist/{pythonRapidkitExec-UMFLDIYR.js → pythonRapidkitExec-S35OEIEF.js} +1 -1
  65. package/dist/{verified-goal-XI4RQESU.js → verified-goal-RN4TOV34.js} +1 -1
  66. package/dist/{workspace-EYXAKMVI.js → workspace-A33YMF2N.js} +1 -1
  67. package/dist/{workspace-agent-sync-SN55KT6N.js → workspace-agent-sync-VCA4G4DT.js} +1 -1
  68. package/dist/{workspace-context-PW6ESEHH.js → workspace-context-YBWLSKR6.js} +1 -1
  69. package/dist/{workspace-contract-FPLFL4G3.js → workspace-contract-3QUZDBMM.js} +1 -1
  70. package/dist/{workspace-explain-TVQ5IF5D.js → workspace-explain-NXYRAQFI.js} +1 -1
  71. package/dist/{workspace-foundation-DWIJPZRH.js → workspace-foundation-DZ52PECX.js} +1 -1
  72. package/dist/{workspace-graph-stream-RUTNWLQB.js → workspace-graph-stream-4VT46HZ7.js} +1 -1
  73. package/dist/{workspace-intelligence-4CA2CSPZ.js → workspace-intelligence-FKYQQDJ6.js} +1 -1
  74. package/dist/{workspace-intelligence-runner-VM5SXXAT.js → workspace-intelligence-runner-3K2JZH6Q.js} +1 -1
  75. package/dist/{workspace-knowledge-graph-JXN2ZOAF.js → workspace-knowledge-graph-CPBKNXQI.js} +1 -1
  76. package/dist/workspace-knowledge-graph-snapshot-67XDXUOT.js +1 -0
  77. package/dist/{workspace-mcp-serve-4WN4CSD7.js → workspace-mcp-serve-UXPKX7K6.js} +1 -1
  78. package/dist/{workspace-model-D4IECQML.js → workspace-model-POCPMNRT.js} +1 -1
  79. package/dist/{workspace-onboarding-6XWDKLM5.js → workspace-onboarding-KLG3GG7S.js} +1 -1
  80. package/dist/{workspace-registry-summary-Y3ET36NH.js → workspace-registry-summary-M4WMFDQ4.js} +1 -1
  81. package/dist/{workspace-repair-engine-HBUXRHDY.js → workspace-repair-engine-2VGN42QD.js} +1 -1
  82. package/dist/workspace-run-5YQR7GEZ.js +1 -0
  83. package/dist/{workspace-verify-OOAZ3NMZ.js → workspace-verify-PLAKTF3J.js} +1 -1
  84. package/dist/{workspace-watch-BNM5B6HU.js → workspace-watch-VNU4KVYN.js} +1 -1
  85. package/docs/README.md +4 -2
  86. package/docs/agent-framework-adapters.md +168 -39
  87. package/docs/ci-workflows.md +40 -22
  88. package/docs/commands-reference.md +19 -8
  89. package/docs/create-planner-capabilities.md +1 -0
  90. package/docs/creating-workspaces-and-projects.md +28 -9
  91. package/docs/doctor-command.md +9 -4
  92. package/docs/model-gateways.md +204 -0
  93. package/docs/native-kit-baselines.md +4 -2
  94. package/docs/workspace-run.md +3 -1
  95. package/package.json +5 -1
  96. package/scripts/enterprise-package-smoke.mjs +200 -5
  97. package/dist/analyze-6UEBC5OJ.js +0 -1
  98. package/dist/autopilot-release-H5TO6NYY.js +0 -1
  99. package/dist/capabilities-command-VK3LQLP2.js +0 -1
  100. package/dist/chunk-3N27P3KO.js +0 -7
  101. package/dist/chunk-3RNWBFRP.js +0 -4
  102. package/dist/chunk-66O62XNJ.js +0 -97
  103. package/dist/chunk-7NKM6EHE.js +0 -7
  104. package/dist/chunk-BR6QIYQS.js +0 -1
  105. package/dist/chunk-DFREJHG7.js +0 -1
  106. package/dist/chunk-E42IFQFR.js +0 -6
  107. package/dist/chunk-EWD6QTAM.js +0 -2
  108. package/dist/chunk-G5UCEXP6.js +0 -1
  109. package/dist/chunk-JKAAKE4Z.js +0 -6
  110. package/dist/chunk-LARREYZN.js +0 -1
  111. package/dist/chunk-RGNCL5OB.js +0 -1
  112. package/dist/chunk-SZHRPELL.js +0 -1
  113. package/dist/chunk-VXFIMEC6.js +0 -2
  114. package/dist/chunk-X7OI24LO.js +0 -418
  115. package/dist/platform-capabilities-DB4BZPTD.js +0 -1
  116. package/dist/proof-carrying-change-O37XUPIZ.js +0 -1
  117. package/dist/workspace-knowledge-graph-snapshot-KBNUXA64.js +0 -1
  118. package/dist/workspace-run-VN7KV4BU.js +0 -1
@@ -568,10 +568,10 @@
568
568
  "path": "contracts/agent-framework-capabilities.v1.json"
569
569
  },
570
570
  "adapterManifestSchema": "contracts/workspace-intelligence/agent-framework-adapter-manifest.v1.json",
571
- "conformanceReportSchema": "contracts/workspace-intelligence/agent-framework-conformance-report.v1.json",
571
+ "conformanceReportSchema": "contracts/workspace-intelligence/agent-framework-conformance-report.v2.json",
572
572
  "changePlanSchema": "contracts/workspace-intelligence/agent-framework-change-plan.v1.json",
573
573
  "ownershipReceiptSchema": "contracts/workspace-intelligence/agent-framework-ownership-receipt.v1.json",
574
- "admissionCandidateSchema": "contracts/workspace-intelligence/agent-framework-admission-candidate.v1.json",
574
+ "admissionCandidateSchema": "contracts/workspace-intelligence/agent-framework-admission-candidate.v2.json",
575
575
  "rules": [
576
576
  "Create kits and existing-project attachment must consume the same framework adapter contract.",
577
577
  "A framework adapter owns runtime integration, never canonical Model, Graph, Goal, PCC, or verification truth.",
@@ -681,7 +681,11 @@
681
681
  "dotnet.webapi.clean",
682
682
  "rust.axum",
683
683
  "agent.microsoft.python",
684
- "agent.microsoft.dotnet"
684
+ "agent.microsoft.dotnet",
685
+ "agent.openai.python",
686
+ "agent.openai.typescript",
687
+ "gateway.openrouter.typescript",
688
+ "gateway.openrouter.python"
685
689
  ],
686
690
  "officialCreate": [
687
691
  "frontend.nextjs",
@@ -0,0 +1 @@
1
+ export{b as printAnalyzeReport,a as runAnalyze}from'./chunk-223SWPTL.js';
@@ -0,0 +1 @@
1
+ export{b as AUTOPILOT_RELEASE_ALIAS_FILENAME,a as AUTOPILOT_RELEASE_LAST_RUN_FILENAME,c as runAutopilotRelease}from'./chunk-E7WJ2QX7.js';
@@ -0,0 +1 @@
1
+ export{b as runDoctorCapabilities}from'./chunk-4ZUBPFSO.js';
@@ -1,4 +1,4 @@
1
- import {f,e,h as h$1,g}from'./chunk-XF65LQ6M.js';import {a,b}from'./chunk-COOVCORC.js';import {b as b$1,c as c$1}from'./chunk-DFREJHG7.js';import {a as a$1}from'./chunk-NMXGSVMD.js';import {p,a as a$2}from'./chunk-VXFIMEC6.js';import {k as k$2,m,l}from'./chunk-7NKM6EHE.js';import {h}from'./chunk-BLEIUQL6.js';import {k,t,u}from'./chunk-VQZ5PI5J.js';import {p as p$1,q}from'./chunk-ODK4LCEL.js';import k$1 from'fs';import c from'path';import s from'chalk';var ee=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function E(e){try{return await k$1.promises.access(e,k$1.constants.F_OK),true}catch{return false}}async function F(e){try{let n=JSON.parse(await k$1.promises.readFile(e,"utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function C(e){try{return await k$1.promises.readFile(e,"utf-8")}catch{return ""}}function re(e){return a(e)}async function oe(e,n){return await ne([...u(e,"project.json"),...u(e,"context.json")])?true:b(e)?false:c.resolve(e)===c.resolve(n)?k$2(e).length>0:k$2(e).length>0}async function ie(e){let n=await a$1(e,{skipDirs:ee,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:oe}),o=(await a$2(e)).filter(i=>i.relationship==="adopted"||i.source==="adopted-local").map(i=>c.resolve(i.path)).filter(i=>k$1.existsSync(i)),r=[...new Set([...n.map(i=>c.resolve(i)),...o])];return r.length>0?r:b(e)?[]:k$2(e).length>0?[e]:[]}function ae(e,n){return c.relative(e,n).replace(/\\/g,"/")||"."}async function T(e,n){for(let t of n)if(await E(c.join(e,t)))return true;return false}async function se(e,n,t=4){let o=async(r,i)=>{if(i>t)return false;let l;try{l=await k$1.promises.readdir(r,{withFileTypes:true});}catch{return false}for(let a of l)if(a.isFile()&&n.has(a.name.toLowerCase())||a.isDirectory()&&!a.isSymbolicLink()&&!ee.has(a.name)&&await o(c.join(r,a.name),i+1))return true;return false};return o(e,0)}async function ne(e){for(let n of e)if(await E(n))return true;return false}async function te(e){for(let n of e){let t=await F(n);if(t)return t}return null}async function ce(e,n){if(await T(e,[".env",".env.local"]))return true;let t=n?.contracts&&typeof n.contracts=="object"?n.contracts:null;if(Array.isArray(t?.env)&&t.env.length>0)return true;let o=await F(c.join(e,"package.json")),r={...o?.dependencies??{},...o?.devDependencies??{}};if(Object.keys(r).some(a=>/^(?:dotenv|dotenv-flow|env-cmd)$/iu.test(a)))return true;let i=await C(c.join(e,"pyproject.toml"));if(/\b(?:python-dotenv|pydantic-settings)\b/iu.test(i))return true;let l=[await C(c.join(e,"compose.yaml")),await C(c.join(e,"compose.yml")),await C(c.join(e,"docker-compose.yml")),await C(c.join(e,"docker-compose.yaml"))].join(`
1
+ import {f,e,h as h$1,g}from'./chunk-XF65LQ6M.js';import {a,b}from'./chunk-SVO2GGTV.js';import {b as b$1,c as c$1}from'./chunk-5KXOV7W4.js';import {a as a$1}from'./chunk-NMXGSVMD.js';import {p,a as a$2}from'./chunk-IHWS3ALP.js';import {k as k$2,m,l}from'./chunk-LUPKDFQ3.js';import {h}from'./chunk-BLEIUQL6.js';import {k,t,u}from'./chunk-VQZ5PI5J.js';import {p as p$1,q}from'./chunk-ODK4LCEL.js';import k$1 from'fs';import c from'path';import s from'chalk';var ee=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function E(e){try{return await k$1.promises.access(e,k$1.constants.F_OK),true}catch{return false}}async function F(e){try{let n=JSON.parse(await k$1.promises.readFile(e,"utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function C(e){try{return await k$1.promises.readFile(e,"utf-8")}catch{return ""}}function re(e){return a(e)}async function oe(e,n){return await ne([...u(e,"project.json"),...u(e,"context.json")])?true:b(e)?false:c.resolve(e)===c.resolve(n)?k$2(e).length>0:k$2(e).length>0}async function ie(e){let n=await a$1(e,{skipDirs:ee,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:oe}),o=(await a$2(e)).filter(i=>i.relationship==="adopted"||i.source==="adopted-local").map(i=>c.resolve(i.path)).filter(i=>k$1.existsSync(i)),r=[...new Set([...n.map(i=>c.resolve(i)),...o])];return r.length>0?r:b(e)?[]:k$2(e).length>0?[e]:[]}function ae(e,n){return c.relative(e,n).replace(/\\/g,"/")||"."}async function T(e,n){for(let t of n)if(await E(c.join(e,t)))return true;return false}async function se(e,n,t=4){let o=async(r,i)=>{if(i>t)return false;let l;try{l=await k$1.promises.readdir(r,{withFileTypes:true});}catch{return false}for(let a of l)if(a.isFile()&&n.has(a.name.toLowerCase())||a.isDirectory()&&!a.isSymbolicLink()&&!ee.has(a.name)&&await o(c.join(r,a.name),i+1))return true;return false};return o(e,0)}async function ne(e){for(let n of e)if(await E(n))return true;return false}async function te(e){for(let n of e){let t=await F(n);if(t)return t}return null}async function ce(e,n){if(await T(e,[".env",".env.local"]))return true;let t=n?.contracts&&typeof n.contracts=="object"?n.contracts:null;if(Array.isArray(t?.env)&&t.env.length>0)return true;let o=await F(c.join(e,"package.json")),r={...o?.dependencies??{},...o?.devDependencies??{}};if(Object.keys(r).some(a=>/^(?:dotenv|dotenv-flow|env-cmd)$/iu.test(a)))return true;let i=await C(c.join(e,"pyproject.toml"));if(/\b(?:python-dotenv|pydantic-settings)\b/iu.test(i))return true;let l=[await C(c.join(e,"compose.yaml")),await C(c.join(e,"compose.yml")),await C(c.join(e,"docker-compose.yml")),await C(c.join(e,"docker-compose.yaml"))].join(`
2
2
  `);return /^\s*(?:env_file|environment)\s*:/imu.test(l)}async function de(e){return (await g(e)).detected}async function le(e){let n=await F(c.join(e,"package.json")),t=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return Object.keys(t).sort()}function w(e,n,t,o,r,i,l){return {id:e,severity:n,target:t,title:o,detail:r,remediation:i,...l&&l.length>0?{files:[...l]}:{}}}function pe(e){let n=e.reduce((t,o)=>o.severity==="fail"?t+28:o.severity==="warn"?t+12:t+3,0);return Math.max(0,100-n)}async function ue(e,n,t){let o=await te(u(n,"project.json")),r=m(n,o),i=l(n),l$1=r.runtime==="unknown"?i[0]||"unknown":r.runtime,a=[l$1,...i.filter(G=>G!==l$1)],u$1=r.key==="unknown"&&new Set(a.filter(G=>G!=="unknown")).size>1,b=await b$1(n,o,{runtime:l$1,framework:r.key}),m$1=["backend","service","worker","agent"].includes(b),h=["backend","service","worker"].includes(b),v=m$1&&/^(?:fastapi|django|flask|nestjs|express|fastify|springboot|gofiber|gogin|dotnet-webapi|laravel|rails|phoenix|axum|actix|rocket)$/u.test(r.key),j=ae(e,n),f=j,$=await le(n),P=await ne([...u(n,"project.json"),...u(n,"context.json")]),x=await de(n),R=await T(n,["Dockerfile","dockerfile"]),g=await T(n,[".env.example","env.example","config/env.example"])||await se(n,new Set([".env.example","env.example"])),p=await ce(n,o),d=await c$1({projectPath:n,declaration:t?.governance}),z=d.ci.status==="repository",D=await h$1(n),y=[];return r.key==="unknown"&&y.push(w(u$1?"project.stack.aggregate":"project.stack.unknown",u$1?"info":"fail",f,u$1?"Multi-runtime aggregate boundary detected":"Project stack is unknown",u$1?`Workspai detected multiple runtimes (${a.join(", ")}) and intentionally did not promote one nested framework as the aggregate project identity.`:"Workspai cannot confidently classify this backend project.",u$1?"Adopt independently operated nested projects when they need separate lifecycle, ownership, or release evidence.":"Add .workspai/project.json metadata or import the project with `workspai import`.")),P||y.push(w("project.marker.missing","warn",f,"Workspai marker is missing","The project can be detected by files, but it is not registered with Workspai metadata.","Run `workspai import <path>` from a workspace or create the project through Workspai.")),x||y.push(w("project.tests.missing","warn",f,"Test entrypoint is missing","No common test folder, config, or package test script was found.","Add a test command so `workspai workspace run test --affected` can gate changes.")),m$1&&p&&!g&&y.push(w("project.env.example.missing","info",f,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.",[".env.example"])),d.ci.status==="unknown"?y.push(w("project.ci.missing","warn",f,"CI governance is not proven","No repository CI surface or canonical external CI declaration was found for this project.","Add repository CI configuration or declare the external CI authority in the workspace contract.",[".github/workflows/ci.yml"])):d.ci.status==="external-observed"&&y.push(w("project.ci.external-observed","info",f,"Continuous integration appears externally managed",`Repository documentation references an external CI control plane (${d.ci.evidence.join(", ")}).`,"Declare the external CI provider in the canonical workspace contract when authoritative release gating depends on it.")),v&&!D&&y.push(w("project.health.missing","info",f,"Health or readiness probe is missing","The project has no obvious health or readiness endpoint to support automated deployment and runtime checks.","Add a simple health endpoint and document it for readiness gates and observability.")),h&&!R&&y.push(w("project.container.missing","info",f,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.",["Dockerfile"])),{name:typeof o?.name=="string"&&o.name.trim()?o.name.trim():c.basename(n),path:n,relativePath:j,runtime:l$1,runtimeCandidates:a,framework:r.key,confidence:r.confidence,supportTier:r.supportTier,hasRapidKitMarker:P,hasTests:x,hasDockerfile:R,hasEnvExample:g,hasCiConfig:z,governance:d,hasHealthEndpoint:D,scripts:$,findings:y,score:pe(y)}}function me(e){return e.name.toLowerCase()}async function fe(e){let n=new Map(e.map(r=>[me(r),r])),t=[];for(let r of e){let i=await F(c.join(r.path,"package.json")),l={...i?.dependencies??{},...i?.devDependencies??{},...i?.peerDependencies??{}};for(let u of Object.keys(l)){let b=u.replace(/^@[^/]+\//,"").toLowerCase(),m=n.get(b);m&&m.relativePath!==r.relativePath&&t.push({from:r.relativePath,to:m.relativePath,kind:"package"});}let a=await C(c.join(r.path,"pyproject.toml"));for(let u of e)u.relativePath!==r.relativePath&&a.includes(u.name)&&t.push({from:r.relativePath,to:u.relativePath,kind:"workspace-reference"});}let o=new Set;return t.filter(r=>{let i=`${r.from}\0${r.to}\0${r.kind}`;return o.has(i)?false:(o.add(i),true)})}function ge(e,n){let t=new Map;for(let o of e)t.set(o.relativePath,{project:o.relativePath,directDependents:0,directDependencies:0});for(let o of n){let r=t.get(o.from),i=t.get(o.to);r&&(r.directDependencies+=1),i&&(i.directDependents+=1);}return Array.from(t.values()).sort((o,r)=>r.directDependents-o.directDependents||r.directDependencies-o.directDependencies)}async function ye(e){let n=await te(t(e,"workspace.json"));return typeof n?.profile=="string"?n.profile:null}function we(e){return {fail:e.filter(n=>n.severity==="fail").length,warn:e.filter(n=>n.severity==="warn").length,info:e.filter(n=>n.severity==="info").length}}function ke(e){if(e.projectCount===0)return e.workspaceDetected?["Add your first project: npx workspai create project <name> --kit <kit>","Import an existing service: npx workspai import <path>"]:["Create a Workspai workspace: npx workspai create workspace my-workspace --profile polyglot","Import an existing service: npx workspai import ../service"];let n=[];return e.findings.some(t=>t.id==="workspace.marker.missing")&&n.push("Initialize workspace metadata with `workspai bootstrap --profile polyglot`."),e.findings.some(t=>t.id==="project.marker.missing")&&n.push("Register detected projects with `workspai import <path>` or recreate them via `workspai create project`."),e.findings.some(t=>t.id==="project.tests.missing")&&n.push("Add test entrypoints, then gate changes with `workspai workspace run test --affected --strict`."),e.findings.some(t=>t.id==="project.ci.missing")&&n.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(t=>t.id==="project.health.missing")&&n.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasCanonicalGraph||n.push("Generate canonical topology with `workspai workspace model --write --include-evidence`."),n.push("Run `workspai autopilot release --mode audit --json` before release."),Array.from(new Set(n))}async function Te(e$1={}){let n=c.resolve(e$1.workspacePath||process.cwd());if(!await E(n))throw new Error(`Workspace path does not exist: ${n}`);let t=re(n)??n,o=k(t),r=await ye(t),i=await ie(t),l;try{l=(await p({workspacePath:t})).contract;}catch{}let a=await Promise.all(i.map(p=>{let d=l?.projects.find(z=>{let D=z.externalPath??z.relativePath;return c.resolve(t,D)===c.resolve(p)});return ue(t,p,d)})),u=await fe(a),b=ge(a,u),m=[];o||m.push(w("workspace.marker.missing","warn",".","Workspace metadata is missing","The directory can be analyzed, but it is not a registered Workspai workspace.","Run `workspai create workspace` or `workspai bootstrap --profile polyglot` in a workspace root.")),a.length===0&&m.push(w("workspace.projects.missing","warn",".","No backend projects detected","Workspai did not find runtime markers or project metadata under this root.","Create a project with `workspai create project` or import one with `workspai import <path>`."));let h$1=[...m,...a.flatMap(p=>p.findings)],v=we(h$1),j={};for(let p of a)for(let d of p.runtimeCandidates)j[d]=(j[d]||0)+1;let f$1=a.length>0?Math.round(a.reduce((p,d)=>p+d.score,0)/a.length):0,$=m.reduce((p,d)=>p+(d.severity==="fail"?20:d.severity==="warn"?8:2),0),P=Math.max(0,f$1-$),x=a.length===0&&v.fail===0&&h$1.length>0&&h$1.every(p=>p.id==="workspace.projects.missing"&&p.severity==="warn"),R=v.fail>0||e$1.strict&&v.warn>0&&!x?"blocked":v.warn>0?"needs-attention":"ready",g={schemaVersion:q.analyze,generatedAt:new Date().toISOString(),workspacePath:t,workspaceDetected:o,profile:r,summary:{statusScope:"source-structure",releaseReadiness:"not-evaluated",score:P,verdict:R,projectCount:a.length,runtimeCount:Object.keys(j).length,findings:v},runtimes:j,projects:a,dependencyGraph:{status:u.length>0?"generated":"empty",edges:u,topImpactedProjects:b.slice(0,5)},findings:h$1,nextActions:ke({findings:h$1,projectCount:a.length,hasCanonicalGraph:await E(c.join(t,p$1.knowledgeGraph)),workspaceDetected:o}),enterpriseControls:{jsonReady:true,ciGateCommand:"workspai analyze --json --strict",releaseGateCommand:"workspai autopilot release --mode enforce --json",evidencePath:p$1.analyze}};if(e$1.output&&(await k$1.promises.mkdir(c.dirname(c.resolve(e$1.output)),{recursive:true}),await k$1.promises.writeFile(c.resolve(e$1.output),`${JSON.stringify(g,null,2)}
3
3
  `)),!e$1.output&&o){let p=f(g,{commandId:"workspaceAnalyze",exitCode:g.summary.verdict==="blocked"?2:g.summary.verdict==="needs-attention"?1:0,generatedAt:g.generatedAt,blockers:g.findings.filter(d=>d.severity==="fail").map(d=>d.title).slice(0,12),runId:e()});await h(t,p$1.analyze,p);}return g}function Ne(e){let n=e.summary.verdict==="ready"?s.green:e.summary.verdict==="needs-attention"?s.yellow:s.red;if(console.log(s.bold(`
4
4
  Workspai Workspace Analysis
@@ -0,0 +1,4 @@
1
+ import {a as a$1}from'./chunk-FIK343LI.js';import {c as c$1}from'./chunk-DWKCFHHL.js';import {l,q}from'./chunk-IDETNYCF.js';import {f,h as h$2,g}from'./chunk-3SQIV3F4.js';import {a as a$3}from'./chunk-4CXV3PPV.js';import {i,h as h$1,d,b as b$1,a as a$2,c as c$2,k as k$1}from'./chunk-BLEIUQL6.js';import {b as b$3}from'./chunk-VN2MKTQO.js';import {a}from'./chunk-AFIFZTOY.js';import {a as a$4}from'./chunk-XWKGZRHN.js';import {c,d as d$1}from'./chunk-EWZZUQBR.js';import {b as b$2}from'./chunk-25AWHAB5.js';import {h,i as i$1,m,k,n,o,g as g$1,l as l$1,j as j$1,s,e,f as f$1}from'./chunk-ODK4LCEL.js';import {a as a$5}from'./chunk-FB7SCXAZ.js';import {randomUUID,createHash}from'crypto';import b from'path';import z from'fs-extra';var nt=new Set(["committed","rejected","aborted","superseded"]);function u(e,t){if(!e)throw new Error(`Decision protocol violation: ${t}`)}function st(e){return [...new Set(e)].sort()}function We(e,t){return t.digestCanonical(e.effects.map(a=>({id:a.id,status:a.status,key:a.idempotencyKey})))}function Me(e,t,a){u(!e.some(r=>r.id===t),`${a} receipt '${t}' already exists`);}function it(e,t){Me(e.effects,t.id,"effect");let a=e.effects.find(r=>r.idempotencyKey===t.idempotencyKey);return u(!a,`effect idempotency key '${t.idempotencyKey}' was already recorded by '${a?.id}'`),[...e.effects,t]}function ot(e,t,a){return Me(e.verifications,t.id,"verification"),u(t.target.effectHeadDigest===We(e,a),`verification '${t.id}' does not bind the current effect head`),[...e.verifications,t]}function ct(e){return e.requiredCriteria.every(t=>{let a=e.verifications.filter(r=>r.criterionId===t);return a.length>0&&a.at(-1)?.status==="passed"})}function dt(e$1,t,a){if(t.kind==="created"){u(e$1===null,"created must be the first event");let y=t.payload.references?.[0];u(y,"created must bind an intent artifact");let p=t.payload.references?.filter(k=>k.role==="success-criterion").map(k=>k.artifact)??[];return {schemaVersion:e,id:t.transactionId,purpose:"proof-carrying-change",createdAt:t.occurredAt,updatedAt:t.occurredAt,state:"draft",generation:1,eventCount:t.sequence,eventHeadDigest:t.digest,intent:y,requiredCriteria:st(p),scope:null,evidence:[],plans:[],authorization:null,effects:[],verifications:[],blockers:[]}}u(e$1,`${t.kind} cannot occur before created`),u(!nt.has(e$1.state),`${t.kind} cannot follow terminal state ${e$1.state}`);let r=e$1.state,n=e$1.scope,s=e$1.evidence,d=e$1.plans,f=e$1.authorization,l=e$1.effects,o=e$1.verifications,c=e$1.blockers,h=e$1.terminalReason;switch(t.kind){case "scope-bound":u(e$1.state==="draft"||e$1.state==="scoped","scope-bound requires draft or scoped state"),u(t.payload.scope,"scope-bound requires scope"),n=t.payload.scope,r="scoped";break;case "evidence-attached":u(e$1.state==="scoped"||e$1.state==="evidence-ready","evidence-attached requires scoped state"),u((t.payload.references?.length??0)>0,"evidence-attached requires references"),s=[...s,...t.payload.references??[]],r="evidence-ready";break;case "plan-attached":u(e$1.state==="evidence-ready","plan-attached requires evidence-ready state"),u((t.payload.references?.length??0)>0,"plan-attached requires references"),d=[...d,...t.payload.references??[]];break;case "authorized":u(e$1.state==="evidence-ready","authorization requires evidence-ready state"),u(t.payload.authorization,"authorized requires a bounded authorization grant"),f=t.payload.authorization,r="authorized";break;case "effect-requested":u(e$1.state==="authorized"||e$1.state==="executing","effect-requested requires authorization"),r="executing";break;case "effect-recorded":u(e$1.state==="authorized"||e$1.state==="executing","effect-recorded requires authorization"),u(t.payload.effect,"effect-recorded requires a receipt"),u(f?.effectClasses.includes(t.payload.effect.effectClass),`effect class '${t.payload.effect.effectClass}' is outside the authorization grant`),l=it(e$1,t.payload.effect),r=t.payload.effect.status==="succeeded"?"executing":"blocked",t.payload.effect.status!=="succeeded"&&(c=[...c,{code:t.payload.effect.status==="uncertain"?"decision.effect.uncertain":"decision.effect.failed",actionable:true,details:t.payload.effect.summary}]);break;case "effect-uncertain":u(e$1.state==="authorized"||e$1.state==="executing","effect-uncertain requires an active execution"),r="blocked",c=[...c,t.payload.blocker??{code:"decision.effect.uncertain",actionable:true}];break;case "verification-started":u(e$1.state==="authorized"||e$1.state==="executing","verification-started requires authorized or executing state"),r="verifying";break;case "verification-recorded":{u(e$1.state==="verifying","verification-recorded requires verifying state"),u(t.payload.verification,"verification-recorded requires a receipt"),o=ot(e$1,t.payload.verification,a),r=t.payload.verification.status==="failed"?"blocked":t.payload.verification.status==="inconclusive"?"awaiting-human":"verifying";break}case "human-required":r="awaiting-human";break;case "blocked":u(t.payload.blocker,"blocked requires a structured blocker"),c=[...c,t.payload.blocker],r="blocked";break;case "resumed":u(e$1.state==="blocked"||e$1.state==="awaiting-human","resumed requires a paused state"),u(t.payload.resumeTo,"resumed requires an explicit target state"),r=t.payload.resumeTo,c=[];break;case "committed":u(e$1.state==="verifying","commit requires verifying state"),u(ct(e$1),"every required criterion needs a latest passing receipt"),u(!e$1.effects.some(y=>y.status!=="succeeded"),"all effects must be certainly successful"),r="committed",h=t.payload.reason??t.payload.summary;break;case "rejected":case "aborted":case "superseded":r=t.kind,h=t.payload.reason??t.payload.summary;break;default:throw new Error(`Decision protocol violation: unsupported event ${t.kind}`)}return {...e$1,updatedAt:t.occurredAt,state:r,generation:e$1.generation+1,eventCount:t.sequence,eventHeadDigest:t.digest,scope:n,evidence:s,plans:d,authorization:f,effects:l,verifications:o,blockers:c,...h?{terminalReason:h}:{}}}function Be(e,t,a,r){let n=(t?.sequence??0)+1,s={schemaVersion:f$1,transactionId:e,sequence:n,kind:a.kind,occurredAt:a.occurredAt,actor:a.actor,previousEventDigest:t?.digest??null,payload:a.payload};return {...s,digest:r.digestCanonical(s)}}function ee(e,t){u(e.length>0,"at least one event is required");let a=null,r=null;for(let n of e){u(n.schemaVersion===f$1,`unsupported event schema ${n.schemaVersion}`),u(n.sequence===(r?.sequence??0)+1,`event sequence ${n.sequence} is not contiguous`),u(n.previousEventDigest===(r?.digest??null),`event ${n.sequence} has an invalid previous digest`);let{digest:s,...d}=n;u(n.digest===t.digestCanonical(d),`event ${n.sequence} digest is invalid`),u(!r||n.transactionId===r.transactionId,"events cross transaction boundaries"),a=dt(a,n,t),r=n;}return a}function he(e,t,a){return {schemaVersion:g$1,transactionId:e.id,generatedAt:t,generation:e.generation,eventCount:e.eventCount,eventHeadDigest:e.eventHeadDigest,state:e.state,transactionDigest:a.digestCanonical(e)}}function te(e,t){return We(e,t)}var M={digestCanonical:c};function ft(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid decision transaction id: ${e}`);return t}function L(e){let a=`.workspai/decisions/${ft(e)}`;return {directory:a,transaction:`${a}/transaction.json`,checkpoint:`${a}/checkpoint.json`,events:`${a}/events.jsonl`,lock:`${a}.lock`}}function gt(e,t){return e.split(/\r?\n/).filter(r=>r.trim().length>0).map((r,n)=>{try{return JSON.parse(r)}catch(s){throw new Error(`Decision event log is corrupt at ${t}:${n+1}: ${s.message}`)}})}async function Le(e,t){let a=L(t),r=await b$1(e,a.events);return r?gt(await z.readFile(r,"utf8"),r):[]}function Ue(e,t){let a=L(t);return {directory:a$2(e,a.directory),transaction:a$2(e,a.transaction),checkpoint:a$2(e,a.checkpoint),events:a$2(e,a.events)}}async function ht(e,t,a$1,r){let n=L(t.id),s=he(t,r,M);for(let[d,f]of a$1.entries())a(f,"contracts/workspace-intelligence/decision-event.v1.json",`Decision event ${d+1}`);return b$3(n.transaction,t),b$3(n.checkpoint,s),await k$1(e,n.events,`${a$1.map(d=>JSON.stringify(d)).join(`
2
+ `)}
3
+ `),await h$1(e,n.transaction,t),await h$1(e,n.checkpoint,s),{transaction:t,checkpoint:s,events:a$1,paths:Ue(e,t.id)}}async function Fe(e){let t=L(e.transactionId),a=a$2(e.workspacePath,t.lock);return a$4(a,async()=>{let r=await Le(e.workspacePath,e.transactionId),n=r.at(-1)??null;if((n?.digest??null)!==e.expectedHeadDigest)throw new Error(`Decision transaction head changed: expected ${e.expectedHeadDigest??"<empty>"}, observed ${n?.digest??"<empty>"}`);r.length>0&&ee(r,M);let s=Be(e.transactionId,n,e.event,M),d=[...r,s],f=ee(d,M);return ht(e.workspacePath,f,d,e.event.occurredAt)},{purpose:`decision:${e.transactionId}`,timeoutMs:3e4,staleMs:6e4})}async function Je(e,t){let a=await Le(e,t);if(a.length===0)throw new Error(`Decision transaction not found: ${t}`);let r=ee(a,M),n=he(r,r.updatedAt,M);return {transaction:r,checkpoint:n,events:a,paths:Ue(e,t)}}function U(e){return L(e).directory}var me={digestCanonical:c},ut="workspai.deleted-artifact-tombstone.v1";function mt(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid proof-carrying change id: ${e}`);return t}function V(e){let a=`.workspai/changes/${mt(e)}`;return {directory:a,lease:`${a}/lease.json`,prediction:`${a}/predicted-overlay.json`,actualOverlay:`${a}/actual-overlay.json`,surprises:`${a}/architecture-surprises.json`,workspaceVerification:`${a}/verification/workspace-verify.json`,capsule:`${a}/capsule.json`,privateBaselineGraph:`${a}/private/baseline-graph.json`}}function wt(e,t){return {kind:e,id:t}}function T(e){return {role:e.role,artifact:e.artifact,schemaVersion:e.schemaVersion,digest:{algorithm:"sha256",semantics:e.semantics??"canonical-json-v1",value:e.value}}}async function A(e,t){let a=await b$1(e,t);return a?await z.readJson(a):null}async function Qe(e,t){let a=await d(e,v(t));return !a||!(await z.stat(a).catch(()=>null))?.isFile()?null:createHash("sha256").update(await z.readFile(a)).digest("hex")}async function yt(e,t){let a=new Map;await Promise.all(t.proofs.map(async n=>{let s=v(n.artifact),d=a.get(s);d||(d=Qe(e,s),a.set(s,d)),await d;}));let r=Object.fromEntries((await Promise.all([...a.entries()].map(async([n,s])=>[n,await s]))).filter(n=>typeof n[1]=="string"));return {...t,pccArtifactContentHashes:r}}async function vt(e){let a=(await A(e,s.workspaceContract.artifactPath))?.workspace?.name;if(typeof a=="string"&&a.trim())return a.trim();let r=await A(e,".workspai/workspace.json"),n=r?.workspace_name??r?.name;return typeof n=="string"&&n.trim()?n.trim():b.basename(e)}async function F(e,t){let a=await c$2(e,t.artifact);if(!a)return false;if(t.digest.semantics==="raw-bytes-v1"){let s=await z.readFile(a);return createHash("sha256").update(s).digest("hex")===t.digest.value}let r=await z.readJson(a).catch(()=>null);return r?(t.digest.semantics==="workspace-model-structural-v1"?d$1(r):c(r))===t.digest.value:false}function Ze(e){return c({schemaVersion:ut,artifact:v(e),deleted:true})}function kt(e){let t=v(e.artifact);if(!t||t==="."||t===".."||t.startsWith("../"))throw new Error(`Deleted artifact identity must be a contained relative path: ${e.artifact}`);return {artifact:t,observedAt:e.observedAt??new Date().toISOString(),digest:{algorithm:"sha256",semantics:"deletion-tombstone-v1",value:Ze(t)}}}async function et(e,t){if(t.digest.algorithm!=="sha256"||t.digest.semantics!=="deletion-tombstone-v1"||t.digest.value!==Ze(t.artifact))return false;let a=await d(e,t.artifact);return a!==null&&!await z.pathExists(a)}async function Pt(e,t){let a=await A(e,V(t).lease);if(!a||a.schemaVersion!==h)throw new Error(`Architecture lease is missing or unsupported for ${t}.`);if(a.changeId!==t)throw new Error(`Architecture lease binding failed for ${t}.`);return a}async function J(e){let t=await a$3(e);if(t.status==="miss")throw new Error(`A current canonical Model and Graph are required (${t.reason}). Run workspai workspace intelligence run --for-agent generic --strict --json.`);return t}function Ct(e,t,a){return c({modelHash:e,graphHash:t,inputHash:a})}function Y(e){let t=d$1(e.model),a=c(e.graph),r=e.graph.source.inputs?.hash;if(!r)throw new Error("The canonical Graph has no live input fingerprint.");return {modelHash:t,graphHash:a,inputHash:r,generation:Ct(t,a,r)}}async function we(e,t){let a=await J(e),r=Y(a);if(r.generation!==t.generation)throw new Error(`Architecture lease ${t.changeId} is stale. Expected generation ${t.generation}, observed ${r.generation}. Abort or begin a new change from current evidence.`);return a}function C(e,t,a,r,n=new Date().toISOString()){return {kind:e,payload:t,occurredAt:n,actor:wt(a,r)}}async function I(e,t,a,r){return Fe({workspacePath:e,transactionId:a,expectedHeadDigest:t?.transaction.eventHeadDigest??null,event:r})}function D(e,t,a){return `${e}\0${t}\0${a}`}var tt="agent-framework-change-plan",It=new Set(["init","test","build"]);function At(e){if(!e.record.transaction.plans.some(n=>n.role===tt))return false;let a=new Set(e.lease.scope.projects),r=e.verify.steps.filter(n=>{if(n.scope!=="project"||!n.project||!a.has(n.project))return false;let s=n.id.split(".").at(-1);return s!==void 0&&It.has(s)});return r.some(n=>n.status==="fail")?false:r.length===0||r.some(n=>n.status==="missing")}function bt(e){let t=[];for(let[a,r]of [["entity",e.entities],["relation",e.relations],["proof",e.proofs]])t.push(...r.added.map(n=>({operation:"add",targetKind:a,targetId:n.id}))),t.push(...r.removed.map(n=>({operation:"remove",targetKind:a,targetId:n.id}))),t.push(...r.changed.map(n=>({operation:"change",targetKind:a,targetId:n.id})));return t.push(...e.changedArtifacts.map(a=>({operation:"change",targetKind:"artifact",targetId:a}))),t.sort((a,r)=>D(a.operation,a.targetKind,a.targetId).localeCompare(D(r.operation,r.targetKind,r.targetId)))}function Et(e,t){let a=new Set(t.filter(o=>o.targetKind==="artifact").map(o=>v(o.targetId)));if(a.size===0)return new Set;let r=new Set,n=new Set,s=(o,c)=>{a.has(v(c.artifact))&&(n.add(c.id),r.add(D(o,"proof",c.id)));};e.proofs.added.forEach(o=>s("add",o)),e.proofs.removed.forEach(o=>s("remove",o)),e.proofs.changed.forEach(o=>{let c=o.after??o.before;c&&s("change",c);});let d=new Set,f=(o,c)=>{c.proofIds.some(h=>n.has(h))&&(d.add(c.id),r.add(D(o,"entity",c.id)));};e.entities.added.forEach(o=>f("add",o)),e.entities.removed.forEach(o=>f("remove",o)),e.entities.changed.forEach(o=>{let c=o.after??o.before;c&&f("change",c);});let l=(o,c)=>{!c.proofIds.some(h=>n.has(h))&&!d.has(c.from)&&!d.has(c.to)||r.add(D(o,"relation",c.id));};return e.relations.added.forEach(o=>l("add",o)),e.relations.removed.forEach(o=>l("remove",o)),e.relations.changed.forEach(o=>{let c=o.after??o.before;c&&l("change",c);}),r}function Dt(e){let t=e.prediction?.operations.map(c=>({operation:c.operation,targetKind:c.targetKind,targetId:c.targetId}))??[],a=bt(e.actual),r=new Set(t.map(c=>D(c.operation,c.targetKind,c.targetId))),n=new Set(a.map(c=>D(c.operation,c.targetKind,c.targetId))),s=Et(e.actual,t),d=a.filter(c=>r.has(D(c.operation,c.targetKind,c.targetId))||s.has(D(c.operation,c.targetKind,c.targetId))),f=a.filter(c=>!r.has(D(c.operation,c.targetKind,c.targetId))&&!s.has(D(c.operation,c.targetKind,c.targetId))),l=t.filter(c=>!n.has(D(c.operation,c.targetKind,c.targetId))),o=e.prediction?f.length===0&&l.length===0&&s.size===0?"exact":f.length===0?"within-expectation":"surprising":"no-prediction";return {schemaVersion:j$1,changeId:e.changeId,generatedAt:e.generatedAt,prediction:e.predictionReference,actual:e.actualReference,matched:d,unpredicted:f,missing:l,summary:{predicted:t.length,actual:a.length,matched:d.length,unpredicted:f.length,missing:l.length,verdict:o}}}async function pe(e){let t=await A(e.workspacePath,e.relativePath);return t?T({role:e.role,artifact:e.relativePath,schemaVersion:e.schemaVersion,value:c(t)}):null}function Rt(e){let{integrity:t,...a}=e;return a}async function ye(e){let t=V(e.lease.changeId),[a,r,n]=await Promise.all([pe({workspacePath:e.workspacePath,relativePath:t.prediction,role:"prediction",schemaVersion:i$1}),pe({workspacePath:e.workspacePath,relativePath:t.actualOverlay,role:"actual-architecture-overlay",schemaVersion:a$5}),pe({workspacePath:e.workspacePath,relativePath:t.surprises,role:"architecture-surprises",schemaVersion:j$1})]),s=T({role:"decision-transaction",artifact:`${U(e.lease.changeId)}/transaction.json`,schemaVersion:e.record.transaction.schemaVersion,value:c(e.record.transaction)}),d=e.record.transaction.effects.flatMap(g=>g.artifacts),f=e.record.transaction.effects.flatMap(g=>g.deletedArtifacts??[]),l=e.record.transaction.verifications.flatMap(g=>g.artifacts),o=await A(e.workspacePath,t.actualOverlay),c$1=o?!ue(o):false,h=[{id:"intent-bound",status:"passed",summary:"The transaction is hash-bound to its immutable Goal Pack."},{id:"baseline-pinned",status:"passed",summary:"The architecture lease pins exact Model, Graph, and live-input identities."},{id:"effects-receipted",status:e.record.transaction.effects.length>0&&e.record.transaction.effects.every(g=>g.status==="succeeded")||e.record.transaction.effects.length===0&&c$1?"passed":e.record.transaction.effects.length===0?"pending":"failed",summary:e.record.transaction.effects.length===0&&c$1?"Fresh Graph observation proves this was a no-effect change.":`${e.record.transaction.effects.length} typed effect receipt(s) are bound to the transaction ledger.`},{id:"architecture-reobserved",status:r?"passed":"pending",summary:r?"The actual architecture delta was derived from a fresh canonical Graph.":"No post-effect architecture overlay has been observed yet."},{id:"independently-verified",status:e.record.transaction.state==="committed"?"passed":e.record.transaction.verifications.some(g=>g.status==="failed")?"failed":"pending",summary:`${e.record.transaction.verifications.length} independent verification receipt(s) are recorded.`}],y=await A(e.workspacePath,t.surprises),p=[...e.record.transaction.effects.length===0&&o&&ue(o)?["No typed effect receipt explains the observed architecture generation."]:[],...y?.summary.unpredicted?[`${y.summary.unpredicted} actual architecture operation(s) were not predicted.`]:[],...e.record.transaction.blockers.map(g=>g.details??g.code)],k$1=e.record.transaction.state==="committed"?"sealed":e.record.transaction.state==="aborted"?"aborted":e.record.transaction.state==="blocked"||e.record.transaction.state==="awaiting-human"?"blocked":e.record.transaction.state==="verifying"&&e.record.transaction.verifications.some(g=>g.status==="passed")?"verified":"open",i={schemaVersion:k,changeId:e.lease.changeId,goalId:e.lease.goalId,generatedAt:e.record.transaction.updatedAt,status:k$1,workspace:e.lease.workspace,scope:e.lease.scope,decision:{transaction:s,eventHeadDigest:e.record.transaction.eventHeadDigest,effectHeadDigest:te(e.record.transaction,me),state:e.record.transaction.state,generation:e.record.transaction.generation},intent:e.record.transaction.intent,baseline:e.lease.baseline,prediction:a,actualOverlay:r,surpriseReport:n,effects:d,deletedArtifacts:f,verification:l,assurances:h,remainingUncertainty:[...new Set(p)]};return {...i,integrity:{algorithm:"sha256",semantics:"canonical-json-v1",capsuleDigest:c(i)}}}async function O(e,t,a){let r=await ye({workspacePath:e,lease:t,record:a});return await h$1(e,V(t.changeId).capsule,r),r}function j(e){let t=V(e.lease.changeId),a$1={schemaVersion:l$1,operation:e.operation,changeId:e.lease.changeId,state:e.record.transaction.state,capsule:e.capsule,artifacts:{lease:t.lease,prediction:e.capsule.prediction?.artifact??null,actualOverlay:e.capsule.actualOverlay?.artifact??null,surpriseReport:e.capsule.surpriseReport?.artifact??null,transaction:`${U(e.lease.changeId)}/transaction.json`,events:`${U(e.lease.changeId)}/events.jsonl`,capsule:t.capsule},nextActions:e.nextActions};return a(a$1,"contracts/workspace-intelligence/change-operation-result.v1.json","Proof-Carrying Change operation result"),b$2({kind:"operation.completed",status:e.record.transaction.state==="blocked"||e.record.transaction.state==="awaiting-human"?"blocked":e.record.transaction.state==="aborted"?"cancelled":"succeeded",component:"proof-carrying-change",correlationId:e.lease.changeId,message:`${e.operation}: ${e.record.transaction.state}`,evidenceBindings:[{kind:"artifact",ref:t.capsule,role:"output",provenance:"authoritative"},{kind:"artifact",ref:`${U(e.lease.changeId)}/transaction.json`,role:"subject",provenance:"authoritative"}],attributes:{operation:e.operation,changeId:e.lease.changeId,goalId:e.lease.goalId,decisionState:e.record.transaction.state,assurancePassed:e.capsule.assurances.filter(r=>r.status==="passed").length,assuranceTotal:e.capsule.assurances.length}}),a$1}async function R(e,t){let a=await Pt(e,t),r=await Je(e,t);return {lease:a,record:r}}async function da(e){let t=b.resolve(e.workspacePath),a=await l({workspacePath:t,goalId:e.goalId,validateBindings:true}),r=a.goalPack;if(!r||!a.active)throw new Error("No active Goal Pack is available, or the named Goal is not active.");if(r.state!=="ready-to-plan")throw new Error(`Goal ${r.id} cannot begin a change while its state is ${r.state}.`);let n=await J(t),s=Y(n);if(s.modelHash!==r.sourceBinding.model.hash||(r.sourceBinding.graph.inputHash?s.inputHash!==r.sourceBinding.graph.inputHash:s.graphHash!==r.sourceBinding.graph.hash))throw new Error(`Goal ${r.id} is no longer bound to the current architecture generation.`);let d=`change-${r.intent.category}-${randomUUID().replace(/-/g,"").slice(0,16)}`,f=V(d),l$1=new Date().toISOString(),o=await yt(t,n.graph),c$1=c(o),h$1={schemaVersion:h,changeId:d,goalId:r.id,createdAt:l$1,workspace:r.workspace,scope:{kind:r.scope.kind,projects:[...r.scope.projects]},baseline:{model:T({role:"baseline-model",artifact:r.sourceBinding.model.artifact,schemaVersion:r.sourceBinding.model.schemaVersion,value:r.sourceBinding.model.hash,semantics:"workspace-model-structural-v1"}),graph:{...T({role:"baseline-graph",artifact:r.sourceBinding.graph.artifact,schemaVersion:r.sourceBinding.graph.schemaVersion,value:s.graphHash}),inputHash:s.inputHash}},generation:s.generation,semantics:"optimistic-generation-guard",privateMaterialization:{artifact:f.privateBaselineGraph,role:"hash-bound-baseline-cache",portable:false,authoritative:false,digest:{algorithm:"sha256",semantics:"canonical-json-v1",value:c$1}}};await i(t,f.lease,[{relativePath:f.privateBaselineGraph,payload:o},{relativePath:f.lease,payload:h$1}]);let y=e.actorKind??"cli",p=e.actorId??"workspai-change",k=T({role:"intent",artifact:a.active.goalPack,schemaVersion:r.schemaVersion,value:c(r)}),i$1=r.successCriteria.map(E=>T({role:"success-criterion",artifact:E.id,schemaVersion:"workspai.goal-success-criterion.v1",value:c(E)})),g=await I(t,null,d,C("created",{summary:`Begin proof-carrying change for ${r.id}.`,references:[k,...i$1]},y,p,l$1));g=await I(t,g,d,C("scope-bound",{summary:"Bind immutable Goal scope.",scope:h$1.scope},y,p)),g=await I(t,g,d,C("evidence-attached",{summary:"Attach exact architecture generation and lease.",references:[h$1.baseline.model,{role:h$1.baseline.graph.role,artifact:h$1.baseline.graph.artifact,schemaVersion:h$1.baseline.graph.schemaVersion,digest:h$1.baseline.graph.digest},T({role:"architecture-lease",artifact:f.lease,schemaVersion:h$1.schemaVersion,value:c(h$1)})]},y,p)),await q({workspacePath:t,goalId:r.id,changeId:d});let P=await O(t,h$1,g);return j({operation:"begin",lease:h$1,record:g,capsule:P,nextActions:[`workspai change predict --change ${d} --file <prediction.json> --json`,`workspai change authorize --change ${d} --effects filesystem,command --json`]})}async function la(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId);if(await we(e.workspacePath,t),a.transaction.state!=="evidence-ready")throw new Error(`Prediction requires evidence-ready state, observed ${a.transaction.state}.`);let r={...e.prediction,schemaVersion:i$1,changeId:e.changeId,goalId:t.goalId,baselineGeneration:t.generation,nonCanonical:true,proofEligible:false,operations:[...e.prediction.operations].sort((f,l)=>D(f.operation,f.targetKind,f.targetId).localeCompare(D(l.operation,l.targetKind,l.targetId)))};await h$1(e.workspacePath,V(e.changeId).prediction,r);let n=T({role:"noncanonical-prediction",artifact:V(e.changeId).prediction,schemaVersion:r.schemaVersion,value:c(r)}),s=await I(e.workspacePath,a,e.changeId,C("plan-attached",{summary:"Attach an explicitly noncanonical architecture prediction.",references:[n]},e.actorKind??"agent",e.actorId??"workspai-agent")),d=await O(e.workspacePath,t,s);return j({operation:"predict",lease:t,record:s,capsule:d,nextActions:[`workspai change authorize --change ${e.changeId} --effects filesystem,command --json`]})}async function fa(e){let{lease:t,record:a$1}=await R(e.workspacePath,e.changeId);if(await we(e.workspacePath,t),a$1.transaction.state!=="evidence-ready")throw new Error(`Plan attachment requires evidence-ready state, observed ${a$1.transaction.state}.`);let r=e.role.trim().toLowerCase();if(!/^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$/.test(r))throw new Error(`Invalid proof-carrying plan role: ${e.role}`);if(!e.schemaVersion.trim())throw new Error("Plan schema version is required.");let n=e.contractPath.replace(/\\/g,"/");if(!n.startsWith("contracts/")||n.split("/").some(l=>l===".."||l==="."))throw new Error(`Plan contract path must resolve inside the published contract root: ${e.contractPath}`);if(!e.payload||typeof e.payload!="object"||e.payload.schemaVersion!==e.schemaVersion)throw new Error("Plan payload schema version does not match its PCC reference.");a(e.payload,n,`${r} plan`);let s=c(e.payload),d=`${V(e.changeId).directory}/plans/${r}-${s}.json`;await h$1(e.workspacePath,d,e.payload);let f=await I(e.workspacePath,a$1,e.changeId,C("plan-attached",{summary:`Attach ${r} execution plan.`,references:[T({role:r,artifact:d,schemaVersion:e.schemaVersion,value:s})]},e.actorKind??"cli",e.actorId??"workspai-plan"));return await O(e.workspacePath,t,f),{changeId:e.changeId,state:f.transaction.state,artifact:d,digest:s}}async function ga(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId);if(await we(e.workspacePath,t),e.effectClasses.length===0)throw new Error("Authorization requires at least one effect class.");let r=await I(e.workspacePath,a,e.changeId,C("authorized",{summary:`Authorize bounded effect classes: ${e.effectClasses.join(", ")}.`,authorization:{grantedBy:e.grantedBy,grant:"bounded-effects",effectClasses:[...new Set(e.effectClasses)].sort()}},e.actorKind??"human",e.grantedBy)),n=await O(e.workspacePath,t,r);return j({operation:"authorize",lease:t,record:r,capsule:n,nextActions:[`workspai change effect record --change ${e.changeId} --file <effect-receipt.json> --json`,`workspai change verify --change ${e.changeId} --json`]})}async function ha(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId);if(a.transaction.state!=="blocked"&&a.transaction.state!=="awaiting-human")throw new Error(`Resume requires blocked or awaiting-human state, observed ${a.transaction.state}.`);let r=await I(e.workspacePath,a,e.changeId,C("resumed",{summary:e.reason,reason:e.reason,resumeTo:e.resumeTo},"human",e.actorId)),n=await O(e.workspacePath,t,r);return j({operation:"resume",lease:t,record:r,capsule:n,nextActions:e.resumeTo==="verifying"?[`workspai change verification record --change ${e.changeId} --file <verification-receipt.json> --json`]:[`workspai change effect record --change ${e.changeId} --file <effect-receipt.json> --json`]})}async function pa(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId),r=new Set(e.receipt.artifacts.map(f=>v(f.artifact))),n=(e.receipt.deletedArtifacts??[]).map(f=>v(f.artifact));if(new Set(n).size!==n.length)throw new Error("Effect receipt contains duplicate deleted-artifact identities.");if(n.some(f=>r.has(f)))throw new Error("An effect artifact cannot be both present and deleted in one receipt.");if(n.length>0&&e.receipt.status!=="succeeded")throw new Error("Only a succeeded effect may carry deleted-artifact tombstones.");for(let f of e.receipt.artifacts)if(!await F(e.workspacePath,f))throw new Error(`Effect artifact is missing or corrupt: ${f.artifact}`);for(let f of e.receipt.deletedArtifacts??[])if(!await et(e.workspacePath,f))throw new Error(`Deleted effect artifact is present, outside the governed scope, or has an invalid tombstone: ${f.artifact}`);let s=await I(e.workspacePath,a,e.changeId,C("effect-recorded",{summary:e.receipt.summary,effect:e.receipt},e.actorKind??"agent",e.actorId??"workspai-agent")),d=await O(e.workspacePath,t,s);return j({operation:"effect-record",lease:t,record:s,capsule:d,nextActions:s.transaction.state==="blocked"?[`workspai change status --change ${e.changeId} --json`]:[`workspai change verify --change ${e.changeId} --json`]})}async function ua(e){let t=b.resolve(e.workspacePath),{lease:a,record:r}=await R(t,e.changeId);if(!r.transaction.requiredCriteria.includes(e.receipt.criterionId))throw new Error(`Verification criterion '${e.receipt.criterionId}' is outside the immutable Goal contract.`);let n=await J(t),s=V(e.changeId),[d,f]=await Promise.all([A(t,s.actualOverlay),A(t,s.surprises)]),l=r.transaction.verifications.some(i=>i.criterionId==="workspace-verify"&&i.status==="passed");if(!d||!f||!l)throw new Error("Domain verification can be admitted only after change verify re-observes the Graph and records a passing Workspace Verify receipt.");let o=Y(n),c=te(r.transaction,me);if(e.receipt.target.modelHash!==o.modelHash||e.receipt.target.graphHash!==o.graphHash||e.receipt.target.effectHeadDigest!==c)throw new Error("Verification receipt does not target the current Model, Graph, and effect head.");for(let i of e.receipt.artifacts)if(!await F(t,i))throw new Error(`Verification artifact is missing or corrupt: ${i.artifact}`);let h=e.actorKind??"ci",y=e.actorId??"workspai-verifier",p=r;if(p.transaction.state==="blocked"){if(!p.transaction.blockers.every(g=>g.code==="change.verification.criteria_missing"))throw new Error("The change is blocked by a condition that a verification receipt cannot resume.");p=await I(t,p,e.changeId,C("resumed",{summary:"Resume to admit a missing verification receipt.",resumeTo:"verifying"},h,y));}else if(p.transaction.state!=="verifying")throw new Error(`Verification receipt requires verifying or criteria-blocked state; observed ${p.transaction.state}.`);p=await I(t,p,e.changeId,C("verification-recorded",{summary:e.receipt.summary,verification:e.receipt},h,y)),p.transaction.state==="verifying"&&p.transaction.requiredCriteria.every(g=>p.transaction.verifications.filter(E=>E.criterionId===g).at(-1)?.status==="passed")&&(p=await I(t,p,e.changeId,C("committed",{summary:"Seal the independently verified proof-carrying change."},h,y)));let k=await O(t,a,p);return j({operation:"verification-record",lease:a,record:p,capsule:k,nextActions:p.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}function ae(e,t,a,r="verification"){return T({role:r,artifact:e,schemaVersion:t,value:c(a)})}function ue(e){return e.summary.entityAdds+e.summary.entityRemovals+e.summary.entityChanges+e.summary.relationAdds+e.summary.relationRemovals+e.summary.relationChanges+e.summary.proofAdds+e.summary.proofRemovals+e.summary.proofChanges>0}function v(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function $t(e){if(e.scope.kind==="workspace")return e.overlay;let t=new Set(e.scope.projects),a=i=>!!(i.projectId&&t.has(i.projectId)),r={added:e.overlay.entities.added.filter(a),removed:e.overlay.entities.removed.filter(a),changed:e.overlay.entities.changed.filter(i=>a(i.after??i.before??{}))},n=i=>e.scopedEntityIds.has(i.from)||e.scopedEntityIds.has(i.to),s={added:e.overlay.relations.added.filter(n),removed:e.overlay.relations.removed.filter(n),changed:e.overlay.relations.changed.filter(i=>{let g=i.after??i.before;return !!(g&&n(g))})},d=new Set([...r.added.flatMap(i=>i.proofIds),...r.removed.flatMap(i=>i.proofIds),...r.changed.flatMap(i=>[...i.before?.proofIds??[],...i.after?.proofIds??[]]),...s.added.flatMap(i=>i.proofIds),...s.removed.flatMap(i=>i.proofIds),...s.changed.flatMap(i=>[...i.before?.proofIds??[],...i.after?.proofIds??[]])]),f=i=>{let g=v(i);return e.projectPrefixes.includes(".")?true:e.projectPrefixes.some(P=>g===P||g.startsWith(`${P}/`))},l=i=>d.has(i.id)||f(i.artifact),o={added:e.overlay.proofs.added.filter(l),removed:e.overlay.proofs.removed.filter(l),changed:e.overlay.proofs.changed.filter(i=>{let g=i.after??i.before;return !!(g&&l(g))})},c=e.overlay.impactedEntityIds.filter(i=>e.scopedEntityIds.has(i)),h=e.overlay.changedArtifacts.filter(f),y=r.removed.length+s.removed.length+o.removed.length,p=y+r.added.length+r.changed.length+s.added.length+s.changed.length+o.added.length+o.changed.length,k=p===0?"none":y>0||c.length>=10?"high":c.length>=5||p>=5?"medium":"low";return {...e.overlay,entities:r,relations:s,proofs:o,impactedEntityIds:c,changedArtifacts:h,summary:{entityAdds:r.added.length,entityRemovals:r.removed.length,entityChanges:r.changed.length,relationAdds:s.added.length,relationRemovals:s.removed.length,relationChanges:s.changed.length,proofAdds:o.added.length,proofRemovals:o.removed.length,proofChanges:o.changed.length,impactedEntities:c.length,changedArtifacts:h.length,risk:k}}}function Ye(e){let t=b.normalize(b.resolve(e));return process.platform==="win32"?t.toLowerCase():t}async function St(e){let t=new Set(e.receiptedArtifacts.map(v)),a=new Set;for(let n of t){let s=await d(e.workspacePath,n);s&&a.add(Ye(s));}let r=[];for(let n of e.changedArtifacts){let s=v(n);if(t.has(s))continue;let d$1=await d(e.workspacePath,s);d$1&&a.has(Ye(d$1))||r.push(n);}return r}function Vt(e){let t=v(e.artifact);return e.receiptedArtifacts.has(t)||e.scope.kind==="workspace"||e.projectPrefixes.includes(".")?true:e.projectPrefixes.some(a=>t===a||t.startsWith(`${a}/`))}async function xt(e){let t=v(e.artifact),a=f=>{let l=f.proofs.filter(o=>v(o.artifact)===t);return l.length===0?[]:l.some(o=>!o.contentHash)?null:[...new Set(l.map(o=>o.contentHash))].sort()},r=a(e.baseline),n=a(e.head),s=await Qe(e.workspacePath,t),d=e.baseline.pccArtifactContentHashes?.[t];return d?s===null||s!==d:r&&r.length>0?s===null||!r.includes(s):r&&r.length===0?s!==null||!!n?.length:r===null||n===null?true:c(r)!==c(n)}async function ma(e){let t=b.resolve(e.workspacePath),{lease:a,record:r}=await R(t,e.changeId);if(r.transaction.state!=="authorized"&&r.transaction.state!=="executing")throw new Error(`Verification requires authorized or executing state, observed ${r.transaction.state}.`);e.refresh!==false&&await c$1({workspacePath:t,strict:false,agent:"generic"});let n=await J(t),s=await A(t,a.privateMaterialization.artifact);if(!s||c(s)!==a.privateMaterialization.digest.value)throw new Error(`The hash-bound baseline materialization is missing or corrupt for ${e.changeId}.`);let d=new Date().toISOString(),f$1=n.model.projects.filter(w=>a.scope.projects.includes(w.name)).map(w=>v(w.path).replace(/\/$/u,"")).filter(Boolean),l=$t({overlay:a$1(s,n.graph,new Date(d)),scope:a.scope,projectPrefixes:f$1,scopedEntityIds:new Set([...s.entities,...n.graph.entities].filter(w=>w.projectId&&a.scope.projects.includes(w.projectId)).map(w=>w.id))}),o=V(e.changeId);await h$1(t,o.actualOverlay,l);let c$2=ae(o.actualOverlay,l.schemaVersion,l,"actual-architecture-overlay"),h=await A(t,o.prediction),y=h?ae(o.prediction,h.schemaVersion,h,"noncanonical-prediction"):null,p=Dt({changeId:e.changeId,generatedAt:d,prediction:h,predictionReference:y,actual:l,actualReference:c$2});await h$1(t,o.surprises,p);let k=ae(o.surprises,p.schemaVersion,p,"architecture-surprises"),i=r,g$1=e.actorKind??"cli",P=e.actorId??"workspai-change-verify";if(ue(l)&&i.transaction.effects.length===0){i=await I(t,i,e.changeId,C("blocked",{summary:"Observed architecture change has no typed effect receipt.",blocker:{code:"change.effect_receipt.missing",actionable:true,details:"Record the actual mutation effect before verification can claim causality."}},g$1,P));let w=await O(t,a,i);return j({operation:"verify",lease:a,record:i,capsule:w,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Record missing effect receipt" --json`]})}let E=i.transaction.effects.filter(w=>w.status==="succeeded").flatMap(w=>[...w.artifacts.map(x=>x.artifact),...(w.deletedArtifacts??[]).map(x=>x.artifact)]),G=new Set(E.map(v)),$=(await Promise.all(l.changedArtifacts.map(async w=>({artifact:w,contentChanged:await xt({workspacePath:t,artifact:w,baseline:s,head:n.graph})})))).filter(({artifact:w,contentChanged:x})=>x&&Vt({artifact:w,scope:a.scope,projectPrefixes:f$1,receiptedArtifacts:G})).map(({artifact:w})=>w),S=await St({workspacePath:t,changedArtifacts:$,receiptedArtifacts:E});if(S.length>0){i=await I(t,i,e.changeId,C("blocked",{summary:"Observed architecture artifacts are not covered by typed effect receipts.",blocker:{code:"change.effect_receipt.coverage_missing",actionable:true,details:`Uncovered artifacts: ${S.slice(0,20).join(", ")}`}},g$1,P));let w=await O(t,a,i);return j({operation:"verify",lease:a,record:i,capsule:w,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Cover observed artifacts" --json`]})}let K=await f({workspacePath:t});if(!h$2(K,{strict:e.strict===true}).passed&&At({record:i,lease:a,verify:K})){await g(K,t);let w=await O(t,a,i),x=a.scope.projects[0];return j({operation:"verify",lease:a,record:i,capsule:w,nextActions:[...x?[`workspai workspace run init --workspace ${JSON.stringify(t)} --scope ${JSON.stringify(x)} --json`,`workspai workspace run test --workspace ${JSON.stringify(t)} --scope ${JSON.stringify(x)} --json`,`workspai workspace run build --workspace ${JSON.stringify(t)} --scope ${JSON.stringify(x)} --json`]:[],`workspai change verify --change ${e.changeId} --json`]})}i=await I(t,i,e.changeId,C("verification-started",{summary:"Begin independent post-effect verification."},g$1,P));let X=await g(K,t),ke=b.relative(t,X).split(b.sep).join("/"),re=await A(t,ke);if(!re)throw new Error(`Workspace Verify evidence was not persisted at ${ke}.`);await h$1(t,o.workspaceVerification,re);let Q=await A(t,o.workspaceVerification);if(!Q)throw new Error(`Change-scoped Workspace Verify evidence was not persisted at ${o.workspaceVerification}.`);let N=h$2(re,{strict:e.strict===true}),Pe=Y(n),Ce={id:`verify-workspace-${c({generatedAt:d,verify:Q,gate:N}).slice(0,16)}`,criterionId:"workspace-verify",status:N.passed?"passed":"failed",summary:N.passed?`Workspace Verify passed in ${N.mode} mode.`:`Workspace Verify blocked in ${N.mode} mode: ${N.reasons.join("; ")}`,target:{modelHash:Pe.modelHash,graphHash:Pe.graphHash,effectHeadDigest:te(i.transaction,me)},artifacts:[ae(o.workspaceVerification,Q.schemaVersion,Q),c$2,k],observedAt:d};if(i=await I(t,i,e.changeId,C("verification-recorded",{summary:Ce.summary,verification:Ce},g$1,P)),i.transaction.state==="verifying"){let w=i.transaction.requiredCriteria.filter(x=>i.transaction.verifications.filter(rt=>rt.criterionId===x).at(-1)?.status!=="passed");w.length>0?i=await I(t,i,e.changeId,C("blocked",{summary:"Required outcome verification is incomplete.",blocker:{code:"change.verification.criteria_missing",actionable:true,details:`Missing passing receipts: ${w.join(", ")}`}},g$1,P)):i=await I(t,i,e.changeId,C("committed",{summary:"Seal the independently verified proof-carrying change."},g$1,P));}let at=await O(t,a,i);return j({operation:"verify",lease:a,record:i,capsule:at,nextActions:i.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}async function wa(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId),r=await ye({workspacePath:e.workspacePath,lease:t,record:a});return j({operation:e.operation??"status",lease:t,record:a,capsule:r,nextActions:a.transaction.state==="evidence-ready"?[`workspai change authorize --change ${e.changeId} --effects filesystem,command --json`]:a.transaction.state==="authorized"||a.transaction.state==="executing"?[`workspai change verify --change ${e.changeId} --json`]:[]})}async function ya(e){let t=b.resolve(e.workspacePath),a$1=await b$1(t,".workspai/changes","directory"),n=(a$1?await z.readdir(a$1,{withFileTypes:true}):[]).filter(l=>l.isDirectory()&&/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(l.name)).map(l=>l.name).sort(),s=[],d=null;for(let l of n)try{let{lease:o,record:c}=await R(t,l);d??=o.workspace.name;let h=await ye({workspacePath:t,lease:o,record:c}),y=await ve({workspacePath:t,changeId:l}),p=c.transaction.blockers.map(i=>i.details??i.code),k=h.status==="blocked"?h.assurances.filter(i=>i.status==="failed").map(i=>`${i.id}: ${i.summary}`):[];s.push({changeId:l,goalId:o.goalId,state:c.transaction.state,status:h.status,createdAt:c.transaction.createdAt,updatedAt:c.transaction.updatedAt,scope:o.scope,assurance:{passed:h.assurances.filter(i=>i.status==="passed").length,total:h.assurances.length},blockers:[...new Set([...p,...k])],capsuleArtifact:V(l).capsule,valid:y.valid,errors:y.errors});}catch(o){s.push({changeId:l,goalId:null,state:null,status:"invalid",createdAt:null,updatedAt:null,scope:null,assurance:{passed:0,total:5},blockers:[],capsuleArtifact:V(l).capsule,valid:false,errors:[o instanceof Error?o.message:String(o)]});}s.sort((l,o)=>(o.updatedAt??"").localeCompare(l.updatedAt??"")||l.changeId.localeCompare(o.changeId));let f={schemaVersion:m,generatedAt:new Date().toISOString(),workspace:{name:d??await vt(t)},changes:s,summary:{total:s.length,open:s.filter(l=>l.status==="open"||l.status==="verified").length,blocked:s.filter(l=>l.status==="blocked").length,sealed:s.filter(l=>l.status==="sealed").length,aborted:s.filter(l=>l.status==="aborted").length,invalid:s.filter(l=>!l.valid).length}};return a(f,"contracts/workspace-intelligence/proof-carrying-change-list.v1.json","Proof-Carrying Change list"),f}async function va(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId),r=await I(e.workspacePath,a,e.changeId,C("aborted",{summary:e.reason,reason:e.reason},"human",e.actorId)),n=await O(e.workspacePath,t,r);return j({operation:"abort",lease:t,record:r,capsule:n,nextActions:[]})}async function ve(e){let t=V(e.changeId),a$1=await A(e.workspacePath,t.capsule);if(!a$1)throw new Error(`Proof-carrying change capsule not found: ${e.changeId}`);let r=[];a$1.schemaVersion!==k&&r.push(`Unsupported capsule schema: ${a$1.schemaVersion}`),a$1.changeId!==e.changeId&&r.push("Capsule change binding does not match."),c(Rt(a$1))!==a$1.integrity.capsuleDigest&&r.push("Capsule integrity digest does not match its canonical content.");let{lease:n$1,record:s}=await R(e.workspacePath,e.changeId),d=s.transaction.evidence.find(o=>o.role==="architecture-lease");(!d||d.digest.value!==c(n$1))&&r.push("Architecture lease does not match the decision-ledger evidence binding."),(n$1.goalId!==a$1.goalId||n$1.generation!==c({modelHash:n$1.baseline.model.digest.value,graphHash:n$1.baseline.graph.digest.value,inputHash:n$1.baseline.graph.inputHash}))&&r.push("Architecture lease identity or generation binding is invalid."),s.transaction.eventHeadDigest!==a$1.decision.eventHeadDigest&&r.push("Capsule does not bind the current decision event head."),c(s.transaction)!==a$1.decision.transaction.digest.value&&r.push("Decision transaction projection digest does not match the capsule.");let f=await A(e.workspacePath,n$1.privateMaterialization.artifact);(!f||c(f)!==n$1.privateMaterialization.digest.value)&&r.push("Hash-bound baseline materialization is missing or corrupt.");for(let o of [a$1.intent,a$1.decision.transaction,a$1.prediction,a$1.actualOverlay,a$1.surpriseReport,...a$1.effects,...a$1.verification].filter(c=>!!c))await F(e.workspacePath,o)||r.push(`Referenced artifact is missing or corrupt: ${o.artifact}`);for(let o of a$1.deletedArtifacts??[])await et(e.workspacePath,o)||r.push(`Deleted artifact tombstone is invalid or the artifact exists again: ${o.artifact}`);let l={schemaVersion:n,changeId:e.changeId,validatedAt:new Date().toISOString(),valid:r.length===0,errors:r,capsule:a$1};return a(l,"contracts/workspace-intelligence/proof-carrying-change-capsule-validation.v1.json","Proof-Carrying Change capsule validation"),l}async function ka(e){let t=await ve(e);if(!t.valid)throw new Error(`Cannot export an invalid capsule: ${t.errors.join("; ")}`);let a$1=b.resolve(e.workspacePath),r=b.resolve(a$1,e.outputPath),n=b.relative(a$1,r);if(n===".."||n.startsWith(`..${b.sep}`)||b.isAbsolute(n))throw new Error("Capsule export path must remain inside the workspace.");let s=n.split(b.sep).join("/"),d=await h$1(a$1,s,t.capsule),f={schemaVersion:o,changeId:e.changeId,outputPath:d,validation:t};return a(f,"contracts/workspace-intelligence/proof-carrying-change-capsule-export.v1.json","Proof-Carrying Change capsule export"),f}function Pa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Prediction input must be a JSON object.");let t=e;if(!Array.isArray(t.operations)||!Array.isArray(t.assumptions))throw new Error("Prediction input requires operations[] and assumptions[].");let a=new Set(["add","remove","change"]),r=new Set(["entity","relation","proof","artifact"]),n=new Set(["high","medium","low"]);for(let d of t.operations)if(!d||!a.has(d.operation)||!r.has(d.targetKind)||typeof d.targetId!="string"||d.targetId.trim().length===0||typeof d.rationale!="string"||!n.has(d.confidence))throw new Error("Prediction contains an invalid operation.");let s=t.predictedRisk;if(!s||!["none","low","medium","high"].includes(s))throw new Error("Prediction requires predictedRisk: none, low, medium, or high.");return {schemaVersion:i$1,changeId:t.changeId??"change-placeholder",goalId:t.goalId??"goal-placeholder",generatedAt:t.generatedAt??new Date().toISOString(),baselineGeneration:t.baselineGeneration??"pending-binding",nonCanonical:true,proofEligible:false,operations:t.operations,assumptions:t.assumptions.filter(d=>typeof d=="string"),predictedRisk:s}}function Ca(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Effect receipt input must be a JSON object.");let t=e;if(typeof t.id!="string"||!["filesystem","command","configuration","dependency","external"].includes(String(t.effectClass))||!["succeeded","failed","uncertain"].includes(String(t.status))||typeof t.summary!="string"||typeof t.observedAt!="string"||typeof t.idempotencyKey!="string"||!Array.isArray(t.artifacts))throw new Error("Effect receipt is missing required typed fields.");if(t.deletedArtifacts!==void 0&&(!Array.isArray(t.deletedArtifacts)||t.deletedArtifacts.some(r=>!r||typeof r.artifact!="string"||r.observedAt!==void 0&&typeof r.observedAt!="string"||r.digest!==void 0&&(r.digest.algorithm!=="sha256"||r.digest.semantics!=="deletion-tombstone-v1"||typeof r.digest.value!="string"))))throw new Error("Effect receipt contains an invalid deleted-artifact tombstone.");let a=t;return {...a,...a.deletedArtifacts?{deletedArtifacts:a.deletedArtifacts.map(r=>r.digest?r:kt({artifact:r.artifact,observedAt:r.observedAt??a.observedAt}))}:{}}}function Ia(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Verification receipt input must be a JSON object.");let t=e;if(typeof t.id!="string"||typeof t.criterionId!="string"||!["passed","failed","inconclusive"].includes(String(t.status))||typeof t.summary!="string"||typeof t.observedAt!="string"||!t.target||typeof t.target.modelHash!="string"||typeof t.target.graphHash!="string"||typeof t.target.effectHeadDigest!="string"||!Array.isArray(t.artifacts))throw new Error("Verification receipt is missing required typed fields.");return t}function Aa(e,t){return e.decision.eventHeadDigest===t.eventHeadDigest&&e.decision.transaction.digest.value===c(t)}async function ba(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId);if(t.goalId!==e.goalId)throw new Error(`Proof-carrying change ${e.changeId} is not bound to Goal ${e.goalId}.`);let r=new Set(["authorized","executing","verifying"]),n=a.transaction.state==="blocked"&&a.transaction.blockers.length>0&&a.transaction.blockers.every(i=>i.code==="change.verification.criteria_missing");if(!r.has(a.transaction.state)&&!n)throw new Error(`Proof-carrying change ${e.changeId} is not an applied scaffold pending verification.`);let s=a.transaction.effects.filter(i=>i.effectClass==="filesystem");if(s.length===0)throw new Error(`Proof-carrying change ${e.changeId} has no succeeded filesystem effect receipt.`);if(s.some(i=>i.status!=="succeeded"||i.artifacts.length===0))throw new Error(`Proof-carrying change ${e.changeId} has incomplete or unsuccessful filesystem effects.`);for(let i of s)for(let g of i.artifacts)if(!await F(e.workspacePath,g))throw new Error(`Proof-carrying change ${e.changeId} no longer matches effect artifact ${g.artifact}.`);let d=a.transaction.plans.find(i=>i.role===tt);if(d){let i=await A(e.workspacePath,d.artifact);if(!i||c(i)!==d.digest.value)throw new Error(`Proof-carrying change ${e.changeId} has a missing or corrupt agent framework plan.`);let g=i.target,P=typeof g?.artifactPrefix=="string"?v(g.artifactPrefix).replace(/\/$/u,""):"",E=Array.isArray(i.files)?i.files.flatMap(S=>{if(!S||typeof S!="object")return [];let K=S.path;if(typeof K!="string")return [];let X=v(K);return [P?`${P}/${X}`:X]}):[],G=new Set(s.flatMap(S=>S.artifacts.map(K=>v(K.artifact)))),$=E.filter(S=>!G.has(S));if(E.length===0||$.length>0)throw new Error(`Proof-carrying change ${e.changeId} has a partial filesystem effect receipt.`)}let f=await J(e.workspacePath),l=Y(f),o=await A(e.workspacePath,t.privateMaterialization.artifact);if(!o||c(o)!==t.privateMaterialization.digest.value)throw new Error(`Proof-carrying change ${e.changeId} has a missing or corrupt architecture baseline.`);let c$1=a$1(o,f.graph),h=new Set,y=await b$1(e.workspacePath,".workspai/changes","directory"),p=y?await z.readdir(y,{withFileTypes:true}):[];for(let i of p){if(!i.isDirectory()||!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(i.name))continue;let g=await R(e.workspacePath,i.name).catch(()=>null);if(!g||g.record.transaction.createdAt<t.createdAt)continue;let P=g.record.transaction.effects.filter($=>$.effectClass==="filesystem"&&$.status==="succeeded");if(P.length===0)continue;for(let $ of P)for(let S of $.artifacts)await F(e.workspacePath,S)&&h.add(v(S.artifact));let E=g.record.transaction.plans.find($=>$.role==="noncanonical-prediction");if(!E)continue;let G=await A(e.workspacePath,E.artifact);if(!(!G||c(G)!==E.digest.value))for(let $ of G.operations)$.targetKind==="artifact"&&h.add(v($.targetId));}let k=c$1.changedArtifacts.map(v).filter(i=>!h.has(i));if(k.length>0)throw new Error(`Proof-carrying change ${e.changeId} does not explain current architecture artifacts: ${k.slice(0,3).join(", ")}.`);return {modelHash:l.modelHash,graphHash:l.graphHash}}async function Ea(e){let t=await ve({workspacePath:e.workspacePath,changeId:e.changeId});if(!t.valid)throw new Error(`Proof-carrying change ${e.changeId} failed capsule validation.`);let{lease:a,record:r}=await R(e.workspacePath,e.changeId);if(a.goalId!==e.goalId||r.transaction.state!=="committed"||t.capsule.status!=="sealed")throw new Error(`Proof-carrying change ${e.changeId} is not a sealed change for ${e.goalId}.`);let n=[...r.transaction.verifications].reverse().find(s=>s.status==="passed");if(!n)throw new Error(`Proof-carrying change ${e.changeId} has no passing verification receipt.`);return {modelHash:n.target.modelHash,graphHash:n.target.graphHash}}
4
+ export{Je as a,kt as b,da as c,la as d,fa as e,ga as f,ha as g,pa as h,ua as i,St as j,ma as k,wa as l,ya as m,va as n,ve as o,ka as p,Pa as q,Ca as r,Ia as s,Aa as t,ba as u,Ea as v};
@@ -1,2 +1,2 @@
1
- import {r,m,n,l}from'./chunk-LARREYZN.js';import {a}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {d as d$1}from'./chunk-VXFIMEC6.js';import {h as h$1}from'./chunk-BLEIUQL6.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e,d,b as b$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import k from'path';import V from'fs-extra';import {spawnSync}from'child_process';function ue(){let e={...process.env};return delete e.GIT_DIR,delete e.GIT_WORK_TREE,delete e.GIT_INDEX_FILE,delete e.GIT_PREFIX,e}function x(e,t,a){let r=spawnSync("git",t,{cwd:e,env:ue(),encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(r.status!==0)return {ok:false,stdout:""};let i=r.stdout??"";return {ok:true,stdout:a?.preserveWhitespace?i:i.trim()}}function ge(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return t===".workspai/AGENT-GROUNDING.md"?true:[".workspai/reports/",".workspai/cache/",".rapidkit/reports/",".rapidkit/cache/"].some(a=>t.startsWith(a))}function ke(e){let t=[],a=[],r=[];for(let i of e.split(`
1
+ import {r,m,n,l}from'./chunk-SEZTSMRR.js';import {a}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {d as d$1}from'./chunk-IHWS3ALP.js';import {h as h$1}from'./chunk-BLEIUQL6.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e,d,b as b$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import k from'path';import V from'fs-extra';import {spawnSync}from'child_process';function ue(){let e={...process.env};return delete e.GIT_DIR,delete e.GIT_WORK_TREE,delete e.GIT_INDEX_FILE,delete e.GIT_PREFIX,e}function x(e,t,a){let r=spawnSync("git",t,{cwd:e,env:ue(),encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(r.status!==0)return {ok:false,stdout:""};let i=r.stdout??"";return {ok:true,stdout:a?.preserveWhitespace?i:i.trim()}}function ge(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return t===".workspai/AGENT-GROUNDING.md"?true:[".workspai/reports/",".workspai/cache/",".rapidkit/reports/",".rapidkit/cache/"].some(a=>t.startsWith(a))}function ke(e){let t=[],a=[],r=[];for(let i of e.split(`
2
2
  `)){if(!i.trim())continue;let n=i.slice(0,2),c=i.slice(3).trim();if(c&&!ge(c)){if(n==="??"){a.push(c);continue}n.includes("D")&&r.push(c),t.push(c);}}return {changedFiles:[...new Set(t)].sort(),untrackedFiles:[...new Set(a)].sort(),deletedFiles:[...new Set(r)].sort()}}function Q(e,t){let a={available:false,dirty:false,changedFiles:[],untrackedFiles:[],deletedFiles:[]},r=x(e,["rev-parse","--is-inside-work-tree"]);if(!r.ok||r.stdout!=="true")return a;let i=x(e,["rev-parse","--abbrev-ref","HEAD"]),n=x(e,["rev-parse","HEAD"]),c=x(e,["status","--porcelain=v1","--untracked-files=all"],{preserveWhitespace:true}),p=ke(c.stdout),m=p.changedFiles.length>0||p.untrackedFiles.length>0||p.deletedFiles.length>0;return {available:true,branch:i.ok?i.stdout:void 0,commit:n.ok?n.stdout:void 0,ref:t?.ref,dirty:m,changedFiles:p.changedFiles,untrackedFiles:p.untrackedFiles,deletedFiles:p.deletedFiles}}var oe=q.snapshot,L=q.diff,T=p.snapshot,ae=p.diff,he=q.impact,we=p.impact;function ye(e$1){if(e$1.model.projectTopology||!e$1.model.graph||e$1.modelHash!==e(e$1.model))return null;let t={...e$1.model,projectTopology:e$1.model.graph,graph:e$1.model.graph};return {...e$1,modelHash:d(t),model:t}}function ne(e){let t=e.trim().toLowerCase();return t==="git"||t.startsWith("git:")}function We(e){let t=e.trim();return t.toLowerCase()==="git"?"HEAD":t.toLowerCase().startsWith("git:")&&t.slice(4).trim()||"HEAD"}function se(e,t){return k.isAbsolute(t)?t:k.join(e,t)}async function be(e){let t=await V.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace model input is not a JSON object: ${e}`);let a=t;if(a.schemaVersion===oe){a$1(t,"contracts/workspace-intelligence/workspace-model-snapshot.v1.json",`Workspace model snapshot ${e}`);let r=a;if(!r.model||r.model.schemaVersion!==l)throw new Error(`Invalid workspace model snapshot: ${e}`);let i=d(r.model);if(r.modelHash!==i){let n=ye(r);if(!n)throw new Error(`Workspace model snapshot hash mismatch: ${e}`);return {model:n.model,hash:n.modelHash}}return {model:r.model,hash:r.modelHash}}if(a.schemaVersion===l){a$1(t,"contracts/workspace-intelligence/workspace-model.v1.json",`Workspace model ${e}`);let r=a;return {model:r,hash:d(r)}}throw a.schemaVersion===L?new Error(`workspace diff --from received a diff report (${k.basename(e)}). Use a workspace model snapshot or model report as baseline, e.g. ${T}. To analyze an existing diff report, run: npx workspai workspace impact --from ${k.basename(e)} --json`):new Error(`Unsupported workspace model input schema: ${String(a.schemaVersion)}`)}async function ve(e){let t=await V.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace diff input is not a JSON object: ${e}`);let a=t;if(a.schemaVersion!==L)return null;a$1(t,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Workspace model diff ${e}`);let r=a;if(!r.currentModel||r.currentModel.schemaVersion!==l||!r.summary||!Array.isArray(r.changes))throw new Error(`Invalid workspace model diff report: ${e}`);if(r.toHash!==d(r.currentModel))throw new Error(`Workspace model diff current-model hash mismatch: ${e}`);return r}async function Ye(e){let t=e.model??await r({workspacePath:e.workspacePath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {schemaVersion:oe,generatedAt:(e.now??new Date).toISOString(),modelHash:d(t),modelRef:m,model:t}}async function Qe(e,t){return h$1(t,T,d$1(e))}function F(e){let{evidence:t,...a}=e;return a}function h(e,t){e.push(t);}function je(e,t){let a=[],r=["name","profile","type"],i=["workspaceType","surfaces","runtimeFamilies","businessCapabilities"];for(let n of r){let c=e.workspace[n],p=t.workspace[n];b$1(c)!==b$1(p)&&h(a,{type:"workspace.changed",severity:"info",target:`workspace.${n}`,message:`Workspace metadata field changed: ${String(n)}`,before:c,after:p});}for(let n of i){let c=e.identity[n],p=t.identity[n];b$1(c)!==b$1(p)&&h(a,{type:"workspace.changed",severity:"info",target:`identity.${n}`,message:`Workspace identity field changed: ${String(n)}`,before:c,after:p});}return b$1(e.policies)!==b$1(t.policies)&&h(a,{type:"workspace.changed",severity:"warning",target:"policies",message:"Workspace policy summary changed.",before:e.policies,after:t.policies}),b$1(e.discovery)!==b$1(t.discovery)&&h(a,{type:"workspace.changed",severity:"info",target:"discovery",message:"Workspace discovery settings changed.",before:e.discovery,after:t.discovery}),e.contracts.exists!==t.contracts.exists&&h(a,{type:"workspace.changed",severity:t.contracts.exists?"info":"warning",target:t.contracts.workspaceContractPath,message:"Workspace contract presence changed.",before:e.contracts.exists,after:t.contracts.exists}),a}function Me(e,t){let a=e.validation??null,r=t.validation??null;return b$1(a)===b$1(r)?[]:[{type:"validation.changed",severity:r?.status==="failed"?"critical":"warning",target:"validation",message:"Workspace model validation changed.",before:a,after:r}]}function Ie(e,t){let a=[],r=new Map(e.projects.map(n=>[n.path,n])),i=new Map(t.projects.map(n=>[n.path,n]));for(let[n,c]of i.entries()){let p=r.get(n);if(!p){h(a,{type:"project.added",severity:"info",target:n,message:`Project added: ${c.name}`,after:F(c)});continue}let m=F(p),l=F(c);if(b$1(m)!==b$1(l)){let u=p.runtime!==c.runtime||p.framework!==c.framework;h(a,{type:"project.changed",severity:u?"warning":"info",target:n,message:`Project changed: ${c.name}`,before:m,after:l});}}for(let[n,c]of r.entries())i.has(n)||h(a,{type:"project.removed",severity:"warning",target:n,message:`Project removed: ${c.name}`,before:F(c)});return a.sort((n,c)=>`${n.type}:${n.target}`.localeCompare(`${c.type}:${c.target}`))}async function Pe(e){let t=k.resolve(e.workspacePath),a=ne(e.fromPath),r$1=a?We(e.fromPath):void 0,i=e.fromPath;if(a){let f=k.join(t,T);if(!await V.pathExists(f))throw new Error("Git-aware workspace diff requires an existing snapshot at .workspai/reports/workspace-model-snapshot.json. Run: npx workspai workspace snapshot --json");i=T;}let n=se(t,i),c=await be(n),p=e.model??await r({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),m$1=d(p),l=[...je(c.model,p),...Ie(c.model,p),...Me(c.model,p)],u;e.includeGitObservation!==false&&(u=e.gitObservation??Q(t,{ref:r$1}),u.available&&Se(l,u,p));let v=c.hash!==m$1;v&&!l.some(f=>!f.type.startsWith("git."))&&h(l,{type:"workspace.changed",severity:"warning",target:"model.structural-hash",message:"Workspace structural identity changed outside the currently classified diff fields.",before:c.hash,after:m$1});let P=l.filter(f=>f.type.startsWith("git.")).length,w=a?`git:${r$1??"HEAD"}`:k.relative(t,n).split(k.sep).join("/");return {schemaVersion:L,generatedAt:(e.now??new Date).toISOString(),fromRef:w,toRef:m,fromHash:c.hash,toHash:m$1,summary:{changed:v||P>0,addedProjects:l.filter(f=>f.type==="project.added").length,removedProjects:l.filter(f=>f.type==="project.removed").length,changedProjects:l.filter(f=>f.type==="project.changed").length,workspaceChanges:l.filter(f=>f.type==="workspace.changed").length,validationChanges:l.filter(f=>f.type==="validation.changed").length,gitChangedFiles:P},git:u?.available?Oe(u,r$1):{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:l,currentModel:p}}async function Ze(e,t){return h$1(t,ae,d$1(e))}function I(e){return {none:0,low:1,medium:2,high:3,critical:4}[e]}function Z(e){return e.reduce((t,a)=>I(a)>I(t)?a:t,"none")}var N=["none","low","medium","high","critical"];function Re(e){let t=Math.max(1,I(e)-1);return N[t]}function Ce(e){let t=Math.min(N.length-1,I(e)+1);return N[t]}function ee(e){return e.join(" ")}function b(e,t,a,r){return {id:e,label:t,scope:r.scope,project:r.project,display:ee(["npx","workspai",...a]),execute:ee(["npx","--yes","--package","workspai","workspai",...a]),required:r.required!==false}}function te(e){let t=`project:${e.name}`,a=e.commands.fleetStages,r={init:`Run init for ${e.name}`,test:`Run tests for ${e.name}`,build:`Run build for ${e.name}`,start:`Run start for ${e.name}`};return ["init","test","build","start"].filter(i=>a.includes(i)).map(i=>b(`project.${e.name}.${i}`,r[i],["workspace","run",i,"--scope",t,"--json"],{scope:"project",project:e.name}))}function _(){return [b("workspace.doctor","Run workspace doctor",["doctor","workspace","--json"],{scope:"workspace"}),b("workspace.contract.verify","Verify workspace contract",["workspace","contract","verify","--json"],{scope:"workspace"}),b("workspace.readiness","Run release readiness",["readiness","--json"],{scope:"workspace"}),b("workspace.analyze","Run workspace analyze",["analyze","--json"],{scope:"workspace",required:false}),b("workspace.pipeline","Run governance pipeline",["pipeline","--json"],{scope:"workspace",required:false}),b("workspace.doctor-fix","Verify doctor fix result",["doctor","workspace","--fix","--json"],{scope:"workspace",required:false})]}function Ee(e,t){let a=t.split(k.sep).join("/");return e.projects.filter(i=>{let n=i.path.split(k.sep).join("/");return a===n||a.startsWith(`${n}/`)}).sort((i,n)=>n.path.length-i.path.length)[0]}function Se(e,t,a){let r=new Set(e.map(n=>n.target)),i=(n,c)=>{let p=c.split(k.sep).join("/"),m=`git:${p}`;if(r.has(m))return;let l=Ee(a,p),u=l?`${l.name} (${l.path})`:"workspace";h(e,{type:n,severity:n==="git.deleted"?"warning":"info",target:m,message:`Git ${n==="git.untracked"?"untracked":n==="git.deleted"?"deleted":"changed"} file affects ${u}: ${p}`,after:{path:p,project:l?.name,projectPath:l?.path}}),r.add(m);};for(let n of t.changedFiles)i("git.file.changed",n);for(let n of t.untrackedFiles)i("git.untracked",n);for(let n of t.deletedFiles)i("git.deleted",n);}function Oe(e,t){return {available:true,ref:t??e.ref,branch:e.branch,commit:e.commit,dirty:e.dirty,changedFiles:e.changedFiles.length,untrackedFiles:e.untrackedFiles.length,deletedFiles:e.deletedFiles.length}}function Ae(e){let t=new Set,a=[];for(let r of e){let i=`${r.scope}:${r.project??""}:${r.display}`;t.has(i)||(t.add(i),a.push(r));}return a}function De(e){return e.type==="project.removed"?"high":e.severity==="critical"?"critical":e.severity==="warning"?"high":("medium")}function $e(e,t){return e.severity==="critical"?"critical":e.target==="policies"||e.target.includes("contract")?"high":e.type==="validation.changed"?(t?.projectCount??0)===0?"low":"high":e.target==="evidence"?"low":e.severity==="warning"?"medium":"low"}function xe(e){return e.affectedProjects>0||e.projectCount>0||!e.changes.every(a=>a.severity==="critical"?false:a.type.startsWith("git.")||a.type==="validation.changed")?e.risk:I(e.risk)>=I("high")||e.risk==="medium"?"low":e.risk}function re(e,t){if(!e||e==="workspace")return true;let a=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return [t.name,t.path,k.basename(t.path),t.absolutePath].filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase()).includes(a)}function Fe(e){if(!e.changed)return {headline:"No workspace model impact detected.",bullets:["The current workspace model matches the provided snapshot/report."],unsafeAssumptions:["Do not claim runtime verification passed unless a report exists."]};let t=e.affectedProjects.map(a=>a.project?.name??a.target);return {headline:`Workspace impact risk: ${e.risk}.`,bullets:[`Affected projects: ${t.length?t.join(", "):"none"}.`,`Workspace-level items: ${e.workspaceImpact.length}.`,"Use the verification plan before recommending apply, rollback, or release actions."],unsafeAssumptions:["Do not infer test/build success from impact alone.","Do not apply fixes without project scope and verification evidence.","Use display commands for users and execute commands for automation."]}}async function et(e){let t=k.resolve(e.workspacePath),a$1=ne(e.fromPath),r=e.diff;if(!r&&!a$1){let o=se(t,e.fromPath);r=await ve(o)??void 0;}r||(r=await Pe({workspacePath:t,fromPath:e.fromPath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,includeGitObservation:e.includeGitObservation,gitObservation:e.gitObservation,now:e.now,model:e.model}));let i=new Map(r.currentModel.projects.map(o=>[o.path,o])),n$1=new Map(r.currentModel.projects.map(o=>[o.name,o])),c$1=r.changes.filter(o=>o.type.startsWith("project.")),p=new Map;for(let o of c$1){let d=(i.get(o.target)??(typeof o.before?.name=="string"?n$1.get(o.before.name):void 0))?.path??o.target,y=p.get(d)??[];y.push(o),p.set(d,y);}let m=[];for(let[o,s]of p.entries()){let d=i.get(o);if(d&&!re(e.scope,d))continue;let y=Z(s.map(De)),C=d?.name??(typeof s[0]?.before?.name=="string"?String(s[0].before.name):o);m.push({id:`project:${C}`,scope:"project",target:o,title:`Project impact: ${C}`,summary:s.map(j=>j.message).join(" "),risk:y,reasons:s.map(j=>`${j.type}: ${j.message}`),project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?te(d):_()});}let l=n(r.currentModel),u=l?a(l):void 0,v=new Set(m.map(o=>o.project?.name).filter(o=>typeof o=="string")),P=new Map;for(let o of m)if(o.project?.name){let s=u?.byId.get(o.project.name);s&&(o.centrality={fanIn:s.fanIn,fanOut:s.fanOut,reach:s.reach,betweenness:s.betweenness,isHotspot:s.isHotspot},s.isHotspot&&(o.risk=Ce(o.risk),o.reasons=[...o.reasons,`graph.hotspot: critical-path project with ${s.reach} transitive dependent(s); risk escalated.`])),o.origin="direct",o.distance=0,P.set(o.project.name,o.risk);}let w=[],f=0;if(l&&v.size>0){let o=c(l,v);for(let s of o.values()){if(s.distance===0||v.has(s.id))continue;let d=n$1.get(s.id);if(d&&!re(e.scope,d))continue;let y=s.path[0],C=s.path[s.path.length-2]??y,j=P.get(y)??"medium",de=Re(j),M=u?.byId.get(s.id);f=Math.max(f,s.distance),w.push({id:`transitive:${s.id}`,scope:"project",target:d?.path??s.id,title:`Transitive impact: ${s.id}`,summary:`Depends on changed project ${y}${s.via?` via ${s.via}`:""} (distance ${s.distance}).`,risk:de,reasons:[`graph.dependent: depends on ${C}${s.via?` via ${s.via}`:""} (path ${s.path.join(" -> ")})`],project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?te(d):_(),origin:"transitive",distance:s.distance,path:s.path,via:s.via,...M?{centrality:{fanIn:M.fanIn,fanOut:M.fanOut,reach:M.reach,betweenness:M.betweenness,isHotspot:M.isHotspot}}:{}});}}w.sort((o,s)=>o.target.localeCompare(s.target));let ie=u?u.hotspots.flatMap(o=>{let s=u.byId.get(o);return s?[{project:o,fanIn:s.fanIn,fanOut:s.fanOut,reach:s.reach,betweenness:s.betweenness}]:[]}):[],ce=r.changes.filter(o=>!o.type.startsWith("project.")),K=r.currentModel.summary?.projectCount??r.currentModel.projects.length,R=ce.map(o=>({id:`workspace:${o.target}`,scope:"workspace",target:o.target,title:`Workspace impact: ${o.target}`,summary:o.message,risk:$e(o,{projectCount:K}),reasons:[`${o.type}: ${o.message}`],verification:_()})),B=Ae([...m.flatMap(o=>o.verification),...w.flatMap(o=>o.verification),...R.flatMap(o=>o.verification),...r.summary.changed?_():[]]).filter(o=>o.required),pe=Z([...m.map(o=>o.risk),...w.map(o=>o.risk),...R.map(o=>o.risk)]),z=xe({risk:pe,affectedProjects:m.length,projectCount:K,changes:r.changes}),q={changed:r.summary.changed,risk:z,affectedProjects:m.length,workspaceItems:R.length,recommendedCommands:B.length,blastRadius:{directlyAffected:m.length,transitivelyAffected:w.length,maxDistance:f,graphEdges:l?.edges.length??0}};return {schemaVersion:he,generatedAt:(e.now??new Date).toISOString(),fromRef:r.fromRef,diffRef:ae,workspace:{name:r.currentModel.workspace.name,profile:r.currentModel.workspace.profile,type:r.currentModel.workspace.type},summary:q,affectedProjects:m.sort((o,s)=>o.target.localeCompare(s.target)),transitiveImpact:w,criticalPathHotspots:ie,workspaceImpact:R.sort((o,s)=>o.target.localeCompare(s.target)),verificationPlan:B,agentBrief:Fe({changed:q.changed,risk:z,affectedProjects:m,workspaceImpact:R}),diff:r}}async function tt(e,t){return h$1(t,we,d$1(e))}export{Q as a,oe as b,L as c,T as d,ae as e,he as f,we as g,ye as h,ne as i,We as j,Ye as k,Qe as l,Pe as m,Ze as n,_ as o,et as p,tt as q};
@@ -0,0 +1 @@
1
+ import {b as b$1,c,d as d$1}from'./chunk-UP3UWAJV.js';import {a as a$3}from'./chunk-X7FYEKLI.js';import {c as c$2}from'./chunk-P5LI5DL3.js';import {c as c$1,d as d$4}from'./chunk-N4B2M44I.js';import {a as a$1,b as b$2}from'./chunk-PYCJWW4B.js';import {p as p$1,a,o,g as g$1,d as d$3,f}from'./chunk-3EPR3D5Q.js';import {r,n,d as d$5}from'./chunk-SEZTSMRR.js';import {d as d$2}from'./chunk-IHWS3ALP.js';import {g,h as h$1}from'./chunk-BLEIUQL6.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {d}from'./chunk-EWZZUQBR.js';import {q,p,t,r as r$1,s}from'./chunk-ODK4LCEL.js';import k from'path';import w from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return d$5({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function ge(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function me(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function st(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=q.verify,G=p.verify;function je(e,t){return k.isAbsolute(t)?t:k.join(e,t)}async function ke(e){let t=await w.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$2(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$2(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let a=s.transitiveImpact.reduce((l,d)=>Math.max(l,d.distance??0),0);s.summary.blastRadius.maxDistance!==a&&i.push("blastRadius.maxDistance does not match transitive impact distances");let g=n(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==g&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ae(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function Ee(e,t){if(e.id==="workspace.doctor")return k.join(t,p.doctor);if(e.id==="workspace.contract.verify")return k.join(t,p.contractVerify);if(e.id==="workspace.readiness")return k.join(t,p.readiness);if(e.id==="workspace.analyze")return k.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return k.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return k.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return k.join(t,".workspai","reports","workspace-run-last.json")}function h(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function We(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$3(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function Pe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function xe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=h(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===s.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s$1=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s$1.length>0)return {status:"fail",message:`Doctor fix result reports ${s$1.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function $e(e,t$1){let r=await g(e,t.doctorRemediationPlan);if(!r)return false;try{let s=h(await w.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let a=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!a||!t$1)return true;let g=Date.parse(a),l=Date.parse(t$1);return !Number.isFinite(g)||!Number.isFinite(l)?true:g>=l}catch{return false}}function Fe(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=h(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=h(e.projectStages)??h(h(e.enterpriseControls)?.projectStages);if(!s)return null;let i=t.replace(/\\/g,"/").toLowerCase(),a=Object.entries(s).filter(([d,y])=>{let c=d.replace(/\\/g,"/").toLowerCase(),n=h(y),o=h(n?.[r]),p=typeof o?.projectName=="string"?o.projectName.toLowerCase():"",f=typeof o?.relativePath=="string"?o.relativePath.replace(/\\/g,"/").toLowerCase():"";return c===i||p===i||f===i});if(a.length>1)return "ambiguous";let g=h(a[0]?.[1]),l=h(g?.[r]);return l?{generatedAt:typeof l.generatedAt=="string"?l.generatedAt:void 0,status:typeof l.status=="string"?l.status:void 0}:null}function Be(e,t,r){let s=Fe(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let a=i.stage;if(s&&a!==s)return {status:"missing",message:`Workspace run evidence is for stage "${a}", expected "${s}".`};let g=Array.isArray(i.projects)?i.projects:[],l=t.project?.toLowerCase();if(!l)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=g.filter(c=>{let n=h(c);if(!n)return false;let o=typeof n.projectName=="string"?n.projectName.toLowerCase():"",p=["projectPath","relativePath","path"].map(f=>n[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return o===l||p.some(f=>f===l)});if(d.length>1)return {status:"fail",message:`Workspace run evidence is ambiguous for project ${t.project}.`};let y=d[0];if(y){let c=b(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(c)return {status:"fail",message:c};let n=h(y),o=typeof n?.status=="string"?n.status:"unknown";if(o==="failed"||o==="blocked")return {status:"fail",message:`Workspace run evidence ${o} for ${t.project}.`};if(o==="passed")return {status:"pass",message:`Workspace run evidence passed for ${t.project}.`};if(o==="skipped"){let p=De(e,l,s??i.stage);if(p==="ambiguous")return {status:"fail",message:`Workspace run history is ambiguous for project ${t.project}.`};if(p){let f=b(p.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(f)return {status:"fail",message:f};if(p.status==="passed")return {status:"pass",message:`Workspace run evidence passed for ${t.project} from keyed project/stage history.`};if(p.status==="failed"||p.status==="blocked")return {status:"fail",message:`Workspace run evidence ${p.status} for ${t.project}.`}}return {status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}}return {status:"warn",message:`Workspace run evidence status is ${o} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function b(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function _e(e){if(e.id==="workspace.doctor")return r$1.doctor;if(e.id==="workspace.readiness")return r$1.readiness;if(e.id==="workspace.contract.verify")return r$1.contractVerify;if(e.id==="workspace.analyze")return r$1.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function Ne(e,t,r,s$1){let i=Ee(e,t),a=i?k.relative(t,i).split(k.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let g$1=i?await g(t,a??""):null;if(!i||!g$1)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:a,message:a?`Missing evidence report: ${a}`:"No evidence mapping exists for this command."};let l;try{l=await w.readJson(g$1);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:a,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=h(l);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:a,message:"Evidence report is not a JSON object."};let y=_e(e);if(y)try{a$2(d,y,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:a,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=b(d.generatedAt,s$1,"Doctor evidence");n?c={status:"fail",message:n}:c=We(d);}else if(e.id==="workspace.readiness"){let n=b(d.generatedAt,s$1,"Release readiness evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.contract.verify"){let n=b(d.generatedAt,s$1,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.analyze"){let n=b(d.generatedAt,s$1,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=b(d.generatedAt,s$1,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===s.doctorFixResult.schemaVersion?d:d.fixResult,o=h(n),p=typeof o?.generatedAt=="string"?o.generatedAt:void 0,f=b(p,s$1,"Doctor fix result");f?c={status:"fail",message:f}:await $e(t,p)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=Be(d,e,s$1);else {let n=b(d.generatedAt,s$1,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:a,message:c.message}}function He(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,a=e.filter(n=>n.status==="missing").length,g=e.filter(n=>n.status==="skipped").length,l=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,y="ready",c=0;return l.length>0||t.blockingReasons.length>0?(y="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(y="needs-attention",c=1),{verdict:y,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:a,stepsSkipped:g}}function Me(e,t){let r=P(e.affectedProjects.map(o=>o.project?.name).filter(o=>typeof o=="string")),s=new Set(r.map(o=>o.toLowerCase())),i=P(e.transitiveImpact.map(o=>o.project?.name).filter(o=>typeof o=="string").filter(o=>!s.has(o.toLowerCase()))),a=new Map;for(let o of t){if(o.scope!=="project"||!o.project)continue;let p=o.project.toLowerCase(),f=a.get(p)??[];f.push(o),a.set(p,f);}let g=[],l=[],d=[],y=[],c=false,n=(o,p)=>{let f=a.get(o.toLowerCase())??[];if(f.length===0){d.push(o);return}let x=f.filter(m=>m.status==="fail"),R=x.filter(m=>m.required),I=f.filter(m=>m.status==="missing"),A=I.filter(m=>m.required),V=f.some(m=>m.status==="pass"||m.status==="warn");if(R.length>0){l.push(o),y.push(`graph.subgraph.${o}: ${p} has failed verification evidence (${R.map(m=>m.id).join(", ")}).`);return}if(x.length>0){l.push(o),c=true;return}if(A.length>0){l.push(o),y.push(`graph.subgraph.${o}: ${p} has missing required verification evidence (${A.map(m=>m.id).join(", ")}).`);return}if(I.length>0){l.push(o),c=true;return}if(V){g.push(o);return}d.push(o);};for(let o of r)n(o,"directly-changed");for(let o of i)n(o,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:P(g),uncovered:P(l),unverifiable:P(d)},blockingReasons:y,needsAttention:c}}function P(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Te(e){let t=k.resolve(e.workspacePath);if(e.fromImpactPath){let a=je(t,e.fromImpactPath);return {impact:await ke(a),fromImpactRef:k.relative(t,a).split(k.sep).join("/"),impactFromDisk:true}}let r$1=k.join(t,g$1);if(await w.pathExists(r$1))return {impact:await ke(r$1),fromImpactRef:g$1,impactFromDisk:true};let s=k.join(t,d$3);if(await w.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e.scope,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await r({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {impact:{schemaVersion:f,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",diffRef:p.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:n(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:q.diff,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",toRef:p.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Le(e,t){if(t)return e.generatedAt}async function wt(e){let t=k.resolve(e.workspacePath),{impact:r$1,fromImpactRef:s,impactFromDisk:i}=await Te(e),a$2=r$1.diff.currentModel,g=i?await r({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):a$2,l=[];if(i){let u=await p$1({workspacePath:t,fromPath:r$1.diff.fromRef,diff:r$1.diff,scope:e.scope,now:e.now}),E=[r$1.affectedProjects,r$1.transitiveImpact,r$1.verificationPlan],j=[u.affectedProjects,u.transitiveImpact,u.verificationPlan];JSON.stringify(E)!==JSON.stringify(j)&&l.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(g)!==r$1.diff.toHash&&l.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r$1.diff.git;if(i&&d$2?.available){let u=a(t,{ref:d$2.ref}),E=r$1.diff.changes.filter(v=>v.type.startsWith("git.")).map(v=>`${v.type}:${v.target.replace(/^git:/,"")}`).sort(),j=[...u.changedFiles.map(v=>`git.file.changed:${v}`),...u.untrackedFiles.map(v=>`git.untracked:${v}`),...u.deletedFiles.map(v=>`git.deleted:${v}`)].sort();(!u.available||u.commit!==d$2.commit||JSON.stringify(j)!==JSON.stringify(E))&&l.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let y=Le(r$1,i),c$1=Ae([...o(),...r$1.verificationPlan]).filter(u=>Se(e.scope,u)),n$1=[];for(let u of c$1)n$1.push(await Ne(u,t,a$2.contracts.exists===true,y));let o$1=Me(r$1,n$1),p=a$1(n(a$2)??{nodes:[],edges:[]}),f=b$1(a$2),x=await ze(t),R=c(f,x?.freshness?.projectHashes),I={verdict:R.verdict,baseline:R.baseline,changed:R.changed,added:R.added,removed:R.removed,projectHashes:d$1(f)},A=b$2(p),V=a$2.policies?.mode??"warn",m=await qe(a$2,t),B=Ke(V,m),S=He(n$1,{blockingReasons:[...o$1.blockingReasons,...A,...B.blockingReasons,...l],needsAttention:o$1.needsAttention||B.needsAttention}),he=n$1.filter(u=>u.status==="missing"&&u.evidencePath).map(u=>u.evidencePath),_=[...n$1.filter(u=>u.required&&(u.status==="fail"||u.status==="missing")).map(u=>`${u.id}: ${u.message}`),...o$1.blockingReasons,...A,...B.blockingReasons,...l],ve=m.filter(u=>u.severity==="error").length,be=a$2.summary?.projectCount??a$2.projects.length,U=me({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(u=>u.trim()).filter(Boolean))).slice(0,12).map((u,E)=>{let j=n$1.find(v=>u.startsWith(`${v.id}:`));return ge({reason:u,blockerId:`blocker-${E+1}`,sourceCommand:j?.command.display,sourceArtifact:j?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r$1.summary.changed,risk:r$1.summary.risk,affectedProjects:r$1.summary.affectedProjects,recommendedCommands:r$1.summary.recommendedCommands},summary:S,steps:n$1,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:o$1.subgraph,graphIntegrity:p,freshness:I,policyMode:V,policyViolations:m}}async function qe(e,t){let r=[];for(let i of e.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await g(t,p.contractVerify);try{if(s&&await w.pathExists(s)){let i=await w.readJson(s);if(Array.isArray(i.violations))for(let a of i.violations)typeof a=="string"&&a.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:a});}}catch{}return r.sort((i,a)=>i.source!==a.source?i.source.localeCompare(a.source):i.code!==a.code?i.code.localeCompare(a.code):i.message.localeCompare(a.message))}function Ke(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function ze(e){let t=k.join(e,G);try{if(!await w.pathExists(t))return null;let r=await w.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function Rt(e,t){return h$1(t,G,d$2(e))}function Je(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Ct(e,t){return Je(e,t).exitCode}export{fe as a,st as b,ye as c,G as d,Me as e,wt as f,Rt as g,Je as h,Ct as i};
@@ -1 +1 @@
1
- import {a}from'./chunk-COOVCORC.js';import {m as m$1}from'./chunk-7NKM6EHE.js';import {a as a$1}from'./chunk-GR6442P7.js';import {i,h}from'./chunk-BLEIUQL6.js';import {s,t}from'./chunk-ODK4LCEL.js';import {createHash}from'crypto';import l from'path';import {execa}from'execa';import v from'fs-extra';var D=s.projectTestCoverage.schemaVersion,P=t.projectTestCoverage,G=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deps.edn","project.clj","build.sbt","CMakeLists.txt","meson.build","deno.json","deno.jsonc"];function p(t){let e=Number(t);return Number.isFinite(e)&&e>=0?e:0}function m(t,e,o=0){let n=p(t),s=Math.min(p(e),n),r=p(o);return {total:n,covered:s,skipped:r,percent:n>0?Math.round(s/n*1e4)/100:null}}function W(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;return m(e.total,e.covered,e.skipped)}function y(t,e){let o=l.isAbsolute(e)?e:l.resolve(t,e),n=l.relative(t,o);return n&&!n.startsWith("..")?n.split(l.sep).join("/"):e}async function C(t){return createHash("sha256").update(await v.readFile(t)).digest("hex")}async function I(t){let e=l.resolve(t);for(;;){let o=await v.pathExists(l.join(e,".workspai","project.json"))||await v.pathExists(l.join(e,".rapidkit","project.json")),n=(await v.readdir(e).catch(()=>[])).some(r=>r.toLowerCase().endsWith(".gemspec"));if(o||n||(await Promise.all(G.map(r=>v.pathExists(l.join(e,r))))).some(Boolean))return e;let s=l.dirname(e);if(s===e)return l.resolve(t);e=s;}}async function V(t){return m$1(t).runtime}async function U(t,e,o=5){let n=[],s=[{dir:t,depth:0}],r=new Set([".git",".workspai",".rapidkit","node_modules",".venv","vendor","deps"]);for(;s.length>0;){let a=s.shift();if(!a)break;let i=await v.readdir(a.dir,{withFileTypes:true}).catch(()=>[]);for(let c of i){if(r.has(c.name)||a$1(c.name))continue;let u=l.join(a.dir,c.name),g=l.relative(t,u).split(l.sep).join("/");c.isFile()&&e(c.name,g)&&n.push(u),c.isDirectory()&&a.depth<o&&s.push({dir:u,depth:a.depth+1});}}return n}async function L(t,e){let o=await v.readJson(e),n=o.total??o,s={};for(let a of ["lines","branches","functions","statements"]){let i=W(n[a]);i&&(s[a]=i);}let r=[];for(let[a,i]of Object.entries(o)){if(a==="total"||!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u={};for(let g of ["lines","branches","functions","statements"]){let b=W(c[g]);b&&(u[g]=b);}r.push({path:y(t,a),metrics:u});}return {metrics:s,files:r,source:{format:"istanbul-json",path:e,sha256:await C(e)}}}async function z(t,e){let o=await v.readJson(e),n=o.totals??{},s={lines:m(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(s.branches=m(n.num_branches,n.covered_branches));let r=[];for(let[a,i]of Object.entries(o.files??{})){let c=i?.summary??{};r.push({path:y(t,a),metrics:{lines:m(c.num_statements,c.covered_lines),...p(c.num_branches)>0?{branches:m(c.num_branches,c.covered_branches)}:{}}});}return {metrics:s,files:r,source:{format:"coverage-py-json",path:e,sha256:await C(e)}}}function j(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,o=p(e.count),n=p(e.covered);return o>0?m(o,n):void 0}async function B(t,e){let o=await v.readJson(e),n=Array.isArray(o.data)?o.data[0]??{}:o,s=n.totals??{},r={};r.lines=j(s.lines),r.functions=j(s.functions),r.branches=j(s.branches),r.statements=j(s.regions);let a=[];for(let i of Array.isArray(n.files)?n.files:[]){if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u=c.summary??{};a.push({path:y(t,String(c.filename??"unknown")),metrics:{lines:j(u.lines),functions:j(u.functions),branches:j(u.branches),statements:j(u.regions)}});}return {metrics:r,files:a,source:{format:"llvm-cov-json",path:e,sha256:await C(e)}}}async function E(t,e){let o=await v.readFile(e,"utf8"),n=[],s="",r=0,a=0,i=0,c=0,u=0,g=0,b=d=>{s&&(n.push({path:y(t,s),metrics:{lines:m(d.lineTotal,d.lineCovered),functions:m(d.functionTotal,d.functionCovered),branches:m(d.branchTotal,d.branchCovered)}}),r+=d.lineTotal,a+=d.lineCovered,i+=d.functionTotal,c+=d.functionCovered,u+=d.branchTotal,g+=d.branchCovered);},h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0};for(let d of o.split(/\r?\n/))d.startsWith("SF:")?s=d.slice(3):d.startsWith("LF:")?h.lineTotal=p(d.slice(3)):d.startsWith("LH:")?h.lineCovered=p(d.slice(3)):d.startsWith("FNF:")?h.functionTotal=p(d.slice(4)):d.startsWith("FNH:")?h.functionCovered=p(d.slice(4)):d.startsWith("BRF:")?h.branchTotal=p(d.slice(4)):d.startsWith("BRH:")?h.branchCovered=p(d.slice(4)):d==="end_of_record"&&(b(h),s="",h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0});return {metrics:{lines:m(r,a),functions:m(i,c),branches:m(u,g)},files:n,source:{format:"lcov",path:e,sha256:await C(e)}}}async function K(t,e){let o=await v.readFile(e,"utf8"),n=new Map;for(let a of o.split(/\r?\n/).slice(1)){let i=/^(.+?):\d+\.\d+,\d+\.\d+\s+(\d+)\s+(\d+)$/.exec(a.trim());if(!i)continue;let c=n.get(i[1])??{total:0,covered:0},u=p(i[2]);c.total+=u,p(i[3])>0&&(c.covered+=u),n.set(i[1],c);}let s=[...n.entries()].map(([a,i])=>({path:y(t,a),metrics:{statements:m(i.total,i.covered)}})),r=[...n.values()].reduce((a,i)=>({total:a.total+i.total,covered:a.covered+i.covered}),{total:0,covered:0});return {metrics:{statements:m(r.total,r.covered)},files:s,source:{format:"go-coverprofile",path:e,sha256:await C(e)}}}function k(t,e){let n=[...t.matchAll(new RegExp(`<counter\\s+type=["']${e}["']\\s+missed=["'](\\d+)["']\\s+covered=["'](\\d+)["']\\s*\\/?\\s*>`,"gi"))].at(-1);return n?m(Number(n[1])+Number(n[2]),n[2]):void 0}async function x(t,e){let o=await v.readFile(t,"utf8"),n={};if(e==="cobertura-xml"){let s=/<coverage\b([^>]*)>/i.exec(o)?.[1]??"",r=/\bline-rate=["']([\d.]+)["']/i.exec(s)?.[1],a=/\bbranch-rate=["']([\d.]+)["']/i.exec(s)?.[1];r&&(n.lines=m(1e4,Math.round(Number(r)*1e4))),a&&(n.branches=m(1e4,Math.round(Number(a)*1e4)));}if(e==="clover-xml"){let r=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",a=g=>p(new RegExp(`\\b${g}=["'](\\d+)["']`,"i").exec(r)?.[1]),i=a("statements"),c=a("methods"),u=a("conditionals");i>0&&(n.statements=m(i,a("coveredstatements"))),c>0&&(n.functions=m(c,a("coveredmethods"))),u>0&&(n.branches=m(u,a("coveredconditionals")));}return n.lines??=k(o,"LINE"),n.branches??=k(o,"BRANCH"),n.functions??=k(o,"METHOD"),n.statements??=k(o,"INSTRUCTION"),{metrics:n,files:[],source:{format:e,path:t,sha256:await C(t)}}}async function X(t){let e=await v.readFile(t,"utf8"),o=/<scoverage\b([^>]*)>/i.exec(e)?.[1]??"",n=b=>p(new RegExp(`\\b${b}=["']([\\d.]+)["']`,"i").exec(o)?.[1]),s=n("statement-count"),r=n("statements-invoked"),a=n("branch-count"),i=n("branches-invoked"),c=n("statement-rate"),u=n("branch-rate"),g={};return s>0?g.statements=m(s,r):c>0&&(g.statements=m(1e4,Math.round(c*100))),a>0?g.branches=m(a,i):u>0&&(g.branches=m(1e4,Math.round(u*100))),{metrics:g,files:[],source:{format:"scoverage-xml",path:t,sha256:await C(t)}}}async function Q(t,e){let o=await v.readJson(e),n=new Map;for(let a of Object.values(o)){let i=a?.coverage;if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[c,u]of Object.entries(i)){if(!Array.isArray(u))continue;let g=n.get(c)??[];u.forEach((b,h)=>{typeof b=="number"&&(g[h]=Math.max(g[h]??0,b));}),n.set(c,g);}}let s=[...n.entries()].map(([a,i])=>{let c=i.filter(u=>typeof u=="number");return {path:y(t,a),metrics:{lines:m(c.length,c.filter(u=>u>0).length)}}}),r=s.reduce((a,i)=>{let c=i.metrics.lines;return {total:a.total+(c?.total??0),covered:a.covered+(c?.covered??0)}},{total:0,covered:0});return {metrics:{lines:m(r.total,r.covered)},files:s,source:{format:"simplecov-json",path:e,sha256:await C(e)}}}async function q(t,e={}){let o=[{relativePath:"coverage/coverage-summary.json",parser:r=>L(t,r)},{relativePath:"coverage.json",parser:async r=>{let a=await v.readJson(r);return Array.isArray(a.data)?B(t,r):z(t,r)}},{relativePath:"coverage/lcov.info",parser:r=>E(t,r)},{relativePath:"cover/lcov.info",parser:r=>E(t,r)},{relativePath:"lcov.info",parser:r=>E(t,r)},{relativePath:"coverage.out",parser:r=>K(t,r)},{relativePath:"target/site/jacoco/jacoco.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"build/reports/jacoco/test/jacocoTestReport.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"coverage.xml",parser:r=>x(r,"clover-xml")},{relativePath:".resultset.json",parser:r=>Q(t,r)}];for(let r of o){let a=l.join(t,r.relativePath);if(await v.pathExists(a))return r.parser(a)}if(e.recursive===false)return null;let s=(await U(t,(r,a)=>r==="coverage.cobertura.xml"||r==="jacoco.xml"||r==="clover.xml"||r==="scoverage.xml"||a.endsWith("/coverage-summary.json"),7)).sort()[0];return s?s.endsWith("coverage-summary.json")?L(t,s):s.endsWith("jacoco.xml")?x(s,"jacoco-xml"):s.endsWith("coverage.cobertura.xml")?x(s,"cobertura-xml"):s.endsWith("scoverage.xml")?X(s):x(s,"clover-xml"):null}async function Y(t){return v.readJson(l.join(t,"package.json")).catch(()=>null)}async function H(t,e){let o=(n,s)=>({cwd:t,executable:n,args:s});if(e==="node"||e==="bun"){let s=(await Y(t))?.scripts??{},r=["test:coverage","test:cov","coverage"].find(i=>typeof s[i]=="string"),a=e==="bun"?"bun":await v.pathExists(l.join(t,"pnpm-lock.yaml"))?"pnpm":await v.pathExists(l.join(t,"yarn.lock"))?"yarn":"npm";if(r)return {runner:String(s[r]).split(/\s+/)[0]||a,invocations:[o(a,a==="yarn"?[r]:["run",r])],diagnostics:[]};if(typeof s.test=="string"){let i=a==="yarn"?["test","--coverage"]:a==="bun"?["test","--coverage","--coverage-reporter=lcov"]:["test","--","--coverage"];return {runner:String(s.test).split(/\s+/)[0]||a,invocations:[o(a,i)],diagnostics:[]}}return {runner:null,invocations:[],diagnostics:["No project-owned test or coverage script was detected."]}}if(e==="deno")return {runner:"deno",invocations:[o("deno",["test","--coverage=coverage"]),o("deno",["coverage","--lcov","--output=coverage/lcov.info","coverage"])],diagnostics:[]};if(e==="python")return {runner:"pytest-cov",invocations:[o(await v.pathExists(l.join(t,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"))?l.join(".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"):process.platform==="win32"?"python":"python3",["-m","pytest","--cov=.","--cov-report=json:coverage.json"])],diagnostics:[]};if(e==="go")return {runner:"go test",invocations:[o("go",["test","./...","-coverprofile=coverage.out"])],diagnostics:[]};if(e==="java"){let n=await v.pathExists(l.join(t,"gradlew")),s=await v.pathExists(l.join(t,"gradlew.bat")),r=n||s,a=await v.pathExists(l.join(t,"mvnw")),i=await v.pathExists(l.join(t,"mvnw.cmd")),c=r?process.platform==="win32"&&s?".\\gradlew.bat":"./gradlew":await v.pathExists(l.join(t,"pom.xml"))?process.platform==="win32"&&i?".\\mvnw.cmd":a?"./mvnw":"mvn":"gradle";return {runner:r?"jacoco/gradle":"jacoco/maven",invocations:[o(c,r?["test","jacocoTestReport"]:["test","jacoco:report"])],diagnostics:[]}}return e==="dotnet"?{runner:"dotnet coverlet",invocations:[o("dotnet",["test","--collect:XPlat Code Coverage"])],diagnostics:[]}:e==="rust"?{runner:"cargo llvm-cov",invocations:[o("cargo",["llvm-cov","--json","--output-path","coverage.json"])],diagnostics:["cargo-llvm-cov must be available in the project toolchain."]}:e==="php"?{runner:"phpunit",invocations:[o(process.platform==="win32"?"vendor\\bin\\phpunit.bat":"vendor/bin/phpunit",["--coverage-clover","coverage.xml"])],diagnostics:[]}:e==="ruby"?{runner:"simplecov",invocations:[o("bundle",["exec","rspec"])],diagnostics:["The test suite must enable SimpleCov to emit .resultset.json."]}:e==="elixir"?{runner:"mix cover",invocations:[o("mix",["test","--cover"])],diagnostics:["Configure ExCoveralls for JSON or LCOV interchange when machine-readable coverage is required."]}:e==="clojure"?{runner:"cloverage",invocations:[o("clojure",["-M:coverage"])],diagnostics:["The project must declare a coverage alias such as cloverage."]}:e==="scala"?{runner:"sbt-scoverage",invocations:[o("sbt",["clean","coverage","test","coverageReport"])],diagnostics:["The project must declare the scoverage plugin."]}:e==="kotlin"?{runner:"jacoco/gradle",invocations:[o(await v.pathExists(l.join(t,process.platform==="win32"?"gradlew.bat":"gradlew"))?process.platform==="win32"?".\\gradlew.bat":"./gradlew":"gradle",["test","jacocoTestReport"])],diagnostics:["The project must declare the JaCoCo Gradle plugin."]}:e==="c"||e==="cpp"?{runner:"CTest/LLVM coverage",invocations:[o("ctest",["--test-dir","build","--output-on-failure"])],diagnostics:["The native build must be instrumented for coverage and export LCOV, Cobertura, or LLVM JSON evidence."]}:{runner:null,invocations:[],diagnostics:["Project runtime could not be detected."]}}async function ve(t,e){let o=await I(t),n=e??await V(o),s=await H(o,n),r=await q(o,{recursive:false}).catch(()=>null),a=r?.source.path&&r.source.sha256?[{path:l.relative(o,r.source.path).split(l.sep).join("/"),sha256:r.source.sha256}]:[],i=[...s.diagnostics],c=r?"available":s.invocations.length===0||n==="unknown"?"unsupported":i.length>0?"requires-setup":"available";return {runtime:n,runner:s.runner,status:c,existingEvidence:a,invocations:s.invocations,prerequisites:i}}function Z(t,e){let o=t?l.relative(t,e).split(l.sep).join("/"):l.resolve(e),n=l.basename(e).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",s=createHash("sha256").update(o).digest("hex").slice(0,12);return `${n}--${s}`}function ee(t){return t.lines?"lines":t.statements?"statements":t.branches?"branches":"functions"}async function me(t={}){let e=await I(t.projectPath??process.cwd()),o=a(e),n=t.runtime??await V(e),s=Math.max(0,Math.min(100,Math.round(t.target??80))),r=await H(e,n),a$1=[],i$1=Date.now();if(t.run)for(let f of r.invocations){let w=await execa(f.executable,f.args,{cwd:f.cwd,reject:false,timeout:6e5}).catch(()=>({exitCode:1}));if(a$1.push(Number(w.exitCode??1)),Number(w.exitCode??1)!==0)break}let c=await q(e).catch(()=>null),u=c?ee(c.metrics):"lines",g=c?.metrics[u]?.percent??null,b=t.run&&a$1.some(f=>f!==0)?"failed":g===null?"unavailable":g>=s?"passed":"below-target",h$1=Z(o,e),d=l.join(e,P),R=o?`.workspai/reports/projects/${h$1}/project-test-coverage-last-run.json`:null,T={schemaVersion:D,generatedAt:new Date().toISOString(),status:b,project:{id:h$1,name:l.basename(e),path:e,workspacePath:o},runtime:n,runner:r.runner,target:{metric:u,percent:s},metrics:c?.metrics??{},files:c?.files??[],lowCoverageFiles:(c?.files??[]).map(f=>{let w=f.metrics[u]??f.metrics.lines??f.metrics.statements;return {path:f.path,percent:w?.percent??null,uncovered:Math.max(0,(w?.total??0)-(w?.covered??0))}}).filter(f=>f.percent===null||f.percent<s).sort((f,w)=>w.uncovered-f.uncovered||f.path.localeCompare(w.path)),source:c?.source??{format:"unknown",path:null,sha256:null},execution:{requested:t.run===true,invocations:r.invocations,exitCodes:a$1,durationMs:Date.now()-i$1},diagnostics:[...r.diagnostics,...c?[]:["No supported machine-readable coverage artifact was found."]],artifactPaths:{project:d,workspaceLatest:o?l.join(o,P):null,workspaceProject:o&&R?l.join(o,R):null}};return o&&R&&await i(o,P,[{relativePath:P,payload:T},{relativePath:R,payload:T}]),await h(e,P,T),T}export{D as a,P as b,ve as c,me as d};
1
+ import {a}from'./chunk-SVO2GGTV.js';import {m as m$1}from'./chunk-LUPKDFQ3.js';import {a as a$1}from'./chunk-GR6442P7.js';import {i,h}from'./chunk-BLEIUQL6.js';import {s,t}from'./chunk-ODK4LCEL.js';import {createHash}from'crypto';import l from'path';import {execa}from'execa';import v from'fs-extra';var D=s.projectTestCoverage.schemaVersion,P=t.projectTestCoverage,G=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deps.edn","project.clj","build.sbt","CMakeLists.txt","meson.build","deno.json","deno.jsonc"];function p(t){let e=Number(t);return Number.isFinite(e)&&e>=0?e:0}function m(t,e,o=0){let n=p(t),s=Math.min(p(e),n),r=p(o);return {total:n,covered:s,skipped:r,percent:n>0?Math.round(s/n*1e4)/100:null}}function W(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;return m(e.total,e.covered,e.skipped)}function y(t,e){let o=l.isAbsolute(e)?e:l.resolve(t,e),n=l.relative(t,o);return n&&!n.startsWith("..")?n.split(l.sep).join("/"):e}async function C(t){return createHash("sha256").update(await v.readFile(t)).digest("hex")}async function I(t){let e=l.resolve(t);for(;;){let o=await v.pathExists(l.join(e,".workspai","project.json"))||await v.pathExists(l.join(e,".rapidkit","project.json")),n=(await v.readdir(e).catch(()=>[])).some(r=>r.toLowerCase().endsWith(".gemspec"));if(o||n||(await Promise.all(G.map(r=>v.pathExists(l.join(e,r))))).some(Boolean))return e;let s=l.dirname(e);if(s===e)return l.resolve(t);e=s;}}async function V(t){return m$1(t).runtime}async function U(t,e,o=5){let n=[],s=[{dir:t,depth:0}],r=new Set([".git",".workspai",".rapidkit","node_modules",".venv","vendor","deps"]);for(;s.length>0;){let a=s.shift();if(!a)break;let i=await v.readdir(a.dir,{withFileTypes:true}).catch(()=>[]);for(let c of i){if(r.has(c.name)||a$1(c.name))continue;let u=l.join(a.dir,c.name),g=l.relative(t,u).split(l.sep).join("/");c.isFile()&&e(c.name,g)&&n.push(u),c.isDirectory()&&a.depth<o&&s.push({dir:u,depth:a.depth+1});}}return n}async function L(t,e){let o=await v.readJson(e),n=o.total??o,s={};for(let a of ["lines","branches","functions","statements"]){let i=W(n[a]);i&&(s[a]=i);}let r=[];for(let[a,i]of Object.entries(o)){if(a==="total"||!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u={};for(let g of ["lines","branches","functions","statements"]){let b=W(c[g]);b&&(u[g]=b);}r.push({path:y(t,a),metrics:u});}return {metrics:s,files:r,source:{format:"istanbul-json",path:e,sha256:await C(e)}}}async function z(t,e){let o=await v.readJson(e),n=o.totals??{},s={lines:m(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(s.branches=m(n.num_branches,n.covered_branches));let r=[];for(let[a,i]of Object.entries(o.files??{})){let c=i?.summary??{};r.push({path:y(t,a),metrics:{lines:m(c.num_statements,c.covered_lines),...p(c.num_branches)>0?{branches:m(c.num_branches,c.covered_branches)}:{}}});}return {metrics:s,files:r,source:{format:"coverage-py-json",path:e,sha256:await C(e)}}}function j(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,o=p(e.count),n=p(e.covered);return o>0?m(o,n):void 0}async function B(t,e){let o=await v.readJson(e),n=Array.isArray(o.data)?o.data[0]??{}:o,s=n.totals??{},r={};r.lines=j(s.lines),r.functions=j(s.functions),r.branches=j(s.branches),r.statements=j(s.regions);let a=[];for(let i of Array.isArray(n.files)?n.files:[]){if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u=c.summary??{};a.push({path:y(t,String(c.filename??"unknown")),metrics:{lines:j(u.lines),functions:j(u.functions),branches:j(u.branches),statements:j(u.regions)}});}return {metrics:r,files:a,source:{format:"llvm-cov-json",path:e,sha256:await C(e)}}}async function E(t,e){let o=await v.readFile(e,"utf8"),n=[],s="",r=0,a=0,i=0,c=0,u=0,g=0,b=d=>{s&&(n.push({path:y(t,s),metrics:{lines:m(d.lineTotal,d.lineCovered),functions:m(d.functionTotal,d.functionCovered),branches:m(d.branchTotal,d.branchCovered)}}),r+=d.lineTotal,a+=d.lineCovered,i+=d.functionTotal,c+=d.functionCovered,u+=d.branchTotal,g+=d.branchCovered);},h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0};for(let d of o.split(/\r?\n/))d.startsWith("SF:")?s=d.slice(3):d.startsWith("LF:")?h.lineTotal=p(d.slice(3)):d.startsWith("LH:")?h.lineCovered=p(d.slice(3)):d.startsWith("FNF:")?h.functionTotal=p(d.slice(4)):d.startsWith("FNH:")?h.functionCovered=p(d.slice(4)):d.startsWith("BRF:")?h.branchTotal=p(d.slice(4)):d.startsWith("BRH:")?h.branchCovered=p(d.slice(4)):d==="end_of_record"&&(b(h),s="",h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0});return {metrics:{lines:m(r,a),functions:m(i,c),branches:m(u,g)},files:n,source:{format:"lcov",path:e,sha256:await C(e)}}}async function K(t,e){let o=await v.readFile(e,"utf8"),n=new Map;for(let a of o.split(/\r?\n/).slice(1)){let i=/^(.+?):\d+\.\d+,\d+\.\d+\s+(\d+)\s+(\d+)$/.exec(a.trim());if(!i)continue;let c=n.get(i[1])??{total:0,covered:0},u=p(i[2]);c.total+=u,p(i[3])>0&&(c.covered+=u),n.set(i[1],c);}let s=[...n.entries()].map(([a,i])=>({path:y(t,a),metrics:{statements:m(i.total,i.covered)}})),r=[...n.values()].reduce((a,i)=>({total:a.total+i.total,covered:a.covered+i.covered}),{total:0,covered:0});return {metrics:{statements:m(r.total,r.covered)},files:s,source:{format:"go-coverprofile",path:e,sha256:await C(e)}}}function k(t,e){let n=[...t.matchAll(new RegExp(`<counter\\s+type=["']${e}["']\\s+missed=["'](\\d+)["']\\s+covered=["'](\\d+)["']\\s*\\/?\\s*>`,"gi"))].at(-1);return n?m(Number(n[1])+Number(n[2]),n[2]):void 0}async function x(t,e){let o=await v.readFile(t,"utf8"),n={};if(e==="cobertura-xml"){let s=/<coverage\b([^>]*)>/i.exec(o)?.[1]??"",r=/\bline-rate=["']([\d.]+)["']/i.exec(s)?.[1],a=/\bbranch-rate=["']([\d.]+)["']/i.exec(s)?.[1];r&&(n.lines=m(1e4,Math.round(Number(r)*1e4))),a&&(n.branches=m(1e4,Math.round(Number(a)*1e4)));}if(e==="clover-xml"){let r=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",a=g=>p(new RegExp(`\\b${g}=["'](\\d+)["']`,"i").exec(r)?.[1]),i=a("statements"),c=a("methods"),u=a("conditionals");i>0&&(n.statements=m(i,a("coveredstatements"))),c>0&&(n.functions=m(c,a("coveredmethods"))),u>0&&(n.branches=m(u,a("coveredconditionals")));}return n.lines??=k(o,"LINE"),n.branches??=k(o,"BRANCH"),n.functions??=k(o,"METHOD"),n.statements??=k(o,"INSTRUCTION"),{metrics:n,files:[],source:{format:e,path:t,sha256:await C(t)}}}async function X(t){let e=await v.readFile(t,"utf8"),o=/<scoverage\b([^>]*)>/i.exec(e)?.[1]??"",n=b=>p(new RegExp(`\\b${b}=["']([\\d.]+)["']`,"i").exec(o)?.[1]),s=n("statement-count"),r=n("statements-invoked"),a=n("branch-count"),i=n("branches-invoked"),c=n("statement-rate"),u=n("branch-rate"),g={};return s>0?g.statements=m(s,r):c>0&&(g.statements=m(1e4,Math.round(c*100))),a>0?g.branches=m(a,i):u>0&&(g.branches=m(1e4,Math.round(u*100))),{metrics:g,files:[],source:{format:"scoverage-xml",path:t,sha256:await C(t)}}}async function Q(t,e){let o=await v.readJson(e),n=new Map;for(let a of Object.values(o)){let i=a?.coverage;if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[c,u]of Object.entries(i)){if(!Array.isArray(u))continue;let g=n.get(c)??[];u.forEach((b,h)=>{typeof b=="number"&&(g[h]=Math.max(g[h]??0,b));}),n.set(c,g);}}let s=[...n.entries()].map(([a,i])=>{let c=i.filter(u=>typeof u=="number");return {path:y(t,a),metrics:{lines:m(c.length,c.filter(u=>u>0).length)}}}),r=s.reduce((a,i)=>{let c=i.metrics.lines;return {total:a.total+(c?.total??0),covered:a.covered+(c?.covered??0)}},{total:0,covered:0});return {metrics:{lines:m(r.total,r.covered)},files:s,source:{format:"simplecov-json",path:e,sha256:await C(e)}}}async function q(t,e={}){let o=[{relativePath:"coverage/coverage-summary.json",parser:r=>L(t,r)},{relativePath:"coverage.json",parser:async r=>{let a=await v.readJson(r);return Array.isArray(a.data)?B(t,r):z(t,r)}},{relativePath:"coverage/lcov.info",parser:r=>E(t,r)},{relativePath:"cover/lcov.info",parser:r=>E(t,r)},{relativePath:"lcov.info",parser:r=>E(t,r)},{relativePath:"coverage.out",parser:r=>K(t,r)},{relativePath:"target/site/jacoco/jacoco.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"build/reports/jacoco/test/jacocoTestReport.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"coverage.xml",parser:r=>x(r,"clover-xml")},{relativePath:".resultset.json",parser:r=>Q(t,r)}];for(let r of o){let a=l.join(t,r.relativePath);if(await v.pathExists(a))return r.parser(a)}if(e.recursive===false)return null;let s=(await U(t,(r,a)=>r==="coverage.cobertura.xml"||r==="jacoco.xml"||r==="clover.xml"||r==="scoverage.xml"||a.endsWith("/coverage-summary.json"),7)).sort()[0];return s?s.endsWith("coverage-summary.json")?L(t,s):s.endsWith("jacoco.xml")?x(s,"jacoco-xml"):s.endsWith("coverage.cobertura.xml")?x(s,"cobertura-xml"):s.endsWith("scoverage.xml")?X(s):x(s,"clover-xml"):null}async function Y(t){return v.readJson(l.join(t,"package.json")).catch(()=>null)}async function H(t,e){let o=(n,s)=>({cwd:t,executable:n,args:s});if(e==="node"||e==="bun"){let s=(await Y(t))?.scripts??{},r=["test:coverage","test:cov","coverage"].find(i=>typeof s[i]=="string"),a=e==="bun"?"bun":await v.pathExists(l.join(t,"pnpm-lock.yaml"))?"pnpm":await v.pathExists(l.join(t,"yarn.lock"))?"yarn":"npm";if(r)return {runner:String(s[r]).split(/\s+/)[0]||a,invocations:[o(a,a==="yarn"?[r]:["run",r])],diagnostics:[]};if(typeof s.test=="string"){let i=a==="yarn"?["test","--coverage"]:a==="bun"?["test","--coverage","--coverage-reporter=lcov"]:["test","--","--coverage"];return {runner:String(s.test).split(/\s+/)[0]||a,invocations:[o(a,i)],diagnostics:[]}}return {runner:null,invocations:[],diagnostics:["No project-owned test or coverage script was detected."]}}if(e==="deno")return {runner:"deno",invocations:[o("deno",["test","--coverage=coverage"]),o("deno",["coverage","--lcov","--output=coverage/lcov.info","coverage"])],diagnostics:[]};if(e==="python")return {runner:"pytest-cov",invocations:[o(await v.pathExists(l.join(t,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"))?l.join(".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"):process.platform==="win32"?"python":"python3",["-m","pytest","--cov=.","--cov-report=json:coverage.json"])],diagnostics:[]};if(e==="go")return {runner:"go test",invocations:[o("go",["test","./...","-coverprofile=coverage.out"])],diagnostics:[]};if(e==="java"){let n=await v.pathExists(l.join(t,"gradlew")),s=await v.pathExists(l.join(t,"gradlew.bat")),r=n||s,a=await v.pathExists(l.join(t,"mvnw")),i=await v.pathExists(l.join(t,"mvnw.cmd")),c=r?process.platform==="win32"&&s?".\\gradlew.bat":"./gradlew":await v.pathExists(l.join(t,"pom.xml"))?process.platform==="win32"&&i?".\\mvnw.cmd":a?"./mvnw":"mvn":"gradle";return {runner:r?"jacoco/gradle":"jacoco/maven",invocations:[o(c,r?["test","jacocoTestReport"]:["test","jacoco:report"])],diagnostics:[]}}return e==="dotnet"?{runner:"dotnet coverlet",invocations:[o("dotnet",["test","--collect:XPlat Code Coverage"])],diagnostics:[]}:e==="rust"?{runner:"cargo llvm-cov",invocations:[o("cargo",["llvm-cov","--json","--output-path","coverage.json"])],diagnostics:["cargo-llvm-cov must be available in the project toolchain."]}:e==="php"?{runner:"phpunit",invocations:[o(process.platform==="win32"?"vendor\\bin\\phpunit.bat":"vendor/bin/phpunit",["--coverage-clover","coverage.xml"])],diagnostics:[]}:e==="ruby"?{runner:"simplecov",invocations:[o("bundle",["exec","rspec"])],diagnostics:["The test suite must enable SimpleCov to emit .resultset.json."]}:e==="elixir"?{runner:"mix cover",invocations:[o("mix",["test","--cover"])],diagnostics:["Configure ExCoveralls for JSON or LCOV interchange when machine-readable coverage is required."]}:e==="clojure"?{runner:"cloverage",invocations:[o("clojure",["-M:coverage"])],diagnostics:["The project must declare a coverage alias such as cloverage."]}:e==="scala"?{runner:"sbt-scoverage",invocations:[o("sbt",["clean","coverage","test","coverageReport"])],diagnostics:["The project must declare the scoverage plugin."]}:e==="kotlin"?{runner:"jacoco/gradle",invocations:[o(await v.pathExists(l.join(t,process.platform==="win32"?"gradlew.bat":"gradlew"))?process.platform==="win32"?".\\gradlew.bat":"./gradlew":"gradle",["test","jacocoTestReport"])],diagnostics:["The project must declare the JaCoCo Gradle plugin."]}:e==="c"||e==="cpp"?{runner:"CTest/LLVM coverage",invocations:[o("ctest",["--test-dir","build","--output-on-failure"])],diagnostics:["The native build must be instrumented for coverage and export LCOV, Cobertura, or LLVM JSON evidence."]}:{runner:null,invocations:[],diagnostics:["Project runtime could not be detected."]}}async function ve(t,e){let o=await I(t),n=e??await V(o),s=await H(o,n),r=await q(o,{recursive:false}).catch(()=>null),a=r?.source.path&&r.source.sha256?[{path:l.relative(o,r.source.path).split(l.sep).join("/"),sha256:r.source.sha256}]:[],i=[...s.diagnostics],c=r?"available":s.invocations.length===0||n==="unknown"?"unsupported":i.length>0?"requires-setup":"available";return {runtime:n,runner:s.runner,status:c,existingEvidence:a,invocations:s.invocations,prerequisites:i}}function Z(t,e){let o=t?l.relative(t,e).split(l.sep).join("/"):l.resolve(e),n=l.basename(e).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",s=createHash("sha256").update(o).digest("hex").slice(0,12);return `${n}--${s}`}function ee(t){return t.lines?"lines":t.statements?"statements":t.branches?"branches":"functions"}async function me(t={}){let e=await I(t.projectPath??process.cwd()),o=a(e),n=t.runtime??await V(e),s=Math.max(0,Math.min(100,Math.round(t.target??80))),r=await H(e,n),a$1=[],i$1=Date.now();if(t.run)for(let f of r.invocations){let w=await execa(f.executable,f.args,{cwd:f.cwd,reject:false,timeout:6e5}).catch(()=>({exitCode:1}));if(a$1.push(Number(w.exitCode??1)),Number(w.exitCode??1)!==0)break}let c=await q(e).catch(()=>null),u=c?ee(c.metrics):"lines",g=c?.metrics[u]?.percent??null,b=t.run&&a$1.some(f=>f!==0)?"failed":g===null?"unavailable":g>=s?"passed":"below-target",h$1=Z(o,e),d=l.join(e,P),R=o?`.workspai/reports/projects/${h$1}/project-test-coverage-last-run.json`:null,T={schemaVersion:D,generatedAt:new Date().toISOString(),status:b,project:{id:h$1,name:l.basename(e),path:e,workspacePath:o},runtime:n,runner:r.runner,target:{metric:u,percent:s},metrics:c?.metrics??{},files:c?.files??[],lowCoverageFiles:(c?.files??[]).map(f=>{let w=f.metrics[u]??f.metrics.lines??f.metrics.statements;return {path:f.path,percent:w?.percent??null,uncovered:Math.max(0,(w?.total??0)-(w?.covered??0))}}).filter(f=>f.percent===null||f.percent<s).sort((f,w)=>w.uncovered-f.uncovered||f.path.localeCompare(w.path)),source:c?.source??{format:"unknown",path:null,sha256:null},execution:{requested:t.run===true,invocations:r.invocations,exitCodes:a$1,durationMs:Date.now()-i$1},diagnostics:[...r.diagnostics,...c?[]:["No supported machine-readable coverage artifact was found."]],artifactPaths:{project:d,workspaceLatest:o?l.join(o,P):null,workspaceProject:o&&R?l.join(o,R):null}};return o&&R&&await i(o,P,[{relativePath:P,payload:T},{relativePath:R,payload:T}]),await h(e,P,T),T}export{D as a,P as b,ve as c,me as d};
@@ -1,4 +1,4 @@
1
- import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-IVYPC36J.js';import {c,e,d}from'./chunk-QYEQVNBF.js';import {d as d$1,b}from'./chunk-SZHRPELL.js';import {g}from'./chunk-GDOO2YZW.js';import {r,n}from'./chunk-LARREYZN.js';import {p,d as d$2}from'./chunk-VXFIMEC6.js';import {h}from'./chunk-BLEIUQL6.js';import {b as b$1}from'./chunk-VN2MKTQO.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import j from'path';import P from'fs-extra';function Y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Q(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function E(e,n,o){try{if(!await P.pathExists(e))return null;let r=await P.readJson(e);return n?b$1(n,r,e):o&&a$2(r,o,e),r}catch(r){if((n||o)&&await P.pathExists(e))throw r;return null}}function q(e,n){if(!e)return null;let o=n.trim().toLowerCase();return e.projects.find(r=>r.slug.toLowerCase()===o||r.relativePath.toLowerCase()===o)??null}function U(e,n$1,o){let r=o.trim().toLowerCase(),t=(n(e)?.nodes.map(a=>a.id)??e.projects.map(a=>a.name)).find(a=>a.toLowerCase()===r);if(t)return t;let m=e.projects.find(a=>[a.name,a.path,j.basename(a.path)].filter(u=>u.trim().length>0).some(u=>u.toLowerCase()===r));if(m)return m.name;let p=q(n$1,o);if(p){let a=e.projects.find(u=>u.path===p.relativePath||u.path.endsWith(`/${p.relativePath}`));if(a)return a.name}return o}function Z(e,n){if(!e)return [];let o=n.trim().toLowerCase(),r=new Set;for(let d of e.projects){d.contracts.dependsOn?.some(t=>t.toLowerCase()===o)&&r.add(d.slug);for(let t of d.contracts.consumes??[])for(let m of e.projects)m.contracts.publishes?.includes(t)&&m.slug===o&&r.add(d.slug);}return [...r].sort()}function ee(e,n){if(!e)return [];let o=n.trim().toLowerCase();return e.steps.filter(r=>r.scope==="project"&&r.project?.toLowerCase()===o&&r.command?.display).map(r=>r.command.display).slice(0,8)}function l(e,n,o){return {id:e,title:n,body:o.trim()}}async function he(e){let n$1=j.resolve(e.workspacePath),o=(e.now??new Date).toISOString(),r$1=e.model??await r({workspacePath:n$1,includeEvidence:true}),d=e.contract;if(d===void 0)try{d=(await p({workspacePath:n$1})).contract;}catch{d=null;}let t=e.verify;t===void 0&&(t=await E(j.join(n$1,d$1),d$1));let m=e.impact;if(m===void 0&&(m=await E(j.join(n$1,g),g)),e.target.kind==="release-blocked"){let s=t?.blockingReasons??[],c=(r$1.summary?.projectCount??r$1.projects.length)===0,g=[l("verdict",c?"Workspace scaffold posture":"Release verdict",t?c?`Scaffold posture: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Freshness: **${t.freshness.verdict}**. No registered projects yet \u2014 release gates apply after the first project is added.`:`Verdict: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Risk: **${t.impact.risk}**. Freshness: **${t.freshness.verdict}**.`:"No workspace verify report found. Run `npx workspai workspace verify --json --write` first."),l("blockers",c?"Pre-project signals":"Blocking reasons",s.length?s.map(h=>`- ${h}`).join(`
1
+ import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-IVYPC36J.js';import {c,e,d}from'./chunk-QYEQVNBF.js';import {d as d$1,b}from'./chunk-3SQIV3F4.js';import {g}from'./chunk-3EPR3D5Q.js';import {r,n}from'./chunk-SEZTSMRR.js';import {p,d as d$2}from'./chunk-IHWS3ALP.js';import {h}from'./chunk-BLEIUQL6.js';import {b as b$1}from'./chunk-VN2MKTQO.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import j from'path';import P from'fs-extra';function Y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Q(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function E(e,n,o){try{if(!await P.pathExists(e))return null;let r=await P.readJson(e);return n?b$1(n,r,e):o&&a$2(r,o,e),r}catch(r){if((n||o)&&await P.pathExists(e))throw r;return null}}function q(e,n){if(!e)return null;let o=n.trim().toLowerCase();return e.projects.find(r=>r.slug.toLowerCase()===o||r.relativePath.toLowerCase()===o)??null}function U(e,n$1,o){let r=o.trim().toLowerCase(),t=(n(e)?.nodes.map(a=>a.id)??e.projects.map(a=>a.name)).find(a=>a.toLowerCase()===r);if(t)return t;let m=e.projects.find(a=>[a.name,a.path,j.basename(a.path)].filter(u=>u.trim().length>0).some(u=>u.toLowerCase()===r));if(m)return m.name;let p=q(n$1,o);if(p){let a=e.projects.find(u=>u.path===p.relativePath||u.path.endsWith(`/${p.relativePath}`));if(a)return a.name}return o}function Z(e,n){if(!e)return [];let o=n.trim().toLowerCase(),r=new Set;for(let d of e.projects){d.contracts.dependsOn?.some(t=>t.toLowerCase()===o)&&r.add(d.slug);for(let t of d.contracts.consumes??[])for(let m of e.projects)m.contracts.publishes?.includes(t)&&m.slug===o&&r.add(d.slug);}return [...r].sort()}function ee(e,n){if(!e)return [];let o=n.trim().toLowerCase();return e.steps.filter(r=>r.scope==="project"&&r.project?.toLowerCase()===o&&r.command?.display).map(r=>r.command.display).slice(0,8)}function l(e,n,o){return {id:e,title:n,body:o.trim()}}async function he(e){let n$1=j.resolve(e.workspacePath),o=(e.now??new Date).toISOString(),r$1=e.model??await r({workspacePath:n$1,includeEvidence:true}),d=e.contract;if(d===void 0)try{d=(await p({workspacePath:n$1})).contract;}catch{d=null;}let t=e.verify;t===void 0&&(t=await E(j.join(n$1,d$1),d$1));let m=e.impact;if(m===void 0&&(m=await E(j.join(n$1,g),g)),e.target.kind==="release-blocked"){let s=t?.blockingReasons??[],c=(r$1.summary?.projectCount??r$1.projects.length)===0,g=[l("verdict",c?"Workspace scaffold posture":"Release verdict",t?c?`Scaffold posture: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Freshness: **${t.freshness.verdict}**. No registered projects yet \u2014 release gates apply after the first project is added.`:`Verdict: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Risk: **${t.impact.risk}**. Freshness: **${t.freshness.verdict}**.`:"No workspace verify report found. Run `npx workspai workspace verify --json --write` first."),l("blockers",c?"Pre-project signals":"Blocking reasons",s.length?s.map(h=>`- ${h}`).join(`
2
2
  `):c?"No pre-project signals in the latest verify report.":"No blocking reasons in the latest verify report.")];return t?.resolutionHints?.length&&g.push(l("resolution","Resolution hints",t.resolutionHints.map(h=>`- **${h.blockerId}** (${h.resolutionClass}): ${h.commandRetryHint??h.fixHints[0]?.detail??"See fix hints"}`).join(`
3
3
  `))),{schemaVersion:a,generatedAt:o,workspacePath:n$1,target:e.target,summary:t?c?b(s.length,t.summary.verdict):s.length>0||t.summary.verdict==="blocked"?`Release blocked: ${t.summary.verdict} with ${s.length} blocking reason(s).`:t.summary.verdict==="needs-attention"?"Release needs attention: advisory or incomplete verification evidence remains; no blocking reason was reported.":`Release posture: ${t.summary.verdict}; no blocking reason was reported.`:"Release posture unknown \u2014 verify report missing.",sections:g,releaseVerdict:t?.summary.verdict,evidenceFreshness:t?.freshness.verdict,blocking:!!(t&&(t.summary.verdict==="blocked"||s.length>0)),releaseRisk:t?.impact.risk,blockingReasons:s,resolutionHints:t?.resolutionHints}}if(e.target.kind==="blocker"){let s=e.target,f=t?.resolutionHints?.find(g=>g.blockerId===s.blockerId),c=t?.blockingReasons.find(g=>g.includes(s.blockerId))??t?.blockingReasons[0];return {schemaVersion:a,generatedAt:o,workspacePath:n$1,target:s,summary:f?`Blocker ${s.blockerId}: ${f.resolutionClass}`:`Blocker ${s.blockerId} (no structured hint)`,sections:[l("reason","Blocking signal",c??"No matching blocking reason in verify."),l("hint","Resolution class",f?`${f.resolutionClass}
4
4
 
@@ -1,4 +1,4 @@
1
- import {a as a$1}from'./chunk-XWKGZRHN.js';import {m,k,j as j$1,b,t,n,i}from'./chunk-RGNCL5OB.js';import {a}from'./chunk-2FIX2MDC.js';import {c,d}from'./chunk-VQZ5PI5J.js';import Et from'crypto';import nt from'os';import l from'path';import*as p from'fs-extra';import {execa}from'execa';var vt=["version","project","create","add","list","info","upgrade","diff","doctor","license","commands","reconcile","rollback","uninstall","checkpoint","optimize","snapshot","frameworks","modules","merge"],B=new Set(vt);var y=a();async function it(t){for(let e of [c,d]){let n=l.join(t,e);if(await p.pathExists(n))try{let r=await p.readJson(n);if(r&&typeof r=="object")return r}catch{return null}}return null}function j(){let t=[],e=i=>{let o=i?.trim();o&&t.push(o);};e(process.env.RAPIDKIT_BRIDGE_PYTHON),e(process.env.RAPIDKIT_PYTHON_CMD),e(process.env.POETRY_PYTHON);let n=x();(n.startsWith("/")||n.startsWith(".")||n.startsWith(".."))&&!n.startsWith("file:")&&e(m(l.join(l.resolve(n),".venv")));for(let i of k())i.args.length===1&&i.args[0]==="--version"&&e(i.command);for(let i of j$1())e(i);return [...new Set(t)]}function w(t,e){return t==="py"?["-3",...e]:e}function Z(t){if(!t)return t;let e=["Installed Poetry version does not support '--no-update'. Falling back to 'poetry lock'."];return t.split(/\r?\n/).filter(i=>!e.some(o=>i.includes(o))).join(`
1
+ import {a as a$1}from'./chunk-XWKGZRHN.js';import {m,k,j as j$1,b,z,t,i}from'./chunk-6BO4QHKA.js';import {a}from'./chunk-2FIX2MDC.js';import {c,d}from'./chunk-VQZ5PI5J.js';import Et from'crypto';import nt from'os';import l from'path';import*as p from'fs-extra';import {execa}from'execa';var vt=["version","project","create","add","list","info","upgrade","diff","doctor","license","commands","reconcile","rollback","uninstall","checkpoint","optimize","snapshot","frameworks","modules","merge"],B=new Set(vt);var y=a();async function it(t){for(let e of [c,d]){let n=l.join(t,e);if(await p.pathExists(n))try{let r=await p.readJson(n);if(r&&typeof r=="object")return r}catch{return null}}return null}function j(){let t=[],e=i=>{let o=i?.trim();o&&t.push(o);};e(process.env.RAPIDKIT_BRIDGE_PYTHON),e(process.env.RAPIDKIT_PYTHON_CMD),e(process.env.POETRY_PYTHON);let n=x();(n.startsWith("/")||n.startsWith(".")||n.startsWith(".."))&&!n.startsWith("file:")&&e(m(l.join(l.resolve(n),".venv")));for(let i of k())i.args.length===1&&i.args[0]==="--version"&&e(i.command);for(let i of j$1())e(i);return [...new Set(t)]}function w(t,e){return t==="py"?["-3",...e]:e}function Z(t){if(!t)return t;let e=["Installed Poetry version does not support '--no-update'. Falling back to 'poetry lock'."];return t.split(/\r?\n/).filter(i=>!e.some(o=>i.includes(o))).join(`
2
2
  `)}var h=class extends Error{code;constructor(e,n){super(n),this.code=e;}};function O(t){if(t instanceof h)switch(t.code){case "PYTHON_NOT_FOUND":return `Workspai could not find Python (python3/python/py) on your PATH.
3
3
  Install Python 3.10+ and ensure \`${i()}\` is available, then retry.
4
4
  Tip: if you are inside a RapidKit project, use the local ./rapidkit launcher.`;case "BRIDGE_VENV_CREATE_FAILED":return `Workspai failed to create its bridge virtual environment.
@@ -15,10 +15,10 @@ Details: ${t.message}`;case "BRIDGE_VENV_LOCK_FAILED":return `Workspai could not
15
15
  Another Workspai process may still be preparing the environment; retry after it completes.
16
16
  Details: ${t.message}`;case "BRIDGE_VENV_HEALTH_FAILED":return `Workspai created the Python bridge environment, but its Core runtime health check failed.
17
17
  The incomplete bridge was discarded so the next run can rebuild it safely.
18
- Details: ${t.message}`;default:return `Workspai bridge error: ${t.message}`}return `Workspai failed to run the Python core engine: ${t instanceof Error?t.message:String(t)}`}function x(){let t=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE;return t&&t.trim()?t.trim():"rapidkit-core"}function Pt(){let t=x(),e=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE_ID,n=e&&e.trim()?`${t}|${e.trim()}`:t;return Et.createHash("sha256").update(n).digest("hex").slice(0,12)}function T(){let t=process.env.XDG_CACHE_HOME;return t&&t.trim()?t:l.join(nt.homedir(),".cache")}function Ct(){return l.join(T(),"rapidkit","npm-bridge","venv")}function K(){let t=Pt();return l.join(T(),"rapidkit","npm-bridge",`venv-${t}`)}function M(t){return m(t)}function L(t){return n(t)}async function F(t){let e=[],n=L(t);await p.pathExists(n)&&e.push({cmd:n,args:["--version","--json"]}),e.push({cmd:M(t),args:["-m","rapidkit","--version","--json"]});let r=[];for(let i of e)try{let o=await execa(i.cmd,i.args,{reject:false,stdio:"pipe",timeout:3e4});if(o.exitCode===0&&await _(o.stdout))return {healthy:true,details:""};let c=[o.stdout,o.stderr].map(s=>(s??"").toString().trim()).filter(Boolean).join(`
18
+ Details: ${t.message}`;default:return `Workspai bridge error: ${t.message}`}return `Workspai failed to run the Python core engine: ${t instanceof Error?t.message:String(t)}`}function x(){let t=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE;return t&&t.trim()?t.trim():"rapidkit-core"}function Pt(){let t=x(),e=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE_ID,n=e&&e.trim()?`${t}|${e.trim()}`:t;return Et.createHash("sha256").update(n).digest("hex").slice(0,12)}function T(){let t=process.env.XDG_CACHE_HOME;return t&&t.trim()?t:l.join(nt.homedir(),".cache")}function Ct(){return l.join(T(),"rapidkit","npm-bridge","venv")}function K(){let t=Pt();return l.join(T(),"rapidkit","npm-bridge",`venv-${t}`)}function M(t){return m(t)}function L(t$1){return t(t$1)}async function F(t){let e=[],n=L(t);await p.pathExists(n)&&e.push({cmd:n,args:["--version","--json"]}),e.push({cmd:M(t),args:["-m","rapidkit","--version","--json"]});let r=[];for(let i of e)try{let o=await execa(i.cmd,i.args,{reject:false,stdio:"pipe",timeout:3e4});if(o.exitCode===0&&await _(o.stdout))return {healthy:true,details:""};let c=[o.stdout,o.stderr].map(s=>(s??"").toString().trim()).filter(Boolean).join(`
19
19
  `);r.push(c||`${i.cmd} exited with ${String(o.exitCode)}`);}catch(o){r.push(o instanceof Error?o.message:String(o));}return {healthy:false,details:r.join(`
20
- `)}}async function ot(t$1=process.platform,e=process.env){let n=b(t$1)?["rapidkit.exe","rapidkit.cmd"]:["rapidkit"],r=t(e,t$1).flatMap(i=>n.map(o=>l.join(i,o)));for(let i of [...new Set(r)])try{if(!await p.pathExists(i))continue;let o=await execa(i,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(o.exitCode===0&&await _(o.stdout))return {cmd:i,baseArgs:[]}}catch{}return null}async function st(t=process.platform,e=process.env){let n=b(t)?"rapidkit.exe":"rapidkit",r=(e.PATH??"").split(l.delimiter).filter(Boolean);for(let i of r){let o=l.join(i,n);try{if(!await p.pathExists(o))continue;let c=await execa(o,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(c.exitCode===0&&await _(c.stdout,{requireSchema:true}))return {cmd:o,baseArgs:[]}}catch{}}return null}function at(t){return /[<>=!~]=|@|\.whl$|\.tar\.gz$|\.zip$|git\+|https?:\/\//.test(t)}function _t(t){return l.dirname(l.dirname(t))}function ct(){return l.join(T(),"rapidkit","npm-bridge","core-commands.json")}async function dt(t){let e=!!process.env.RAPIDKIT_DEBUG,n=r=>{e&&process.stderr.write(`[DEBUG] tryRapidkit(${t}): ${r}
21
- `);};try{n("probing interpreter-specific rapidkit script");let i=((await execa(t,w(t,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"]),{reject:false,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(n(`script path: ${i}`),i)try{if(await p.pathExists(i)){n(`found script at ${i}; invoking --version --json`);let o=await execa(i,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(n(`script exitCode=${o.exitCode}`),o.exitCode===0){let c=(o.stdout??"").toString().trim();try{let s=JSON.parse(c),a=!!s&&typeof s=="object"&&s!==null&&"version"in s;if(n(`script JSON parse ok=${a}`),a)return true}catch{n("script output not valid JSON");}}}}catch(o){n(`interpreter-specific script probe failed: ${String(o)}`);}}catch(r){n(`interpreter-specific script probe error: ${String(r)}`);}try{n('probing importlib.find_spec("rapidkit")');let r=await execa(t,w(t,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"]),{reject:false,stdio:"pipe",timeout:2e3});if(n(`import probe exitCode=${r.exitCode} stdout=${(r.stdout??"").toString().trim()}`),r.exitCode===0&&(r.stdout??"").toString().trim()==="1")return true}catch(r){n(`import probe error: ${String(r)}`);}try{n("probing python -m rapidkit");let r=await execa(t,w(t,["-m","rapidkit","--version","--json"]),{reject:false,stdio:"pipe",timeout:8e3});if(n(`-m probe exitCode=${r.exitCode}`),r.exitCode===0)return true}catch(r){n(`-m probe error: ${String(r)}`);}try{n("probing PATH for rapidkit executables");let r=(process.env.PATH??"").split(l.delimiter).filter(Boolean);for(let i of r){let o=l.join(i,b()?"rapidkit.exe":"rapidkit");try{if(await p.pathExists(o)){n(`found candidate on PATH: ${o}; invoking --version --json`);let c=await execa(o,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(n(`candidate exitCode=${c.exitCode}`),c.exitCode===0){let s=(c.stdout??"").toString().trim();try{let a=JSON.parse(s),d=a;if(a&&typeof a=="object"&&a!==null&&"version"in d&&d.schema_version===1)return true}catch{n("candidate output not valid JSON, skipping");}}}}catch(c){n(`error probing candidate ${o}: ${String(c)}`);}}return n("no valid rapidkit found on PATH"),false}catch(r){return n(`PATH probe error: ${String(r)}`),false}}async function _(t,e){let n=(t??"").toString().trim();if(!n)return false;try{let r=JSON.parse(n);if(!r||typeof r!="object"||r===null)return false;let i=r;return "version"in i?e?.requireSchema?i.schema_version===1||i.schemaVersion==="rapidkit-core-version-v1":true:false}catch{return false}}async function ut(t,e=process.platform){let n$1=async o=>{try{let a=(await it(o))?.metadata?.python?.venvPath;return typeof a!="string"||!a.trim()?null:l.isAbsolute(a)?a:l.join(o,a)}catch{return null}},r=async(o,c)=>{let s=n(c,e);if(await p.pathExists(s)){let d=await execa(s,["--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:o});if(d.exitCode===0&&await _(d.stdout))return {cmd:s,baseArgs:[],workspaceDir:o}}let a=m(c,e);if(await p.pathExists(a)){let d=await execa(a,["-m","rapidkit","--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:o});if(d.exitCode===0&&await _(d.stdout))return {cmd:a,baseArgs:["-m","rapidkit"],workspaceDir:o}}return null},i=t;for(let o=0;o<25;o+=1){let c=await n$1(i),s=[l.join(i,".venv"),c].filter(d=>!!d);for(let d of [...new Set(s)]){let E=await r(i,d);if(E)return E}let a=l.dirname(i);if(a===i)break;i=a;}return null}async function kt(t){try{let e=l.join(t,".python-version");if(await p.pathExists(e)){let r=(await p.readFile(e,"utf-8")).trim();if(r)return r}}catch{}try{let e=await it(t);if(typeof e?.pythonVersion=="string"&&e.pythonVersion.trim())return e.pythonVersion.trim();let r=e?.metadata?.python?.pythonVersion;if(typeof r=="string"&&r.trim())return r.trim()}catch{}return null}async function H(t){if(t&&t.trim())try{let s=await ut(t);if(s){let a=s.workspaceDir??(l.dirname(s.cmd).includes(".venv")?l.dirname(l.dirname(l.dirname(s.cmd))):l.dirname(s.cmd)),d=await kt(a);return d&&(process.env.PYENV_VERSION=d),s}}catch{}let e=await Ot();if(e.kind==="venv"){let s=_t(e.pythonPath),a=L(s);return await p.pathExists(a)?{cmd:a,baseArgs:[]}:{cmd:e.pythonPath,baseArgs:["-m","rapidkit"]}}try{if((await execa(e.cmd,["-m","rapidkit","--version","--json"],{reject:false,stdio:"pipe",timeout:4e3})).exitCode===0)return {cmd:e.cmd,baseArgs:["-m","rapidkit"]}}catch{}try{let a=((await execa(e.cmd,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"],{reject:false,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(a&&await p.pathExists(a))try{let d=await execa(a,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(d.exitCode===0&&await _(d.stdout))return {cmd:a,baseArgs:[]}}catch{}}catch{}let n=await ot();if(n)return n;let r=await st();if(r)return r;let i=K(),o=await N(e.cmd),c=L(i);return await p.pathExists(c)?{cmd:c,baseArgs:[]}:{cmd:o,baseArgs:["-m","rapidkit"]}}async function pt(){for(let t of j())try{if((await execa(t,w(t,["--version"]),{reject:false,stdio:"pipe",timeout:2e3})).exitCode===0)return t}catch{}return null}async function G(){let t=null,e=false;for(let n of j()){try{if((await execa(n,w(n,["--version"]),{reject:false,stdio:"pipe",timeout:2e3})).exitCode!==0)continue;e=true;}catch{continue}try{return await N(n)}catch(r){t=r;continue}}throw e?t instanceof h?t:t instanceof Error?new h("BRIDGE_VENV_BOOTSTRAP_FAILED",t.message):new h("BRIDGE_VENV_BOOTSTRAP_FAILED","Python was detected, but the Workspai bridge environment could not be created."):new h("PYTHON_NOT_FOUND","No Python interpreter found (python3/python/py).")}async function xt(){let t=!!process.env.RAPIDKIT_DEBUG,e=r=>{t&&process.stderr.write(`[DEBUG] checkRapidkitCore: ${r}
20
+ `)}}async function ot(t=process.platform,e=process.env){let n=b(t)?["rapidkit.exe","rapidkit.cmd"]:["rapidkit"],r=z(e,t).flatMap(i=>n.map(o=>l.join(i,o)));for(let i of [...new Set(r)])try{if(!await p.pathExists(i))continue;let o=await execa(i,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(o.exitCode===0&&await _(o.stdout))return {cmd:i,baseArgs:[]}}catch{}return null}async function st(t=process.platform,e=process.env){let n=b(t)?"rapidkit.exe":"rapidkit",r=(e.PATH??"").split(l.delimiter).filter(Boolean);for(let i of r){let o=l.join(i,n);try{if(!await p.pathExists(o))continue;let c=await execa(o,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(c.exitCode===0&&await _(c.stdout,{requireSchema:true}))return {cmd:o,baseArgs:[]}}catch{}}return null}function at(t){return /[<>=!~]=|@|\.whl$|\.tar\.gz$|\.zip$|git\+|https?:\/\//.test(t)}function _t(t){return l.dirname(l.dirname(t))}function ct(){return l.join(T(),"rapidkit","npm-bridge","core-commands.json")}async function dt(t){let e=!!process.env.RAPIDKIT_DEBUG,n=r=>{e&&process.stderr.write(`[DEBUG] tryRapidkit(${t}): ${r}
21
+ `);};try{n("probing interpreter-specific rapidkit script");let i=((await execa(t,w(t,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"]),{reject:false,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(n(`script path: ${i}`),i)try{if(await p.pathExists(i)){n(`found script at ${i}; invoking --version --json`);let o=await execa(i,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(n(`script exitCode=${o.exitCode}`),o.exitCode===0){let c=(o.stdout??"").toString().trim();try{let s=JSON.parse(c),a=!!s&&typeof s=="object"&&s!==null&&"version"in s;if(n(`script JSON parse ok=${a}`),a)return true}catch{n("script output not valid JSON");}}}}catch(o){n(`interpreter-specific script probe failed: ${String(o)}`);}}catch(r){n(`interpreter-specific script probe error: ${String(r)}`);}try{n('probing importlib.find_spec("rapidkit")');let r=await execa(t,w(t,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"]),{reject:false,stdio:"pipe",timeout:2e3});if(n(`import probe exitCode=${r.exitCode} stdout=${(r.stdout??"").toString().trim()}`),r.exitCode===0&&(r.stdout??"").toString().trim()==="1")return true}catch(r){n(`import probe error: ${String(r)}`);}try{n("probing python -m rapidkit");let r=await execa(t,w(t,["-m","rapidkit","--version","--json"]),{reject:false,stdio:"pipe",timeout:8e3});if(n(`-m probe exitCode=${r.exitCode}`),r.exitCode===0)return true}catch(r){n(`-m probe error: ${String(r)}`);}try{n("probing PATH for rapidkit executables");let r=(process.env.PATH??"").split(l.delimiter).filter(Boolean);for(let i of r){let o=l.join(i,b()?"rapidkit.exe":"rapidkit");try{if(await p.pathExists(o)){n(`found candidate on PATH: ${o}; invoking --version --json`);let c=await execa(o,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(n(`candidate exitCode=${c.exitCode}`),c.exitCode===0){let s=(c.stdout??"").toString().trim();try{let a=JSON.parse(s),d=a;if(a&&typeof a=="object"&&a!==null&&"version"in d&&d.schema_version===1)return true}catch{n("candidate output not valid JSON, skipping");}}}}catch(c){n(`error probing candidate ${o}: ${String(c)}`);}}return n("no valid rapidkit found on PATH"),false}catch(r){return n(`PATH probe error: ${String(r)}`),false}}async function _(t,e){let n=(t??"").toString().trim();if(!n)return false;try{let r=JSON.parse(n);if(!r||typeof r!="object"||r===null)return false;let i=r;return "version"in i?e?.requireSchema?i.schema_version===1||i.schemaVersion==="rapidkit-core-version-v1":true:false}catch{return false}}async function ut(t$1,e=process.platform){let n=async o=>{try{let a=(await it(o))?.metadata?.python?.venvPath;return typeof a!="string"||!a.trim()?null:l.isAbsolute(a)?a:l.join(o,a)}catch{return null}},r=async(o,c)=>{let s=t(c,e);if(await p.pathExists(s)){let d=await execa(s,["--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:o});if(d.exitCode===0&&await _(d.stdout))return {cmd:s,baseArgs:[],workspaceDir:o}}let a=m(c,e);if(await p.pathExists(a)){let d=await execa(a,["-m","rapidkit","--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:o});if(d.exitCode===0&&await _(d.stdout))return {cmd:a,baseArgs:["-m","rapidkit"],workspaceDir:o}}return null},i=t$1;for(let o=0;o<25;o+=1){let c=await n(i),s=[l.join(i,".venv"),c].filter(d=>!!d);for(let d of [...new Set(s)]){let E=await r(i,d);if(E)return E}let a=l.dirname(i);if(a===i)break;i=a;}return null}async function kt(t){try{let e=l.join(t,".python-version");if(await p.pathExists(e)){let r=(await p.readFile(e,"utf-8")).trim();if(r)return r}}catch{}try{let e=await it(t);if(typeof e?.pythonVersion=="string"&&e.pythonVersion.trim())return e.pythonVersion.trim();let r=e?.metadata?.python?.pythonVersion;if(typeof r=="string"&&r.trim())return r.trim()}catch{}return null}async function H(t){if(t&&t.trim())try{let s=await ut(t);if(s){let a=s.workspaceDir??(l.dirname(s.cmd).includes(".venv")?l.dirname(l.dirname(l.dirname(s.cmd))):l.dirname(s.cmd)),d=await kt(a);return d&&(process.env.PYENV_VERSION=d),s}}catch{}let e=await Ot();if(e.kind==="venv"){let s=_t(e.pythonPath),a=L(s);return await p.pathExists(a)?{cmd:a,baseArgs:[]}:{cmd:e.pythonPath,baseArgs:["-m","rapidkit"]}}try{if((await execa(e.cmd,["-m","rapidkit","--version","--json"],{reject:false,stdio:"pipe",timeout:4e3})).exitCode===0)return {cmd:e.cmd,baseArgs:["-m","rapidkit"]}}catch{}try{let a=((await execa(e.cmd,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"],{reject:false,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(a&&await p.pathExists(a))try{let d=await execa(a,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(d.exitCode===0&&await _(d.stdout))return {cmd:a,baseArgs:[]}}catch{}}catch{}let n=await ot();if(n)return n;let r=await st();if(r)return r;let i=K(),o=await N(e.cmd),c=L(i);return await p.pathExists(c)?{cmd:c,baseArgs:[]}:{cmd:o,baseArgs:["-m","rapidkit"]}}async function pt(){for(let t of j())try{if((await execa(t,w(t,["--version"]),{reject:false,stdio:"pipe",timeout:2e3})).exitCode===0)return t}catch{}return null}async function G(){let t=null,e=false;for(let n of j()){try{if((await execa(n,w(n,["--version"]),{reject:false,stdio:"pipe",timeout:2e3})).exitCode!==0)continue;e=true;}catch{continue}try{return await N(n)}catch(r){t=r;continue}}throw e?t instanceof h?t:t instanceof Error?new h("BRIDGE_VENV_BOOTSTRAP_FAILED",t.message):new h("BRIDGE_VENV_BOOTSTRAP_FAILED","Python was detected, but the Workspai bridge environment could not be created."):new h("PYTHON_NOT_FOUND","No Python interpreter found (python3/python/py).")}async function xt(){let t=!!process.env.RAPIDKIT_DEBUG,e=r=>{t&&process.stderr.write(`[DEBUG] checkRapidkitCore: ${r}
22
22
  `);},n=Array.from(new Set([...j$1(),...k(14,10).map(r=>r.command)]));for(let r of n)try{e(`Method 1: trying ${r} import`);let i=await execa(r,w(r,["-c","import rapidkit_core; print(1)"]),{reject:false,stdio:"pipe",timeout:y});if(i.exitCode===0&&i.stdout?.trim()==="1")return e(`\u2713 Found via ${r} import`),true}catch{continue}for(let r of n)try{e(`Method 2: trying ${r} -m pip show`);let i=await execa(r,w(r,["-m","pip","show","rapidkit-core"]),{reject:false,stdio:"pipe",timeout:y});if(i.exitCode===0&&i.stdout?.includes("Name: rapidkit-core"))return e(`\u2713 Found via ${r} -m pip show`),true}catch{continue}for(let r of ["pip","pip3"])try{e(`Method 3: trying ${r} show`);let i=await execa(r,["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:y});if(i.exitCode===0&&i.stdout?.includes("Name: rapidkit-core"))return e(`\u2713 Found via ${r} show`),true}catch{continue}try{e("Method 4: checking pyenv versions");let r=await execa("pyenv",["versions","--bare"],{reject:false,stdio:"pipe",timeout:y});if(r.exitCode===0&&r.stdout){let i=r.stdout.split(`
23
23
  `).filter(o=>o.trim());e(`Found pyenv versions: ${i.join(", ")}`);for(let o of i){let c=process.env.PYENV_ROOT||l.join(nt.homedir(),".pyenv"),s=l.join(c,"versions",o.trim(),"bin","pip");try{let a=await execa(s,["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:y});if(a.exitCode===0&&a.stdout?.includes("Name: rapidkit-core"))return e(`\u2713 Found in pyenv ${o}`),true}catch{try{let a=await execa("pyenv",["exec","pip","show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:y,env:{...process.env,PYENV_VERSION:o.trim()}});if(a.exitCode===0&&a.stdout?.includes("Name: rapidkit-core"))return e(`\u2713 Found in pyenv ${o} via PYENV_VERSION`),true}catch{continue}}}}}catch{e("pyenv not available");}for(let r of n)try{e(`Method 5: checking ${r} user site`);let i=await execa(r,w(r,["-m","site","--user-site"]),{reject:false,stdio:"pipe",timeout:y});if(i.exitCode===0&&i.stdout){let o=i.stdout.trim(),c=l.join(o,"rapidkit_core");if(await p.pathExists(c))return e("\u2713 Found in user site-packages"),true}}catch{continue}try{e("Method 6: checking pipx");let r=await execa("pipx",["list"],{reject:false,stdio:"pipe",timeout:y});if(r.exitCode===0&&r.stdout?.includes("rapidkit-core"))return e("\u2713 Found via pipx"),true}catch{e("pipx not available");}for(let r of n)try{e(`Method 6: checking ${r} -m pipx list`);let i=await execa(r,w(r,["-m","pipx","list"]),{reject:false,stdio:"pipe",timeout:y});if(i.exitCode===0&&i.stdout?.includes("rapidkit-core"))return e(`\u2713 Found via ${r} -m pipx list`),true}catch{continue}try{if(e("Method 7: checking poetry"),(await execa("poetry",["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:y})).exitCode===0)return e("\u2713 Found via poetry"),true}catch{e("poetry check failed");}for(let r of n)try{if(e(`Method 7: checking ${r} -m poetry show rapidkit-core`),(await execa(r,w(r,["-m","poetry","show","rapidkit-core"]),{reject:false,stdio:"pipe",timeout:y})).exitCode===0)return e(`\u2713 Found via ${r} -m poetry`),true}catch{continue}try{e("Method 8: checking conda");let r=await execa("conda",["list","rapidkit-core"],{reject:false,stdio:"pipe",timeout:y});if(r.exitCode===0&&r.stdout?.includes("rapidkit-core"))return e("\u2713 Found via conda"),true}catch{e("conda not available");}return e("\u2717 Not found in any environment"),false}function Rt(t){let e=t.trim();if(!e||!e.startsWith("rapidkit-core"))return null;let n=e.slice(13).trim();return !n||/[\/@]|\.whl$|\.tar\.gz$|\.zip$|git\+|https?:\/\//.test(n)?null:n}function X(t){let e=t.trim();if(!e)return null;let n=e.split("."),r=[];for(let i of n){let o=i.match(/^(\d+)/);if(!o){r.push(0);continue}r.push(Number.parseInt(o[1],10));}return r}function Q(t,e){let n=Math.max(t.length,e.length);for(let r=0;r<n;r+=1){let i=r<t.length?t[r]:0,o=r<e.length?e[r]:0;if(i>o)return 1;if(i<o)return -1}return 0}function bt(t){return t.length<=1?[t[0]+1]:t.length===2?[t[0]+1,0]:[t[0],t[1]+1,0]}function At(t){let e=t.split(",").map(r=>r.trim()).filter(Boolean);if(e.length===0)return null;let n=[];for(let r of e){let i=r.match(/^(==|>=|<=|>|<|~=)\s*([0-9][0-9A-Za-z+._-]*)$/);if(!i)return null;n.push({op:i[1],version:i[2]});}return n}function lt(t,e){let n=X(t);if(!n)return false;let r=At(e);if(!r)return false;for(let i of r){let o=X(i.version);if(!o)return false;let c=Q(n,o);if(i.op==="=="&&c!==0||i.op===">="&&c<0||i.op==="<="&&c>0||i.op===">"&&c<=0||i.op==="<"&&c>=0)return false;if(i.op==="~="){if(c<0)return false;let s=bt(o);if(Q(n,s)>=0)return false}}return true}async function It(){let t=Array.from(new Set([...j$1(),...k(14,10).map(n=>n.command)])),e=n=>{let r=n.match(/^Version:\s*(.+)$/m);return r?r[1].trim():null};for(let n of t)try{let r=await execa(n,w(n,["-m","pip","show","rapidkit-core"]),{reject:false,stdio:"pipe",timeout:y});if(r.exitCode===0){let i=e(r.stdout||"");if(i)return i}}catch{continue}for(let n of ["pip","pip3"])try{let r=await execa(n,["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:y});if(r.exitCode===0){let i=e(r.stdout||"");if(i)return i}}catch{continue}try{let n=await execa("pipx",["list"],{reject:false,stdio:"pipe",timeout:y});if(n.exitCode===0&&n.stdout){let r=n.stdout.match(/rapidkit-core\s+([0-9][0-9A-Za-z+._-]*)/i);if(r?.[1])return r[1]}}catch{}return null}async function Dt(){let t=x(),e=Rt(t);if(!e)return {isCompatible:false,installedVersion:null,expectedConstraint:null,reason:at(t)?"constraint-unsupported":"constraint-missing"};let n=await It();if(!n)return {isCompatible:false,installedVersion:null,expectedConstraint:e,reason:"version-not-detected"};let r=lt(n,e);return {isCompatible:r,installedVersion:n,expectedConstraint:e,reason:r?"compatible":"incompatible-version"}}async function N(t){let e=K(),n=Math.max(6e4,Number(process.env.RAPIDKIT_BRIDGE_LOCK_TIMEOUT_MS??10*6e4)),r=Math.max(n+6e4,Number(process.env.RAPIDKIT_BRIDGE_LOCK_STALE_MS??15*6e4));try{return await a$1(`${e}.lock`,()=>St(t),{timeoutMs:n,staleMs:r,purpose:"python-core-bridge-bootstrap"})}catch(i){if(i instanceof h)throw i;let o=i instanceof Error?i.message:String(i);throw new h("BRIDGE_VENV_LOCK_FAILED",o)}}async function St(t){let e=K(),n=Ct(),r=x(),i=[e];!at(r)&&!await p.pathExists(e)&&await p.pathExists(n)&&i.push(n);for(let m of i){let g=M(m);if(await p.pathExists(g))try{if((await F(m)).healthy)return g;await p.remove(m);}catch{await p.remove(m);}}let o=e,c={...process.env,PIP_DISABLE_PIP_VERSION_CHECK:"1"},s=Math.max(0,Number(process.env.RAPIDKIT_BRIDGE_PIP_RETRY??"2")),a=Math.max(200,Number(process.env.RAPIDKIT_BRIDGE_PIP_RETRY_DELAY_MS??"800")),d=Math.max(1e4,Number(process.env.RAPIDKIT_BRIDGE_PIP_TIMEOUT_MS??"120000")),E=m=>new Promise(g=>setTimeout(g,m)),k=async(m,g,P)=>{let f=await execa(m,g,{reject:false,stdio:["ignore","pipe","inherit"],env:c,timeout:P});if(f.exitCode===0)return;let v=(f.stdout??"").toString(),V=(f.stderr??"").toString(),A=[v,V].filter(Boolean).join(`
24
24
  `),gt=A?`${m} ${g.join(" ")}
@@ -1 +1 @@
1
- import {b,d}from'./chunk-ZGVODK5C.js';import {g as g$1}from'./chunk-BLEIUQL6.js';import {p,q}from'./chunk-ODK4LCEL.js';import A from'fs-extra';function t(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function S(e){let s=t(e);return !!(s&&s.schemaVersion===q.model&&t(s.workspace)&&Array.isArray(s.projects)&&(t(s.projectTopology)||t(s.graph)))}function W(e){let s=t(e);return !!(s&&s.schemaVersion===q.knowledgeGraph&&t(s.source)&&t(s.workspace)&&Array.isArray(s.entities)&&Array.isArray(s.relations)&&Array.isArray(s.proofs)&&Array.isArray(s.providers)&&t(s.quality))}async function g(e){try{return await A.readJson(e)}catch{return null}}async function I(e){let[s,i]=await Promise.all([g$1(e,p.model),g$1(e,p.knowledgeGraph)]);if(!s)return {status:"miss",reason:"missing-model"};if(!i)return {status:"miss",reason:"missing-graph"};let[n,o]=await Promise.all([g(s),g(i)]);if(!S(n))return {status:"miss",reason:"invalid-model"};if(!W(o))return {status:"miss",reason:"invalid-graph"};if(o.proofs.some(r=>r.freshness==="stale"))return {status:"miss",reason:"stale-proof"};try{b(o,n);}catch{return {status:"miss",reason:"source-mismatch"}}let a=o.source.inputs;if(!a)return {status:"miss",reason:"missing-input-fingerprint"};let f=a.scopes.filter(r=>r.kind==="workspace"),m=a.scopes.filter(r=>r.kind==="project"),k=n.projects.map(r=>r.name).sort(),w=m.map(r=>r.id).sort(),y=new Set(m.map(r=>r.fileLimit));if(a.schemaVersion!=="workspace-knowledge-graph-inputs.v1"||a.strategy!=="hybrid-git-content-v2"||a.hashAlgorithm!=="sha256"||f.length!==1||y.size>1||JSON.stringify(k)!==JSON.stringify(w))return {status:"miss",reason:"invalid-input-fingerprint"};let u;try{u=await d({workspacePath:e,projects:n.projects.map(r=>({id:r.name,path:r.path,...r.absolutePath?{absolutePath:r.absolutePath}:{}})),expected:a});}catch{return {status:"miss",reason:"input-scan-failed"}}return u?{status:"hit",model:n,graph:o,modelPath:s,graphPath:i}:{status:"miss",reason:"live-input-mismatch"}}export{I as a};
1
+ import {b,d}from'./chunk-HRVHQBTA.js';import {g as g$1}from'./chunk-BLEIUQL6.js';import {p,q}from'./chunk-ODK4LCEL.js';import A from'fs-extra';function t(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function S(e){let s=t(e);return !!(s&&s.schemaVersion===q.model&&t(s.workspace)&&Array.isArray(s.projects)&&(t(s.projectTopology)||t(s.graph)))}function W(e){let s=t(e);return !!(s&&s.schemaVersion===q.knowledgeGraph&&t(s.source)&&t(s.workspace)&&Array.isArray(s.entities)&&Array.isArray(s.relations)&&Array.isArray(s.proofs)&&Array.isArray(s.providers)&&t(s.quality))}async function g(e){try{return await A.readJson(e)}catch{return null}}async function I(e){let[s,i]=await Promise.all([g$1(e,p.model),g$1(e,p.knowledgeGraph)]);if(!s)return {status:"miss",reason:"missing-model"};if(!i)return {status:"miss",reason:"missing-graph"};let[n,o]=await Promise.all([g(s),g(i)]);if(!S(n))return {status:"miss",reason:"invalid-model"};if(!W(o))return {status:"miss",reason:"invalid-graph"};if(o.proofs.some(r=>r.freshness==="stale"))return {status:"miss",reason:"stale-proof"};try{b(o,n);}catch{return {status:"miss",reason:"source-mismatch"}}let a=o.source.inputs;if(!a)return {status:"miss",reason:"missing-input-fingerprint"};let f=a.scopes.filter(r=>r.kind==="workspace"),m=a.scopes.filter(r=>r.kind==="project"),k=n.projects.map(r=>r.name).sort(),w=m.map(r=>r.id).sort(),y=new Set(m.map(r=>r.fileLimit));if(a.schemaVersion!=="workspace-knowledge-graph-inputs.v1"||a.strategy!=="hybrid-git-content-v2"||a.hashAlgorithm!=="sha256"||f.length!==1||y.size>1||JSON.stringify(k)!==JSON.stringify(w))return {status:"miss",reason:"invalid-input-fingerprint"};let u;try{u=await d({workspacePath:e,projects:n.projects.map(r=>({id:r.name,path:r.path,...r.absolutePath?{absolutePath:r.absolutePath}:{}})),expected:a});}catch{return {status:"miss",reason:"input-scan-failed"}}return u?{status:"hit",model:n,graph:o,modelPath:s,graphPath:i}:{status:"miss",reason:"live-input-mismatch"}}export{I as a};