workspai 0.58.0 → 0.59.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 (140) hide show
  1. package/README.md +80 -32
  2. package/contracts/agent-customization-pack.v1.json +52 -4
  3. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +90 -0
  4. package/contracts/extension-cli-compatibility.v1.json +3 -1
  5. package/contracts/project-workspace-resolution.v1.json +15 -2
  6. package/contracts/published-contract-catalog.v1.json +10 -0
  7. package/contracts/runtime-command-surface.v1.json +54 -0
  8. package/contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json +247 -0
  9. package/contracts/workspace-intelligence/agent-customization-pack-report.v1.json +16 -1
  10. package/contracts/workspace-intelligence/goal-index.v1.json +7 -1
  11. package/contracts/workspace-intelligence/goal-pack.v1.json +2 -1
  12. package/contracts/workspace-intelligence/project-agent-entry.v1.json +204 -0
  13. package/contracts/workspace-intelligence/project-context-agent.v1.json +43 -26
  14. package/contracts/workspace-intelligence/workspace-context.v1.json +14 -1
  15. package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +15 -2
  16. package/contracts/workspace-repair-capabilities.v1.json +5 -0
  17. package/dist/analyze-52TEGLDR.js +1 -0
  18. package/dist/{artifact-remediation-plan-JRX4XZ7C.js → artifact-remediation-plan-HPNQTNJ2.js} +1 -1
  19. package/dist/autopilot-release-KQGDM2AA.js +1 -0
  20. package/dist/capabilities-command-VBLZXP2T.js +1 -0
  21. package/dist/chunk-4PUJVYRM.js +1 -0
  22. package/dist/{chunk-4NN5QWOB.js → chunk-5NIZNXRS.js} +1 -1
  23. package/dist/{chunk-HYY5PQCV.js → chunk-5PSKBJKJ.js} +1 -1
  24. package/dist/{chunk-AA4PNQKR.js → chunk-5SFCBZOH.js} +1 -1
  25. package/dist/{chunk-MFJ6ZP7S.js → chunk-6FBNSTUS.js} +1 -1
  26. package/dist/{chunk-FY6OHOXR.js → chunk-7DSYI7YN.js} +1 -1
  27. package/dist/chunk-7SFXADXO.js +2 -0
  28. package/dist/{chunk-GRGUPSNP.js → chunk-CCDGHPEJ.js} +1 -1
  29. package/dist/{chunk-T63WRURN.js → chunk-D65FCQIO.js} +1 -1
  30. package/dist/{chunk-YYCPRYP7.js → chunk-DGGTTRYE.js} +1 -1
  31. package/dist/{chunk-SM55RK3C.js → chunk-ENKGGWRX.js} +1 -1
  32. package/dist/{chunk-RMDVRNU7.js → chunk-GPOZILMY.js} +1 -1
  33. package/dist/{chunk-C4NYG57I.js → chunk-HCFWT42C.js} +1 -1
  34. package/dist/chunk-HOUQIT7U.js +1 -0
  35. package/dist/{chunk-RJDGC6AQ.js → chunk-HS3DJMU5.js} +1 -1
  36. package/dist/{chunk-HI7ONEFI.js → chunk-J3X56S7L.js} +1 -1
  37. package/dist/{chunk-N3DFX4BY.js → chunk-KBR4Y4RW.js} +1 -1
  38. package/dist/{chunk-H545P6LN.js → chunk-KTN2ARZJ.js} +1 -1
  39. package/dist/chunk-LPCWROQ3.js +1 -0
  40. package/dist/{chunk-6TNSCVR4.js → chunk-M3IKRWXA.js} +1 -1
  41. package/dist/{chunk-CFBAGPB4.js → chunk-M4UOXP5T.js} +1 -1
  42. package/dist/{chunk-LGJAAPNR.js → chunk-N4QQADXX.js} +1 -1
  43. package/dist/{chunk-FXIE2WVG.js → chunk-NOZ4JCH7.js} +1 -1
  44. package/dist/chunk-NZ3WZYD5.js +1 -0
  45. package/dist/{chunk-VAWV3UKV.js → chunk-OFWSZYUX.js} +1 -1
  46. package/dist/{chunk-XC26FNRL.js → chunk-OLC7EYUA.js} +3 -3
  47. package/dist/chunk-PVXSIYLP.js +1 -0
  48. package/dist/{chunk-7KXRA5ST.js → chunk-PXWKMPPI.js} +1 -1
  49. package/dist/{chunk-II4ROT6X.js → chunk-QCKWQFCD.js} +1 -1
  50. package/dist/{chunk-4YICCES6.js → chunk-QFBVQUKV.js} +1 -1
  51. package/dist/{chunk-G4VMNWSU.js → chunk-QJCCZLOF.js} +1 -1
  52. package/dist/{chunk-A3JCETSF.js → chunk-QMPFNXI7.js} +1 -1
  53. package/dist/{chunk-YMY6EFX4.js → chunk-RBBBXFEU.js} +1 -1
  54. package/dist/{chunk-TTLVG5AR.js → chunk-RHK53ZK7.js} +1 -1
  55. package/dist/chunk-S45YGN2I.js +142 -0
  56. package/dist/chunk-S4CWUZ4K.js +1 -0
  57. package/dist/{chunk-EEMRRCGR.js → chunk-SP5EHSWG.js} +1 -1
  58. package/dist/chunk-TCURN5VD.js +2 -0
  59. package/dist/{chunk-CHMCKYJJ.js → chunk-UVBPEX3E.js} +1 -1
  60. package/dist/chunk-V3ABABV5.js +39 -0
  61. package/dist/{chunk-WSDVFLHT.js → chunk-W6FHVXNL.js} +1 -1
  62. package/dist/{chunk-M2BK3XTP.js → chunk-WQX3JYEP.js} +1 -1
  63. package/dist/{chunk-AUCHMXUZ.js → chunk-WSRUPDZN.js} +1 -1
  64. package/dist/{chunk-GVS5OFUB.js → chunk-YEEAWZWI.js} +1 -1
  65. package/dist/{chunk-I5PDN2P2.js → chunk-ZJCM37KX.js} +1 -1
  66. package/dist/{create-QIN56Y4M.js → create-6QWIJTGU.js} +1 -1
  67. package/dist/{doctor-RP4Q2CKJ.js → doctor-NAZEKMGU.js} +1 -1
  68. package/dist/goal-lifecycle-ECIRCHN5.js +1 -0
  69. package/dist/goal-pack-HBOPVZFO.js +1 -0
  70. package/dist/index.d.ts +8 -1
  71. package/dist/index.js +134 -132
  72. package/dist/{pipeline-77NUVYQD.js → pipeline-5LLFP5ZH.js} +1 -1
  73. package/dist/project-agent-entry-AFKDDRDL.js +1 -0
  74. package/dist/{project-intelligence-lens-AM2B2PXU.js → project-intelligence-lens-U2V3VNZG.js} +1 -1
  75. package/dist/{project-test-coverage-MUSS7Z7V.js → project-test-coverage-HP37HUV2.js} +1 -1
  76. package/dist/{verified-goal-ZSIZYNVO.js → verified-goal-HUYJ6LBI.js} +1 -1
  77. package/dist/{workspace-LFESVKE7.js → workspace-CQ43AWUF.js} +1 -1
  78. package/dist/{workspace-agent-sync-JMRX6J2Y.js → workspace-agent-sync-YMXYUGYY.js} +1 -1
  79. package/dist/{workspace-archive-MFHCFCDO.js → workspace-archive-ZBCKJHXS.js} +1 -1
  80. package/dist/{workspace-context-TBKRMVMT.js → workspace-context-RAO62QVU.js} +1 -1
  81. package/dist/{workspace-contract-KKVC2DUQ.js → workspace-contract-ACSIHJIO.js} +1 -1
  82. package/dist/workspace-explain-RH27OQB4.js +1 -0
  83. package/dist/workspace-explain-contract-ZL4NMLZI.js +1 -0
  84. package/dist/{workspace-feedback-O6J3RQML.js → workspace-feedback-RQ4TGJW6.js} +1 -1
  85. package/dist/{workspace-foundation-JQWT7YGC.js → workspace-foundation-JH2GFSAZ.js} +1 -1
  86. package/dist/{workspace-graph-stream-V5WOXP4B.js → workspace-graph-stream-ZZZEQQTE.js} +1 -1
  87. package/dist/workspace-graph-token-efficiency-D7CUT6NX.js +1 -0
  88. package/dist/{workspace-history-TOCRMJUJ.js → workspace-history-SYCDK7FO.js} +1 -1
  89. package/dist/{workspace-intelligence-SDBIRKMK.js → workspace-intelligence-3YERTBA3.js} +1 -1
  90. package/dist/{workspace-intelligence-evaluation-E4UMWDAZ.js → workspace-intelligence-evaluation-CQDKOYZZ.js} +1 -1
  91. package/dist/{workspace-intelligence-runner-DIMNL6CJ.js → workspace-intelligence-runner-YXMOT6GK.js} +1 -1
  92. package/dist/{workspace-intelligence-runtime-registry-YGWB2RRS.js → workspace-intelligence-runtime-registry-IW6J53LO.js} +1 -1
  93. package/dist/{workspace-knowledge-graph-MUW6UAGI.js → workspace-knowledge-graph-HZZP6ZRB.js} +1 -1
  94. package/dist/{workspace-knowledge-graph-query-6DAOXGGT.js → workspace-knowledge-graph-query-ON45H6Y7.js} +1 -1
  95. package/dist/workspace-knowledge-graph-snapshot-7DWHMEM2.js +1 -0
  96. package/dist/{workspace-mcp-serve-2SWLIH4I.js → workspace-mcp-serve-5TTAN243.js} +1 -1
  97. package/dist/{workspace-model-VPFCKTYQ.js → workspace-model-EIQSKDX7.js} +1 -1
  98. package/dist/{workspace-onboarding-GHI6UTQJ.js → workspace-onboarding-SHHW4R4G.js} +1 -1
  99. package/dist/{workspace-readme-RASXBZRQ.js → workspace-readme-56YZ4EAZ.js} +1 -1
  100. package/dist/{workspace-registry-summary-7QT7YMIU.js → workspace-registry-summary-OV5KX3WC.js} +1 -1
  101. package/dist/workspace-repair-engine-BNXZHW35.js +3 -0
  102. package/dist/workspace-run-7EJEBHAH.js +1 -0
  103. package/dist/{workspace-verify-RYCQZYYB.js → workspace-verify-W4P6LBIH.js} +1 -1
  104. package/dist/{workspace-watch-U3YGN3GG.js → workspace-watch-EZ4D4VCF.js} +1 -1
  105. package/docs/GLOSSARY.md +13 -10
  106. package/docs/README.md +24 -19
  107. package/docs/README_CONTENT_CONTRACT.md +12 -8
  108. package/docs/agent-entry.md +194 -0
  109. package/docs/ci-workflows.md +1 -1
  110. package/docs/commands-reference.md +26 -2
  111. package/docs/contracts/ARTIFACT_CATALOG.md +9 -3
  112. package/docs/contracts/COMMAND_OWNERSHIP_MATRIX.md +3 -0
  113. package/docs/contracts/README.md +7 -0
  114. package/docs/goal-packs.md +70 -9
  115. package/docs/workspace-operations.md +16 -8
  116. package/docs/workspace-repair-engine.md +36 -5
  117. package/package.json +3 -2
  118. package/scripts/enterprise-package-smoke.mjs +4 -0
  119. package/dist/analyze-MAU36FTX.js +0 -1
  120. package/dist/autopilot-release-TA2L7SCB.js +0 -1
  121. package/dist/capabilities-command-HE2FICLG.js +0 -1
  122. package/dist/chunk-42Q5E2YV.js +0 -1
  123. package/dist/chunk-7IRGSM25.js +0 -1
  124. package/dist/chunk-CNWUIXF3.js +0 -1
  125. package/dist/chunk-FPJNWPKU.js +0 -1
  126. package/dist/chunk-HH54C3XJ.js +0 -1
  127. package/dist/chunk-NQ5H4R2I.js +0 -83
  128. package/dist/chunk-PCXBPQO6.js +0 -1
  129. package/dist/chunk-QXW3SLEX.js +0 -1
  130. package/dist/chunk-TMOKXYAQ.js +0 -2
  131. package/dist/chunk-VIFTO53Y.js +0 -1
  132. package/dist/chunk-ZDYGO3T7.js +0 -36
  133. package/dist/goal-lifecycle-YTBU3ICP.js +0 -1
  134. package/dist/goal-pack-MYYH7K43.js +0 -1
  135. package/dist/workspace-explain-RGGZL5IW.js +0 -1
  136. package/dist/workspace-explain-contract-4ZZ6CJ44.js +0 -1
  137. package/dist/workspace-graph-token-efficiency-TF23UYEF.js +0 -1
  138. package/dist/workspace-knowledge-graph-snapshot-7IU2QAXI.js +0 -1
  139. package/dist/workspace-repair-engine-AZTJIFCY.js +0 -3
  140. package/dist/workspace-run-VMZY6LIF.js +0 -1
@@ -1,2 +1,2 @@
1
- import {a as a$1}from'./chunk-T5YRFRJV.js';import {w}from'./chunk-WP3CXMVA.js';import {a}from'./chunk-GR6442P7.js';import {a as a$2,d,c,e as e$2}from'./chunk-GRGUPSNP.js';import {b}from'./chunk-T63WRURN.js';import {i,e,h,f}from'./chunk-HH54C3XJ.js';import {l}from'./chunk-OCGZNSOE.js';import {e as e$1}from'./chunk-RO73VVHW.js';import {t,s}from'./chunk-MOSXTVPU.js';import g from'path';import h$1 from'fs-extra';var ue="unknown-run";function Z(e){let t=e$1();return !t||t===ue?e:{...e,runId:t}}var xe="workspace-dependency-graph.v1",Q=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],X=["inferred","contract","manual"];var E=i.workspaceContract,me=e.contractVerify,S=h.workspaceContract.schemaVersion,ge=f.contractVerify,x=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function ne(e){return e.replace(/\\/g,"/")}function V(e){let t=ne(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function ee(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function fe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function te(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(p=>{if(!p||typeof p!="object"||Array.isArray(p))return null;let c=p,m=Number(c.port);if(!Number.isInteger(m)||m<1||m>65535)return null;let d=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:m,protocol:d}}).filter(p=>p!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,a=Number(e.port??o?.default_port);return Number.isInteger(a)&&a>=1&&a<=65535?[{name:"http",port:a,protocol:"http"}]:[]}async function he(e){let t=g.join(e,"Dockerfile");if(!await h$1.pathExists(t))return [];try{let r=await h$1.readFile(t,"utf8"),o=new Map;for(let a of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let p of a[1].split(/\s+/)){let c=p.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),m=Number(c?.[1]);if(!c||!Number.isInteger(m)||m<1||m>65535)continue;let d=c[2]?.toLowerCase();o.set(m,{name:"http",port:m,protocol:d==="udp"?"udp":"http"});}return [...o.values()].sort((a,p)=>a.port-p.port)}catch{return []}}async function G(e){for(let t of e)if(await h$1.pathExists(t))return t;return null}async function ke(e){for(let t of s(e,"workspace.json"))try{let r=await h$1.readJson(t);return {name:typeof r.workspace_name=="string"&&r.workspace_name.trim()||typeof r.name=="string"&&r.name.trim()||g.basename(e),profile:typeof r.profile=="string"?r.profile:void 0}}catch{}return {name:g.basename(e)}}async function we(e){let t$1=[],r=[e],o=new Set,a$1=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let p=r.shift();if(!p||o.has(p))continue;o.add(p);let c=await G(t(p,"project.json")),m=await G(t(p,"context.json"));if(c||m){t$1.push(c??m??"");continue}let d;try{d=await h$1.readdir(p,{withFileTypes:true});}catch{continue}for(let l of d)!l.isDirectory()||a$1.has(l.name)||a(l.name)||r.push(g.join(p,l.name));}return t$1.sort()}function Pe(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function Ce(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("vscode-extension")?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function I(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function T(e,t,r){let o=e!==void 0&&e.source===void 0,a=Ce(t.kit,t.runtime),p=e?.ports||[],c=t.ports||[],m=(t.kit||"").toLowerCase().includes("vscode-extension"),d=t.source==="adopted-local"&&e?.source==="adopted-local",l=d,i=(m&&c.length===0?[]:d?c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]:p.length>0?p:c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]).map(P=>({...P,port:I(P.port,r)}));for(let P of i)r.add(P.port);let k={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&V(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:l?t.runtime:e?.runtime||t.runtime,framework:l?t.framework:e?.framework||t.framework,kit:l?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:i,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},f=JSON.stringify(e||null)!==JSON.stringify(k);return {project:k,changed:f}}async function ae(e){let t$1=g.resolve(e.workspacePath),r=await ke(t$1),o=await we(t$1),a=await a$1(t$1),p=[];for(let l of a){let s=g.resolve(l.path),i=await G(t(s,"project.json"))??await G(t(s,"context.json"));!i||o.some(k=>g.resolve(k)===g.resolve(i))||p.push({projectJsonPath:i,registryEntry:l});}let c=[],m=[...o.map(l=>({projectJsonPath:l})),...p];for(let{projectJsonPath:l,registryEntry:s}of m){let i=g.dirname(g.dirname(l)),k=ne(g.relative(t$1,i)),f=s!==void 0&&!V(k),P=ee(s?.name||g.basename(i),g.basename(i)),C=f?`external/${P}`:k||P,w=await h$1.readJson(l),j=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,n=typeof w.framework=="string"&&w.framework||Pe(j);c.push({slug:s?.name||C||g.basename(i),relativePath:C,source:s?.source??"workspace",relationship:s?.relationship,externalPath:f?i:void 0,runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:n,kit:j,modules:fe(w.modules),ports:te(w).length>0?te(w):await he(i),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let d=new Map;for(let l of c){let s=ee(l.slug,l.relativePath),i=d.get(s);(!i||i.source!=="workspace"&&l.source==="workspace")&&d.set(s,l);}return {schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function Ue(e){let t=g.resolve(e.outputPath||a$2(e.workspacePath,E));if(await h$1.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await ae({workspacePath:e.workspacePath,now:e.now}),o=new Set,a={...r,projects:r.projects.map(c=>T(void 0,c,o).project)},p=await ie({workspacePath:e.workspacePath,contractPath:t,contract:a});if(e.strict&&p.status==="failed")throw new x(p);return await se({workspacePath:e.workspacePath,contractPath:t,contract:a,now:e.now}),{contractPath:t,contract:a}}async function ze(e){let t=g.resolve(e.workspacePath),r=a$2(t,E),o=await d(t,E)??r,a=await ae({workspacePath:t,now:e.now}),p=await h$1.pathExists(o)?await h$1.readJson(o):null,c=new Map((p?.projects||[]).map(f=>[f.slug,f])),m=new Set,d$1=[],l=[],s=[];for(let f of a.projects){let P=c.get(f.slug),C=T(P,f,m);P?C.changed&&l.push(f.slug):d$1.push(f.slug),s.push(C.project),c.delete(f.slug);}for(let f of c.values()){if(f.source)continue;let P=T(f,f,m);s.push(P.project);}let i={schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...p?.workspace||{},...a.workspace,name:a.workspace.name||p?.workspace?.name||g.basename(t)},projects:s.sort((f,P)=>f.slug.localeCompare(P.slug))},k=await ie({workspacePath:t,contractPath:r,contract:i});if(e.strict&&k.status==="failed")throw new x(k);return await se({workspacePath:t,contractPath:r,contract:i,now:e.now}),{contractPath:r,contract:i,addedProjects:d$1,updatedProjects:l,verification:k}}async function re(e){return await h$1.pathExists(e)?{exists:true,contents:await h$1.readFile(e)}:{exists:false}}async function oe(e,t){if(!t.exists){await h$1.remove(e);return}await h$1.outputFile(e,t.contents);}async function se(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-7QT7YMIU.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),a=a$2(e.workspacePath,r),p=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:m,...d}=c;return JSON.stringify(d)};if(await h$1.pathExists(e.contractPath)&&await h$1.pathExists(a)){let[c,m]=await Promise.all([h$1.readJson(e.contractPath),h$1.readJson(a)]);if(p(c)===p(e.contract)&&p(m)===p(o))return}b(E,e.contract),b(r,o),await c(e.workspacePath,E,async()=>{let[c,m]=await Promise.all([re(e.contractPath),re(a)]);try{if(e.contractPath===a$2(e.workspacePath,E)?await e$2(e.workspacePath,E,e.contract):(await h$1.ensureDir(g.dirname(e.contractPath)),await h$1.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await e$2(e.workspacePath,r,o);}catch(d){let s=(await Promise.allSettled([oe(e.contractPath,c),oe(a,m)])).filter(i=>i.status==="rejected");throw s.length>0?new AggregateError([d,...s.map(i=>i.reason)],"Workspace contract publication failed and rollback was incomplete."):d}});}async function ce(e){let t=e.contractPath??(await d(e.workspacePath,E)||a$2(e.workspacePath,E)),r=await h$1.readJson(t);return {contractPath:t,contract:r}}var ye={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function Ee(e,t){return t.externalPath?g.resolve(t.externalPath):g.resolve(e,t.relativePath)}async function be(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(ye))for(let a of o)await h$1.pathExists(g.join(e,a))&&t[r].push(a);try{let r=await h$1.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,a)=>o.localeCompare(a));return t}function A(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function We(e){try{let t=await h$1.readJson(g.join(e,"package.json")),r={runtime:A(t.dependencies),development:A(t.devDependencies),peer:A(t.peerDependencies),optional:A(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:A(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function ve(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await h$1.readFile(g.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,a)=>o.localeCompare(a))}catch{}return []}function Ae(e,t){try{let r=w(e);if(r.engine!=="unknown")return r;let o=h$1.pathExistsSync(g.join(e,"package.json"))?"npm":h$1.pathExistsSync(g.join(e,"pyproject.toml"))?"python":h$1.pathExistsSync(g.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Se(e,t,r){let o=e.projects.map(a=>({id:a.slug,path:a.relativePath,runtime:a.runtime,framework:a.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function Ye(e$1){let{contractPath:t,contract:r}=await ce(e$1),o=e$1.now??new Date,a=o.toISOString(),{buildWorkspaceModel:p,workspaceModelProjectTopology:c}=await import('./workspace-model-VPFCKTYQ.js'),{hashWorkspaceModel:m}=await import('./workspace-model-hash-ZXYPIGCW.js'),d=await p({workspacePath:e$1.workspacePath,includeEvidence:false,now:o}),l=c(d)??Se(r,a,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(l.nodes.map(n=>[n.id,n.operationalProfile])),{buildWorkspaceKnowledgeGraph:i}=await import('./workspace-knowledge-graph-MUW6UAGI.js'),k=await i({workspacePath:e$1.workspacePath,workspace:{name:d.workspace.name,...d.workspace.profile?{profile:d.workspace.profile}:{}},contract:r,projectTopology:l,now:o,projects:d.projects.map(n=>({id:n.name,path:n.path,...n.absolutePath?{absolutePath:n.absolutePath}:{},runtime:n.runtime,runtimeCandidates:n.runtimeCandidates,framework:n.framework,...n.kit?{kit:n.kit}:{}})),source:{kind:"workspace-model",artifact:e.model,hashAlgorithm:"sha256",hash:m(d)}}),f=await Promise.all(r.projects.map(async n=>{let u=Ee(e$1.workspacePath,n),[R,W,pe]=await Promise.all([be(u),We(u),ve(u)]),y=Ae(u,n);return {id:n.slug,label:n.slug,relativePath:n.relativePath,source:n.source,relationship:n.relationship,externalPath:n.externalPath,runtime:n.runtime??y.runtime,framework:n.framework??y.framework,kit:n.kit,modules:n.modules,ports:n.ports,apis:n.contracts.apis,owns:n.contracts.owns,env:[...new Set([...n.contracts.env,...pe])].sort((le,de)=>le.localeCompare(de)),contracts:{owns:[...n.contracts.owns],apis:[...n.contracts.apis],publishes:[...n.contracts.publishes],consumes:[...n.contracts.consumes],dependsOn:[...n.contracts.dependsOn],env:[...n.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:R,...W?{package:W}:{},...s.get(n.slug)?{operationalProfile:s.get(n.slug)}:{}}})),P=new Set(f.map(n=>n.id)),C=new Map,w=[];for(let n of r.projects){for(let u of n.contracts.dependsOn||[])P.has(u)&&w.push({from:u,to:n.slug,type:"dependency",label:"dependsOn"});for(let u of n.contracts.publishes||[])C.has(u)||C.set(u,new Set),C.get(u)?.add(n.slug);}for(let n of r.projects)for(let u of n.contracts.consumes||[]){let R=C.get(u);if(R)for(let W of R)W!==n.slug&&w.push({from:W,to:n.slug,type:"event",label:u});}let j={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:a,nodes:f.sort((n,u)=>n.id.localeCompare(u.id)),edges:w.sort((n,u)=>`${n.from}:${n.to}:${n.type}:${n.label}`.localeCompare(`${u.from}:${u.to}:${u.type}:${u.label}`)),dependencyGraph:l,knowledgeGraph:k,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:f.length,dependencyEdges:w.filter(n=>n.type==="dependency").length,eventEdges:w.filter(n=>n.type==="event").length,portCount:f.reduce((n,u)=>n+u.ports.length,0),apiCount:f.reduce((n,u)=>n+u.apis.length,0),relationshipEdges:l.stats.edgeCount,inferredEdges:l.stats.inferredEdges,authoritativeEdges:l.stats.authoritativeEdges,orphanProjects:l.stats.orphanCount,hotspotProjects:l.stats.hotspotCount,evidenceCoverageRatio:l.stats.evidenceCoverageRatio,edgeCoverageRatio:l.stats.edgeCoverageRatio,connectedProjects:l.stats.connectedNodeCount,lowConfidenceEdges:l.stats.lowConfidenceEdges,hasCycle:l.stats.hasCycle,manifestCount:f.reduce((n,u)=>n+u.files.manifests.length,0),entrypointCount:f.reduce((n,u)=>n+u.files.entrypoints.length,0),diagnostics:l.diagnostics?.length??0,relationshipKinds:Object.fromEntries(Q.map(n=>[n,l.edges.filter(u=>u.kind===n).length])),relationshipSources:Object.fromEntries(X.map(n=>[n,l.edges.filter(u=>u.source===n).length])),entityCount:k.quality.entityCount,knowledgeRelations:k.quality.relationCount,proofCount:k.quality.proofCount,providerCount:k.providers.length,knowledgeUnknowns:k.quality.unknownCount}};return {contractPath:t,graph:j}}async function ie(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,E),contract:e.contract}:await ce(e),{contractPath:r,contract:o}=t,a=[],p=[];o.kind!=="rapidkit.workspace.contract"&&a.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==S&&a.push(`Contract schemaVersion must be ${S}.`),o.workspace?.name||a.push("Contract workspace.name is required."),Array.isArray(o.projects)||a.push("Contract projects must be an array.");let c=new Set,m=new Map;for(let s of o.projects||[]){if(!s.slug){a.push("Every project must declare slug.");continue}c.has(s.slug)&&a.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?V(s.relativePath)||a.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):a.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||a.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),g.isAbsolute(s.externalPath)||a.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let i of s.ports||[]){(!Number.isInteger(i.port)||i.port<1||i.port>65535)&&a.push(`Project ${s.slug} declares invalid port: ${i.port}.`);let k=m.get(i.port);k&&a.push(`Port ${i.port} is claimed by both ${k} and ${s.slug}.`),m.set(i.port,s.slug);}for(let i of s.contracts?.apis||[])(!i.name?.trim()||!i.basePath?.startsWith("/"))&&a.push(`Project ${s.slug} declares invalid API contract.`);for(let i of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])i.trim()||a.push(`Project ${s.slug} declares an empty event contract.`);for(let i of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(i)||a.push(`Project ${s.slug} declares invalid env contract: ${i}.`);for(let i of s.contracts?.dependsOn||[])c.has(i);}for(let s of o.projects||[])for(let i of s.contracts?.dependsOn||[])c.has(i)||a.push(`Project ${s.slug} depends on unknown project: ${i}.`);p.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===S?"passed":"failed",message:"Contract schema and kind are valid."}),p.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),p.push({id:"ports",status:a.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),p.push({id:"dependencies",status:a.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),p.push({id:"contracts",status:a.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let d=await l(e.workspacePath);if(d.moduleCount>0){for(let s of d.issues)a.push(`${g.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);p.push({id:"module-paths",status:d.status,message:d.status==="passed"?`All ${d.moduleCount} registered module(s) resolve under canonical paths.`:`${d.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&p.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:a.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:p,violations:a}}async function qe(e){let t=g.resolve(e.workspacePath),r={schemaVersion:ge,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return e$2(t,me,Z(r))}
1
+ import {w}from'./chunk-WP3CXMVA.js';import {a as a$1}from'./chunk-T5YRFRJV.js';import {a}from'./chunk-GR6442P7.js';import {a as a$2,d,c,e as e$2}from'./chunk-CCDGHPEJ.js';import {b}from'./chunk-D65FCQIO.js';import {i,e,h,f}from'./chunk-NZ3WZYD5.js';import {l}from'./chunk-OCGZNSOE.js';import {e as e$1}from'./chunk-RO73VVHW.js';import {t,s}from'./chunk-MOSXTVPU.js';import g from'path';import h$1 from'fs-extra';var ue="unknown-run";function Z(e){let t=e$1();return !t||t===ue?e:{...e,runId:t}}var xe="workspace-dependency-graph.v1",Q=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],X=["inferred","contract","manual"];var E=i.workspaceContract,me=e.contractVerify,S=h.workspaceContract.schemaVersion,ge=f.contractVerify,x=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function ne(e){return e.replace(/\\/g,"/")}function V(e){let t=ne(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function ee(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function fe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function te(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(p=>{if(!p||typeof p!="object"||Array.isArray(p))return null;let c=p,m=Number(c.port);if(!Number.isInteger(m)||m<1||m>65535)return null;let d=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:m,protocol:d}}).filter(p=>p!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,a=Number(e.port??o?.default_port);return Number.isInteger(a)&&a>=1&&a<=65535?[{name:"http",port:a,protocol:"http"}]:[]}async function he(e){let t=g.join(e,"Dockerfile");if(!await h$1.pathExists(t))return [];try{let r=await h$1.readFile(t,"utf8"),o=new Map;for(let a of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let p of a[1].split(/\s+/)){let c=p.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),m=Number(c?.[1]);if(!c||!Number.isInteger(m)||m<1||m>65535)continue;let d=c[2]?.toLowerCase();o.set(m,{name:"http",port:m,protocol:d==="udp"?"udp":"http"});}return [...o.values()].sort((a,p)=>a.port-p.port)}catch{return []}}async function G(e){for(let t of e)if(await h$1.pathExists(t))return t;return null}async function ke(e){for(let t of s(e,"workspace.json"))try{let r=await h$1.readJson(t);return {name:typeof r.workspace_name=="string"&&r.workspace_name.trim()||typeof r.name=="string"&&r.name.trim()||g.basename(e),profile:typeof r.profile=="string"?r.profile:void 0}}catch{}return {name:g.basename(e)}}async function we(e){let t$1=[],r=[e],o=new Set,a$1=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let p=r.shift();if(!p||o.has(p))continue;o.add(p);let c=await G(t(p,"project.json")),m=await G(t(p,"context.json"));if(c||m){t$1.push(c??m??"");continue}let d;try{d=await h$1.readdir(p,{withFileTypes:true});}catch{continue}for(let l of d)!l.isDirectory()||a$1.has(l.name)||a(l.name)||r.push(g.join(p,l.name));}return t$1.sort()}function Pe(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function Ce(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("vscode-extension")?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function I(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function T(e,t,r){let o=e!==void 0&&e.source===void 0,a=Ce(t.kit,t.runtime),p=e?.ports||[],c=t.ports||[],m=(t.kit||"").toLowerCase().includes("vscode-extension"),d=t.source==="adopted-local"&&e?.source==="adopted-local",l=d,i=(m&&c.length===0?[]:d?c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]:p.length>0?p:c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]).map(P=>({...P,port:I(P.port,r)}));for(let P of i)r.add(P.port);let k={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&V(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:l?t.runtime:e?.runtime||t.runtime,framework:l?t.framework:e?.framework||t.framework,kit:l?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:i,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},f=JSON.stringify(e||null)!==JSON.stringify(k);return {project:k,changed:f}}async function ae(e){let t$1=g.resolve(e.workspacePath),r=await ke(t$1),o=await we(t$1),a=await a$1(t$1),p=[];for(let l of a){let s=g.resolve(l.path),i=await G(t(s,"project.json"))??await G(t(s,"context.json"));!i||o.some(k=>g.resolve(k)===g.resolve(i))||p.push({projectJsonPath:i,registryEntry:l});}let c=[],m=[...o.map(l=>({projectJsonPath:l})),...p];for(let{projectJsonPath:l,registryEntry:s}of m){let i=g.dirname(g.dirname(l)),k=ne(g.relative(t$1,i)),f=s!==void 0&&!V(k),P=ee(s?.name||g.basename(i),g.basename(i)),C=f?`external/${P}`:k||P,w=await h$1.readJson(l),j=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,n=typeof w.framework=="string"&&w.framework||Pe(j);c.push({slug:s?.name||C||g.basename(i),relativePath:C,source:s?.source??"workspace",relationship:s?.relationship,externalPath:f?i:void 0,runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:n,kit:j,modules:fe(w.modules),ports:te(w).length>0?te(w):await he(i),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let d=new Map;for(let l of c){let s=ee(l.slug,l.relativePath),i=d.get(s);(!i||i.source!=="workspace"&&l.source==="workspace")&&d.set(s,l);}return {schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function Ue(e){let t=g.resolve(e.outputPath||a$2(e.workspacePath,E));if(await h$1.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await ae({workspacePath:e.workspacePath,now:e.now}),o=new Set,a={...r,projects:r.projects.map(c=>T(void 0,c,o).project)},p=await ie({workspacePath:e.workspacePath,contractPath:t,contract:a});if(e.strict&&p.status==="failed")throw new x(p);return await se({workspacePath:e.workspacePath,contractPath:t,contract:a,now:e.now}),{contractPath:t,contract:a}}async function ze(e){let t=g.resolve(e.workspacePath),r=a$2(t,E),o=await d(t,E)??r,a=await ae({workspacePath:t,now:e.now}),p=await h$1.pathExists(o)?await h$1.readJson(o):null,c=new Map((p?.projects||[]).map(f=>[f.slug,f])),m=new Set,d$1=[],l=[],s=[];for(let f of a.projects){let P=c.get(f.slug),C=T(P,f,m);P?C.changed&&l.push(f.slug):d$1.push(f.slug),s.push(C.project),c.delete(f.slug);}for(let f of c.values()){if(f.source)continue;let P=T(f,f,m);s.push(P.project);}let i={schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...p?.workspace||{},...a.workspace,name:a.workspace.name||p?.workspace?.name||g.basename(t)},projects:s.sort((f,P)=>f.slug.localeCompare(P.slug))},k=await ie({workspacePath:t,contractPath:r,contract:i});if(e.strict&&k.status==="failed")throw new x(k);return await se({workspacePath:t,contractPath:r,contract:i,now:e.now}),{contractPath:r,contract:i,addedProjects:d$1,updatedProjects:l,verification:k}}async function re(e){return await h$1.pathExists(e)?{exists:true,contents:await h$1.readFile(e)}:{exists:false}}async function oe(e,t){if(!t.exists){await h$1.remove(e);return}await h$1.outputFile(e,t.contents);}async function se(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-OV5KX3WC.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),a=a$2(e.workspacePath,r),p=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:m,...d}=c;return JSON.stringify(d)};if(await h$1.pathExists(e.contractPath)&&await h$1.pathExists(a)){let[c,m]=await Promise.all([h$1.readJson(e.contractPath),h$1.readJson(a)]);if(p(c)===p(e.contract)&&p(m)===p(o))return}b(E,e.contract),b(r,o),await c(e.workspacePath,E,async()=>{let[c,m]=await Promise.all([re(e.contractPath),re(a)]);try{if(e.contractPath===a$2(e.workspacePath,E)?await e$2(e.workspacePath,E,e.contract):(await h$1.ensureDir(g.dirname(e.contractPath)),await h$1.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await e$2(e.workspacePath,r,o);}catch(d){let s=(await Promise.allSettled([oe(e.contractPath,c),oe(a,m)])).filter(i=>i.status==="rejected");throw s.length>0?new AggregateError([d,...s.map(i=>i.reason)],"Workspace contract publication failed and rollback was incomplete."):d}});}async function ce(e){let t=e.contractPath??(await d(e.workspacePath,E)||a$2(e.workspacePath,E)),r=await h$1.readJson(t);return {contractPath:t,contract:r}}var ye={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function Ee(e,t){return t.externalPath?g.resolve(t.externalPath):g.resolve(e,t.relativePath)}async function be(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(ye))for(let a of o)await h$1.pathExists(g.join(e,a))&&t[r].push(a);try{let r=await h$1.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,a)=>o.localeCompare(a));return t}function A(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function We(e){try{let t=await h$1.readJson(g.join(e,"package.json")),r={runtime:A(t.dependencies),development:A(t.devDependencies),peer:A(t.peerDependencies),optional:A(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:A(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function ve(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await h$1.readFile(g.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,a)=>o.localeCompare(a))}catch{}return []}function Ae(e,t){try{let r=w(e);if(r.engine!=="unknown")return r;let o=h$1.pathExistsSync(g.join(e,"package.json"))?"npm":h$1.pathExistsSync(g.join(e,"pyproject.toml"))?"python":h$1.pathExistsSync(g.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Se(e,t,r){let o=e.projects.map(a=>({id:a.slug,path:a.relativePath,runtime:a.runtime,framework:a.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function Ye(e$1){let{contractPath:t,contract:r}=await ce(e$1),o=e$1.now??new Date,a=o.toISOString(),{buildWorkspaceModel:p,workspaceModelProjectTopology:c}=await import('./workspace-model-EIQSKDX7.js'),{hashWorkspaceModel:m}=await import('./workspace-model-hash-ZXYPIGCW.js'),d=await p({workspacePath:e$1.workspacePath,includeEvidence:false,now:o}),l=c(d)??Se(r,a,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(l.nodes.map(n=>[n.id,n.operationalProfile])),{buildWorkspaceKnowledgeGraph:i}=await import('./workspace-knowledge-graph-HZZP6ZRB.js'),k=await i({workspacePath:e$1.workspacePath,workspace:{name:d.workspace.name,...d.workspace.profile?{profile:d.workspace.profile}:{}},contract:r,projectTopology:l,now:o,projects:d.projects.map(n=>({id:n.name,path:n.path,...n.absolutePath?{absolutePath:n.absolutePath}:{},runtime:n.runtime,runtimeCandidates:n.runtimeCandidates,framework:n.framework,...n.kit?{kit:n.kit}:{}})),source:{kind:"workspace-model",artifact:e.model,hashAlgorithm:"sha256",hash:m(d)}}),f=await Promise.all(r.projects.map(async n=>{let u=Ee(e$1.workspacePath,n),[R,W,pe]=await Promise.all([be(u),We(u),ve(u)]),y=Ae(u,n);return {id:n.slug,label:n.slug,relativePath:n.relativePath,source:n.source,relationship:n.relationship,externalPath:n.externalPath,runtime:n.runtime??y.runtime,framework:n.framework??y.framework,kit:n.kit,modules:n.modules,ports:n.ports,apis:n.contracts.apis,owns:n.contracts.owns,env:[...new Set([...n.contracts.env,...pe])].sort((le,de)=>le.localeCompare(de)),contracts:{owns:[...n.contracts.owns],apis:[...n.contracts.apis],publishes:[...n.contracts.publishes],consumes:[...n.contracts.consumes],dependsOn:[...n.contracts.dependsOn],env:[...n.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:R,...W?{package:W}:{},...s.get(n.slug)?{operationalProfile:s.get(n.slug)}:{}}})),P=new Set(f.map(n=>n.id)),C=new Map,w=[];for(let n of r.projects){for(let u of n.contracts.dependsOn||[])P.has(u)&&w.push({from:u,to:n.slug,type:"dependency",label:"dependsOn"});for(let u of n.contracts.publishes||[])C.has(u)||C.set(u,new Set),C.get(u)?.add(n.slug);}for(let n of r.projects)for(let u of n.contracts.consumes||[]){let R=C.get(u);if(R)for(let W of R)W!==n.slug&&w.push({from:W,to:n.slug,type:"event",label:u});}let j={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:a,nodes:f.sort((n,u)=>n.id.localeCompare(u.id)),edges:w.sort((n,u)=>`${n.from}:${n.to}:${n.type}:${n.label}`.localeCompare(`${u.from}:${u.to}:${u.type}:${u.label}`)),dependencyGraph:l,knowledgeGraph:k,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:f.length,dependencyEdges:w.filter(n=>n.type==="dependency").length,eventEdges:w.filter(n=>n.type==="event").length,portCount:f.reduce((n,u)=>n+u.ports.length,0),apiCount:f.reduce((n,u)=>n+u.apis.length,0),relationshipEdges:l.stats.edgeCount,inferredEdges:l.stats.inferredEdges,authoritativeEdges:l.stats.authoritativeEdges,orphanProjects:l.stats.orphanCount,hotspotProjects:l.stats.hotspotCount,evidenceCoverageRatio:l.stats.evidenceCoverageRatio,edgeCoverageRatio:l.stats.edgeCoverageRatio,connectedProjects:l.stats.connectedNodeCount,lowConfidenceEdges:l.stats.lowConfidenceEdges,hasCycle:l.stats.hasCycle,manifestCount:f.reduce((n,u)=>n+u.files.manifests.length,0),entrypointCount:f.reduce((n,u)=>n+u.files.entrypoints.length,0),diagnostics:l.diagnostics?.length??0,relationshipKinds:Object.fromEntries(Q.map(n=>[n,l.edges.filter(u=>u.kind===n).length])),relationshipSources:Object.fromEntries(X.map(n=>[n,l.edges.filter(u=>u.source===n).length])),entityCount:k.quality.entityCount,knowledgeRelations:k.quality.relationCount,proofCount:k.quality.proofCount,providerCount:k.providers.length,knowledgeUnknowns:k.quality.unknownCount}};return {contractPath:t,graph:j}}async function ie(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,E),contract:e.contract}:await ce(e),{contractPath:r,contract:o}=t,a=[],p=[];o.kind!=="rapidkit.workspace.contract"&&a.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==S&&a.push(`Contract schemaVersion must be ${S}.`),o.workspace?.name||a.push("Contract workspace.name is required."),Array.isArray(o.projects)||a.push("Contract projects must be an array.");let c=new Set,m=new Map;for(let s of o.projects||[]){if(!s.slug){a.push("Every project must declare slug.");continue}c.has(s.slug)&&a.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?V(s.relativePath)||a.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):a.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||a.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),g.isAbsolute(s.externalPath)||a.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let i of s.ports||[]){(!Number.isInteger(i.port)||i.port<1||i.port>65535)&&a.push(`Project ${s.slug} declares invalid port: ${i.port}.`);let k=m.get(i.port);k&&a.push(`Port ${i.port} is claimed by both ${k} and ${s.slug}.`),m.set(i.port,s.slug);}for(let i of s.contracts?.apis||[])(!i.name?.trim()||!i.basePath?.startsWith("/"))&&a.push(`Project ${s.slug} declares invalid API contract.`);for(let i of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])i.trim()||a.push(`Project ${s.slug} declares an empty event contract.`);for(let i of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(i)||a.push(`Project ${s.slug} declares invalid env contract: ${i}.`);for(let i of s.contracts?.dependsOn||[])c.has(i);}for(let s of o.projects||[])for(let i of s.contracts?.dependsOn||[])c.has(i)||a.push(`Project ${s.slug} depends on unknown project: ${i}.`);p.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===S?"passed":"failed",message:"Contract schema and kind are valid."}),p.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),p.push({id:"ports",status:a.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),p.push({id:"dependencies",status:a.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),p.push({id:"contracts",status:a.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let d=await l(e.workspacePath);if(d.moduleCount>0){for(let s of d.issues)a.push(`${g.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);p.push({id:"module-paths",status:d.status,message:d.status==="passed"?`All ${d.moduleCount} registered module(s) resolve under canonical paths.`:`${d.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&p.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:a.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:p,violations:a}}async function qe(e){let t=g.resolve(e.workspacePath),r={schemaVersion:ge,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return e$2(t,me,Z(r))}
2
2
  export{Z as a,xe as b,Q as c,E as d,me as e,S as f,ge as g,x as h,we as i,ae as j,Ue as k,ze as l,ce as m,Ye as n,ie as o,qe as p};
@@ -0,0 +1,2 @@
1
+ import {k}from'./chunk-HOUQIT7U.js';import {b}from'./chunk-GPOZILMY.js';import {a as a$1}from'./chunk-5NIZNXRS.js';import {c}from'./chunk-EWZZUQBR.js';import {b as b$1}from'./chunk-D65FCQIO.js';import {a}from'./chunk-AFIFZTOY.js';import {h,i,e}from'./chunk-NZ3WZYD5.js';import he from'crypto';import G from'fs';import M from'fs/promises';import f from'path';var te=h.projectAgentEntry.schemaVersion,R=i.projectAgentEntry,fe="workspai.agent-bootstrap-receipt.v1",_e="<!-- WORKSPAI:AGENT-ENTRY:START -->",Ne="<!-- WORKSPAI:AGENT-ENTRY:END -->",O=["generic","codex","claude","gemini","qwen","kimi","grok","copilot","cursor","windsurf","amazon-q"],He=["CLAUDE.md","GEMINI.md","QWEN.md",".amazonq/rules/workspai-agent-entry.md"];function me(t){let s=t?.trim().toLowerCase()||"generic";if(s==="orca")return "grok";if(O.includes(s))return s;throw new Error(`Unsupported agent host "${s}". Expected one of: ${O.join(", ")}.`)}function oe(t){let s=t.map(i=>i.id).sort(),n=[...O].sort();if(s.length!==n.length||s.some((i,c)=>i!==n[c]))throw new Error("Project agent entry must define each supported host exactly once.")}function L(t){let{integrity:s,...n}=t;return n}function E(t){return c(t)}function Ge(t){oe(t.hosts);let s={schemaVersion:te,generatedAt:t.context.generatedAt,project:{name:t.context.project.name,relativePath:t.context.project.relativePath,...t.context.project.runtime?{runtime:t.context.project.runtime}:{},...t.context.project.framework?{framework:t.context.project.framework}:{}},workspace:{name:t.context.workspace.name,relationship:t.context.workspace.relationship,localBinding:i.projectWorkspaceLink,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},canonical:{projectContext:i.projectContextAgent,projectGrounding:".workspai/PROJECT-GROUNDING.md",goalIndex:`workspace:${i.goalIndex}`,workspaceIndex:`workspace:${e.agentIndex}`,workspaceContext:`workspace:${e.agentContext}`,workspaceModel:`workspace:${e.model}`,knowledgeGraph:`workspace:${e.knowledgeGraph}`},protocol:{mode:"canonical-first",bootstrapCommand:"workspai agent bootstrap --for-agent generic --strict --json",verifyCommand:"workspai project agent-entry verify --for-agent all --strict --json",requiredReadOrder:[R,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",i.projectContextAgent,`workspace:${i.goalIndex}`,`workspace:${e.agentIndex}`,`workspace:${e.agentContext}`,`workspace:${e.model}`,`workspace:${e.knowledgeGraph}`,"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json","source:targeted-live-files"],sourcePolicy:{liveSourceAuthority:"exact-implementation",workspaceEvidenceAuthority:"identity-topology-readiness-goals",broadScanBeforeBootstrap:false,sourceMutation:"governed-only",verificationClaims:"cli-evidence-only"},degradedMode:{discloseMissingEvidence:true,allowCompleteArchitectureClaims:false,allowReadOnlySourceInspection:true}},hosts:[...t.hosts].sort((i,c)=>i.id.localeCompare(c.id))},n={...s,integrity:{algorithm:"sha256",projectContextHash:t.context.integrity.payloadHash,payloadHash:E(s),portable:true,absolutePathsEmitted:false}};if(!y(n))throw new Error("Project agent entry rejected a non-portable local path.");return a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n}function y(t){return typeof t=="string"?!(/^[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])file:\/\//i.test(t)||/(?:^|[\s("'`])\\\\[^\\\s]+[\\]/.test(t)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(t)):Array.isArray(t)?t.every(y):t&&typeof t=="object"?Object.values(t).every(y):true}async function ue(t){let s=f.join(t,R),n=JSON.parse(await M.readFile(s,"utf8"));if(a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n.integrity.payloadHash!==E(L(n)))throw new Error("Project agent entry integrity validation failed.");if(oe(n.hosts),!y(n)||n.integrity.absolutePathsEmitted)throw new Error("Project agent entry contains a non-portable local path.");return n}async function ye(t){let s=f.join(t,i.projectContextAgent),n=JSON.parse(await M.readFile(s,"utf8"));a(n,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent");let i$1=L(n),c=he.createHash("sha256").update(JSON.stringify(i$1)).digest("hex");if(n.integrity.payloadHash!==c)throw new Error("Project context agent integrity validation failed.");if(!y(n)||n.integrity.absolutePathsEmitted)throw new Error("Project context agent contains a non-portable local path.");return n}function we(t){return t.includes("blocked")?"blocked":t.includes("degraded")?"degraded":"ready"}async function Oe(t){let s=b({startPath:f.resolve(t.startPath??process.cwd()),strict:true,requireProjectMembership:true});if(!s?.projectPath)throw new Error("No canonically bound Workspai project was resolved.");let n=s.projectPath,i$1=s.workspacePath,c=await ue(n),o=await ye(n);if(c.integrity.projectContextHash!==o.integrity.payloadHash||c.project.name!==o.project.name||c.workspace.name!==o.workspace.name)throw new Error("Project agent entry is not bound to the current project context.");let $=t.forAgent?.trim().toLowerCase()||"generic",F=$==="all",g=F?"all":me($),W=g,h=F?c.hosts:c.hosts.filter(e=>e.id===g),K=c.hosts.find(e=>e.id==="generic");if(h.length===0&&K&&h.push(K),h.length===0)throw new Error("Project agent entry does not define generic host coverage.");let w=[],p=(e,r,S,u)=>w.push({id:e,status:r,message:S,...u?{artifact:u}:{}});p("workspace-binding","passed","Canonical workspace membership is resolved."),p("entry-integrity","passed","Project entry manifest integrity is valid.",R),p("project-context-integrity","passed","Project context integrity and manifest binding are valid.",i.projectContextAgent);let I=[...new Set(h.flatMap(e=>e.entryFiles))].sort(),ne=I.filter(e=>!G.existsSync(f.join(n,e))),m=h.some(e=>e.status==="blocked")||ne.length>0?"blocked":h.some(e=>e.status==="degraded")?"degraded":"ready";p("host-discovery",m==="ready"?"passed":m==="degraded"?"warning":"failed",m==="ready"?`${g} has discoverable Workspai entry coverage.`:m==="degraded"?h.find(e=>e.reason)?.reason??`${g} entry coverage is degraded.`:`${g} entry coverage is missing required files.`,I[0]);let V=[e.agentIndex,e.agentContext,e.model,e.knowledgeGraph],j=V.filter(e=>!G.existsSync(f.join(i$1,e)));p("canonical-evidence",j.length===0?"passed":"failed",j.length===0?"Required canonical workspace evidence is present.":`Required canonical evidence is missing: ${j.join(", ")}.`);let k$1=[],v=null,q=null;for(let e$1 of V)if(!j.includes(e$1))try{let r=JSON.parse(await M.readFile(f.join(i$1,e$1),"utf8"));b$1(e$1,r,e$1),e$1===e.model&&(v=r),e$1===e.knowledgeGraph&&(q=r);}catch{k$1.push(e$1);}p("canonical-contracts",k$1.length===0?"passed":"failed",k$1.length===0?"Canonical workspace evidence satisfies its published schemas.":`Canonical evidence failed contract validation: ${k$1.join(", ")}.`);let re=v?.workspace,se=q?.workspace,ae=Array.isArray(v?.projects)?v.projects:[],B=k$1.length===0&&re?.name===o.workspace.name&&se?.name===o.workspace.name&&ae.some(e=>e.name===o.project.name);p("canonical-project-membership",B?"passed":"failed",B?"The project and workspace identities agree across the entry, Model, and Graph.":"The project or workspace identity is missing or inconsistent in canonical evidence.");let J=!o.intelligence.freshness.graphMatchesModel||["missing","stale"].includes(o.intelligence.freshness.model)||["missing","stale"].includes(o.intelligence.freshness.graph)?"failed":o.intelligence.freshness.model==="unknown"||o.intelligence.freshness.graph==="unknown"?"warning":"passed",P=false,C;if(t.validateLiveInputs!==false)try{let e=await a$1(i$1);P=e.status==="hit";let r=e.status==="hit"?"Live project inputs match the persisted Model and Knowledge Graph snapshot.":`Live project inputs require an intelligence refresh (${e.reason}).`;C={id:"live-inputs",status:P?"passed":"failed",message:r};}catch{C={id:"live-inputs",status:"failed",message:"Live project inputs could not be validated against canonical graph evidence."};}else C={id:"live-inputs",status:"warning",message:"Live input validation was skipped; persisted compatibility was checked only."};let b$2=J==="warning"&&o.intelligence.freshness.model==="unknown"&&o.intelligence.freshness.graph==="fresh"&&o.intelligence.freshness.graphMatchesModel&&P?"passed":J;p("persisted-freshness",b$2,b$2==="passed"?o.intelligence.freshness.model==="unknown"?"Model and Graph bindings are current; live input validation closes structural freshness while verify-before-use facts remain individually governed.":"Persisted Model and Knowledge Graph bindings are current.":b$2==="warning"?"Persisted evidence is compatible, but at least one freshness state is unknown.":"Persisted Model or Knowledge Graph evidence is missing, stale, or mismatched."),w.push(C);let l={present:false,appliesToProject:false,status:"none"},T=[],ie=f.join(i$1,i.goalIndex);if(G.existsSync(ie)){let e=null;try{e=await k({workspacePath:i$1,validateBindings:false});}catch{T.push("workspai goal --list --json"),p("active-goal","failed","The Goal index is present but invalid.");}if(e?.active&&(l={present:true,appliesToProject:e.active.scope.projects.includes(o.project.name),status:"invalid",id:e.active.id,objective:e.active.objective,lifecycle:e.active.lifecycle,goalPack:`workspace:${e.active.goalPack}`,agentHandoff:`workspace:${e.active.agentHandoff}`}),e)try{let r=await k({workspacePath:i$1,validateBindings:true});r.active&&(l={present:true,appliesToProject:r.active.scope.projects.includes(o.project.name),status:"ready",id:r.active.id,objective:r.active.objective,lifecycle:r.active.lifecycle,goalPack:`workspace:${r.active.goalPack}`,agentHandoff:`workspace:${r.active.agentHandoff}`}),p("active-goal","passed",r.active?"The active Goal Pack and agent handoff have valid canonical bindings.":"No active Goal Pack is selected.");}catch(r){let S=r instanceof Error?r.message:String(r),u=l.present&&/\bstale\b|--refresh/i.test(S);if(l.present&&(l.status=u?"stale":"invalid"),u&&l.objective){let N=e.active,ge=N?.scope.kind==="project"&&N.scope.projects.length===1?`project:${N.scope.projects[0]}`:"workspace";T.push(`workspai goal ${JSON.stringify(l.objective)} --scope ${ge} --for-agent generic --refresh --json`);}else T.push("workspai goal --status --json");p("active-goal","failed",u?"The selected Goal Pack is present but stale; regenerate it against current canonical evidence before acting.":l.present?"The selected Goal Pack is present but its canonical binding or handoff is invalid.":"The Goal index could not be validated.");}}else p("active-goal","passed","No Goal index is present for this workspace.");let ce=w.some(e=>e.status==="failed")?"blocked":w.some(e=>e.status==="warning")?"degraded":"ready",x=we([m,ce]),le=`command:workspai agent bootstrap --for-agent ${g} --strict --json`,pe=c.protocol.requiredReadOrder.map(e=>e==="command:workspai agent bootstrap --for-agent generic --strict --json"?le:e),U={schemaVersion:fe,generatedAt:(t.now??new Date).toISOString(),status:x,requestedAgent:W,resolvedHost:g,project:{name:o.project.name,relativePath:o.project.relativePath,...o.project.runtime?{runtime:o.project.runtime}:{},...o.project.framework?{framework:o.project.framework}:{}},workspace:{name:o.workspace.name,relationship:o.workspace.relationship,resolved:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},entry:{artifact:R,schemaVersion:te,hostStatus:m,entryFiles:I},canonicalEvidence:{projectContext:i.projectContextAgent,workspaceIndex:`workspace:${e.agentIndex}`,workspaceContext:`workspace:${e.agentContext}`,workspaceModel:`workspace:${e.model}`,knowledgeGraph:`workspace:${e.knowledgeGraph}`,modelFreshness:o.intelligence.freshness.model,graphFreshness:o.intelligence.freshness.graph,graphMatchesModel:o.intelligence.freshness.graphMatchesModel,liveInputsValidated:P,blockerCount:o.blockers.length},activeGoal:l,requiredReadOrder:pe,claims:{architecture:x==="ready"?"allowed-with-citations":"prohibited",sourceInspection:"bounded-and-targeted",sourceMutation:"governed-cli-transaction-only",verification:"cli-evidence-only"},checks:w,nextActions:x==="ready"?[...l.present&&l.appliesToProject&&l.agentHandoff?[`read:${l.agentHandoff}`]:[],`workspai workspace graph search <task-query> --scope project:${o.project.name} --limit 12 --json`,"inspect only the returned proof paths and target source files"]:[...T,"workspai workspace intelligence run --for-agent generic --strict --json",`workspai agent bootstrap --for-agent ${g} --strict --json`]},Y=E(L(c)),de=E({manifestHash:Y,projectContextHash:o.integrity.payloadHash,requestedAgent:W,status:x,generatedAt:U.generatedAt}),D={...U,receiptId:de},_={...D,integrity:{algorithm:"sha256",manifestHash:Y,projectContextHash:o.integrity.payloadHash,payloadHash:E(D),portable:true,absolutePathsEmitted:false}};if(!y(_))throw new Error("Agent bootstrap receipt rejected a non-portable local path.");return a(_,"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json","Agent bootstrap receipt"),_}
2
+ export{te as a,R as b,fe as c,_e as d,Ne as e,O as f,He as g,me as h,Ge as i,Oe as j};
@@ -1,4 +1,4 @@
1
- import {d,b,e}from'./chunk-WSDVFLHT.js';import {a}from'./chunk-2647BYBC.js';import {d as d$2}from'./chunk-S5KTATOU.js';import {a as a$1}from'./chunk-27UR373Z.js';import {p as p$1,w,t as t$1}from'./chunk-WP3CXMVA.js';import {h,j,f,e as e$2}from'./chunk-ZCPT6KC3.js';import {d as d$1}from'./chunk-GRGUPSNP.js';import {e as e$1,i}from'./chunk-HH54C3XJ.js';import {a as a$2}from'./chunk-TQEMLBAG.js';import {t,p,s}from'./chunk-MOSXTVPU.js';import {e as e$3,g}from'./chunk-RJIYCDVC.js';import U from'fs';import k from'path';import T from'chalk';import {execa}from'execa';function Le(e){return U.existsSync(k.join(e,"bun.lock"))||U.existsSync(k.join(e,"bunfig.toml"))?"bun":U.existsSync(k.join(e,"pnpm-lock.yaml"))?"pnpm":U.existsSync(k.join(e,"yarn.lock"))?"yarn":(U.existsSync(k.join(e,"package-lock.json")),"npm")}function Ge(e,r,t=Le(e)){return t==="npm"?`npm run ${r}`:`${t} run ${r}`}function Be(e,r=Le(e)){return `${r} install`}var ct={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},dt={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],c:["cmake -S . -B build"],cpp:["cmake -S . -B build"],elixir:["mix deps.get"],ruby:["bundle install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],c:["ctest --test-dir build --output-on-failure"],cpp:["ctest --test-dir build --output-on-failure"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],c:["cmake --build build"],cpp:["cmake --build build"],elixir:["mix compile"],ruby:["gem build *.gemspec"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],c:[],cpp:[],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function te(e,r){if(r){let t=r.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=e$2(r),s=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:t==="fiber"?"fiber":t==="aspnetcore"||t==="asp-net-core"?"aspnetcore":t}`;return ct[s]}}function He(e,r,t){if(r){let n=te(e,r);if(n&&n.commands[t])return n.commands[t]}if(["init","test","build","start"].includes(t)){let n=dt[t]?.[e]??[];return n.length>0?n[0]:void 0}}var lt={test:"test",build:"build",start:"start"};function ge(e){if(e.stage==="init")return e.runtime==="node"?Be(e.projectPath):He(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let r=lt[e.stage];if(r){let t=t$1(e.projectPath,r,{framework:e.framework});if(t)return Ge(e.projectPath,t.scriptName)}}return He(e.runtime,e.framework,e.stage)}function mt(e){let r=h(e).map(t=>t==="python"?"python":t==="node"||t==="bun"?"node":t==="go"?"go":t==="java"?"java":t==="php"?"php":t==="rust"?"rust":t==="dotnet"?"dotnet":t==="elixir"?"elixir":t==="ruby"?"ruby":t==="clojure"||t==="scala"||t==="kotlin"?"jvm-generic":null).filter(t=>t!==null).filter((t,n,o)=>o.indexOf(t)===n);return {primary:r.length>0?r[0]:"unknown",secondary:r.slice(1)}}function ze(e){return mt(e).primary}function ye(e,r){if(!e)return "unknown";r||(r={setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[t,n]of Object.entries(r))for(let o of n)if(new RegExp(o,"i").test(e))return t;return "unknown"}async function re(e){let r=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(r))return {valid:true};try{let n=process.platform==="win32"?"where":"which";if((await execa(n,[r],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${r}' not found or not executable`}}function Je(e,r,t){if(!r)return e;let n=typeof r=="object"&&!Array.isArray(r)&&("dev"in r||"staging"in r||"prod"in r||"default"in r)&&!Object.keys(r).some(o=>["init","test","build","start"].includes(o))?r:{};return t&&typeof n[t]=="string"?n[t]:typeof n.default=="string"?n.default:e}async function qe(e,r){if(!e)return {healthy:true};switch(e.type){case "port":{let t=e.value;try{let n=await import('net');return new Promise(o=>{let s=new n.Socket,u=5e3;s.setTimeout(u),s.on("connect",()=>{s.destroy(),o({healthy:true,reason:`Port ${t} is listening`});}),s.on("timeout",()=>{s.destroy(),o({healthy:false,reason:`Port ${t} timeout after ${u}ms`});}),s.on("error",c=>{s.destroy(),o({healthy:false,reason:`Port ${t} error: ${String(c)}`});}),s.connect(t,"localhost");})}catch(n){return {healthy:false,reason:`Port check error: ${n instanceof Error?n.message:String(n)}`}}}case "http":{let t=e.value,n;try{let o=new AbortController;n=setTimeout(()=>o.abort(),5e3);let s=await fetch(t,{method:"GET",signal:o.signal});return {healthy:s.status===200,reason:`HTTP ${s.status}`,metadata:{status:s.status}}}catch(o){return {healthy:false,reason:`HTTP check error: ${o instanceof Error?o.message:String(o)}`}}finally{n&&clearTimeout(n);}}case "log":{let t=e.value;if(!r)return {healthy:true};try{let n=[k.join(r,".workspai","last-run.log"),k.join(r,".rapidkit","last-run.log")].find(o=>U.existsSync(o));if(n){let o=U.readFileSync(n,"utf-8"),s=new RegExp(t,"i");return {healthy:s.test(o),reason:s.test(o)?"Log pattern found":"Log pattern not found"}}return {healthy:true,reason:"No log file to check"}}catch(n){return {healthy:false,reason:`Log check error: ${n instanceof Error?n.message:String(n)}`}}}case "command":{let t=e.value;try{let n=await execa(t,[],{cwd:r,reject:false,shell:true});return {healthy:n.exitCode===0,reason:n.exitCode===0?"Health check passed":"Health check failed",metadata:{exitCode:n.exitCode}}}catch(n){return {healthy:false,reason:`Command check error: ${n instanceof Error?n.message:String(n)}`}}}default:return {healthy:true}}}var Ye={init:"init",test:"test",build:"build",start:"start"};function pt(e){return e in Ye?Ye[e]:null}function ft(e,r){let n=p$1(e)?.contextJson?.commands;if(!n||typeof n!="object"||Array.isArray(n))return;let o=n[r];if(typeof o=="string"&&o.trim().length>0)return o.trim();if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,u=s.default??s.dev;if(typeof u=="string"&&u.trim().length>0)return u.trim()}}function Qe(e,r,t=w(e)){let n=pt(r);if(!n)return ft(e,r)?{supported:true}:{supported:false,reason:`Workspace stage "${r}" is not part of the Workspai fleet contract.`};if(!t.projectRoot)return {supported:false,reason:"No Workspai project metadata was detected for this target."};let o=t.commandMap[n];if(!o||o.status!=="supported"){let s=t.runtimeSupportTier==="observed"||t.frameworkSupportTier==="observed";return {supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!s}}return {supported:true}}var gt=new Set(["init","test","build","start"]),yt=new Set([".git","node_modules",".workspai",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function B(e){try{return await U.promises.access(e,U.constants.F_OK),true}catch{return false}}async function ht(e){for(let r of e)if(await B(r))return true;return false}async function kt(e,r,t){if(r==="python"){let o=[k.join(e,".workspai","cli.py"),k.join(e,".rapidkit","cli.py")];for(let s of o)if(await B(s))return {valid:true};return {valid:false,reason:"Project-local .workspai/cli.py is missing. Run `workspai init` in this project first."}}let n=t.trim().split(/\s+/)[0];if(n&&["npm","npx","pnpm","yarn"].includes(n)){let o=e$3(n);if((await execa(o.command,[...o.prefixArgs,"--version"],{reject:false,env:g()})).exitCode===0)return {valid:true}}return re(t)}async function ne(e){let r=await U.promises.readFile(e,"utf-8");return JSON.parse(r)}function D(e){return e.replace(/\\/g,"/")}function bt(e){let r=e?.trim();return r?r.startsWith("project:")?r.slice(8).trim()||null:r:null}async function wt(e){let r=k.join(e,e$1.model);if(await B(r))try{let n=((await ne(r)).projects??[]).map(o=>typeof o.path=="string"?k.resolve(e,o.path):null).filter(o=>!!o).filter((o,s,u)=>u.indexOf(o)===s).filter(o=>U.existsSync(o));if(n.length>0)return n.sort()}catch{}return a$1(e,{skipDirs:yt,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t$1,n)=>await ht([...t(t$1,"context.json"),...t(t$1,"project.json")])?true:k.resolve(t$1)===k.resolve(n)?false:h(t$1).length>0})}async function xt(e){for(let r of [k.join(".workspai","project.json"),k.join(".workspai","context.json"),k.join(".rapidkit","project.json"),k.join(".rapidkit","context.json")]){let t=k.join(e,r);if(await B(t))try{let n=await ne(t),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function vt(e,r,t){let n=bt(t);if(!n)return {projects:r,normalizedScope:null};let o=D(n).toLowerCase(),s=[];for(let u of r){let c=D(k.relative(e,u)),m=k.basename(u),p=await xt(u);[c,m,p].filter(i=>typeof i=="string"&&i.length>0).map(i=>D(i).toLowerCase()).includes(o)&&s.push(u);}if(s.length===0)throw new Error(`Workspace run scope did not match any project: ${t}`);return {projects:s,normalizedScope:n}}async function Rt(e,r,t){let n=await execa("git",["diff","--name-only",`${t}...HEAD`],{cwd:e,reject:false,env:a$2()});if(n.exitCode!==0)return new Set(r);let o=n.stdout.split(/\r?\n/).map(u=>u.trim()).filter(u=>u.length>0).map(u=>D(u));if(o.length===0)return new Set;let s=new Set;for(let u of r){let c=D(k.relative(e,u));if(!c||c===".")continue;let m=`${c}/`;o.some(p=>p===c||p.startsWith(m))&&s.add(u);}return s}async function St(e,r,t){let n=await d$1(e,i.workspaceContract)??p(e,"workspace.contract.json");if(await B(n))try{let d=await Ct(e,r,t,n);if(d.graphStatus!=="missing")return d}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let o=await d$1(e,".workspai/workspace-dependency-graph.json")??p(e,"workspace-dependency-graph.json");if(!await B(o))return {expanded:t,graphStatus:"missing",expansionDepth:0};let s;try{s=await ne(o);}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let u=new Set(r.map(d=>k.resolve(d))),c=new Map;if(!s||typeof s!="object"||Array.isArray(s))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let m=Array.isArray(s.projects)?s.projects:[];for(let d of m){if(!d||typeof d!="object"||Array.isArray(d))continue;let i=d,l=typeof i.path=="string"?i.path:"",y=k.resolve(e,l);if(!u.has(y))continue;let b=Array.isArray(i.dependsOn)?i.dependsOn.filter(S=>typeof S=="string"):[];for(let S of b){let g=k.resolve(e,S);u.has(g)&&(c.has(g)||c.set(g,new Set),c.get(g)?.add(y));}}let p$1=d$2(c,t);return {expanded:p$1.reached,graphStatus:"loaded",expansionDepth:p$1.added}}async function Ct(e,r,t,n){let o=await ne(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let s=o,u=Array.isArray(s.projects)?s.projects:null;if(!u)return {expanded:t,graphStatus:"invalid",expansionDepth:0};let c=new Map,m=new Map;for(let y of r){let b=D(k.relative(e,y));m.set(b,k.resolve(y));}let p=new Map,d=new Map,i=new Map;for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=typeof b.relativePath=="string"?D(b.relativePath):S,v=m.get(g);!S||!v||c.set(S,v);}for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=c.get(S);if(!g)continue;let v=b.contracts&&typeof b.contracts=="object"&&!Array.isArray(b.contracts)?b.contracts:{},E=Array.isArray(v.dependsOn)?v.dependsOn.filter(R=>typeof R=="string"):[],W=Array.isArray(v.publishes)?v.publishes.filter(R=>typeof R=="string"):[],_=Array.isArray(v.consumes)?v.consumes.filter(R=>typeof R=="string"):[];for(let R of E){let j=c.get(R);j&&(i.has(j)||i.set(j,new Set),i.get(j)?.add(g));}for(let R of W)p.has(R)||p.set(R,new Set),p.get(R)?.add(g);for(let R of _)d.has(R)||d.set(R,new Set),d.get(R)?.add(g);}for(let[y,b]of p.entries()){let S=d.get(y);if(S)for(let g of b){i.has(g)||i.set(g,new Set);for(let v of S)v!==g&&i.get(g)?.add(v);}}let l=d$2(i,t);return {expanded:l.reached,graphStatus:"loaded",expansionDepth:l.added}}async function Et(e,r){if(typeof r=="boolean")return r;let t=s(e,"policies.yml").find(s=>U.existsSync(s))??p(e,"policies.yml");if(!await B(t))return true;let n="";try{n=await U.promises.readFile(t,"utf-8");}catch{return true}let o=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o?o[1]==="true":true}function jt(e){let r=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(r){let t=Number.parseInt(r,10);if(Number.isFinite(t)&&t>0)return t}return e==="init"?12e4:9e4}function Xe(e,r){let t=Number.parseInt(process.env[e]??"",10);return Number.isFinite(t)&&t>0?t:r}function he(e){return new Promise(r=>setTimeout(r,e))}async function Pt(e){let r=process.argv[1];if(e.useRapidkitWrapper&&!r)return {exitCode:1,stdout:"",stderr:"Workspai entrypoint is unavailable for startup verification.",healthStatus:{healthy:false,reason:"Workspai entrypoint is unavailable."}};let t=e.useRapidkitWrapper&&r?execa(process.execPath,[r,"start"],{cwd:e.projectPath,reject:false,timeout:e.timeoutMs,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}}):execa(e.finalCommand,[],{cwd:e.projectPath,reject:false,shell:true,timeout:e.timeoutMs}),n=Promise.resolve(t).then(d=>({kind:"exit",result:d}),d=>({kind:"error",error:d})),o=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_GRACE_MS",2e3),s=await Promise.race([n,he(o).then(()=>({kind:"alive"}))]);if(s.kind==="error"){let d=typeof s.error=="object"&&s.error!==null&&"timedOut"in s.error&&!!s.error.timedOut;return {exitCode:d?124:1,stdout:"",stderr:s.error instanceof Error?s.error.message:String(s.error),timedOut:d,healthStatus:{healthy:false,reason:"The start command failed before readiness."}}}if(s.kind==="exit"){let d=Number(s.result.exitCode??0);return {exitCode:d,stdout:String(s.result.stdout??""),stderr:String(s.result.stderr??""),healthStatus:{healthy:d===0,reason:d===0?"The start command completed successfully.":`The start command exited with code ${d} before readiness.`}}}let u=te(e.runtime,e.framework)?.healthCheck,c=u?{healthy:false,reason:"The configured health check has not passed yet."}:{healthy:true,reason:`The service remained alive for ${o}ms (bounded startup smoke).`};if(u){let d=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_HEALTH_TIMEOUT_MS",15e3),i=Date.now()+d;for(;Date.now()<i;){let l=await qe(u,e.projectPath);if(c={healthy:l.healthy,reason:l.reason},l.healthy)break;if((await Promise.race([n,he(350).then(()=>({kind:"alive"}))])).kind!=="alive"){c={healthy:false,reason:"The service exited before its configured health check passed."};break}}}try{t.kill?.("SIGTERM",{forceKillAfterDelay:1e3});}catch{try{t.kill?.();}catch{}}let m=await Promise.race([n,he(2e3).then(()=>({kind:"alive"}))]),p=m.kind==="exit"?m.result:void 0;return {exitCode:c.healthy?0:1,stdout:String(p?.stdout??""),stderr:String(p?.stderr??""),healthStatus:c}}async function ke(e,r,t){let n=process.argv[1];if(!n)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};try{let o=await execa(process.execPath,[n,...e],{cwd:r,reject:false,timeout:t,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr}}catch(o){return {exitCode:typeof o=="object"&&o!==null&&"timedOut"in o&&!!o.timedOut?124:1,stdout:typeof o=="object"&&o!==null&&"stdout"in o?String(o.stdout??""):"",stderr:typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr??""):o instanceof Error?o.message:String(o)}}}function At(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"||e==="rust"||e==="php"}function Ft(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}function Ot(e,r=8){if(e.length<=r)return e.join(`
1
+ import {d,b,e}from'./chunk-W6FHVXNL.js';import {a}from'./chunk-2647BYBC.js';import {a as a$1}from'./chunk-27UR373Z.js';import {d as d$2}from'./chunk-S5KTATOU.js';import {p as p$1,w,t as t$1}from'./chunk-WP3CXMVA.js';import {h,j,f,e as e$2}from'./chunk-ZCPT6KC3.js';import {d as d$1}from'./chunk-CCDGHPEJ.js';import {e as e$1,i}from'./chunk-NZ3WZYD5.js';import {a as a$2}from'./chunk-TQEMLBAG.js';import {t,p,s}from'./chunk-MOSXTVPU.js';import {e as e$3,g}from'./chunk-RJIYCDVC.js';import U from'fs';import k from'path';import T from'chalk';import {execa}from'execa';function Le(e){return U.existsSync(k.join(e,"bun.lock"))||U.existsSync(k.join(e,"bunfig.toml"))?"bun":U.existsSync(k.join(e,"pnpm-lock.yaml"))?"pnpm":U.existsSync(k.join(e,"yarn.lock"))?"yarn":(U.existsSync(k.join(e,"package-lock.json")),"npm")}function Ge(e,r,t=Le(e)){return t==="npm"?`npm run ${r}`:`${t} run ${r}`}function Be(e,r=Le(e)){return `${r} install`}var ct={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},dt={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],c:["cmake -S . -B build"],cpp:["cmake -S . -B build"],elixir:["mix deps.get"],ruby:["bundle install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],c:["ctest --test-dir build --output-on-failure"],cpp:["ctest --test-dir build --output-on-failure"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],c:["cmake --build build"],cpp:["cmake --build build"],elixir:["mix compile"],ruby:["gem build *.gemspec"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],c:[],cpp:[],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function te(e,r){if(r){let t=r.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=e$2(r),s=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:t==="fiber"?"fiber":t==="aspnetcore"||t==="asp-net-core"?"aspnetcore":t}`;return ct[s]}}function He(e,r,t){if(r){let n=te(e,r);if(n&&n.commands[t])return n.commands[t]}if(["init","test","build","start"].includes(t)){let n=dt[t]?.[e]??[];return n.length>0?n[0]:void 0}}var lt={test:"test",build:"build",start:"start"};function ge(e){if(e.stage==="init")return e.runtime==="node"?Be(e.projectPath):He(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let r=lt[e.stage];if(r){let t=t$1(e.projectPath,r,{framework:e.framework});if(t)return Ge(e.projectPath,t.scriptName)}}return He(e.runtime,e.framework,e.stage)}function mt(e){let r=h(e).map(t=>t==="python"?"python":t==="node"||t==="bun"?"node":t==="go"?"go":t==="java"?"java":t==="php"?"php":t==="rust"?"rust":t==="dotnet"?"dotnet":t==="elixir"?"elixir":t==="ruby"?"ruby":t==="clojure"||t==="scala"||t==="kotlin"?"jvm-generic":null).filter(t=>t!==null).filter((t,n,o)=>o.indexOf(t)===n);return {primary:r.length>0?r[0]:"unknown",secondary:r.slice(1)}}function ze(e){return mt(e).primary}function ye(e,r){if(!e)return "unknown";r||(r={setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[t,n]of Object.entries(r))for(let o of n)if(new RegExp(o,"i").test(e))return t;return "unknown"}async function re(e){let r=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(r))return {valid:true};try{let n=process.platform==="win32"?"where":"which";if((await execa(n,[r],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${r}' not found or not executable`}}function Je(e,r,t){if(!r)return e;let n=typeof r=="object"&&!Array.isArray(r)&&("dev"in r||"staging"in r||"prod"in r||"default"in r)&&!Object.keys(r).some(o=>["init","test","build","start"].includes(o))?r:{};return t&&typeof n[t]=="string"?n[t]:typeof n.default=="string"?n.default:e}async function qe(e,r){if(!e)return {healthy:true};switch(e.type){case "port":{let t=e.value;try{let n=await import('net');return new Promise(o=>{let s=new n.Socket,u=5e3;s.setTimeout(u),s.on("connect",()=>{s.destroy(),o({healthy:true,reason:`Port ${t} is listening`});}),s.on("timeout",()=>{s.destroy(),o({healthy:false,reason:`Port ${t} timeout after ${u}ms`});}),s.on("error",c=>{s.destroy(),o({healthy:false,reason:`Port ${t} error: ${String(c)}`});}),s.connect(t,"localhost");})}catch(n){return {healthy:false,reason:`Port check error: ${n instanceof Error?n.message:String(n)}`}}}case "http":{let t=e.value,n;try{let o=new AbortController;n=setTimeout(()=>o.abort(),5e3);let s=await fetch(t,{method:"GET",signal:o.signal});return {healthy:s.status===200,reason:`HTTP ${s.status}`,metadata:{status:s.status}}}catch(o){return {healthy:false,reason:`HTTP check error: ${o instanceof Error?o.message:String(o)}`}}finally{n&&clearTimeout(n);}}case "log":{let t=e.value;if(!r)return {healthy:true};try{let n=[k.join(r,".workspai","last-run.log"),k.join(r,".rapidkit","last-run.log")].find(o=>U.existsSync(o));if(n){let o=U.readFileSync(n,"utf-8"),s=new RegExp(t,"i");return {healthy:s.test(o),reason:s.test(o)?"Log pattern found":"Log pattern not found"}}return {healthy:true,reason:"No log file to check"}}catch(n){return {healthy:false,reason:`Log check error: ${n instanceof Error?n.message:String(n)}`}}}case "command":{let t=e.value;try{let n=await execa(t,[],{cwd:r,reject:false,shell:true});return {healthy:n.exitCode===0,reason:n.exitCode===0?"Health check passed":"Health check failed",metadata:{exitCode:n.exitCode}}}catch(n){return {healthy:false,reason:`Command check error: ${n instanceof Error?n.message:String(n)}`}}}default:return {healthy:true}}}var Ye={init:"init",test:"test",build:"build",start:"start"};function pt(e){return e in Ye?Ye[e]:null}function ft(e,r){let n=p$1(e)?.contextJson?.commands;if(!n||typeof n!="object"||Array.isArray(n))return;let o=n[r];if(typeof o=="string"&&o.trim().length>0)return o.trim();if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,u=s.default??s.dev;if(typeof u=="string"&&u.trim().length>0)return u.trim()}}function Qe(e,r,t=w(e)){let n=pt(r);if(!n)return ft(e,r)?{supported:true}:{supported:false,reason:`Workspace stage "${r}" is not part of the Workspai fleet contract.`};if(!t.projectRoot)return {supported:false,reason:"No Workspai project metadata was detected for this target."};let o=t.commandMap[n];if(!o||o.status!=="supported"){let s=t.runtimeSupportTier==="observed"||t.frameworkSupportTier==="observed";return {supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!s}}return {supported:true}}var gt=new Set(["init","test","build","start"]),yt=new Set([".git","node_modules",".workspai",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function B(e){try{return await U.promises.access(e,U.constants.F_OK),true}catch{return false}}async function ht(e){for(let r of e)if(await B(r))return true;return false}async function kt(e,r,t){if(r==="python"){let o=[k.join(e,".workspai","cli.py"),k.join(e,".rapidkit","cli.py")];for(let s of o)if(await B(s))return {valid:true};return {valid:false,reason:"Project-local .workspai/cli.py is missing. Run `workspai init` in this project first."}}let n=t.trim().split(/\s+/)[0];if(n&&["npm","npx","pnpm","yarn"].includes(n)){let o=e$3(n);if((await execa(o.command,[...o.prefixArgs,"--version"],{reject:false,env:g()})).exitCode===0)return {valid:true}}return re(t)}async function ne(e){let r=await U.promises.readFile(e,"utf-8");return JSON.parse(r)}function D(e){return e.replace(/\\/g,"/")}function bt(e){let r=e?.trim();return r?r.startsWith("project:")?r.slice(8).trim()||null:r:null}async function wt(e){let r=k.join(e,e$1.model);if(await B(r))try{let n=((await ne(r)).projects??[]).map(o=>typeof o.path=="string"?k.resolve(e,o.path):null).filter(o=>!!o).filter((o,s,u)=>u.indexOf(o)===s).filter(o=>U.existsSync(o));if(n.length>0)return n.sort()}catch{}return a$1(e,{skipDirs:yt,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t$1,n)=>await ht([...t(t$1,"context.json"),...t(t$1,"project.json")])?true:k.resolve(t$1)===k.resolve(n)?false:h(t$1).length>0})}async function xt(e){for(let r of [k.join(".workspai","project.json"),k.join(".workspai","context.json"),k.join(".rapidkit","project.json"),k.join(".rapidkit","context.json")]){let t=k.join(e,r);if(await B(t))try{let n=await ne(t),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function vt(e,r,t){let n=bt(t);if(!n)return {projects:r,normalizedScope:null};let o=D(n).toLowerCase(),s=[];for(let u of r){let c=D(k.relative(e,u)),m=k.basename(u),p=await xt(u);[c,m,p].filter(i=>typeof i=="string"&&i.length>0).map(i=>D(i).toLowerCase()).includes(o)&&s.push(u);}if(s.length===0)throw new Error(`Workspace run scope did not match any project: ${t}`);return {projects:s,normalizedScope:n}}async function Rt(e,r,t){let n=await execa("git",["diff","--name-only",`${t}...HEAD`],{cwd:e,reject:false,env:a$2()});if(n.exitCode!==0)return new Set(r);let o=n.stdout.split(/\r?\n/).map(u=>u.trim()).filter(u=>u.length>0).map(u=>D(u));if(o.length===0)return new Set;let s=new Set;for(let u of r){let c=D(k.relative(e,u));if(!c||c===".")continue;let m=`${c}/`;o.some(p=>p===c||p.startsWith(m))&&s.add(u);}return s}async function St(e,r,t){let n=await d$1(e,i.workspaceContract)??p(e,"workspace.contract.json");if(await B(n))try{let d=await Ct(e,r,t,n);if(d.graphStatus!=="missing")return d}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let o=await d$1(e,".workspai/workspace-dependency-graph.json")??p(e,"workspace-dependency-graph.json");if(!await B(o))return {expanded:t,graphStatus:"missing",expansionDepth:0};let s;try{s=await ne(o);}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let u=new Set(r.map(d=>k.resolve(d))),c=new Map;if(!s||typeof s!="object"||Array.isArray(s))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let m=Array.isArray(s.projects)?s.projects:[];for(let d of m){if(!d||typeof d!="object"||Array.isArray(d))continue;let i=d,l=typeof i.path=="string"?i.path:"",y=k.resolve(e,l);if(!u.has(y))continue;let b=Array.isArray(i.dependsOn)?i.dependsOn.filter(S=>typeof S=="string"):[];for(let S of b){let g=k.resolve(e,S);u.has(g)&&(c.has(g)||c.set(g,new Set),c.get(g)?.add(y));}}let p$1=d$2(c,t);return {expanded:p$1.reached,graphStatus:"loaded",expansionDepth:p$1.added}}async function Ct(e,r,t,n){let o=await ne(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let s=o,u=Array.isArray(s.projects)?s.projects:null;if(!u)return {expanded:t,graphStatus:"invalid",expansionDepth:0};let c=new Map,m=new Map;for(let y of r){let b=D(k.relative(e,y));m.set(b,k.resolve(y));}let p=new Map,d=new Map,i=new Map;for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=typeof b.relativePath=="string"?D(b.relativePath):S,v=m.get(g);!S||!v||c.set(S,v);}for(let y of u){if(!y||typeof y!="object"||Array.isArray(y))continue;let b=y,S=typeof b.slug=="string"?b.slug:"",g=c.get(S);if(!g)continue;let v=b.contracts&&typeof b.contracts=="object"&&!Array.isArray(b.contracts)?b.contracts:{},E=Array.isArray(v.dependsOn)?v.dependsOn.filter(R=>typeof R=="string"):[],W=Array.isArray(v.publishes)?v.publishes.filter(R=>typeof R=="string"):[],_=Array.isArray(v.consumes)?v.consumes.filter(R=>typeof R=="string"):[];for(let R of E){let j=c.get(R);j&&(i.has(j)||i.set(j,new Set),i.get(j)?.add(g));}for(let R of W)p.has(R)||p.set(R,new Set),p.get(R)?.add(g);for(let R of _)d.has(R)||d.set(R,new Set),d.get(R)?.add(g);}for(let[y,b]of p.entries()){let S=d.get(y);if(S)for(let g of b){i.has(g)||i.set(g,new Set);for(let v of S)v!==g&&i.get(g)?.add(v);}}let l=d$2(i,t);return {expanded:l.reached,graphStatus:"loaded",expansionDepth:l.added}}async function Et(e,r){if(typeof r=="boolean")return r;let t=s(e,"policies.yml").find(s=>U.existsSync(s))??p(e,"policies.yml");if(!await B(t))return true;let n="";try{n=await U.promises.readFile(t,"utf-8");}catch{return true}let o=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o?o[1]==="true":true}function jt(e){let r=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(r){let t=Number.parseInt(r,10);if(Number.isFinite(t)&&t>0)return t}return e==="init"?12e4:9e4}function Xe(e,r){let t=Number.parseInt(process.env[e]??"",10);return Number.isFinite(t)&&t>0?t:r}function he(e){return new Promise(r=>setTimeout(r,e))}async function Pt(e){let r=process.argv[1];if(e.useRapidkitWrapper&&!r)return {exitCode:1,stdout:"",stderr:"Workspai entrypoint is unavailable for startup verification.",healthStatus:{healthy:false,reason:"Workspai entrypoint is unavailable."}};let t=e.useRapidkitWrapper&&r?execa(process.execPath,[r,"start"],{cwd:e.projectPath,reject:false,timeout:e.timeoutMs,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}}):execa(e.finalCommand,[],{cwd:e.projectPath,reject:false,shell:true,timeout:e.timeoutMs}),n=Promise.resolve(t).then(d=>({kind:"exit",result:d}),d=>({kind:"error",error:d})),o=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_GRACE_MS",2e3),s=await Promise.race([n,he(o).then(()=>({kind:"alive"}))]);if(s.kind==="error"){let d=typeof s.error=="object"&&s.error!==null&&"timedOut"in s.error&&!!s.error.timedOut;return {exitCode:d?124:1,stdout:"",stderr:s.error instanceof Error?s.error.message:String(s.error),timedOut:d,healthStatus:{healthy:false,reason:"The start command failed before readiness."}}}if(s.kind==="exit"){let d=Number(s.result.exitCode??0);return {exitCode:d,stdout:String(s.result.stdout??""),stderr:String(s.result.stderr??""),healthStatus:{healthy:d===0,reason:d===0?"The start command completed successfully.":`The start command exited with code ${d} before readiness.`}}}let u=te(e.runtime,e.framework)?.healthCheck,c=u?{healthy:false,reason:"The configured health check has not passed yet."}:{healthy:true,reason:`The service remained alive for ${o}ms (bounded startup smoke).`};if(u){let d=Xe("WORKSPAI_WORKSPACE_RUN_STARTUP_HEALTH_TIMEOUT_MS",15e3),i=Date.now()+d;for(;Date.now()<i;){let l=await qe(u,e.projectPath);if(c={healthy:l.healthy,reason:l.reason},l.healthy)break;if((await Promise.race([n,he(350).then(()=>({kind:"alive"}))])).kind!=="alive"){c={healthy:false,reason:"The service exited before its configured health check passed."};break}}}try{t.kill?.("SIGTERM",{forceKillAfterDelay:1e3});}catch{try{t.kill?.();}catch{}}let m=await Promise.race([n,he(2e3).then(()=>({kind:"alive"}))]),p=m.kind==="exit"?m.result:void 0;return {exitCode:c.healthy?0:1,stdout:String(p?.stdout??""),stderr:String(p?.stderr??""),healthStatus:c}}async function ke(e,r,t){let n=process.argv[1];if(!n)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};try{let o=await execa(process.execPath,[n,...e],{cwd:r,reject:false,timeout:t,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr}}catch(o){return {exitCode:typeof o=="object"&&o!==null&&"timedOut"in o&&!!o.timedOut?124:1,stdout:typeof o=="object"&&o!==null&&"stdout"in o?String(o.stdout??""):"",stderr:typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr??""):o instanceof Error?o.message:String(o)}}}function At(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"||e==="rust"||e==="php"}function Ft(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}function Ot(e,r=8){if(e.length<=r)return e.join(`
2
2
  `);let t=3;return [...e.slice(0,t),...e.slice(-(r-t))].join(`
3
3
  `)}function Tt(e){let r=/(?:\bnot found\b|\bno such\b|\bmissing\b|\bfailed\b|\berror\b|\bexception\b|\bcannot\b|\bdenied\b|\btimeout\b|\btimed out\b|\benoent\b|\beacces\b|\beperm\b)/i;return [...e].reverse().find(t=>r.test(t))??e.at(-1)}async function Mt(e){let r=process.cwd();try{process.chdir(e);let{handleInitCommand:t}=await import('./index.js');return {exitCode:await t(["init"]),stdout:"",stderr:""}}finally{process.chdir(r);}}async function Ze(e){let r=i=>{let l=f(i);return l==="node"||l==="bun"?"node":l==="python"?"python":l==="go"?"go":l==="java"?"java":l==="php"?"php":l==="ruby"?"ruby":l==="rust"?"rust":l==="dotnet"?"dotnet":l==="elixir"?"elixir":l==="clojure"||l==="scala"||l==="kotlin"?"jvm-generic":ze(e)},t=i=>{if(!i)return;let l=e$2(i);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(l))return l},n=p$1(e),o=n?.detection??j(e,n?.projectJson??null),s=n?.contextJson,u=r(o.runtime),c=t(o.key),m={},p=new Set(["init","test","build","start"]);if(s?.commands&&typeof s.commands=="object")for(let[i,l]of Object.entries(s.commands))typeof l=="string"&&p.has(i)&&(m[i]=l);let d;if(s?.commandEnvironments&&typeof s.commandEnvironments=="object"){let i=s.commandEnvironments;d={dev:typeof i.dev=="string"?i.dev:void 0,staging:typeof i.staging=="string"?i.staging:void 0,prod:typeof i.prod=="string"?i.prod:void 0,default:typeof i.default=="string"?i.default:void 0};}return {runtime:u,framework:c,commandOverrides:Object.keys(m).length>0?m:void 0,environmentCommandVariants:d,environment:typeof s?.environment=="string"?s.environment:void 0}}async function et(e,r,t,n,o,s,u){let c=!o?.[r]&&At(t),m;if(o&&o[r]?m=o[r]:c?m=`rapidkit ${r}`:m=ge({projectPath:e,runtime:t,framework:n,stage:r}),!m)return {exitCode:127,command:`<stage not supported for ${t}>`,message:`No stage command found for runtime '${t}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let p=Je(m,s,u);if(!p)return {exitCode:127,command:m,message:"Failed to resolve stage command",errorCategory:"runtime"};let d=ge({projectPath:e,runtime:t,framework:n,stage:r});if(c){if(d){let x=c?await kt(e,t,d):await re(d);if(!x.valid)return {exitCode:127,command:p,message:x.reason||"Command not available",errorCategory:"setup"}}}else {let x=await re(p);if(!x.valid)return {exitCode:127,command:p,message:x.reason||"Command not available",errorCategory:"setup"}}let i=0,l="",y="",b,S,g=jt(r),v=Date.now();try{let x=r==="start"?await Pt({projectPath:e,finalCommand:p,useRapidkitWrapper:c,runtime:t,framework:n,timeoutMs:g}):c?r==="init"&&Ft()?await Mt(e):await ke([r],e,g):await execa(p,[],{cwd:e,reject:false,shell:true,timeout:g});if(i=Number(x.exitCode??0),l=x.stdout,y=x.stderr,S=r==="start"?x.healthStatus:void 0,i!==0){let I=`${l}
4
4
  ${y}`,V=Date.now()-v;b=i===124||ye(I)==="timeout"||i===143&&V>=Math.floor(g*.8)?"timeout":ye(I);}}catch(x){let I=typeof x=="object"&&x!==null&&"timedOut"in x&&!!x.timedOut;return {exitCode:I?124:1,command:p,message:I?`Stage timed out after ${g}ms`:x instanceof Error?x.message:"Command execution failed",errorCategory:I?"timeout":"runtime"}}let E=`${l}
@@ -0,0 +1,39 @@
1
+ import {b as b$3,a}from'./chunk-THIOE2PB.js';import {h,g as g$2}from'./chunk-S45YGN2I.js';import {b as b$4,g as g$1}from'./chunk-TCURN5VD.js';import {b as b$1,f as f$3,j,k,h as h$2,i as i$2,l,m as m$1,n,o,p as p$1,q,r,t,v,x,s,u as u$1,w,y as y$1,z,A,B,C,D,E,F,G,H as H$1,a as a$2,I}from'./chunk-KBR4Y4RW.js';import {b,c,d as d$1}from'./chunk-7SFXADXO.js';import {b as b$2}from'./chunk-WQX3JYEP.js';import {d as d$2}from'./chunk-YEEAWZWI.js';import {p,k as k$1,f as f$4}from'./chunk-WSRUPDZN.js';import {m}from'./chunk-SP5EHSWG.js';import {d}from'./chunk-CCDGHPEJ.js';import {a as a$1,b as b$5}from'./chunk-D65FCQIO.js';import {f,e,i,h as h$3}from'./chunk-NZ3WZYD5.js';import {f as f$1,g,h as h$1}from'./chunk-MOSXTVPU.js';import i$1 from'path';import f$2 from'fs-extra';var te=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var yt="workspace-operational-skill.v1";function St(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function at(e){let t=St(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:yt,skillId:t,canonicalPath:H$1(t),title:e.title,triggers:[...e.triggers].sort((r,n)=>r.localeCompare(n)),requiredReports:[...e.requiredReports].sort((r,n)=>r.localeCompare(n)),scopedProjects:[...e.scopedProjects??[]].sort((r,n)=>r.localeCompare(n)),verificationCommands:[...e.verificationCommands],answerContractSections:[...te],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var Ct=f.skillsIndex;function ot(e){let t=[...e.skills].sort((n,c)=>n.skillId.localeCompare(c.skillId)),r=e.inputsHash??f$4({skillIds:t.map(n=>n.skillId),paths:t.map(n=>n.canonicalPath)});return {schemaVersion:Ct,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(n=>({skillId:n.skillId,path:n.canonicalPath,schemaVersion:n.schemaVersion,title:n.title}))}}var it=[e.agentIndex,b,d$2],Et=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${e.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${e.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."]},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${e.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${e.verify}\` for verdict and blocking reasons.`,`Read \`${i.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."]},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Require project-scoped test/build commands before promoting the migration.","Document rollback and verification signals."]},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Prefer workspace run test/build for affected projects.","Re-run `workspace verify` after evidence refresh."]},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${i.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."]}];function re(e){return `npx workspai ${e}`.trim()}function bt(e){let t=[`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",...it.map(r=>`- \`${r}\``),"","## Procedure","",...e.template.steps.map((r,n)=>`${n+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",re("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
2
+ `)}function It(e){return e?.safeCommands?.length?e.safeCommands.slice(0,8).map(t=>t.display):[re("workspace verify --json"),re("doctor workspace --json")]}function xt(e){return e?.projects?.length?e.projects.slice(0,12).map(r=>{let n=r.contracts?.owns?.join(", ")||"none",c=r.contracts?.publishes?.join(", ")||"none",l=r.contracts?.consumes?.join(", ")||"none";return `- **${r.slug}**: owns \`${n}\`; publishes \`${c}\`; consumes \`${l}\``}).join(`
3
+ `):void 0}function st(e){let t=e.model.workspace.name,r=e.model.projects.map(l=>l.name).sort(),n=It(e.context??null),c=xt(e.contract??null);return Et.map(l=>{let p=bt({template:l,workspaceName:t,scopedProjects:r,verificationCommands:n,contractSummary:c});return at({skillId:l.skillId,title:l.title,triggers:l.triggers,requiredReports:[...it],scopedProjects:r,verificationCommands:n,promptStem:I[l.skillId],markdown:p})})}async function ct(e){let t=i$1.resolve(e.workspacePath),r=[],n=f$4({skills:e.skills.map(l=>({id:l.skillId,path:l.canonicalPath,hash:f$4({markdown:l.markdown})}))}),c=ot({generatedAt:e.generatedAt,skills:e.skills,inputsHash:n});if(e.write){for(let p of e.skills){let o=i$1.join(t,p.canonicalPath);await f$2.ensureDir(i$1.dirname(o)),await f$2.writeFile(o,p.markdown,"utf8"),r.push(p.canonicalPath);}let l=i$1.join(t,b$1);await f$2.ensureDir(i$1.dirname(l)),await f$2.writeJson(l,c,{spaces:2}),r.push(b$1);}return {skills:e.skills,index:c,writtenPaths:r}}function lt(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.workspai/skills/` before generic repo scans. Legacy `.rapidkit/skills/` playbooks are read only when already present from older workspaces:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",re("workspace agent-sync --write --refresh-context"),"```",""].join(`
4
+ `)}var Tt={"workspai-diagnose-api-failure":p$1,"workspai-release-readiness":t},Ie="## Workspace verification (hydrated)";function Ot(e){let t=[Ie,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx workspai workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`
5
+ `)}async function dt(e){let t=i$1.resolve(e.workspacePath),r=[];for(let n of e.skills){let c=Tt[n.skillId];if(!c)continue;let l=i$1.join(t,c);if(!await f$2.pathExists(l))continue;let p=await f$2.readFile(l,"utf8"),o=Ot(n),A=p.includes(Ie)?p.replace(new RegExp(`${Ie}[\\s\\S]*$`),o.trimEnd()):`${p.trimEnd()}
6
+
7
+ ${o}`;e.write&&await f$2.writeFile(l,`${A.trimEnd()}
8
+ `,"utf8"),r.push(c);}return r}var _t="workspai-agent-customization-pack-capabilities.v1";function pt(){return {schemaVersion:_t,presets:{minimal:{meaning:"Generate the portable grounding index, AGENTS.md, and provider-specific lightweight instructions.",requiredOutputs:[e.agentIndex,e.agentCustomizationPack,e.agents]},enterprise:{meaning:"Generate the full VS Code-native pack: instructions, prompts, skills, custom agents, and validation metadata.",requiredOutputs:[e.agentIndex,e.agentCustomizationPack,e.agents,l,p$1,B,".github/agents/workspai-advisor.agent.md",D,b$1]}},targets:{all:{meaning:"Generate every supported customization surface.",outputFamilies:["portable","vscode","copilot","cursor","claude","gemini","qwen","kimi","grok","windsurf","amazon-q"]},vscode:{meaning:"Generate VS Code-native customizations for Copilot Chat and agent workflows.",outputFamilies:["instructions","prompts","skills","agents","hooks"]},agents:{meaning:"Generate portable AGENTS.md grounding for any agent.",outputFamilies:["portable"]},copilot:{meaning:"Generate GitHub Copilot instructions, prompts, and skills.",outputFamilies:["instructions","prompts","skills"]},cursor:{meaning:"Generate Cursor rules.",outputFamilies:["rules"]},claude:{meaning:"Generate Claude Code grounding files.",outputFamilies:["rules","portable"]},codex:{meaning:"Use AGENTS.md and the report index as the Codex grounding layer.",outputFamilies:["portable"]},gemini:{meaning:"Generate Gemini CLI grounding through GEMINI.md and canonical AGENTS.md.",outputFamilies:["adapter","portable"]},qwen:{meaning:"Generate Qwen Code grounding through QWEN.md and canonical AGENTS.md.",outputFamilies:["adapter","portable"]},kimi:{meaning:"Use AGENTS.md and the report index as the Kimi Code grounding layer.",outputFamilies:["portable"]},grok:{meaning:"Use AGENTS.md and the report index as the xAI Grok grounding layer.",outputFamilies:["portable"]},windsurf:{meaning:"Use AGENTS.md and the report index as the Windsurf grounding layer.",outputFamilies:["portable"]},"amazon-q":{meaning:"Generate an Amazon Q project rule that routes agents to canonical evidence.",outputFamilies:["rules","portable"]},orca:{meaning:"Legacy compatibility alias for AGENTS.md consumers; prefer the grok target.",outputFamilies:["portable"]}},standardAnswerContract:[...te],requiredReports:K.map(e=>({path:e.relativePath,label:e.label,required:e.required})),strictRules:["Required reports must exist.","Generated report paths must stay inside the workspace root.","Generated customization text must be English-only.","Agent answers must not claim pass, ready, or healthy without cited evidence.","Commands must distinguish display guidance from execution requests.","Agent hook files must be advisory and disabled by default unless the user explicitly enables them.","MCP design artifacts must stay read-mostly until write tools have explicit approval boundaries."],outputKinds:["report","grounding","instruction","prompt","skill","skill-resource","operational-skill","skills-index","explain-report","agent","rule","hook","mcp-design"],pathLayers:{l1CanonicalRoots:[".workspai/reports/",`${a$2}/`],l2PrefixedMirrorRoots:[".github/",".cursor/",".claude/",".amazonq/"],l3SharedIndustryFiles:["AGENTS.md",".github/copilot-instructions.md","CLAUDE.md","GEMINI.md","QWEN.md"]}}}var vt=f.agentIndex,Wt=f.agentCustomizationPack,V=e.agentIndex,H=e.agentCustomizationPack;var K=[{relativePath:i.goalIndex,label:"Active Goal Pack index",required:false},{relativePath:i.goalPackLastRun,label:"Latest governed Goal Pack",required:false},{relativePath:b,label:"Agent context pack",required:true},{relativePath:b$1,label:"Operational skills index",required:true},{relativePath:e.model,label:"Workspace model",required:false},{relativePath:e.knowledgeGraph,label:"Workspace knowledge graph",required:false},{relativePath:e.evaluationLastRun,label:"Workspace Intelligence evaluation",required:false},{relativePath:e.doctor,label:"Workspace doctor",required:false},{relativePath:i.doctorProject,label:"Project doctor",required:false},{relativePath:i.doctorRemediationPlan,label:"Doctor remediation plan",required:false},{relativePath:i.artifactRemediationPlan,label:"Artifact remediation plan",required:false},{relativePath:i.doctorFixResult,label:"Doctor fix result",required:false},{relativePath:e.analyze,label:"Workspace analyze",required:false},{relativePath:i.pipelineLastRun,label:"Governance pipeline",required:false},{relativePath:e.readiness,label:"Release readiness",required:false},{relativePath:e.impact,label:"Workspace impact",required:false},{relativePath:e.verify,label:"Workspace verify",required:false},{relativePath:e.snapshot,label:"Workspace model snapshot",required:false},{relativePath:e.diff,label:"Workspace model diff",required:false},{relativePath:e.explain,label:"Workspace explain",required:false},{relativePath:e.contractVerify,label:"Workspace contract verify",required:false},{relativePath:e.history,label:"Workspace intelligence history",required:false}];function Lt(){let e=K.map(n=>n.relativePath),r=b$2().consumers.agents.canonicalReadOrder.filter(n=>n!==V&&e.includes(n));return [...new Set([i.goalIndex,i.goalPackLastRun,...r,...e])]}function y(e){return `npx workspai ${e}`.trim()}function ve(e){return e&&typeof e=="object"?e:null}function xe(e,t=12){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0).slice(0,t):[]}function Nt(e){let t=xe(e.blockers,12);if(t.length>0)return t;let r=xe(e.blockingReasons,12);if(r.length>0)return r;let n=ve(e.summary);return n&&Array.isArray(n.blockingReasons)?xe(n.blockingReasons,12):[]}function jt(e){let t=[...new Set(e.map(r=>r.trim()).filter(Boolean))];return t.filter(r=>{let n=r.toLowerCase();return !t.some(c=>{if(c===r||!c.includes(":"))return false;let l=c.toLowerCase();return l.length>n.length&&l.endsWith(n)})})}function Gt(e){for(let t of ["generatedAt","updatedAt","timestamp"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}if(Array.isArray(e.entries)){let t=e.entries.map(r=>ve(r)?.generatedAt).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim()).filter(r=>Number.isFinite(Date.parse(r)));if(t.length>0)return t.reduce((r,n)=>Date.parse(n)>Date.parse(r)?n:r)}}function Dt(e,t,r){if(!e)return true;let n=Date.parse(e);return Number.isFinite(n)?r.getTime()-n>t*60*60*1e3:true}function $t(e$1,t,r){return e$1.path===e.snapshot?false:Dt(e$1.generatedAt,t,r)}function qt(e){let t=e&&e.length>0?e:["all"];return t.includes("all")?new Set(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"]):new Set(t)}function R(e,t){return e.has("all")||e.has(t)}function wt(e){return R(e,"copilot")||R(e,"vscode")}function Mt(e,t){return t==="generic"?R(e,"agents"):t==="copilot"?wt(e):t==="grok"?R(e,"grok")||R(e,"orca"):R(e,t)}function Kt(e){return e??"enterprise"}function Ht(e){return e===b$1?"skills-index":e.includes("workspace-explain-last-run.json")?"explain-report":(e.startsWith(`${a$2}/`)||e.startsWith(".rapidkit/skills/"))&&e.endsWith(".md")?"operational-skill":e.includes("hooks")||e===F||e===G?"hook":e.includes("mcp")||e===D||e===E?"mcp-design":e.endsWith(".json")?"report":e.includes("/instructions/")||e.endsWith("copilot-instructions.md")?"instruction":e.includes("/prompts/")?"prompt":e.includes("/skills/")&&e.endsWith("/SKILL.md")?"skill":e.includes("/skills/")?"skill-resource":e.includes("/agents/")?"agent":e.includes("/rules/")||e.endsWith(".mdc")?"rule":"grounding"}function Vt(e){return e.startsWith(".github/")?["vscode","copilot"]:e.startsWith(".cursor/")?["cursor"]:e.startsWith(".claude/")||e==="CLAUDE.md"?["claude"]:e==="GEMINI.md"?["gemini"]:e==="QWEN.md"?["qwen"]:e.startsWith(".amazonq/")?["amazon-q"]:e==="AGENTS.md"||e.startsWith(".rapidkit/")?["agents","codex","kimi","grok","copilot","cursor","windsurf","orca","vscode"]:e.startsWith(".vscode/")?["vscode"]:["agents"]}function Ft(e,t){return pt().presets[t].requiredOutputs.includes(e)}async function Ut(e,t){if(t)return t;let r=await d(e,k$1)??i$1.join(e,k$1);if(await f$2.pathExists(r))try{let n=await f$2.readJson(r);return b$5(k$1,n,r),n}catch{}return p({workspacePath:e,includeEvidence:true})}function zt(e){return e.length>0&&!i$1.isAbsolute(e)&&!e.split(/[\\/]+/).includes("..")}function Bt(e){return Object.fromEntries(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"].map(r=>[r,{enabled:e.targets.includes("all")||e.targets.includes(r),outputs:e.outputs.filter(n=>n.targets.includes(r)).map(n=>n.path).sort()}]))}async function Jt(e,t){try{if(!await f$2.pathExists(e))return {payload:null,exists:false,validity:"missing"};let r=await f$2.readJson(e),n=ve(r);return n?a$1(t)?(b$5(t,n,e),{payload:n,exists:true,validity:"valid"}):{payload:n,exists:true,validity:"uncontracted"}:{payload:null,exists:true,validity:"invalid",validationError:"Artifact root must be a JSON object"}}catch(r){return {payload:null,exists:true,validity:"invalid",validationError:r instanceof Error?r.message:String(r)}}}async function ut(e){let t=e.now??new Date,r=e.staleAfterHours??24,n=[],c=[];for(let o of K){let A=await d(e.workspacePath,o.relativePath)??i$1.join(e.workspacePath,o.relativePath),h=await Jt(A,o.relativePath),m=h.payload;h.validity==="invalid"?c.push(`Invalid evidence contract: ${o.relativePath}`):m&&c.push(...Nt(m)),n.push({path:o.relativePath,label:o.label,required:o.required,exists:h.exists,validity:h.validity,validationError:h.validationError,generatedAt:m?Gt(m):void 0,commandId:typeof m?.commandId=="string"?m.commandId:void 0,exitCode:typeof m?.exitCode=="number"?m.exitCode:void 0});}let l=jt(c).slice(0,16),p=b$2();return {schemaVersion:vt,generatedAt:t.toISOString(),workspaceRoot:e.workspacePath,intelligenceChain:{schemaVersion:p.schemaVersion,contractPath:p.contractPath,currentStep:"agent-sync"},readOrder:Lt(),blockers:l,staleAfterHours:r,reports:n,refreshCommand:y("workspace agent-sync --write --refresh-context")}}function Yt(e$1){let t=["# Workspai agent grounding","","Cross-tool instructions for Copilot, Cursor, Claude Code, Codex, Grok, and other agents.","","## Read order (mandatory before workspace diagnosis)","",`1. \`${e.agentIndex}\` \u2014 latest blockers, timestamps, and report paths`,`2. \`${i.goalIndex}\` \u2014 when present, read the active Goal Pack and its handoff before choosing work.`,`3. \`${e.agentContext}\` \u2014 read only task-relevant context`,"4. Read only the task-relevant evidence artifacts listed in the index.","5. Use the Goal Pack retrieval queries, `workspace graph search <query> --limit 12 --json`, or MCP `searchWorkspaceGraph` before loading the full graph.","","Do **not** full-repo scan or inject the complete graph when a bounded query can answer the task.","","## Regenerate intelligence","","```bash",y("workspace agent-sync --write --refresh-context"),y("workspace context --for-agent --json --write"),y("pipeline --json --write"),"```",""];if(e$1.index.blockers.length>0){t.push("## Current blockers","");for(let r of e$1.index.blockers.slice(0,12))t.push(`- ${r}`);t.push("");}if(e$1.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let r of e$1.context.safeCommands.slice(0,10))t.push(`- \`${r.display}\` \u2014 ${r.description}`);t.push("");}return t.push("## Rules","","- Treat `.workspai/reports/*` as the source of truth for health, gates, and release posture.","- Prefer deterministic Workspai CLI commands over heuristic framework guesses.","- If evidence is missing or stale, run the refresh commands above before proposing fixes.","- Keep project-scoped advice aligned with the active project named in the context pack.","- Never claim that an active goal is satisfied until its CLI-owned verification lifecycle is `verified`.",""),t.join(`
9
+ `)}function Xt(e$1){return ["# Workspai agent grounding","",`Generated: ${e$1.generatedAt}`,"",`This file is tool-agnostic. Synced agents should read it together with \`${e.agentIndex}\`.`,"","## Mandatory read order","",...e$1.readOrder.map((t,r)=>`${r+1}. \`${t}\``),"",e$1.blockers.length>0?"## Blockers":"",...e$1.blockers.length>0?e$1.blockers.map(t=>`- ${t}`):[],"","## Refresh","","```bash",e$1.refreshCommand,"```",""].filter(t=>t!=="").join(`
10
+ `)}function Qt(){return ["# Workspai workspace grounding","","Before answering workspace, release, or architecture questions:","","1. Read `AGENTS.md` (managed Workspai section).",`2. Read \`${e.agentIndex}\` and only task-relevant context from \`${e.agentContext}\`.`,"3. Use bounded `workspace graph search` or MCP `searchWorkspaceGraph` before scanning the full repository.","","Regenerate stale intelligence:","","```bash",y("workspace agent-sync --write --refresh-context"),"```",""].join(`
11
+ `)}function Zt(){return ["## Claude Code","",`- Load \`${e.agentIndex}\` before diagnosing blockers.`,"- Use `.claude/rules/workspai-evidence.md` for scoped Workspai evidence rules.","- Treat `.claude/rules/rapidkit-evidence.md` as a legacy compatibility mirror.","- Refresh grounding with `npx workspai workspace agent-sync --write`.",""].join(`
12
+ `)}function Te(e$1){return [`## ${e$1}`,"","- Treat `AGENTS.md` as the portable workspace instruction authority.",`- Load \`${e.agentIndex}\` before diagnosing blockers or architecture.`,`- Read only task-relevant context from \`${e.agentContext}\`.`,"- Use bounded Workspace Knowledge Graph search before broad source discovery.","- Refresh grounding with `workspai workspace agent-sync --write --refresh-context`.",""].join(`
13
+ `)}function er(){return ["---","description: Workspai workspace evidence and intelligence grounding","globs: []","alwaysApply: true","---","","Before proposing fixes in this workspace:","",`1. Read \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Read only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","Refresh when stale:","","```bash",y("workspace agent-sync --write --refresh-context"),"```",""].join(`
14
+ `)}function tr(){return ["---",'applyTo: ".workspai/**,**/.workspai/**,.rapidkit/**,**/.rapidkit/**"',"description: Workspai evidence and intelligence artifacts","---","","When working under `.workspai/` or legacy `.rapidkit/`:","","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.",`- Start from \`${e.agentIndex}\` for read order and blockers.`,"- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.",""].join(`
15
+ `)}function rr(){return ["---",'applyTo: "**"',"description: Workspai workspace scope, evidence, and command discipline","---","","# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context and evidence.`,"- Prefer bounded `workspace graph search` or MCP `searchWorkspaceGraph` over loading the complete graph.","- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","- Do not translate unsupported stack requests into unrelated native kits.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
16
+ `)}function nr(){return ["# Workspai evidence","","Applies when reading or editing `.workspai/reports/*`.","","- Start from `INDEX.json`, then `workspace-context-agent.json`.","- Use report blockers as the primary fix target.","- Regenerate with `npx workspai workspace agent-sync --write`.",""].join(`
17
+ `)}function ar(){return ["# Legacy RapidKit evidence alias","","Compatibility path only. Use `.claude/rules/workspai-evidence.md` as the canonical rule.",""].join(`
18
+ `)}function or(){return ["---","description: Legacy RapidKit metadata compatibility alias",'globs: [".rapidkit/**", "**/.rapidkit/**"]',"alwaysApply: false","---","","Use `.cursor/rules/workspai-grounding.mdc` for canonical Workspai grounding.",""].join(`
19
+ `)}function gt(e){return ["---",'applyTo: ".rapidkit/**,**/.rapidkit/**"',"description: Legacy RapidKit metadata compatibility alias","---","",`Use \`.github/instructions/workspai-${e}.instructions.md\` as the canonical Workspai instruction.`,""].join(`
20
+ `)}function mt(){return ["---","description: Diagnose Workspai workspace blockers from evidence reports","---","","Diagnose this workspace using Workspai evidence only.","","Read:","",`- \`${e.agentIndex}\``,`- \`${e.agentContext}\``,"- Any fail/warn reports referenced in the index","","Return:","","1. Root cause grounded in report blockers","2. Smallest safe fix path (commands + file edits)","3. One verification command to prove recovery",""].join(`
21
+ `)}function ne(e$1){return ["---",`description: ${e$1.description}`,"---","",e$1.objective,"","Read first:","",`- \`${e.agentIndex}\``,`- \`${e.agentContext}\``,"- Any report referenced by the current blocker or task","","Return:","",...e$1.expectedOutput.map((t,r)=>`${r+1}. ${t}`),"","Use the standard Workspai answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
22
+ `)}function L(e){return ["# "+e.title,"",...e.lines,""].join(`
23
+ `)}function ir(){return L({title:"MCP Tool Design",lines:["Workspai MCP is a read-mostly bridge over contract-validated workspace artifacts.","","Candidate read tools:",`- \`getWorkspaceModel\` \u2014 read \`${e.model}\`.`,`- \`getWorkspaceKnowledgeGraph\` \u2014 read \`${e.knowledgeGraph}\`.`,`- \`getWorkspaceEvaluation\` \u2014 read \`${e.evaluationLastRun}\` (or the live evaluation when requested).`,"- `queryWorkspaceEntities` \u2014 filter proof-backed graph entities by kind.","- `searchWorkspaceGraph` \u2014 retrieve bounded proof-backed context by text query.","- `getWorkspaceGraphEvidence` \u2014 resolve evidence for an entity or relation.","- `findWorkspaceGraphPath` \u2014 find a shortest proof-carrying relationship path.",`- \`getEvidenceIndex\` \u2014 read \`${e.agentIndex}\`.`,"- `getBlockers` \u2014 derive current blockers from INDEX and gate reports.","- `getSafeCommands` \u2014 read safe commands from `workspace-context-agent.json`.","- `getProjectContext` \u2014 return one project-scoped slice of the workspace model.","- `getArtifact` \u2014 read one explicit artifact path inside the workspace root.",`- \`listOperationalSkills\` \u2014 read \`${e.skillsIndex}\`.`,"- `getWorkspaceExplain` \u2014 read/build workspace explain for release-blocked or project scope.","- `refreshWorkspaceIntelligence` \u2014 explicit user-approved refresh command only.","","Write or repair tools require explicit approval boundaries and are intentionally not part of the first read-mostly design."]})}function sr(e$1){return `${JSON.stringify({schemaVersion:h$3.workspaiMcpDesign.schemaVersion,generatedAt:e$1.generatedAt,workspaceRoot:e$1.workspacePath,status:"design-only",mode:"read-mostly",safety:{writeToolsEnabled:false,approvalRequiredForRefresh:true,artifactReadsMustStayInsideWorkspace:true},candidateTools:[{name:"getWorkspaceModel",reads:[e.model],mutates:false},{name:"getWorkspaceKnowledgeGraph",reads:[e.knowledgeGraph],mutates:false},{name:"getWorkspaceEvaluation",reads:[e.evaluationLive,e.evaluationLastRun],mutates:false},{name:"queryWorkspaceEntities",reads:[e.knowledgeGraph],mutates:false},{name:"searchWorkspaceGraph",reads:[e.knowledgeGraph],mutates:false},{name:"getWorkspaceGraphEvidence",reads:[e.knowledgeGraph],mutates:false},{name:"findWorkspaceGraphPath",reads:[e.knowledgeGraph],mutates:false},{name:"getEvidenceIndex",reads:[e.agentIndex],mutates:false},{name:"getBlockers",reads:[e.agentIndex,e.verify,i.pipelineLastRun],mutates:false},{name:"getSafeCommands",reads:[e.agentContext],mutates:false},{name:"getProjectContext",reads:[e.model,e.agentContext],mutates:false},{name:"getArtifact",reads:["requested workspace-relative artifact path"],mutates:false},{name:"listOperationalSkills",reads:[e.skillsIndex],mutates:false},{name:"getWorkspaceExplain",reads:[e.explain,e.verify,e.impact],mutates:false},{name:"refreshWorkspaceIntelligence",command:y("workspace agent-sync --write --refresh-context"),mutates:true,approvalRequired:true}]},null,2)}
24
+ `}function cr(e$1){return `${JSON.stringify({schemaVersion:h$3.agentHooks.schemaVersion,generatedAt:e$1.generatedAt,workspaceRoot:e$1.workspacePath,enabledByDefault:false,mode:"advisory",hooks:[{name:"workspai-pre-tool-use-workspace-boundary",event:"PreToolUse",purpose:"Block or warn on state-changing commands outside the active workspace root.",defaultAction:"warn",rules:["Allow read-only commands.","Warn before write/delete commands outside workspaceRoot.","Never run destructive commands without explicit user approval."]},{name:"workspai-post-tool-use-verify-suggestion",event:"PostToolUse",purpose:"Suggest non-destructive verification commands after edits.",defaultAction:"suggest",commands:[y("doctor workspace"),y("workspace verify --strict --json")]},{name:"workspai-user-prompt-submit-scope-hint",event:"UserPromptSubmit",purpose:"Inject lightweight workspace scope and evidence index hints.",defaultAction:"inject-context-hint",reads:[e.agentIndex,e.agentContext]}]},null,2)}
25
+ `}function kt(e$1){let t=["---","name: workspai-workspace-intelligence","description: Use Workspai workspace intelligence reports to answer, repair, verify, and release with evidence","---","","# Workspai Workspace Intelligence","","Use this skill for workspace architecture, project lifecycle, blocker repair, release readiness, agent grounding, and CI evidence questions.","","## Decision flow","","1. Load `resources/scope-model.md`.",`2. Load \`${e.agentIndex}\`.`,`3. Load \`${e.agentContext}\`.`,`4. Load \`${e.skillsIndex}\` when operational playbooks are needed.`,"5. Load the smallest evidence report required for the task.","6. Answer with Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Rules","","- Prefer Workspai reports over full-repo scans.","- Never claim a gate passed without a cited report.","- Separate display commands from execution requests.","- Keep project-scoped fixes inside the active project unless workspace evidence says otherwise.",""];return e$1?.trim()&&t.push(e$1.trim(),""),t.join(`
26
+ `)}function ae(e$1){return ["---",`name: ${e$1.name}`,`description: ${e$1.description}`,`tools: [${e$1.tools.map(t=>`'${t}'`).join(", ")}]`,"---","",`You are the ${e$1.name} agent for Workspai Workspace Intelligence.`,"",`Mode: ${e$1.mode}.`,"",`Start every task by reading \`${e.agentIndex}\` and \`${e.agentContext}\`.`,"","Use this answer contract:","","- Scope","- Evidence","- Diagnosis","- Fix Plan","- Run","- Verify","- Assumptions","","Do not invent health, readiness, or policy status. Cite report paths and command outputs.",""].join(`
27
+ `)}function ft(){return ["---","name: workspai-grounding","description: Load Workspai workspace intelligence reports before diagnosing or changing code","---","","# Workspai grounding","","Use when the user asks about workspace health, release gates, doctor/pipeline failures, or project structure.","","## Workflow","",`1. Read \`${e.agentIndex}\``,`2. Read \`${e.agentContext}\``,"3. Read fail/warn evidence artifacts listed in the index","4. Propose the smallest safe fix with explicit verification commands","","## Refresh stale evidence","","```bash",y("workspace agent-sync --write --refresh-context"),"```",""].join(`
28
+ `)}async function u(e,t,r){return r?(await f$2.ensureDir(i$1.dirname(e)),await f$2.writeFile(e,t,"utf8"),"written"):"skipped"}async function Oe(e){if(!e.write)return "skipped";await We(e.workspacePath,e.absolutePath);let t=await f$2.pathExists(e.absolutePath)?await f$2.readFile(e.absolutePath,"utf8"):null,{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),n=r(t,e.generatedBody),c=e.preamble?`${e.preamble.trimEnd()}
29
+
30
+ ${n}`:n;return await f$2.ensureDir(i$1.dirname(e.absolutePath)),await f$2.writeFile(e.absolutePath,c,"utf8"),"written"}async function ht(e){if(!e.write)return "skipped";await We(e.workspacePath,e.absolutePath);let t=await f$2.pathExists(e.absolutePath)?await f$2.readFile(e.absolutePath,"utf8"):"",{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),n=r(t,e.generatedBody),c=n.includes(e.importLine)?n:`${e.importLine}
31
+
32
+ ${n}`;return await f$2.ensureDir(i$1.dirname(e.absolutePath)),await f$2.writeFile(e.absolutePath,c,"utf8"),"written"}async function We(e,t){let r=i$1.resolve(e),n=i$1.resolve(t),c=i$1.relative(r,n);if(!c||c===".."||c.startsWith(`..${i$1.sep}`)||i$1.isAbsolute(c))throw new Error("Agent output path must remain inside the canonical workspace.");let l=c.split(i$1.sep),p=r;for(let[o,A]of l.entries()){p=i$1.join(p,A);let h=await f$2.lstat(p).catch(_=>{if(_.code==="ENOENT")return null;throw _});if(!h)return;let m=o===l.length-1;if(h.isSymbolicLink()||(m?!h.isFile():!h.isDirectory()))throw new Error(`Agent output path is blocked by authored repository state: ${c}`)}}function nn(e){if(!e?.trim())return;let t=new Set(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"]),r=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>t.has(n));return r.length>0?r:void 0}function lr(e){let t=[...e.outputs].sort((n,c)=>n.path.localeCompare(c.path)),r=b$2();return {schemaVersion:Wt,generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,preset:e.preset,targets:[...e.targets].sort(),sourceReports:e.index.reports.filter(n=>n.exists).map(n=>n.path).sort(),intelligenceChain:{schemaVersion:r.schemaVersion,contractPath:r.contractPath,currentStep:"agent-sync"},outputInventory:t,capabilityMatrix:Bt({targets:e.targets,outputs:t}),drift:{missingRequired:e.missingRequired,staleReports:e.staleReports,strictViolations:e.strictViolations},answerContract:["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"],refreshCommand:y(`workspace agent-sync --write --refresh-context --preset ${e.preset}`),experimental:{hooksEnabled:e.experimentalHooks,mcpReady:t.some(n=>n.kind==="mcp-design")}}}async function _e(e){let t$1=i$1.resolve(e.workspacePath),r$1=e.now??new Date,n$1=e.staleAfterHours??24,c$1=qt(e.targets),l$1=[...c$1].sort(),p$2=Kt(e.preset),o$1=e.write===true,A$1=e.strict===true,h,m$2=null,_=e.model;e.refreshContext&&(_??=await p({workspacePath:t$1,includeEvidence:true}),m$2=await c({workspacePath:t$1,model:_,agent:e.agent??"generic",scope:e.scope,includeEvidence:true}),o$1&&(h=await d$1(m$2,t$1)));let C$1=[],oe=[],ie=[],se=[],d=(s,k)=>{s==="written"?oe.push(k):ie.push(k),se.push({path:k,kind:Ht(k),targets:Vt(k),required:Ft(k,p$2),status:s==="written"?"written":e.dryRun?"planned":"skipped"});},ce="",At=await Ut(t$1,_),le=null;try{le=(await m({workspacePath:t$1})).contract;}catch{le=null;}let Pt=st({model:At,context:m$2,contract:le}),de=await ct({workspacePath:t$1,skills:Pt,generatedAt:r$1.toISOString(),write:o$1});for(let s of de.skills)d(o$1?"written":"skipped",s.canonicalPath);d(o$1?"written":"skipped",b$1),ce=lt(de.index);let E$1=await ut({workspacePath:t$1,staleAfterHours:n$1,now:r$1});if(d(await u(i$1.join(t$1,V),`${JSON.stringify(E$1,null,2)}
33
+ `,o$1),V),d(await u(i$1.join(t$1,f$3),`${Xt(E$1)}
34
+ `,o$1),f$3),["agents","vscode","copilot","cursor","codex","kimi","grok","windsurf","orca"].some(s=>R(c$1,s))&&d(await Oe({workspacePath:t$1,absolutePath:i$1.join(t$1,"AGENTS.md"),generatedBody:Yt({index:E$1,context:m$2}),write:o$1}),"AGENTS.md"),R(c$1,"claude")){let s=i$1.join(t$1,"CLAUDE.md");if(o$1){await We(t$1,s);let{upsertManagedAgentSection:k}=await import('./managed-agent-markers-COE5DJ3W.js'),g=await f$2.pathExists(s)?await f$2.readFile(s,"utf8"):"",P=k(g,Zt()),b=P.includes("@AGENTS.md")?P:`@AGENTS.md
35
+
36
+ ${P}`;await f$2.ensureDir(i$1.dirname(s)),await f$2.writeFile(s,b,"utf8"),oe.push("CLAUDE.md");}else ie.push("CLAUDE.md");d(await u(i$1.join(t$1,j),`${nr()}
37
+ `,o$1),j),d(await u(i$1.join(t$1,k),`${ar()}
38
+ `,o$1),k);}if(R(c$1,"gemini")&&d(await ht({workspacePath:t$1,absolutePath:i$1.join(t$1,"GEMINI.md"),importLine:"@./AGENTS.md",generatedBody:Te("Gemini CLI"),write:o$1}),"GEMINI.md"),R(c$1,"qwen")&&d(await ht({workspacePath:t$1,absolutePath:i$1.join(t$1,"QWEN.md"),importLine:"@AGENTS.md",generatedBody:Te("Qwen Code"),write:o$1}),"QWEN.md"),R(c$1,"amazon-q")&&d(await Oe({workspacePath:t$1,absolutePath:i$1.join(t$1,".amazonq/rules/workspai-agent-entry.md"),generatedBody:Te("Amazon Q Developer"),write:o$1}),".amazonq/rules/workspai-agent-entry.md"),R(c$1,"cursor")&&(d(await u(i$1.join(t$1,h$2),er(),o$1),h$2),d(await u(i$1.join(t$1,i$2),or(),o$1),i$2)),wt(c$1)){if(d(await Oe({workspacePath:t$1,absolutePath:i$1.join(t$1,".github/copilot-instructions.md"),generatedBody:Qt(),write:o$1}),".github/copilot-instructions.md"),d(await u(i$1.join(t$1,l),rr(),o$1),l),d(await u(i$1.join(t$1,m$1),gt("workspace"),o$1),m$1),d(await u(i$1.join(t$1,n),tr(),o$1),n),d(await u(i$1.join(t$1,o),gt("evidence"),o$1),o),d(await u(i$1.join(t$1,p$1),mt(),o$1),p$1),d(await u(i$1.join(t$1,q),mt(),o$1),q),p$2==="enterprise"){let s$1=[[r,ne({description:"Repair Workspai blockers with evidence and verification",objective:"Plan the smallest safe repair for the current Workspai blocker.",expectedOutput:["Blocker and affected workspace/project scope","Evidence paths and exact failing signals","Minimal fix plan","Human-run commands","Verification command and expected success signal"]})],[t,ne({description:"Assess Workspai release readiness from evidence",objective:"Assess whether this workspace is release-ready using Workspai gates.",expectedOutput:["Readiness verdict with cited reports","Blocking gates","Safe next command","Verification checklist"]})],[v,ne({description:"Onboard a project into Workspai Workspace Intelligence",objective:"Guide project onboarding using workspace model and create planner capabilities.",expectedOutput:["Target project scope","Native create, official generator, or existing lane","Safe commands","Post-onboarding verification"]})],[x,ne({description:"Adopt an existing project into Workspai governance",objective:"Adopt an existing project without changing its runtime behavior.",expectedOutput:["Detected stack and confidence","Adoption plan","Generated metadata expectations","Doctor and workspace model verification"]})]];for(let[g,P]of s$1)d(await u(i$1.join(t$1,g),P,o$1),g);let k=[[s,s$1[0][1]],[u$1,s$1[1][1]],[w,s$1[2][1]],[y$1,s$1[3][1]]];for(let[g,P]of k)d(await u(i$1.join(t$1,g),P,o$1),g);if(e.hydratePrompts===true)for(let g of await dt({workspacePath:t$1,skills:de.skills,write:o$1}))d(o$1?"written":"skipped",g);}if(d(await u(i$1.join(t$1,z),ft(),o$1),z),d(await u(i$1.join(t$1,A),ft(),o$1),A),p$2==="enterprise"){d(await u(i$1.join(t$1,B),kt(ce),o$1),B),d(await u(i$1.join(t$1,C),kt(ce),o$1),C);let s=[["artifact-map.md",L({title:"Artifact Map",lines:K.map(g=>`- \`${g.relativePath}\` \u2014 ${g.label}`)})],["command-map.md",L({title:"Command Map",lines:["- `npx workspai workspace agent-sync --write --refresh-context` \u2014 refresh agent grounding.","- `npx workspai workspace model --json --write` \u2014 refresh workspace model.","- `npx workspai doctor workspace` \u2014 refresh health evidence.","- `npx workspai workspace verify --strict --json` \u2014 verify release gates."]})],["scope-model.md",L({title:"Scope Model",lines:["- Workspace scope is the default source of truth.","- Project scope is selected only when the active task targets a specific project.","- Always name the workspace and project when giving repair or lifecycle advice."]})],["runtime-support.md",L({title:"Runtime Support",lines:["- Native create is available only for Workspai-owned scaffold contracts.","- Unsupported stacks should use the official lane when a stable ecosystem generator exists.","- Existing projects should use the existing lane when native create is unavailable."]})],["create-planner-capabilities.md",L({title:"Create Planner Capabilities",lines:["- Use `contracts/create-planner-capabilities.v1.json` to decide native, official, or existing.","- Do not map PHP, WordPress, Laravel, Rails, or Symfony requests to unrelated native kits.","- Explain unsupported native create requests and guide users to adopt/import."]})],["mcp-tools.md",ir()]];for(let[g,P]of s){let b=`${i$1.dirname(B)}/resources/${g}`;d(await u(i$1.join(t$1,b),P,o$1),b);let Ne=`${i$1.dirname(C)}/resources/${g}`;d(await u(i$1.join(t$1,Ne),P,o$1),Ne);}let k=[["workspai-advisor.agent.md",ae({name:"Workspai Advisor",description:"Read-only workspace and project guidance using Workspai evidence",mode:"read-only",tools:["search","read"]})],["workspai-repair.agent.md",ae({name:"Workspai Repair",description:"Turn Workspai blockers into minimal fixes and verification steps",mode:"repair",tools:["search","read","edit"]})],["workspai-release.agent.md",ae({name:"Workspai Release",description:"Assess readiness, governance gates, and release safety from evidence",mode:"release",tools:["search","read"]})],["workspai-project-onboarder.agent.md",ae({name:"Workspai Project Onboarder",description:"Guide create, import, and adopt flows with Workspai contracts",mode:"onboard",tools:["search","read","edit"]})]];for(let[g,P]of k){let b=`.github/agents/${g}`;d(await u(i$1.join(t$1,b),P,o$1),b);}}}if(p$2==="enterprise"){let s=sr({workspacePath:t$1,generatedAt:E$1.generatedAt});b$5(D,JSON.parse(s)),d(await u(i$1.join(t$1,D),s,o$1),D),d(await u(i$1.join(t$1,E),s,o$1),E);}if(p$2==="enterprise"&&e.experimentalHooks===true){let s=cr({workspacePath:t$1,generatedAt:E$1.generatedAt});b$5(F,JSON.parse(s)),d(await u(i$1.join(t$1,F),s,o$1),F),d(await u(i$1.join(t$1,G),s,o$1),G);}let pe=o$1?await ut({workspacePath:t$1,staleAfterHours:n$1,now:r$1}):E$1,F$1=pe.reports.filter(s=>s.required&&!s.exists).map(s=>s.path),U=pe.reports.filter(s=>s.exists&&$t(s,n$1,r$1)).map(s=>s.path);if(A$1){F$1.length>0&&C$1.push(`Missing required reports: ${F$1.join(", ")}`),U.length>0&&C$1.push(`Stale reports (>${n$1}h): ${U.join(", ")}`);let s=se.map(k=>k.path).filter(k=>!zt(k));s.length>0&&C$1.push(`Unsafe generated output paths: ${s.join(", ")}`);}let v$1=o$1?await g$2({workspacePath:t$1,mode:e.projectGrounding??"managed",now:r$1}):void 0;if(A$1&&v$1&&v$1.skipped.length>0&&C$1.push(`Project grounding incomplete: ${v$1.skipped.map(s=>`${s.name} (${s.reason})`).join(", ")}`),A$1&&v$1){let s=v$1.projects.flatMap(k=>(k.hostCoverage??[]).filter(g=>g.status==="blocked"&&Mt(c$1,g.id)).map(g=>`${i$1.basename(k.projectPath)}:${g.id}`));s.length>0&&C$1.push(`Project agent entry coverage blocked: ${s.join(", ")}`);}let Le=lr({workspacePath:t$1,generatedAt:r$1.toISOString(),preset:p$2,targets:l$1,index:pe,outputs:[...se,{path:H,kind:"report",targets:["agents","vscode","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"],required:true,status:o$1?"written":e.dryRun?"planned":"skipped"}],missingRequired:F$1,staleReports:U,strictViolations:C$1,experimentalHooks:e.experimentalHooks===true});if(o$1&&process.env.WORKSPAI_TEST_FAIL_AGENT_SYNC_BEFORE_PACK==="1")throw new Error("Injected agent-sync failure before generation commit.");return d(await u(i$1.join(t$1,H),`${JSON.stringify(Le,null,2)}
39
+ `,o$1),H),{workspacePath:t$1,indexPath:i$1.join(t$1,V),packPath:i$1.join(t$1,H),pack:Le,contextPath:h,writtenFiles:oe,skippedFiles:ie,blockers:E$1.blockers,missingRequired:F$1,staleReports:U,strictViolations:C$1,projectLenses:v$1}}async function an(e){if(e.write!==true)return _e(e);let t=i$1.resolve(e.workspacePath),r=i$1.join(t,".workspai","transactions","agent-sync");await b$3(r);let n=await _e({...e,write:false,dryRun:true});if(!n.pack)throw new Error("Agent-sync dry run did not produce an output inventory.");let c=[...n.pack.outputInventory.map(p=>p.path),V,H],l=await a({journalDirectory:r});try{for(let A of [...new Set(c)].sort()){let h=i$1.resolve(t,A),m=i$1.relative(t,h);if(m===".."||m.startsWith(`..${i$1.sep}`)||i$1.isAbsolute(m))throw new Error(`Agent-sync output escapes workspace root: ${A}`);await l.captureFile(h);}let p=await h(t);for(let A of p.resolved)for(let h of [f$1,g,h$1,b$4,...g$1,"AGENTS.md",".gitignore"])await l.captureFile(i$1.join(A.projectPath,h));let o=await _e(e);return await l.commit(),o}catch(p){try{await l.rollback();}catch(o){throw new AggregateError([p,o],"Agent-sync generation failed and rollback was incomplete.")}throw p}}export{yt as a,Ct as b,_t as c,vt as d,Wt as e,V as f,H as g,K as h,Lt as i,ut as j,nn as k,an as l};
@@ -1 +1 @@
1
- import {c,e}from'./chunk-GRGUPSNP.js';import {i,h as h$1}from'./chunk-HH54C3XJ.js';import {s}from'./chunk-MOSXTVPU.js';import u from'fs';import A from'path';var a=h$1.workspaceRunLast.schemaVersion,W="workspace-run-last.json",o=i.workspaceRunLast;var P=new Set(["init","test","build","start"]);function _(e){return P.has(e)}async function d(e){try{return await u.promises.access(e,u.constants.F_OK),true}catch{return false}}async function w(e){try{let r=await u.promises.readFile(e,"utf-8");return JSON.parse(r)}catch{return null}}function m(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function h(e){let r=e.stage;return typeof r!="string"||r.trim().length===0||!Array.isArray(e.projects)?false:_(r)||/^[a-z][a-z0-9_-]*$/i.test(r)}function T(e){let r=m(e);return !r||r.schemaVersion===a?false:h(r)}function C(e){let r=m(e);return r?r.schemaVersion===a&&r.stages!=null:false}function p(e){if(C(e))return e;if(T(e)){let r=e.stage;return {schemaVersion:a,generatedAt:e.generatedAt,workspacePath:e.workspacePath,latestStage:r,stages:{[r]:e},enterpriseControls:e.enterpriseControls??{jsonReady:true,evidencePath:o}}}return null}function U(e,r){let n=p(e);if(!n)return null;let t=r??n.latestStage;return n.stages[t]??null}async function V(e){let r=(await Promise.all(s(A.resolve(e),"reports",W).map(async t=>await d(t)?t:null))).find(t=>typeof t=="string");if(!r)return null;let n=await w(r);return p(n)}async function j(e$1,r){let n=A.resolve(e$1);return c(n,o,async()=>{let t=(await Promise.all(s(n,"reports",W).map(async s=>await d(s)?s:null))).find(s=>typeof s=="string"),R=t?await w(t):null,i=p(R);if(t&&!i)throw new Error(`Workspace run evidence is unreadable or invalid; refusing to overwrite: ${t}`);let l=i?{...i.stages}:{};l[r.stage]=r;let g={schemaVersion:a,generatedAt:r.generatedAt,workspacePath:r.workspacePath,latestStage:r.stage,stages:l,enterpriseControls:{jsonReady:true,evidencePath:o}};return await e(n,o,g),g})}export{W as a,o as b,U as c,V as d,j as e};
1
+ import {c,e}from'./chunk-CCDGHPEJ.js';import {i,h as h$1}from'./chunk-NZ3WZYD5.js';import {s}from'./chunk-MOSXTVPU.js';import u from'fs';import A from'path';var a=h$1.workspaceRunLast.schemaVersion,W="workspace-run-last.json",o=i.workspaceRunLast;var P=new Set(["init","test","build","start"]);function _(e){return P.has(e)}async function d(e){try{return await u.promises.access(e,u.constants.F_OK),true}catch{return false}}async function w(e){try{let r=await u.promises.readFile(e,"utf-8");return JSON.parse(r)}catch{return null}}function m(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function h(e){let r=e.stage;return typeof r!="string"||r.trim().length===0||!Array.isArray(e.projects)?false:_(r)||/^[a-z][a-z0-9_-]*$/i.test(r)}function T(e){let r=m(e);return !r||r.schemaVersion===a?false:h(r)}function C(e){let r=m(e);return r?r.schemaVersion===a&&r.stages!=null:false}function p(e){if(C(e))return e;if(T(e)){let r=e.stage;return {schemaVersion:a,generatedAt:e.generatedAt,workspacePath:e.workspacePath,latestStage:r,stages:{[r]:e},enterpriseControls:e.enterpriseControls??{jsonReady:true,evidencePath:o}}}return null}function U(e,r){let n=p(e);if(!n)return null;let t=r??n.latestStage;return n.stages[t]??null}async function V(e){let r=(await Promise.all(s(A.resolve(e),"reports",W).map(async t=>await d(t)?t:null))).find(t=>typeof t=="string");if(!r)return null;let n=await w(r);return p(n)}async function j(e$1,r){let n=A.resolve(e$1);return c(n,o,async()=>{let t=(await Promise.all(s(n,"reports",W).map(async s=>await d(s)?s:null))).find(s=>typeof s=="string"),R=t?await w(t):null,i=p(R);if(t&&!i)throw new Error(`Workspace run evidence is unreadable or invalid; refusing to overwrite: ${t}`);let l=i?{...i.stages}:{};l[r.stage]=r;let g={schemaVersion:a,generatedAt:r.generatedAt,workspacePath:r.workspacePath,latestStage:r.stage,stages:l,enterpriseControls:{jsonReady:true,evidencePath:o}};return await e(n,o,g),g})}export{W as a,o as b,U as c,V as d,j as e};