workspai 0.43.0 → 0.44.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 (173) hide show
  1. package/README.md +26 -13
  2. package/contracts/agent-customization-pack.v1.json +1 -1
  3. package/contracts/autopilot-release.v1.json +204 -0
  4. package/contracts/cli-operation-result.v1.json +119 -0
  5. package/contracts/command-capabilities.v1.json +138 -0
  6. package/contracts/compatibility-matrix.v1.json +37 -0
  7. package/contracts/create-planner-capabilities.v1.json +156 -65
  8. package/contracts/doctor-project-scan.v2.json +60 -0
  9. package/contracts/doctor-remediation-plan.v1.json +19 -4
  10. package/contracts/doctor-remediation-plan.v2.json +7 -0
  11. package/contracts/doctor-workspace-cache.v2.json +82 -0
  12. package/contracts/extension-cli-compatibility.v1.json +47 -3
  13. package/contracts/infra-plan.v1.json +189 -0
  14. package/contracts/private-product-manifest.v1.json +155 -0
  15. package/contracts/product-factory-plan.v1.json +200 -0
  16. package/contracts/project-archive.v1.json +40 -0
  17. package/contracts/project-entry-capability.v1.json +127 -0
  18. package/contracts/published-contract-catalog.v1.json +334 -0
  19. package/contracts/runtime-command-surface.v1.json +239 -10
  20. package/contracts/version.v1.json +48 -0
  21. package/contracts/workspace-archive-capabilities.v1.json +90 -0
  22. package/contracts/workspace-archive-manifest.v1.json +107 -0
  23. package/contracts/workspace-archive-operation-result.v1.json +565 -0
  24. package/contracts/workspace-intelligence/agent-customization-pack-report.v1.json +98 -0
  25. package/contracts/workspace-intelligence/agent-hooks.v1.json +38 -0
  26. package/contracts/workspace-intelligence/agent-reports-index.v1.json +56 -0
  27. package/contracts/workspace-intelligence/mcp-design.v1.json +42 -0
  28. package/contracts/workspace-intelligence/workspace-context.v1.json +12 -0
  29. package/contracts/workspace-intelligence/workspace-explain.v1.json +1 -0
  30. package/contracts/workspace-intelligence-architecture.v1.json +723 -0
  31. package/contracts/workspace-intelligence-chain.v1.json +1194 -0
  32. package/contracts/workspace-list.v1.json +56 -0
  33. package/contracts/workspace-model-cache.v1.json +55 -0
  34. package/contracts/workspace-snapshot.v1.json +58 -0
  35. package/contracts/workspace-snapshot.v2.json +97 -0
  36. package/contracts/workspace-sync.v1.json +30 -0
  37. package/contracts/workspace-watch-event.v1.json +112 -0
  38. package/dist/analyze-6OCBM4ID.js +1 -0
  39. package/dist/{artifact-remediation-plan-5GJWPPRS.js → artifact-remediation-plan-Z7OCSME3.js} +3 -3
  40. package/dist/autopilot-release-LI2WJCEW.js +1 -0
  41. package/dist/{chunk-LZQNVH7D.js → chunk-2K3GYCPS.js} +1 -1
  42. package/dist/chunk-2QN6BMM7.js +2 -0
  43. package/dist/chunk-2QOWRBQD.js +1 -0
  44. package/dist/chunk-5AKYMAIL.js +1 -0
  45. package/dist/{chunk-RE773WOX.js → chunk-5PVEQ6CZ.js} +5 -5
  46. package/dist/{chunk-AFSZHLQT.js → chunk-7EIMPQR3.js} +1 -1
  47. package/dist/{chunk-3KXW53QI.js → chunk-7IHLTPZ6.js} +1 -1
  48. package/dist/chunk-7RIWU5TZ.js +1 -0
  49. package/dist/{chunk-T6OR6YOI.js → chunk-7UZVOYF5.js} +1 -1
  50. package/dist/chunk-B66A4TVP.js +1 -0
  51. package/dist/chunk-CL6TGI4Q.js +8 -0
  52. package/dist/chunk-FWJV7CCI.js +2 -0
  53. package/dist/chunk-J4AICQFB.js +1 -0
  54. package/dist/chunk-JICOD2GI.js +1 -0
  55. package/dist/{chunk-OJEWQO3Z.js → chunk-JP25YL3J.js} +17 -17
  56. package/dist/chunk-L2Q7B2OJ.js +1 -0
  57. package/dist/chunk-L3E6IRUQ.js +8 -0
  58. package/dist/chunk-LG6RFLPZ.js +1 -0
  59. package/dist/chunk-LGP6WXS2.js +4 -0
  60. package/dist/{chunk-VRDF2J46.js → chunk-M4VITK6X.js} +52 -50
  61. package/dist/chunk-NTXO7BMH.js +4 -0
  62. package/dist/{chunk-LPZFK3Y6.js → chunk-OW4UNG27.js} +65 -66
  63. package/dist/{chunk-LUP4U6EE.js → chunk-P424XYHP.js} +1 -1
  64. package/dist/chunk-P4SWTY5X.js +33 -0
  65. package/dist/chunk-TQEMLBAG.js +1 -0
  66. package/dist/chunk-TRMDODFM.js +13 -0
  67. package/dist/chunk-UNF72FTB.js +1 -0
  68. package/dist/chunk-V5JN4TDX.js +2 -0
  69. package/dist/chunk-VA5MRHKM.js +2 -0
  70. package/dist/chunk-XIVFLY6G.js +1 -0
  71. package/dist/chunk-YUX4YFGL.js +78 -0
  72. package/dist/{create-WRZO4HK2.js → create-DFAWAS5C.js} +1 -1
  73. package/dist/demo-kit-DZ7TPG7K.js +149 -0
  74. package/dist/doctor-PVSWDBJL.js +1 -0
  75. package/dist/{dotnet-webapi-clean-IPY3MCGQ.js → dotnet-webapi-clean-BYUUHX5Y.js} +20 -20
  76. package/dist/{gofiber-standard-N5N3QGH3.js → gofiber-standard-B6UK5GR7.js} +31 -31
  77. package/dist/{gogin-standard-LAWQTBWL.js → gogin-standard-BXU44VEM.js} +31 -31
  78. package/dist/index.d.ts +250 -24
  79. package/dist/index.js +218 -182
  80. package/dist/pipeline-ND734AJM.js +5 -0
  81. package/dist/{platform-capabilities-XAVU4HSM.js → platform-capabilities-YICBF4FA.js} +1 -1
  82. package/dist/{pythonRapidkitExec-3L3XJBSY.js → pythonRapidkitExec-UJYIB6FL.js} +1 -1
  83. package/dist/{springboot-standard-OZYF7ZM7.js → springboot-standard-PEHDKH2L.js} +27 -27
  84. package/dist/{workspace-PR6VZRBG.js → workspace-FQT3QIRS.js} +1 -1
  85. package/dist/workspace-agent-sync-ZYCPXTU3.js +1 -0
  86. package/dist/workspace-archive-EEGLHZDW.js +10 -0
  87. package/dist/workspace-context-WAGGJCDL.js +1 -0
  88. package/dist/{workspace-contract-XUGMCUSQ.js → workspace-contract-SEI4SNSG.js} +1 -1
  89. package/dist/workspace-explain-MVGGRCDN.js +1 -0
  90. package/dist/workspace-explain-contract-KT757JGQ.js +1 -0
  91. package/dist/{workspace-feedback-R6H4UFZB.js → workspace-feedback-RCB25NFO.js} +1 -1
  92. package/dist/{workspace-foundation-KGSV4E6D.js → workspace-foundation-KXDL6P6X.js} +1 -1
  93. package/dist/{workspace-history-CGCK2DJI.js → workspace-history-M4QQBIPB.js} +1 -1
  94. package/dist/workspace-intelligence-QOGD2TZS.js +1 -0
  95. package/dist/workspace-mcp-serve-CEFKEMYG.js +3 -0
  96. package/dist/{workspace-model-PNXXOGPO.js → workspace-model-GMSRBICO.js} +1 -1
  97. package/dist/workspace-registry-summary-S52SEJAG.js +1 -0
  98. package/dist/workspace-run-VC4OUPRF.js +1 -0
  99. package/dist/{workspace-verify-WSDUUTR5.js → workspace-verify-NP4GMFSV.js} +1 -1
  100. package/dist/workspace-watch-IIBH3Y25.js +1 -0
  101. package/docs/AI_FEATURES.md +67 -34
  102. package/docs/README.md +2 -1
  103. package/docs/commands-reference.md +26 -14
  104. package/docs/contracts/ARTIFACT_CATALOG.md +60 -36
  105. package/docs/contracts/README.md +3 -2
  106. package/docs/create-planner-capabilities.md +36 -18
  107. package/docs/workspace-operations.md +25 -0
  108. package/package.json +35 -13
  109. package/scripts/enterprise-package-smoke.mjs +40 -8
  110. package/scripts/prepack-enterprise.mjs +8 -0
  111. package/templates/kits/fastapi-ddd/.gitignore.j2 +11 -0
  112. package/templates/kits/fastapi-ddd/README.md.j2 +23 -18
  113. package/templates/kits/fastapi-ddd/common/env.example.j2 +2 -2
  114. package/templates/kits/fastapi-ddd/pyproject.toml.j2 +7 -7
  115. package/templates/kits/fastapi-ddd/src/app/config/__init__.py.j2 +1 -1
  116. package/templates/kits/fastapi-ddd/src/cli.py.j2 +6 -9
  117. package/templates/kits/fastapi-ddd/src/main.py.j2 +1 -1
  118. package/templates/kits/fastapi-standard/.gitignore.j2 +11 -0
  119. package/templates/kits/fastapi-standard/README.md.j2 +35 -30
  120. package/templates/kits/fastapi-standard/common/env.example.j2 +2 -2
  121. package/templates/kits/fastapi-standard/pyproject.toml.j2 +7 -7
  122. package/templates/kits/fastapi-standard/src/cli.py.j2 +7 -10
  123. package/templates/kits/fastapi-standard/src/main.py.j2 +1 -1
  124. package/templates/kits/fastapi-standard/src/routing/examples.py.j2 +1 -1
  125. package/templates/kits/fastapi-standard/tests/test_examples.py.j2 +1 -1
  126. package/templates/kits/nestjs-standard/.dockerignore.j2 +11 -0
  127. package/templates/kits/nestjs-standard/.eslintrc.js.j2 +25 -0
  128. package/templates/kits/nestjs-standard/.gitignore.j2 +22 -0
  129. package/templates/kits/nestjs-standard/.node-version.j2 +1 -0
  130. package/templates/kits/nestjs-standard/.nvmrc.j2 +1 -0
  131. package/templates/kits/nestjs-standard/.prettierrc.j2 +7 -0
  132. package/templates/kits/nestjs-standard/README.md.j2 +23 -18
  133. package/templates/kits/nestjs-standard/docs/README.md.j2 +2 -2
  134. package/templates/kits/nestjs-standard/jest.config.ts.j2 +1 -7
  135. package/templates/kits/nestjs-standard/package.json.j2 +1 -1
  136. package/templates/kits/nestjs-standard/src/config/configuration.ts.j2 +4 -4
  137. package/templates/kits/nestjs-standard/src/main.ts.j2 +1 -1
  138. package/templates/kits/nestjs-standard/src/modules/index.ts.j2 +1 -1
  139. package/templates/kits/nestjs-standard/tsconfig.build.json.j2 +1 -1
  140. package/templates/kits/nestjs-standard/tsconfig.json.j2 +1 -1
  141. package/dist/analyze-5BU4QIPK.js +0 -1
  142. package/dist/autopilot-release-QYUOVB26.js +0 -1
  143. package/dist/chunk-54XJNLYC.js +0 -13
  144. package/dist/chunk-5SWNSJGW.js +0 -1
  145. package/dist/chunk-753LOKFZ.js +0 -2
  146. package/dist/chunk-AAKUNWPR.js +0 -78
  147. package/dist/chunk-AQ4XZZC6.js +0 -1
  148. package/dist/chunk-CVTCPPEF.js +0 -1
  149. package/dist/chunk-DNAY5ALC.js +0 -1
  150. package/dist/chunk-EWYYLJQY.js +0 -2
  151. package/dist/chunk-LO4C4VXR.js +0 -4
  152. package/dist/chunk-LYC6AIF2.js +0 -2
  153. package/dist/chunk-NAAQMSO3.js +0 -1
  154. package/dist/chunk-NFUXULIF.js +0 -1
  155. package/dist/chunk-OL64GWQC.js +0 -9
  156. package/dist/chunk-PI5KUXDA.js +0 -7
  157. package/dist/chunk-SI3AQKIP.js +0 -1
  158. package/dist/chunk-VZKSNUEE.js +0 -2
  159. package/dist/chunk-WU4ZRRA5.js +0 -4
  160. package/dist/chunk-XEJD4KCV.js +0 -33
  161. package/dist/demo-kit-AJ5LIM5G.js +0 -149
  162. package/dist/doctor-MF3M3FS3.js +0 -1
  163. package/dist/pipeline-QCUHFWDY.js +0 -5
  164. package/dist/workspace-agent-sync-KTYF3HQR.js +0 -1
  165. package/dist/workspace-archive-GCZNI44O.js +0 -3
  166. package/dist/workspace-context-QUTOP2XV.js +0 -1
  167. package/dist/workspace-explain-JEONEGZZ.js +0 -1
  168. package/dist/workspace-explain-contract-DNS2YEL7.js +0 -1
  169. package/dist/workspace-intelligence-QJGVL37U.js +0 -1
  170. package/dist/workspace-mcp-serve-AK4MYEHQ.js +0 -3
  171. package/dist/workspace-registry-summary-RUJE6RPH.js +0 -1
  172. package/dist/workspace-run-Y7YMUIHX.js +0 -1
  173. package/dist/workspace-watch-AGPOJ74Q.js +0 -1
@@ -1 +0,0 @@
1
- var o="workspace-explain.v1",f=["project","release-blocked","blocker","trace"];function i(t){let r=t.trim();if(!r)return null;if(r==="release-blocked")return {kind:"release-blocked"};if(r.startsWith("project:")){let e=r.slice(8).trim();return e?{kind:"project",project:e}:null}if(r.startsWith("blocker:")){let e=r.slice(8).trim();return e?{kind:"blocker",blockerId:e}:null}if(r.startsWith("trace:")){let e=r.slice(6).trim();return e?{kind:"trace",diffRef:e}:null}return {kind:"project",project:r}}function g(t){let r=t.trim();if(!r)return null;if(r.startsWith("trace:")){let n=i(r);return n?.kind==="trace"?n:null}let e=r.replace(/\\/g,"/").trim().toLowerCase();return e.endsWith(".json")||e.includes("workspace-model-diff")||e.startsWith(".rapidkit/")||e.includes("/.rapidkit/")?{kind:"trace",diffRef:r}:null}function u(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let r=t;return r.schemaVersion===o&&typeof r.generatedAt=="string"&&typeof r.summary=="string"&&Array.isArray(r.sections)&&r.target!=null&&typeof r.target=="object"&&!Array.isArray(r.target)&&typeof r.target.kind=="string"}export{o as a,f as b,i as c,g as d,u as e};
@@ -1 +0,0 @@
1
- import {c as c$3}from'./chunk-753LOKFZ.js';import {a,b as b$2}from'./chunk-PYCJWW4B.js';import {b as b$1,c,d}from'./chunk-3KXW53QI.js';import {m,f as f$1,c as c$2,n,e}from'./chunk-LYC6AIF2.js';import {n as n$1,b as b$3}from'./chunk-5SWNSJGW.js';import {a as a$1}from'./chunk-VZKSNUEE.js';import {c as c$1}from'./chunk-NAAQMSO3.js';import f from'path';import y from'fs-extra';var J="rapidkit-blocker-resolution-v1";function U(e){let t=e.blockers.map(r=>r.trim()).filter(Boolean).slice(0,12),s=e.stderrTail?.trim().slice(-400)??"";return b$3({blockers:t,exitCode:e.exitCode??null,stderrTail:s})}function se(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function re(e){let t=se(e.reason),s=U({blockers:[e.reason]}),r=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",studioActionId:"run-analyze"}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:J,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:s,commandRetryHint:t==="artifact-missing"?"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:r,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function G(e){return Array.from(new Set(e.blockingReasons.map(s=>s.trim()).filter(Boolean))).slice(0,12).map((s,r)=>re({reason:s,blockerId:`blocker-${r+1}`,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}))}function ne(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function ie(e){return e.length===0||e.every(t=>ne(t))}function Y(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&ie(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function Fe(e,t){let s=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${s} \u2014 add your first project to continue.`:`Workspace scaffold${s}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var Q="workspace-verify.v1",$=".workspai/reports/workspace-verify-last-run.json";function oe(e,t){return f.isAbsolute(t)?t:f.join(e,t)}async function X(e$1){let t=await y.readJson(e$1);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e$1}`);let s=t;if(s.schemaVersion!==e)throw new Error(`Unsupported workspace impact schema: ${String(s.schemaVersion)}`);return s}function ae(e){let t=new Set,s=[];for(let r of e){let n=`${r.scope}:${r.project??""}:${r.display}`;t.has(n)||(t.add(n),s.push(r));}return s}function ce(e,t){if(!e||e==="workspace")return true;let s=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===s}function le(e,t){if(e.id==="workspace.doctor")return f.join(t,".workspai","reports","doctor-last-run.json");if(e.id==="workspace.contract.verify")return f.join(t,".workspai","reports","workspace-contract-verify-last-run.json");if(e.id==="workspace.readiness")return f.join(t,".workspai","reports","release-readiness-last-run.json");if(e.id==="workspace.analyze")return f.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return f.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return f.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return f.join(t,".workspai","reports","workspace-run-last.json")}function b(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function ue(e){let t=b(e.healthScore),s=typeof t?.errors=="number"?t.errors:0,r=typeof t?.percent=="number"?t.percent:void 0;return s>0?{status:"fail",message:`Doctor evidence reports ${s} error(s).`}:typeof r=="number"&&r<70?{status:"warn",message:`Doctor health score is ${r}%.`}:{status:"pass",message:"Doctor evidence is present and healthy."}}function de(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function pe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function fe(e){let t=b(e.summary);if(t?.blocking===true||e.blocking===true)return {status:"fail",message:"Analyze evidence reports blocking findings."};let r=typeof t?.status=="string"?t.status:void 0;return r==="warn"||r==="warning"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is present."}}function ge(e){let t=e.schemaVersion==="rapidkit-doctor-fix-result-v1"?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let s=t,r=Array.isArray(s.remainingBlockers)?s.remainingBlockers:[];if(r.length>0)return {status:"fail",message:`Doctor fix result reports ${r.length} remaining blocker(s).`};let n=Array.isArray(s.appliedFixes)?s.appliedFixes:[];return n.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${n.length} applied fix(es) with no remaining blockers.`}}async function me(e,t){let s=await c$1(e,".workspai/reports/doctor-remediation-plan-last-run.json");if(!s)return false;try{let r=b(await y.readJson(s));if(!r||(Array.isArray(r.steps)?r.steps:[]).length>0)return false;let i=typeof r.generatedAt=="string"?r.generatedAt:void 0;if(!i||!t)return true;let k=Date.parse(i),c=Date.parse(t);return !Number.isFinite(k)||!Number.isFinite(c)?true:k>=c}catch{return false}}function ke(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function ye(e){let t=b(e.summary),s=typeof t?.verdict=="string"?t.verdict:void 0;return s==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:s==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:s==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function he(e,t,s){let r=ke(t),n=c$3(e,r??void 0);if(!n)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let i=n.stage;if(r&&i!==r)return {status:"missing",message:`Workspace run evidence is for stage "${i}", expected "${r}".`};let k=Array.isArray(n.projects)?n.projects:[],c=t.project?.toLowerCase();if(!c)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let u=k.find(o=>{let p=b(o);if(!p)return false;let l=typeof p.projectName=="string"?p.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(d=>p[d]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.replace(/\\/g,"/").toLowerCase());return l===c||a.some(d=>d.endsWith(`/${c}`)||d===c)});if(u){let o=v(n.generatedAt,s,`Workspace run evidence for ${t.project??t.id}`);if(o)return {status:"fail",message:o};let p=b(u),l=typeof p?.status=="string"?p.status:"unknown";return l==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:l==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:l==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${l} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function v(e,t,s){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${s} is stale: missing generatedAt timestamp (required after impact ${t}).`;let r=Date.parse(e),n=Date.parse(t);return Number.isFinite(r)?Number.isFinite(n)&&r<n?`${s} is stale: generated at ${e}, before impact ${t}.`:null:`${s} is stale: invalid generatedAt timestamp (required after impact ${t}).`}async function ve(e,t,s,r){let n=le(e,t),i=n?f.relative(t,n).split(f.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!s)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=n?await c$1(t,i??""):null;if(!n||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:i,message:i?`Missing evidence report: ${i}`:"No evidence mapping exists for this command."};let c=b(await y.readJson(k));if(!c)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:i,message:"Evidence report is not a JSON object."};let u;if(e.id==="workspace.doctor"){let o=v(c.generatedAt,r,"Doctor evidence");o?u={status:"fail",message:o}:u=ue(c);}else if(e.id==="workspace.readiness"){let o=v(c.generatedAt,r,"Release readiness evidence");o?u={status:"fail",message:o}:u=de(c);}else if(e.id==="workspace.contract.verify"){let o=v(c.generatedAt,r,"Workspace contract verify evidence");o?u={status:"fail",message:o}:u=pe(c);}else if(e.id==="workspace.analyze"){let o=v(c.generatedAt,r,"Analyze evidence");o?u={status:"fail",message:o}:u=fe(c);}else if(e.id==="workspace.pipeline"){let o=v(c.generatedAt,r,"Pipeline evidence");o?u={status:"fail",message:o}:u=ye(c);}else if(e.id==="workspace.doctor-fix"){let o=c.schemaVersion==="rapidkit-doctor-fix-result-v1"?c:c.fixResult,p=b(o),l=typeof p?.generatedAt=="string"?p.generatedAt:void 0,a=v(l,r,"Doctor fix result");a?u={status:"fail",message:a}:await me(t,l)?u={status:"skipped",message:"No current doctor remediation steps are pending."}:u=ge(c);}else if(e.id.startsWith("project."))u=he(c,e,r);else {let o=v(c.generatedAt,r,"Evidence report");o?u={status:"fail",message:o}:u={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:u.status,required:e.required,evidencePath:i,message:u.message}}function be(e,t={blockingReasons:[],needsAttention:false}){let s=e.filter(l=>l.status==="pass").length,r=e.filter(l=>l.status==="warn").length,n=e.filter(l=>l.status==="fail").length,i=e.filter(l=>l.status==="missing").length,k=e.filter(l=>l.status==="skipped").length,c=e.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),u=e.filter(l=>l.required&&l.status==="missing").length,o="ready",p=0;return c.length>0||t.blockingReasons.length>0?(o="blocked",p=2):(r>0||u>0||t.needsAttention)&&(o="needs-attention",p=1),{verdict:o,exitCode:p,stepsPassed:s,stepsWarn:r,stepsFailed:n,stepsMissing:i,stepsSkipped:k}}function we(e,t){let s=W(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),r=new Set(s.map(a=>a.toLowerCase())),n=W(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!r.has(a.toLowerCase()))),i=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let d=a.project.toLowerCase(),h=i.get(d)??[];h.push(a),i.set(d,h);}let k=[],c=[],u=[],o=[],p=false,l=(a,d)=>{let h=i.get(a.toLowerCase())??[];if(h.length===0){u.push(a);return}let R=h.filter(g=>g.status==="fail"),C=h.filter(g=>g.status==="missing"),w=C.filter(g=>g.required),j=h.some(g=>g.status==="pass"||g.status==="warn");if(R.length>0){c.push(a),o.push(`graph.subgraph.${a}: ${d} has failed verification evidence (${R.map(g=>g.id).join(", ")}).`);return}if(w.length>0){c.push(a),o.push(`graph.subgraph.${a}: ${d} has missing required verification evidence (${w.map(g=>g.id).join(", ")}).`);return}if(C.length>0){c.push(a),p=true;return}if(j){k.push(a);return}u.push(a);};for(let a of s)l(a,"directly-changed");for(let a of n)l(a,"transitive dependent");return {subgraph:{totalProjects:s.length+n.length,directlyChanged:s,transitiveDependents:n,covered:W(k),uncovered:W(c),unverifiable:W(u)},blockingReasons:o,needsAttention:p}}function W(e){return [...new Set(e)].sort((t,s)=>t.localeCompare(s))}async function Re(e$1){let t=f.resolve(e$1.workspacePath);if(e$1.fromImpactPath){let i=oe(t,e$1.fromImpactPath);return {impact:await X(i),fromImpactRef:f.relative(t,i).split(f.sep).join("/"),impactFromDisk:true}}let s=f.join(t,f$1);if(await y.pathExists(s))return {impact:await X(s),fromImpactRef:f$1,impactFromDisk:true};let r=f.join(t,c$2);if(await y.pathExists(r))return {impact:await n({workspacePath:t,fromPath:c$2,scope:e$1.scope,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),fromImpactRef:c$2,impactFromDisk:false};let n$2=await n$1({workspacePath:t,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now});return {impact:{schemaVersion:e,generatedAt:(e$1.now??new Date).toISOString(),fromRef:"baseline",diffRef:".workspai/reports/workspace-model-diff-last-run.json",workspace:{name:n$2.workspace.name,profile:n$2.workspace.profile,type:n$2.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:n$2.graph?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:"workspace-model-diff.v1",generatedAt:(e$1.now??new Date).toISOString(),fromRef:"baseline",toRef:".workspai/reports/workspace-model.json",fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:n$2}},impactFromDisk:false}}function Ce(e,t){if(t)return e.generatedAt}async function Ge(e){let t=f.resolve(e.workspacePath),{impact:s,fromImpactRef:r,impactFromDisk:n}=await Re(e),i=s.diff.currentModel,k=Ce(s,n),c$1=ae([...m(),...s.verificationPlan]).filter(m=>ce(e.scope,m)),u=[];for(let m of c$1)u.push(await ve(m,t,i.contracts.exists===true,k));let o=we(s,u),p=a(i.graph??{nodes:[],edges:[]}),l=b$1(i),a$1=await xe(t),d$1=c(l,a$1?.freshness?.projectHashes),h={verdict:d$1.verdict,baseline:d$1.baseline,changed:d$1.changed,added:d$1.added,removed:d$1.removed,projectHashes:d(l)},R=b$2(p),C=i.policies?.mode??"warn",w=await je(i,t),j=We(C,w),g=be(u,{blockingReasons:[...o.blockingReasons,...R,...j.blockingReasons],needsAttention:o.needsAttention||j.needsAttention}),Z=u.filter(m=>m.status==="missing"&&m.evidencePath).map(m=>m.evidencePath),x=[...u.filter(m=>m.required&&(m.status==="fail"||m.status==="missing")).map(m=>`${m.id}: ${m.message}`),...o.blockingReasons,...R,...j.blockingReasons],ee=w.filter(m=>m.severity==="error").length,te=i.summary?.projectCount??i.projects.length,B=Y({projectCount:te,verdict:g.verdict,exitCode:g.exitCode,blockingReasons:x,policyErrorCount:ee});g.verdict=B.verdict,g.exitCode=B.exitCode;let F=x.length>0?G({blockingReasons:x,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:$}):[];return {schemaVersion:Q,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:r,scope:e.scope,impact:{changed:s.summary.changed,risk:s.summary.risk,affectedProjects:s.summary.affectedProjects,recommendedCommands:s.summary.recommendedCommands},summary:g,steps:u,missingEvidence:Z,blockingReasons:x,...F.length>0?{resolutionHints:F}:{},verificationPlan:c$1,affectedSubgraph:o.subgraph,graphIntegrity:p,freshness:h,policyMode:C,policyViolations:w}}async function je(e,t){let s=[];for(let n of e.validation?.issues??[])s.push({source:"model",severity:n.severity,code:n.code,message:n.message,target:n.target});let r=await c$1(t,".workspai/reports/workspace-contract-verify-last-run.json");try{if(r&&await y.pathExists(r)){let n=await y.readJson(r);if(Array.isArray(n.violations))for(let i of n.violations)typeof i=="string"&&i.trim().length>0&&s.push({source:"contract",severity:"error",code:"contract.violation",message:i});}}catch{}return s.sort((n,i)=>n.source!==i.source?n.source.localeCompare(i.source):n.code!==i.code?n.code.localeCompare(i.code):n.message.localeCompare(i.message))}function We(e,t){let s=t.filter(r=>r.severity==="error");return e==="enforce"&&s.length>0?{blockingReasons:s.map(r=>`policy.${r.code}: ${r.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:s.length>0}}async function xe(e){let t=f.join(e,$);try{if(!await y.pathExists(t))return null;let s=await y.readJson(t);return s&&s.schemaVersion===Q?s:null}catch{return null}}async function Ye(e,t){let s=f.join(t,$);return await y.ensureDir(f.dirname(s)),await y.writeJson(s,a$1(e),{spaces:2}),s}function Se(e,t){let s=t?.strict?"strict":"default",r=[];if(e.summary.verdict==="blocked")return r.push(...e.blockingReasons),r.length===0&&r.push("verify verdict is blocked."),{passed:false,mode:s,exitCode:2,reasons:r};if(s==="strict"){if(e.summary.verdict!=="ready"&&r.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let n=[...e.freshness.changed,...e.freshness.added].slice(0,5);r.push(`freshness is stale${n.length>0?`: ${n.join(", ")}`:""} (strict requires fresh).`);}if(r.length>0)return {passed:false,mode:s,exitCode:1,reasons:r}}return {passed:true,mode:s,exitCode:0,reasons:r}}function Xe(e,t){return Se(e,t).exitCode}export{J as a,Fe as b,Q as c,$ as d,we as e,Ge as f,Ye as g,Se as h,Xe as i};
@@ -1 +0,0 @@
1
- var t=".workspai/skills";var n=".workspai/reports/workspace-skills-index.json",p=".workspai/reports/workspace-explain-last-run.json",e=".workspai/reports/workspace-why-last-run.json",a=".workspai/reports/workspace-trace-last-run.json",_=".workspai/AGENT-GROUNDING.md",c=".rapidkit/AGENT-GROUNDING.md",O=".cursor/rules/workspai-grounding.mdc",P=".cursor/rules/rapidkit-grounding.mdc",I=".claude/rules/workspai-evidence.md",A=".claude/rules/rapidkit-evidence.md",T=".github/instructions/workspai-workspace.instructions.md",E=".github/instructions/rapidkit-workspace.instructions.md",R=".github/instructions/workspai-evidence.instructions.md",L=".github/instructions/rapidkit-evidence.instructions.md",d=".github/prompts/workspai-diagnose.prompt.md",S=".github/prompts/rapidkit-diagnose.prompt.md",k=".github/prompts/workspai-repair.prompt.md",C=".github/prompts/rapidkit-repair.prompt.md",l=".github/prompts/workspai-release-readiness.prompt.md",m=".github/prompts/rapidkit-release-readiness.prompt.md",u=".github/prompts/workspai-project-onboard.prompt.md",N=".github/prompts/rapidkit-project-onboard.prompt.md",g=".github/prompts/workspai-adopt-project.prompt.md",w=".github/prompts/rapidkit-adopt-project.prompt.md",K=".github/skills/workspai-grounding/SKILL.md",x=".github/skills/rapidkit-grounding/SKILL.md",G=".github/skills/workspai-workspace-intelligence/SKILL.md",H=".github/skills/rapidkit-workspace-intelligence/SKILL.md",D=".workspai/reports/workspai-mcp-design.json",h=".workspai/reports/rapidkit-mcp-design.json",W=".vscode/workspai-agent-hooks.json",U=".vscode/rapidkit-agent-hooks.json";function b(o){let s=o.trim();if(!s||s.includes("..")||s.includes("/"))throw new Error(`Invalid operational skill id: ${o}`);return `${t}/${s}.md`}var Y={"workspai-diagnose-api-failure":"workspai-diagnose","workspai-release-readiness":"workspai-release-readiness","workspai-safe-schema-migration":"workspai-safe-schema-migration","workspai-dependency-upgrade":"workspai-dependency-upgrade","workspai-rename-contract":"workspai-rename-contract"};export{x as A,G as B,H as C,D,h as E,W as F,U as G,b as H,Y as I,t as a,n as b,p as c,e as d,a as e,_ as f,c as g,O as h,P as i,I as j,A as k,T as l,E as m,R as n,L as o,d as p,S as q,k as r,C as s,l as t,m as u,u as v,N as w,g as x,w as y,K as z};
@@ -1,2 +0,0 @@
1
- import {n,d,e}from'./chunk-5SWNSJGW.js';import {a}from'./chunk-VZKSNUEE.js';import u from'path';import v from'fs-extra';var $="workspace-context.v1",M=".workspai/reports/workspace-context-agent.json";function F(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="orca"?t:"generic"}function x(e){return `npx --yes --package workspai workspai ${e}`.trim()}function C(e){return `npx workspai ${e}`.trim()}function i(e){return {id:e.id,scope:e.scope,display:C(e.args),execute:x(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:d({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:C(e.args),execute:x(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:".workspai/reports/workspace-model.json",sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function W(e,t){return `workspace run ${t} --scope project:${e.name}`}function R(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function E(e){return [e.name,e.path,u.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function T(e,t,o){let r={generatedAt:e.generatedAt,now:o},a=[i({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...r}),i({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...r}),i({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...r}),i({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...r}),i({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...r})],c=t?[t]:e.projects;for(let n of c)n.commands.fleetStages.includes("test")&&a.push(i({id:`project.${n.name}.test`,scope:"project",project:n.name,args:W(n,"test"),description:`Run tests for ${n.name} through workspace orchestration.`,...r})),n.commands.fleetStages.includes("build")&&a.push(i({id:`project.${n.name}.build`,scope:"project",project:n.name,args:W(n,"build"),description:`Build ${n.name} through workspace orchestration.`,...r}));return a}function O(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function D(e,t){if(!t?.startsWith("project:"))return;let o=R(t);if(o)return e.projects.find(r=>E(r).includes(o))}function V(e,t,o){let r=[...e.validation?.issues??[]];t?.startsWith("project:")&&!o&&r.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let a=r.filter(n=>n.severity==="error").length,c=r.filter(n=>n.severity==="warning").length;return {status:a>0?"failed":c>0?"warning":"passed",errors:a,warnings:c,issues:r}}function I(e){let t=[],o=[];for(let[r,a]of Object.entries(e.evidence))a?.exists?t.push(`${r}: ${a.path}`):o.push(r);return {available:t.sort(),missing:o.sort()}}function N(e){let t=e.summary.projectCount,o=e.summary.runtimes.length?e.summary.runtimes.join(", "):"no runtime",r=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${o} runtime coverage, and ${r}.`}function _(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),e.summary.observedProjects>0&&t.push("Some projects are observed rather than first-class; command support may be partial."),t}async function L(e$1){let t=e$1.model??await n({workspacePath:e$1.workspacePath,includeEvidence:e$1.includeEvidence===true,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),o=F(e$1.agent),r=D(t,e$1.scope),a=V(t,e$1.scope,r);if(e$1.strict===true&&a.status!=="passed"){let s=a.issues.map(p=>`${p.severity}:${p.code}:${p.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${s}`)}let c=e$1.now??new Date,n$1=t.facts??[],b=new Set((r?[r]:t.projects).map(s=>s.name)),g=n$1.filter(s=>s.project?b.has(s.project):true),S=(r?[r]:t.projects).map(s=>{let p=g.filter(P=>P.project===s.name);return {name:s.name,path:s.path,kind:s.kind,runtime:s.runtime,framework:s.frameworkDisplayName,...s.generator?{generator:s.generator}:{},createCapability:s.createCapability,supportTier:s.supportTier,safeCommands:O(s),importantFiles:s.importantFiles,facts:p}}),d$1=I(t),f=N(t),k=T(t,r,c),A=k.map(s=>d({id:`context.command.${s.id}`,label:`${s.id} safe command`,scope:"command",value:{display:s.display,execute:s.execute,scope:s.scope},...s.project?{project:s.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:c,sourceArtifact:".workspai/reports/workspace-context-agent.json",sourcePath:`safeCommands.${s.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),h=[...g,...A],m=e({facts:h,generatedAt:c.toISOString(),now:c});return {schemaVersion:$,generatedAt:c.toISOString(),agent:o,workspaceSummary:f,modelRef:".workspai/reports/workspace-model.json",workspace:{name:t.workspace.name,root:t.workspace.root,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e$1.scope??"workspace",...r?{activeProject:r.name}:{}},projects:S,safeCommands:k,facts:h,factFreshness:m,evidence:d$1,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:a,agentInstructions:["Read `.workspai/reports/INDEX.json` first, then this context pack and linked evidence reports.","Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[..._(t),...m.verifyBeforeUseFacts>0?[`${m.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[f,`Evidence available: ${d$1.available.length}. Missing evidence groups: ${d$1.missing.join(", ")||"none"}.`,r?`Active project scope: ${r.name} (${r.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
2
- `)}}async function G(e,t){let o=u.join(t,M);return await v.ensureDir(u.dirname(o)),await v.writeJSON(o,a(e),{spaces:2}),o}export{$ as a,M as b,L as c,G as d};
@@ -1,4 +0,0 @@
1
- import {f as f$1,e}from'./chunk-T3GJ7YVG.js';import {a,b}from'./chunk-22DT744Z.js';import {c}from'./chunk-NFUXULIF.js';import {d as d$1,e as e$1,g,f as f$2,i}from'./chunk-T6OR6YOI.js';import {a as a$1,d as d$2}from'./chunk-NAAQMSO3.js';import {o}from'./chunk-5XATWNME.js';import d from'chalk';import l from'fs';import p from'path';var L="release-readiness-v1";function D(t,e){let s=p.resolve(t);if(!b(s))return s;let a=V(e,"workspace.contract.json");if(l.existsSync(a))try{let o=JSON.parse(l.readFileSync(a,"utf-8")),n=Array.isArray(o.projects)?o.projects:[];for(let r of n){let u=f(r),m=typeof u.relativePath=="string"?u.relativePath.trim():"";if(m)return p.join(e,m)}}catch{}let i=W(e),c=Array.isArray(i.payload?.projects)?i.payload.projects:[];for(let o of c){let n=f(o),r=typeof n.path=="string"?n.path.trim():"";if(r)return p.resolve(r)}return s}function J(t){let e=d$1(t);return e$1(e,t)?"go":g(e,t)?"java":f$2(e,t)?"node":i(e,t)?"python":"unknown"}function $(t,e){if(!l.existsSync(t))return null;let s=l.readdirSync(t).filter(a=>a.endsWith(".json")&&e.some(i=>i.test(a))).map(a=>p.join(t,a));return s.length===0?null:(s.sort((a,i)=>l.statSync(i).mtimeMs-l.statSync(a).mtimeMs),s[0])}function f(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function I(t){for(let e of t)if(l.existsSync(e))return e;return null}function V(t,...e){let s=o(t,...e);return I(s)??s[0]}function P(t,e){let s=a$1(t,`.workspai/reports/${e}`);return I([s,p.join(t,".rapidkit","reports",e)])??s}async function F(t){let{readWorkspaceRegistrySummary:e,resolveWorkspaceRegisteredProjects:s}=await import('./workspace-registry-summary-RUJE6RPH.js'),a=await e(t);return a?a.projectCount:(await s(t)).summary.projectCount}function M(t,e,s){let a=V(t,"toolchain.lock");if(!l.existsSync(a))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run workspai bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:a};try{let i=JSON.parse(l.readFileSync(a,"utf-8")),c=f(i.runtime),n=["python","node","go","java"].filter(r=>{let u=f(c[r]);return typeof u.version=="string"&&u.version.trim().length>0});if(n.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via workspai setup <runtime> and re-run bootstrap."],evidencePath:a};if(e!=="unknown"){let r=f(c[e]);if(typeof r.version!="string"||r.version.trim().length===0)return {gate:"env",status:"fail",summary:`${s?.hasRegisteredProjects?"Project runtime":"Workspace"} (${e}) is not pinned in toolchain.lock`,details:[`Run workspai setup ${e} and workspai bootstrap to lock ${e} for this workspace.`],evidencePath:a}}return {gate:"env",status:"pass",summary:`Pinned runtimes: ${n.join(", ")}`,details:[],evidencePath:a}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with workspai bootstrap."],evidencePath:a}}}function W(t){let e=P(t,"doctor-last-run.json");if(!l.existsSync(e))return {payload:null,path:e};try{let s=JSON.parse(l.readFileSync(e,"utf-8"));return c(s,"workspace")?{payload:s,path:e}:{payload:null,path:e}}catch{return {payload:null,path:e}}}function _(t){let e=W(t);if(!e.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run workspai doctor workspace --json before release readiness checks."],evidencePath:e.path},payload:null};let s=f(e.payload.summary),a=Number(s.totalIssues??0);return s.hasSystemErrors?{gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:e.path},payload:e.payload}:a>0?{gate:{gate:"doctor",status:"warn",summary:`Doctor found ${a} issue(s)`,details:["Run workspai doctor workspace --fix and re-run readiness checks."],evidencePath:e.path},payload:e.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:e.path},payload:e.payload}}function H(t){let e=P(t,"analyze-last-run.json");if(!l.existsSync(e))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run workspai analyze --json before release readiness checks."],evidencePath:e};try{let s=JSON.parse(l.readFileSync(e,"utf-8")),a=f(s.summary),i=String(a.verdict??"").toLowerCase(),c=Number(a.score??0),o=f(a.findings),n=Number(o.fail??0);return i==="blocked"||n>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${c}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:e}:i==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${c}/100)`,details:["Review analyze warnings before release."],evidencePath:e}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${c}/100)`,details:[],evidencePath:e}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid JSON",details:["Re-run workspai analyze --json to regenerate evidence."],evidencePath:e}}}function K(t){try{let e=JSON.parse(l.readFileSync(t,"utf-8")),s=String(e.status??"").toLowerCase(),a=f(e.summary),i=Number(a.failedChecks??0);return s==="fail"||i>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:t}:s==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:t}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:t}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:t}}}async function B(t,e){if(e.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let s=[a$1(t,".workspai/reports"),p.join(t,".rapidkit","reports")],a=s[0],i=s.map(n=>$(n,[/verify-pack-contract/i,/^verify.*\.json$/i])).find(n=>typeof n=="string")??null;if(i)return K(i);let c=a$1(t,".workspai/reports/workspace-contract-verify-last-run.json"),o=s.map(n=>$(n,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i])).find(n=>typeof n=="string")??null;if(o)try{let n=JSON.parse(l.readFileSync(o,"utf-8")),r=String(n.status??"").toLowerCase();if(r==="passed"||r==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(r==="failed"||r==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(n.violations)?n.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:n}=await import('./workspace-contract-XUGMCUSQ.js'),r=await n({workspacePath:t}),u={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:r.status,contractPath:r.contractPath,projectCount:r.projectCount,checks:r.checks,violations:r.violations};return await d$2(t,".workspai/reports/workspace-contract-verify-last-run.json",u),r.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:r.violations.slice(0,5),evidencePath:c}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:c}}catch(n){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run workspai workspace contract verify --json or export verify-pack contract from CI.",n instanceof Error?n.message:String(n)],evidencePath:p.join(a,"*verify*.json")}}}function U(t,e){let s=P(e,"doctor-last-run.json");if(!t)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run workspai doctor workspace --json to include dependency findings."],evidencePath:s};let a=Array.isArray(t.projects)?t.projects:[],i=a.reduce((o,n)=>{let r=Number(n.vulnerabilities??0);return Number.isFinite(r)?o+Math.max(0,r):o},0),c=a.filter(o=>o.depsInstalled===false).length;return i>0?{gate:"dependency",status:"fail",summary:`${i} dependency vulnerability(ies) reported`,details:["Resolve vulnerabilities (npm/pip/go audit pipelines) before release."],evidencePath:s}:c>0?{gate:"dependency",status:"warn",summary:`${c} project(s) report missing dependencies`,details:["Run project init/bootstrap and regenerate doctor evidence."],evidencePath:s}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:s}}function q(t){return t.some(e=>e.status==="fail")?"fail":t.some(e=>e.status==="warn")?"warn":"pass"}async function Q(t,e){return d$2(t,".workspai/reports/release-readiness-last-run.json",e)}async function T(t={}){let e$1=p.resolve(t.startPath??process.cwd()),s=a(e$1)??e$1,a$1=await F(s)>0,i=a$1&&b(e$1)?s:D(e$1,s),c=i===s?"unknown":J(i),n=M(s,a$1?c:"unknown",{hasRegisteredProjects:a$1}),r=_(s),u=H(s),m=await B(s,{skipVerify:t.skipVerify}),z=U(r.payload,s),h=[n,r.gate,u,m,z],v=q(h),g={schemaVersion:L,generatedAt:new Date().toISOString(),workspacePath:s,projectPath:i,action:t.action,overallStatus:v,blocking:v==="fail",blockingReasons:h.filter(y=>y.status==="fail").map(y=>`${y.gate}: ${y.summary}`),gates:h};if(t.writeReport!==false){let y=f$1(g,{commandId:"workspaceReadiness",exitCode:v==="fail"?2:v==="warn"?1:0,generatedAt:g.generatedAt,blockers:g.blockingReasons,runId:e()});g.evidencePath=await Q(s,y);}return g}function X(t){return t==="pass"?d.green("PASS"):t==="warn"?d.yellow("WARN"):d.red("FAIL")}function Y(t){return t==="pass"?d.green("PASS"):t==="warn"?d.yellow("WARN"):d.red("FAIL")}async function de(t){let e=await T({writeReport:true,skipVerify:t.skipVerify===true});if(t.json)console.log(JSON.stringify(e,null,2));else {console.log(d.bold.cyan(`
2
- \u{1F6A6} Workspai Release Readiness
3
- `)),console.log(d.bold(`Workspace: ${d.cyan(p.basename(e.workspacePath))}`)),console.log(d.gray(`Path: ${e.workspacePath}`)),console.log(`Overall: ${Y(e.overallStatus)}`);for(let s of e.gates){console.log(` - ${s.gate}: ${X(s.status)} ${s.summary}`);for(let a of s.details)console.log(d.gray(` ${a}`));s.evidencePath&&console.log(d.gray(` evidence: ${s.evidencePath}`));}e.evidencePath&&console.log(d.gray(`
4
- Evidence saved: ${e.evidencePath}`));}t.strict&&e.overallStatus!=="pass"&&process.exit(1);}export{T as a,de as b};
@@ -1,2 +0,0 @@
1
- import {n,k as k$1,j}from'./chunk-5SWNSJGW.js';import {a as a$1}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {a}from'./chunk-VZKSNUEE.js';import de from'crypto';import m from'path';import y from'fs-extra';import {spawnSync}from'child_process';function F(e,t){let r=spawnSync("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return r.status!==0?{ok:false,stdout:""}:{ok:true,stdout:(r.stdout??"").trim()}}function pe(e){let t=[],r=[],s=[];for(let c of e.split(`
2
- `)){if(!c.trim())continue;let o=c.slice(0,2),i=c.slice(3).trim();if(i){if(o==="??"){r.push(i);continue}o.includes("D")&&s.push(i),t.push(i);}}return {changedFiles:[...new Set(t)].sort(),untrackedFiles:[...new Set(r)].sort(),deletedFiles:[...new Set(s)].sort()}}function L(e,t){let r={available:false,dirty:false,changedFiles:[],untrackedFiles:[],deletedFiles:[]},s=F(e,["rev-parse","--is-inside-work-tree"]);if(!s.ok||s.stdout!=="true")return r;let c=F(e,["rev-parse","--abbrev-ref","HEAD"]),o=F(e,["rev-parse","HEAD"]),i=F(e,["status","--porcelain=v1","--untracked-files=all"]),p=pe(i.stdout),f=p.changedFiles.length>0||p.untrackedFiles.length>0||p.deletedFiles.length>0;return {available:true,branch:c.ok?c.stdout:void 0,commit:o.ok?o.stdout:void 0,ref:t?.ref,dirty:f,changedFiles:p.changedFiles,untrackedFiles:p.untrackedFiles,deletedFiles:p.deletedFiles}}var X="workspace-model-snapshot.v1",V="workspace-model-diff.v1",$=".workspai/reports/workspace-model-snapshot.json",Z=".workspai/reports/workspace-model-diff-last-run.json",le="workspace-impact.v1",fe=".workspai/reports/workspace-impact-last-run.json";function ee(e){let t=e.trim().toLowerCase();return t==="git"||t.startsWith("git:")}function me(e){let t=e.trim();return t.toLowerCase()==="git"?"HEAD":t.toLowerCase().startsWith("git:")&&t.slice(4).trim()||"HEAD"}function _(e){if(Array.isArray(e))return e.map(t=>_(t));if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=_(e[r]);return t}return e}function k(e){return JSON.stringify(_(e))}function ue(e){return e.facts?.map(t=>({...t,freshness:{schemaVersion:t.freshness.schemaVersion,kind:t.freshness.kind,category:t.freshness.category,ttlSeconds:t.freshness.ttlSeconds,verifyBeforeUse:t.freshness.verifyBeforeUse,sourceArtifact:t.freshness.sourceArtifact,sourcePath:t.freshness.sourcePath,inputsHash:t.freshness.inputsHash,reason:t.freshness.reason}}))}function E(e){let{runId:t,...r}=e,s={...r,generatedAt:"<ignored>",graph:e.graph?{...e.graph,generatedAt:"<ignored>"}:void 0,facts:ue(e),factFreshness:e.factFreshness?{schemaVersion:e.factFreshness.schemaVersion,totalFacts:e.factFreshness.totalFacts,liveFacts:e.factFreshness.liveFacts,verifyBeforeUseFacts:e.factFreshness.verifyBeforeUseFacts,byKind:e.factFreshness.byKind,byCategory:e.factFreshness.byCategory}:void 0,validation:e.validation?{...e.validation,issues:e.validation.issues.map(c=>({...c})).sort((c,o)=>{let i=`${c.severity}:${c.code}:${c.target}:${c.message}`,p=`${o.severity}:${o.code}:${o.target}:${o.message}`;return i.localeCompare(p)})}:void 0};return de.createHash("sha256").update(k(s)).digest("hex")}function te(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ge(e){let t=await y.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace model input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion===X){let s=r;if(!s.model||s.model.schemaVersion!==j)throw new Error(`Invalid workspace model snapshot: ${e}`);return {model:s.model,hash:s.modelHash||E(s.model)}}if(r.schemaVersion===j){let s=r;return {model:s,hash:E(s)}}throw r.schemaVersion===V?new Error(`workspace diff --from received a diff report (${m.basename(e)}). Use a workspace model snapshot or model report as baseline, e.g. ${$}. To analyze an existing diff report, run: npx workspai workspace impact --from ${m.basename(e)} --json`):new Error(`Unsupported workspace model input schema: ${String(r.schemaVersion)}`)}async function ke(e){let t=await y.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace diff input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==V)return null;let s=r;if(!s.currentModel||s.currentModel.schemaVersion!==j||!s.summary||!Array.isArray(s.changes))throw new Error(`Invalid workspace model diff report: ${e}`);return s}async function Ne(e){let t=e.model??await n({workspacePath:e.workspacePath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {schemaVersion:X,generatedAt:(e.now??new Date).toISOString(),modelHash:E(t),modelRef:k$1,model:t}}async function Be(e,t){let r=m.join(t,$);return await y.ensureDir(m.dirname(r)),await y.writeJson(r,a(e),{spaces:2}),r}function A(e){return {name:e.name,path:e.path,kind:e.kind,runtime:e.runtime,framework:e.framework,generator:e.generator,supportTier:e.supportTier,commands:e.commands,importantFiles:e.importantFiles}}function h(e,t){e.push(t);}function he(e,t){let r=[],s=["name","profile","type"],c=["workspaceType","surfaces","runtimeFamilies","businessCapabilities"];for(let o of s){let i=e.workspace[o],p=t.workspace[o];k(i)!==k(p)&&h(r,{type:"workspace.changed",severity:"info",target:`workspace.${o}`,message:`Workspace metadata field changed: ${String(o)}`,before:i,after:p});}for(let o of c){let i=e.identity[o],p=t.identity[o];k(i)!==k(p)&&h(r,{type:"workspace.changed",severity:"info",target:`identity.${o}`,message:`Workspace identity field changed: ${String(o)}`,before:i,after:p});}return k(e.policies)!==k(t.policies)&&h(r,{type:"workspace.changed",severity:"warning",target:"policies",message:"Workspace policy summary changed.",before:e.policies,after:t.policies}),k(e.evidence)!==k(t.evidence)&&h(r,{type:"workspace.changed",severity:"info",target:"evidence",message:"Workspace evidence summary changed.",before:e.evidence,after:t.evidence}),k(e.discovery)!==k(t.discovery)&&h(r,{type:"workspace.changed",severity:"info",target:"discovery",message:"Workspace discovery settings changed.",before:e.discovery,after:t.discovery}),e.contracts.exists!==t.contracts.exists&&h(r,{type:"workspace.changed",severity:t.contracts.exists?"info":"warning",target:t.contracts.workspaceContractPath,message:"Workspace contract presence changed.",before:e.contracts.exists,after:t.contracts.exists}),r}function we(e,t){let r=e.validation??null,s=t.validation??null;return k(r)===k(s)?[]:[{type:"validation.changed",severity:s?.status==="failed"?"critical":"warning",target:"validation",message:"Workspace model validation changed.",before:r,after:s}]}function ye(e,t){let r=[],s=new Map(e.projects.map(o=>[o.path,o])),c=new Map(t.projects.map(o=>[o.path,o]));for(let[o,i]of c.entries()){let p=s.get(o);if(!p){h(r,{type:"project.added",severity:"info",target:o,message:`Project added: ${i.name}`,after:A(i)});continue}let f=A(p),l=A(i);if(k(f)!==k(l)){let g=p.runtime!==i.runtime||p.framework!==i.framework;h(r,{type:"project.changed",severity:g?"warning":"info",target:o,message:`Project changed: ${i.name}`,before:f,after:l});}}for(let[o,i]of s.entries())c.has(o)||h(r,{type:"project.removed",severity:"warning",target:o,message:`Project removed: ${i.name}`,before:A(i)});return r.sort((o,i)=>`${o.type}:${o.target}`.localeCompare(`${i.type}:${i.target}`))}async function We(e){let t=m.resolve(e.workspacePath),r=ee(e.fromPath),s=r?me(e.fromPath):void 0,c=e.fromPath;if(r){let u=m.join(t,$);if(!await y.pathExists(u))throw new Error("Git-aware workspace diff requires an existing snapshot at .workspai/reports/workspace-model-snapshot.json. Run: npx workspai workspace snapshot --json");c=$;}let o=te(t,c),i=await ge(o),p=e.model??await n({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),f=E(p),l=[...he(i.model,p),...ye(i.model,p),...we(i.model,p)],g;e.includeGitObservation!==false&&(g=e.gitObservation??L(t,{ref:s}),g.available&&Me(l,g,p));let b=l.filter(u=>u.type.startsWith("git.")).length,C=i.hash!==f,W=r?`git:${s??"HEAD"}`:m.relative(t,o).split(m.sep).join("/");return {schemaVersion:V,generatedAt:(e.now??new Date).toISOString(),fromRef:W,toRef:k$1,fromHash:i.hash,toHash:f,summary:{changed:C||b>0,addedProjects:l.filter(u=>u.type==="project.added").length,removedProjects:l.filter(u=>u.type==="project.removed").length,changedProjects:l.filter(u=>u.type==="project.changed").length,workspaceChanges:l.filter(u=>u.type==="workspace.changed").length,validationChanges:l.filter(u=>u.type==="validation.changed").length,gitChangedFiles:b},git:g?.available?Pe(g,s):{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:l,currentModel:p}}async function Ke(e,t){let r=m.join(t,Z);return await y.ensureDir(m.dirname(r)),await y.writeJson(r,a(e),{spaces:2}),r}function P(e){return {none:0,low:1,medium:2,high:3,critical:4}[e]}function J(e){return e.reduce((t,r)=>P(r)>P(t)?r:t,"none")}var T=["none","low","medium","high","critical"];function ve(e){let t=Math.max(1,P(e)-1);return T[t]}function be(e){let t=Math.min(T.length-1,P(e)+1);return T[t]}function U(e){return e.join(" ")}function w(e,t,r,s){return {id:e,label:t,scope:s.scope,project:s.project,display:U(["npx","workspai",...r]),execute:U(["npx","--yes","--package","workspai","workspai",...r]),required:s.required!==false}}function Y(e){let t=`project:${e.name}`,r=e.commands.fleetStages;return [w(`project.${e.name}.init`,`Run init for ${e.name}`,["workspace","run","init","--scope",t,"--json"],{scope:"project",project:e.name,required:r.includes("init")}),w(`project.${e.name}.test`,`Run tests for ${e.name}`,["workspace","run","test","--scope",t,"--json"],{scope:"project",project:e.name,required:r.includes("test")}),w(`project.${e.name}.build`,`Run build for ${e.name}`,["workspace","run","build","--scope",t,"--json"],{scope:"project",project:e.name,required:r.includes("build")}),w(`project.${e.name}.start`,`Run start for ${e.name}`,["workspace","run","start","--scope",t,"--json"],{scope:"project",project:e.name,required:r.includes("start")})]}function D(){return [w("workspace.doctor","Run workspace doctor",["doctor","workspace","--json"],{scope:"workspace"}),w("workspace.contract.verify","Verify workspace contract",["workspace","contract","verify","--json"],{scope:"workspace"}),w("workspace.readiness","Run release readiness",["readiness","--json"],{scope:"workspace"}),w("workspace.analyze","Run workspace analyze",["analyze","--json"],{scope:"workspace",required:false}),w("workspace.pipeline","Run governance pipeline",["pipeline","--json"],{scope:"workspace",required:false}),w("workspace.doctor-fix","Verify doctor fix result",["doctor","workspace","--fix","--json"],{scope:"workspace",required:false})]}function je(e,t){let r=t.split(m.sep).join("/");return e.projects.filter(c=>{let o=c.path.split(m.sep).join("/");return r===o||r.startsWith(`${o}/`)}).sort((c,o)=>o.path.length-c.path.length)[0]}function Me(e,t,r){let s=new Set(e.map(o=>o.target)),c=(o,i)=>{let p=i.split(m.sep).join("/"),f=`git:${p}`;if(s.has(f))return;let l=je(r,p),g=l?`${l.name} (${l.path})`:"workspace";h(e,{type:o,severity:o==="git.deleted"?"warning":"info",target:f,message:`Git ${o==="git.untracked"?"untracked":o==="git.deleted"?"deleted":"changed"} file affects ${g}: ${p}`,after:{path:p,project:l?.name,projectPath:l?.path}}),s.add(f);};for(let o of t.changedFiles)c("git.file.changed",o);for(let o of t.untrackedFiles)c("git.untracked",o);for(let o of t.deletedFiles)c("git.deleted",o);}function Pe(e,t){return {available:true,ref:t??e.ref,branch:e.branch,commit:e.commit,dirty:e.dirty,changedFiles:e.changedFiles.length,untrackedFiles:e.untrackedFiles.length,deletedFiles:e.deletedFiles.length}}function Ie(e){let t=new Set,r=[];for(let s of e){let c=`${s.scope}:${s.project??""}:${s.display}`;t.has(c)||(t.add(c),r.push(s));}return r}function Ce(e){return e.type==="project.removed"?"high":e.severity==="critical"?"critical":e.severity==="warning"?"high":("medium")}function Re(e,t){return e.severity==="critical"?"critical":e.target==="policies"||e.target.includes("contract")?"high":e.type==="validation.changed"?(t?.projectCount??0)===0?"low":"high":e.target==="evidence"?"low":e.severity==="warning"?"medium":"low"}function Oe(e){return e.affectedProjects>0||e.projectCount>0||!e.changes.every(r=>r.severity==="critical"?false:r.type.startsWith("git.")||r.type==="validation.changed")?e.risk:P(e.risk)>=P("high")||e.risk==="medium"?"low":e.risk}function Q(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return [t.name,t.path,m.basename(t.path),t.absolutePath].filter(s=>typeof s=="string"&&s.trim().length>0).map(s=>s.trim().toLowerCase()).includes(r)}function Se(e){if(!e.changed)return {headline:"No workspace model impact detected.",bullets:["The current workspace model matches the provided snapshot/report."],unsafeAssumptions:["Do not claim runtime verification passed unless a report exists."]};let t=e.affectedProjects.map(r=>r.project?.name??r.target);return {headline:`Workspace impact risk: ${e.risk}.`,bullets:[`Affected projects: ${t.length?t.join(", "):"none"}.`,`Workspace-level items: ${e.workspaceImpact.length}.`,"Use the verification plan before recommending apply, rollback, or release actions."],unsafeAssumptions:["Do not infer test/build success from impact alone.","Do not apply fixes without project scope and verification evidence.","Use display commands for users and execute commands for automation."]}}async function qe(e){let t=m.resolve(e.workspacePath),r=ee(e.fromPath),s=e.diff;if(!s&&!r){let n=te(t,e.fromPath);s=await ke(n)??void 0;}s||(s=await We({workspacePath:t,fromPath:e.fromPath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,includeGitObservation:e.includeGitObservation,gitObservation:e.gitObservation,now:e.now,model:e.model}));let c$1=new Map(s.currentModel.projects.map(n=>[n.path,n])),o=new Map(s.currentModel.projects.map(n=>[n.name,n])),i=s.changes.filter(n=>n.type.startsWith("project.")),p=new Map;for(let n of i){let d=(c$1.get(n.target)??(typeof n.before?.name=="string"?o.get(n.before.name):void 0))?.path??n.target,v=p.get(d)??[];v.push(n),p.set(d,v);}let f=[];for(let[n,a]of p.entries()){let d=c$1.get(n);if(d&&!Q(e.scope,d))continue;let v=J(a.map(Ce)),R=d?.name??(typeof a[0]?.before?.name=="string"?String(a[0].before.name):n);f.push({id:`project:${R}`,scope:"project",target:n,title:`Project impact: ${R}`,summary:a.map(j=>j.message).join(" "),risk:v,reasons:a.map(j=>`${j.type}: ${j.message}`),project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?Y(d):D()});}let l=s.currentModel.graph,g=l?a$1(l):void 0,b=new Set(f.map(n=>n.project?.name).filter(n=>typeof n=="string")),C=new Map;for(let n of f)if(n.project?.name){let a=g?.byId.get(n.project.name);a&&(n.centrality={fanIn:a.fanIn,fanOut:a.fanOut,reach:a.reach,betweenness:a.betweenness,isHotspot:a.isHotspot},a.isHotspot&&(n.risk=be(n.risk),n.reasons=[...n.reasons,`graph.hotspot: critical-path project with ${a.reach} transitive dependent(s); risk escalated.`])),n.origin="direct",n.distance=0,C.set(n.project.name,n.risk);}let W=[],u=0;if(l&&b.size>0){let n=c(l,b);for(let a of n.values()){if(a.distance===0||b.has(a.id))continue;let d=o.get(a.id);if(d&&!Q(e.scope,d))continue;let v=a.path[0],R=a.path[a.path.length-2]??v,j=C.get(v)??"medium",oe=ve(j),M=g?.byId.get(a.id);u=Math.max(u,a.distance),W.push({id:`transitive:${a.id}`,scope:"project",target:d?.path??a.id,title:`Transitive impact: ${a.id}`,summary:`Depends on changed project ${v}${a.via?` via ${a.via}`:""} (distance ${a.distance}).`,risk:oe,reasons:[`graph.dependent: depends on ${R}${a.via?` via ${a.via}`:""} (path ${a.path.join(" -> ")})`],project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?Y(d):D(),origin:"transitive",distance:a.distance,path:a.path,via:a.via,...M?{centrality:{fanIn:M.fanIn,fanOut:M.fanOut,reach:M.reach,betweenness:M.betweenness,isHotspot:M.isHotspot}}:{}});}}W.sort((n,a)=>n.target.localeCompare(a.target));let re=g?g.hotspots.flatMap(n=>{let a=g.byId.get(n);return a?[{project:n,fanIn:a.fanIn,fanOut:a.fanOut,reach:a.reach,betweenness:a.betweenness}]:[]}):[],se=s.changes.filter(n=>!n.type.startsWith("project.")),G=s.currentModel.summary?.projectCount??s.currentModel.projects.length,I=se.map(n=>({id:`workspace:${n.target}`,scope:"workspace",target:n.target,title:`Workspace impact: ${n.target}`,summary:n.message,risk:Re(n,{projectCount:G}),reasons:[`${n.type}: ${n.message}`],verification:D()})),N=Ie([...f.flatMap(n=>n.verification),...W.flatMap(n=>n.verification),...I.flatMap(n=>n.verification),...s.summary.changed?D():[]]).filter(n=>n.required),ne=J([...f.map(n=>n.risk),...W.map(n=>n.risk),...I.map(n=>n.risk)]),B=Oe({risk:ne,affectedProjects:f.length,projectCount:G,changes:s.changes}),K={changed:s.summary.changed,risk:B,affectedProjects:f.length,workspaceItems:I.length,recommendedCommands:N.length,blastRadius:{directlyAffected:f.length,transitivelyAffected:W.length,maxDistance:u,graphEdges:l?.edges.length??0}};return {schemaVersion:le,generatedAt:(e.now??new Date).toISOString(),fromRef:s.fromRef,diffRef:Z,workspace:{name:s.currentModel.workspace.name,profile:s.currentModel.workspace.profile,type:s.currentModel.workspace.type},summary:K,affectedProjects:f.sort((n,a)=>n.target.localeCompare(a.target)),transitiveImpact:W,criticalPathHotspots:re,workspaceImpact:I.sort((n,a)=>n.target.localeCompare(a.target)),verificationPlan:N,agentBrief:Se({changed:K.changed,risk:B,affectedProjects:f,workspaceImpact:I}),diff:s}}async function ze(e,t){let r=m.join(t,fe);return await y.ensureDir(m.dirname(r)),await y.writeJson(r,a(e),{spaces:2}),r}export{X as a,V as b,$ as c,Z as d,le as e,fe as f,ee as g,me as h,Ne as i,Be as j,We as k,Ke as l,D as m,qe as n,ze as o};
@@ -1 +0,0 @@
1
- import {r,s}from'./chunk-5XATWNME.js';import a from'path';import s$1 from'fs-extra';function o(t,r$1){return a.join(t,r(r$1))}function f(t,r){return a.join(t,s(r))}async function x(t,r){let n=[o(t,r),f(t,r)];for(let i of n)if(await s$1.pathExists(i))return i;return null}async function P(t,r,n){let i=o(t,r);return await s$1.ensureDir(a.dirname(i)),await s$1.writeJson(i,n,{spaces:2}),i}async function d(t,r,n){let i=o(t,r);return await s$1.ensureDir(a.dirname(i)),await s$1.writeFile(i,n,"utf-8"),i}export{o as a,f as b,x as c,P as d,d as e};
@@ -1 +0,0 @@
1
- var c="doctor-workspace-evidence-v1",i="doctor-project-evidence-v1";function s(r){return !r||typeof r!="object"||Array.isArray(r)?null:r}function p(r,n){let t=s(r);if(!t)return false;let e=t.schemaVersion,o=t.evidenceType;return !(typeof e=="string"&&(e!==c&&e!==i||n==="workspace"&&e!==c||n==="project"&&e!==i)||typeof o=="string"&&(o!=="workspace"&&o!=="project"||n&&o!==n))}export{c as a,i as b,p as c};
@@ -1,9 +0,0 @@
1
- import {f as f$2,e}from'./chunk-T3GJ7YVG.js';import {a,b as b$1}from'./chunk-22DT744Z.js';import {h,i}from'./chunk-4KUIFXHM.js';import {e as e$1}from'./chunk-NAAQMSO3.js';import {a as a$1}from'./chunk-GZTYAEWX.js';import {f as f$1,o as o$1,p as p$1}from'./chunk-5XATWNME.js';import b from'fs';import p from'path';import o from'chalk';var _=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function D(e){try{return await b.promises.access(e,b.constants.F_OK),true}catch{return false}}async function x(e){try{let n=JSON.parse(await b.promises.readFile(e,"utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function J(e){try{return await b.promises.readFile(e,"utf-8")}catch{return ""}}function H(e){return a(e)}async function K(e,n){return await M([...p$1(e,"project.json"),...p$1(e,"context.json")])?true:b$1(e)?false:p.resolve(e)===p.resolve(n)?h(e).length>0:h(e).length>0}async function B(e){let n=await a$1(e,{skipDirs:_,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:K});return n.length>0?n:b$1(e)?[]:h(e).length>0?[e]:[]}function U(e,n){return p.relative(e,n).replace(/\\/g,"/")||"."}async function A(e,n){for(let t of n)if(await D(p.join(e,t)))return true;return false}async function M(e){for(let n of e)if(await D(n))return true;return false}async function T(e){for(let n of e){let t=await x(n);if(t)return t}return null}async function V(e){return A(e,["health","health.ts","health.js","health.py","health.go","health.kt","health.rb","health.php","healthcheck","health-check","src/health.ts","src/health.js","src/health.py","src/health.go","src/health.kt","src/health.rb","src/health.php","src/healthcheck.ts","src/healthcheck.js","src/liveness.ts","src/readiness.ts","src/ping.ts"])}async function L(e){if(await A(e,["tests","test","__tests__","src/__tests__","pytest.ini","vitest.config.ts","jest.config.ts"]))return true;let t=await x(p.join(e,"package.json")),r=t?.scripts&&typeof t.scripts=="object"?t.scripts:{};return typeof r.test=="string"&&r.test.trim().length>0}async function q(e){let n=await x(p.join(e,"package.json")),t=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return Object.keys(t).sort()}function f(e,n,t,r,s,a){return {id:e,severity:n,target:t,title:r,detail:s,remediation:a}}function Q(e){let n=e.reduce((t,r)=>r.severity==="fail"?t+28:r.severity==="warn"?t+12:t+3,0);return Math.max(0,100-n)}async function X(e,n){let t=await T(p$1(n,"project.json")),r=i(n,t),s=h(n),a=r.runtime==="unknown"?s[0]||"unknown":r.runtime,i$1=U(e,n),l=i$1,g=await q(n),m=await M([...p$1(n,"project.json"),...p$1(n,"context.json")]),d=await L(n),h$1=await A(n,["Dockerfile","dockerfile"]),k=await A(n,[".env.example","env.example","config/env.example"]),z=await A(n,[".github/workflows/ci.yml",".github/workflows/ci.yaml",".github/workflows/main.yml",".github/workflows/build.yml",".github/workflows/test.yml",".github/workflows/deploy.yml",".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml"]),P=await V(n),u=[];return r.key==="unknown"&&u.push(f("project.stack.unknown","fail",l,"Project stack is unknown","Workspai cannot confidently classify this backend project.","Add .workspai/project.json metadata or import the project with `workspai import`.")),m||u.push(f("project.marker.missing","warn",l,"Workspai marker is missing","The project can be detected by files, but it is not registered with Workspai metadata.","Run `workspai import <path>` from a workspace or create the project through Workspai.")),d||u.push(f("project.tests.missing","warn",l,"Test entrypoint is missing","No common test folder, config, or package test script was found.","Add a test command so `workspai workspace run test --affected` can gate changes.")),k||u.push(f("project.env.example.missing","info",l,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.")),z||u.push(f("project.ci.missing","warn",l,"Continuous integration is missing","No recognized CI/CD configuration file was detected for this project.","Add CI configuration so tests and checks run automatically for every change.")),P||u.push(f("project.health.missing","info",l,"Health or readiness probe is missing","The project has no obvious health or readiness endpoint to support automated deployment and runtime checks.","Add a simple health endpoint and document it for readiness gates and observability.")),h$1||u.push(f("project.container.missing","info",l,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.")),{name:p.basename(n),path:n,relativePath:i$1,runtime:a,framework:r.key,confidence:r.confidence,supportTier:r.supportTier,hasRapidKitMarker:m,hasTests:d,hasDockerfile:h$1,hasEnvExample:k,hasCiConfig:z,hasHealthEndpoint:P,scripts:g,findings:u,score:Q(u)}}function Y(e){return e.name.toLowerCase()}async function Z(e){let n=new Map(e.map(s=>[Y(s),s])),t=[];for(let s of e){let a=await x(p.join(s.path,"package.json")),i={...a?.dependencies??{},...a?.devDependencies??{},...a?.peerDependencies??{}};for(let g of Object.keys(i)){let m=g.replace(/^@[^/]+\//,"").toLowerCase(),d=n.get(m);d&&d.relativePath!==s.relativePath&&t.push({from:s.relativePath,to:d.relativePath,kind:"package"});}let l=await J(p.join(s.path,"pyproject.toml"));for(let g of e)g.relativePath!==s.relativePath&&l.includes(g.name)&&t.push({from:s.relativePath,to:g.relativePath,kind:"workspace-reference"});}let r=new Set;return t.filter(s=>{let a=`${s.from}\0${s.to}\0${s.kind}`;return r.has(a)?false:(r.add(a),true)})}function ee(e,n){let t=new Map;for(let r of e)t.set(r.relativePath,{project:r.relativePath,directDependents:0,directDependencies:0});for(let r of n){let s=t.get(r.from),a=t.get(r.to);s&&(s.directDependencies+=1),a&&(a.directDependents+=1);}return Array.from(t.values()).sort((r,s)=>s.directDependents-r.directDependents||s.directDependencies-r.directDependencies)}async function ne(e){let n=await T(o$1(e,"workspace.json"));return typeof n?.profile=="string"?n.profile:null}function te(e){return {fail:e.filter(n=>n.severity==="fail").length,warn:e.filter(n=>n.severity==="warn").length,info:e.filter(n=>n.severity==="info").length}}function re(e){if(e.projectCount===0)return e.workspaceDetected?["Add your first project: npx workspai create project <name> --kit <kit>","Import an existing service: npx workspai import <path>"]:["Create a Workspai workspace: npx workspai create workspace my-workspace --profile polyglot","Import an existing service: npx workspai import ../service"];let n=[];return e.findings.some(t=>t.id==="workspace.marker.missing")&&n.push("Initialize workspace metadata with `workspai bootstrap --profile polyglot`."),e.findings.some(t=>t.id==="project.marker.missing")&&n.push("Register detected projects with `workspai import <path>` or recreate them via `workspai create project`."),e.findings.some(t=>t.id==="project.tests.missing")&&n.push("Add test entrypoints, then gate changes with `workspai workspace run test --affected --strict`."),e.findings.some(t=>t.id==="project.ci.missing")&&n.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(t=>t.id==="project.health.missing")&&n.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasGraph||n.push("Create `.workspai/workspace-dependency-graph.json` or use analyze output as the first graph seed."),n.push("Run `workspai autopilot release --mode audit --json` before release."),Array.from(new Set(n))}async function fe(e$2={}){let n=p.resolve(e$2.workspacePath||process.cwd());if(!await D(n))throw new Error(`Workspace path does not exist: ${n}`);let t=H(n)??n,r=f$1(t),s=await ne(t),a=await B(t),i=await Promise.all(a.map(c=>X(t,c))),l=await Z(i),g=ee(i,l),m=[];r||m.push(f("workspace.marker.missing","warn",".","Workspace metadata is missing","The directory can be analyzed, but it is not a registered Workspai workspace.","Run `workspai create workspace` or `workspai bootstrap --profile polyglot` in a workspace root.")),i.length===0&&m.push(f("workspace.projects.missing","warn",".","No backend projects detected","Workspai did not find runtime markers or project metadata under this root.","Create a project with `workspai create project` or import one with `workspai import <path>`."));let d=[...m,...i.flatMap(c=>c.findings)],h=te(d),k={};for(let c of i)k[c.runtime]=(k[c.runtime]||0)+1;let z=i.length>0?Math.round(i.reduce((c,y)=>c+y.score,0)/i.length):0,P=m.reduce((c,y)=>c+(y.severity==="fail"?20:y.severity==="warn"?8:2),0),u=Math.max(0,z-P),O=i.length===0&&h.fail===0&&d.length>0&&d.every(c=>c.id==="workspace.projects.missing"&&c.severity==="warn"),N=h.fail>0||e$2.strict&&h.warn>0&&!O?"blocked":h.warn>0?"needs-attention":"ready",w={schemaVersion:"rapidkit-analyze-v1",generatedAt:new Date().toISOString(),workspacePath:t,workspaceDetected:r,profile:s,summary:{score:u,verdict:N,projectCount:i.length,runtimeCount:Object.keys(k).length,findings:h},runtimes:k,projects:i,dependencyGraph:{status:l.length>0?"generated":"empty",edges:l,topImpactedProjects:g.slice(0,5)},findings:d,nextActions:re({findings:d,projectCount:i.length,hasGraph:l.length>0,workspaceDetected:r}),enterpriseControls:{jsonReady:true,ciGateCommand:"workspai analyze --json --strict",releaseGateCommand:"workspai autopilot release --mode enforce --json",evidencePath:".workspai/reports/analyze-last-run.json"}};if(e$2.output&&(await b.promises.mkdir(p.dirname(p.resolve(e$2.output)),{recursive:true}),await b.promises.writeFile(p.resolve(e$2.output),`${JSON.stringify(w,null,2)}
2
- `)),!e$2.output&&r){let c=f$2(w,{commandId:"workspaceAnalyze",exitCode:w.summary.verdict==="blocked"?2:w.summary.verdict==="needs-attention"?1:0,generatedAt:w.generatedAt,blockers:w.findings.filter(y=>y.severity==="fail").map(y=>y.title).slice(0,12),runId:e()});await e$1(t,".workspai/reports/analyze-last-run.json",`${JSON.stringify(c,null,2)}
3
- `);}return w}function he(e){let n=e.summary.verdict==="ready"?o.green:e.summary.verdict==="needs-attention"?o.yellow:o.red;if(console.log(o.bold(`
4
- Workspai Workspace Analysis
5
- `)),console.log(o.cyan("Workspace:"),e.workspacePath),console.log(o.cyan("Profile:"),e.profile||"not configured"),console.log(o.cyan("Score:"),`${e.summary.score}/100`),console.log(o.cyan("Verdict:"),n(e.summary.verdict)),console.log(o.gray(`Projects: ${e.summary.projectCount}, runtimes: ${e.summary.runtimeCount}, findings: ${e.summary.findings.fail} fail / ${e.summary.findings.warn} warn / ${e.summary.findings.info} info`)),e.projects.length>0){console.log(o.bold(`
6
- Projects`));for(let t of e.projects){let r=t.score>=85?o.green("pass"):t.score>=65?o.yellow("watch"):o.red("risk");console.log(` ${t.relativePath} ${o.gray(`${t.runtime}/${t.framework}`)} ${r} ${t.score}/100`);}}if(e.dependencyGraph.status==="generated"&&(console.log(o.bold(`
7
- Dependency Graph`)),console.log(o.gray(` edges: ${e.dependencyGraph.edges.length}`)),e.dependencyGraph.topImpactedProjects.length>0)){console.log(o.gray(" Top impacted projects:"));for(let t of e.dependencyGraph.topImpactedProjects.slice(0,3))console.log(` ${t.project} (${t.directDependents} dependents, ${t.directDependencies} dependencies)`);}if(e.findings.length>0){console.log(o.bold(`
8
- Top Findings`));for(let t of e.findings.slice(0,8)){let r=t.severity==="fail"?o.red:t.severity==="warn"?o.yellow:o.gray;console.log(` ${r(t.severity.toUpperCase())} ${t.target}: ${t.title}`),console.log(o.gray(` ${t.remediation}`));}}console.log(o.bold(`
9
- Next Actions`));for(let t of e.nextActions.slice(0,5))console.log(o.gray(` - ${t}`));console.log();}export{fe as a,he as b};
@@ -1,7 +0,0 @@
1
- import {a as a$1}from'./chunk-WU4ZRRA5.js';import {a as a$3}from'./chunk-22DT744Z.js';import {a as a$2,e}from'./chunk-753LOKFZ.js';import {c,a,d}from'./chunk-NAAQMSO3.js';import l from'chalk';import ee from'fs';import b from'path';import {execa}from'execa';var O="autopilot-release-last-run.json",K="autopilot-release.json";function $(s){try{return JSON.parse(s)}catch{return null}}function ke(s){let e=b.resolve(s),a=a$3(e);if(!a)throw new Error("No Workspai workspace found in current directory or parents");return a}async function S(s,e){let a=process.argv[1];if(!a)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for autopilot execution.",crashed:true};try{let o=await execa(process.execPath,[a,...s],{cwd:e,reject:false,env:{...process.env,RAPIDKIT_AUTOPILOT_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr,crashed:false}}catch(o){return {exitCode:1,stdout:"",stderr:o instanceof Error?o.message:String(o),crashed:true}}}function te(s){let e=s.toLowerCase();return e==="pass"?"pass":e==="warn"?"warn":e==="fail"?"fail":"warn"}function se(s){return s.summary.failed>0||s.gates.results.some(e=>e.status==="fail")?"fail":s.gates.results.some(e=>e.status==="warn")?"warn":"pass"}function he(s){let e=s.filter(o=>o.status!=="skipped");if(e.length===0)return 100;let a=e.reduce((o,t)=>t.status==="pass"?o+1:t.status==="warn"?o+.6:o,0);return Math.round(a/e.length*100)}function ye(s){return s.executionError?["Re-run: npx workspai autopilot release --mode audit --json","Inspect .workspai/reports/autopilot-release-last-run.json for execution failure details"]:s.blockers.length>0?["Run: npx workspai doctor workspace --plan","Run: npx workspai readiness --json --strict","Run: npx workspai workspace run test --affected --strict"]:s.hasWarnings&&s.mode!=="enforce"?["Review warning-level findings in autopilot report","Optionally run: npx workspai autopilot release --mode safe-fix"]:["Workspace is release-ready based on current autopilot policy"]}async function Re(s,e){await ee.promises.mkdir(b.dirname(s),{recursive:true}),await ee.promises.writeFile(s,`${JSON.stringify(e,null,2)}
2
- `,"utf-8");}async function De(s){let e$1=ke(s.workspacePath),a$3=s.mode,o=[],t=[],I,G,C,V,H,q=0,f=false,T=0,L=0,D=-1,N=-1,c$1="skipped",u="skipped",re=a$3==="enforce"?["doctor","workspace","--json","--strict"]:["doctor","workspace","--json","--ci"];if(s.skipPipelineStages)o.push({name:"doctor-workspace",status:"skipped",durationMs:0,summary:"doctor stage skipped (pipeline already executed)"},{name:"analyze",status:"skipped",durationMs:0,summary:"analyze stage skipped (pipeline already executed)"},{name:"readiness",status:"skipped",durationMs:0,summary:"readiness stage skipped (pipeline already executed)"});else {let r=Date.now(),i=await S([...re],e$1),m=Date.now()-r;if(c$1="pass",i.crashed)c$1="fail",f=true,t.push(`doctor workspace execution error: ${i.stderr||"unknown error"}`);else if(i.exitCode===1)c$1="fail",t.push("doctor workspace command failed or reported errors");else if(i.exitCode===2)c$1="warn",t.push("doctor workspace reported warnings");else if(i.exitCode!==0)c$1="fail",t.push("doctor workspace command failed");else {let p=$(i.stdout),j=p&&p.healthScore&&typeof p.healthScore=="object"?p.healthScore:{},h=Number(j.errors??0),E=Number(j.warnings??0);Number.isFinite(h)&&h>0?(c$1="fail",t.push(`doctor workspace reports ${h} error(s)`)):Number.isFinite(E)&&E>0&&(c$1="warn");}D=o.push({name:"doctor-workspace",status:c$1,durationMs:m,summary:c$1==="pass"?"doctor workspace passed":c$1==="warn"?"doctor workspace reported warnings":"doctor workspace reported errors"})-1,a$3==="enforce"&&c$1==="warn"&&t.push("doctor workspace reported warnings under enforce mode");let w=Date.now(),g=await S(["analyze","--json"],e$1),v=Date.now()-w;G=await c(e$1,".workspai/reports/analyze-last-run.json")??a(e$1,".workspai/reports/analyze-last-run.json");let n="pass";if(g.crashed)n="fail",f=true,t.push(`analyze execution error: ${g.stderr||"unknown error"}`);else if(g.exitCode!==0)n=g.exitCode===2?"warn":"fail",t.push(g.exitCode===2?"analyze reported needs-attention verdict":"analyze command failed or reported blocked verdict");else {let p=$(g.stdout),j=p&&p.summary&&typeof p.summary=="object"?p.summary:{},h=String(j.verdict??"ready");h==="blocked"?(n="fail",t.push("analyze reported blocked verdict")):h==="needs-attention"&&(n="warn");}o.push({name:"analyze",status:n,durationMs:v,summary:n==="pass"?"analyze passed":n==="warn"?"analyze reported needs-attention":"analyze reported blocked verdict"}),a$3==="enforce"&&n==="warn"&&t.push("analyze reported warnings under enforce mode");let P=Date.now(),k=await S(["readiness","--json"],e$1),y=Date.now()-P;if(u="fail",k.crashed)u="fail",f=true,t.push(`readiness execution error: ${k.stderr||"unknown error"}`);else if(k.exitCode!==0)u="fail",t.push("readiness command failed");else {let p=$(k.stdout),j=String(p?.overallStatus??"fail");if(u=te(j),typeof p?.evidencePath=="string"&&p.evidencePath.trim().length>0&&(I=p.evidencePath),u==="fail"){let h=Array.isArray(p?.blockingReasons)?p?.blockingReasons.filter(E=>typeof E=="string"):[];h.length>0?t.push(...h.map(E=>`readiness: ${E}`)):t.push("readiness overall status is fail");}}N=o.push({name:"readiness",status:u,durationMs:y,summary:`readiness overall status is ${u}`})-1,a$3==="enforce"&&u==="warn"&&t.push("readiness reported warnings under enforce mode");}let oe=Date.now(),W=await S(["doctor","workspace","--plan","--json"],e$1),ae=Date.now()-oe,R="warn";if(W.crashed)R="fail",f=true,t.push(`doctor remediation plan execution error: ${W.stderr||"unknown error"}`);else if(W.exitCode!==0)R="fail",t.push("doctor remediation plan command failed");else {let r=$(W.stdout),i=r&&r.remediationPlan&&typeof r.remediationPlan=="object"?r.remediationPlan:null,m=Number(i?.totalSteps??0),w=Number(i?.executableSteps??0);Number.isFinite(m)&&m>0&&(T=m),Number.isFinite(w)&&w>0&&(L=w),Number.isFinite(m)&&m===0?R="pass":R="warn";}if(o.push({name:"remediation-plan",status:R,durationMs:ae,summary:R==="pass"?"no remediation steps required":"remediation steps available"}),a$3==="enforce"&&R==="warn"&&t.push("remediation plan has pending steps under enforce mode"),a$3==="safe-fix"){let r=Date.now(),i=await S(["doctor","workspace","--apply"],e$1),m=Date.now()-r,w=i.crashed||i.exitCode!==0?"fail":"pass";if(i.crashed)f=true,t.push(`doctor remediation apply execution error: ${i.stderr||"unknown error"}`);else if(w==="fail")t.push("doctor remediation apply failed");else {q=L>0?L:T>0?T:1;let g=await S(["doctor","workspace","--json"],e$1);if(g.crashed)c$1="fail",f=true,t.push(`post-apply doctor execution error: ${g.stderr||"unknown error"}`);else if(g.exitCode!==0)c$1="fail",t.push("post-apply doctor workspace command failed");else {let n=$(g.stdout),P=n&&n.healthScore&&typeof n.healthScore=="object"?n.healthScore:{},k=Number(P.errors??0),y=Number(P.warnings??0);Number.isFinite(k)&&k>0?(c$1="fail",t.push(`post-apply doctor reports ${k} error(s)`)):Number.isFinite(y)&&y>0?c$1="warn":c$1="pass";}D>=0&&(o[D].status=c$1,o[D].summary=`doctor workspace post-apply status is ${c$1}`);let v=await S(["readiness","--json"],e$1);if(v.crashed)u="fail",f=true,t.push(`post-apply readiness execution error: ${v.stderr||"unknown error"}`);else if(v.exitCode!==0)u="fail",t.push("post-apply readiness command failed");else {let n=$(v.stdout),P=String(n?.overallStatus??"fail");if(u=te(P),typeof n?.evidencePath=="string"&&n.evidencePath.trim().length>0&&(I=n.evidencePath),u==="fail"){let k=Array.isArray(n?.blockingReasons)?n?.blockingReasons.filter(y=>typeof y=="string"):[];k.length>0?t.push(...k.map(y=>`post-apply readiness: ${y}`)):t.push("post-apply readiness overall status is fail");}}N>=0&&(o[N].status=u,o[N].summary=`readiness post-apply overall status is ${u}`);}o.push({name:"remediation-apply",status:w,durationMs:m,summary:w==="pass"?"safe remediation apply completed":"safe remediation apply failed"});}else o.push({name:"remediation-apply",status:"skipped",durationMs:0,summary:"remediation apply is skipped for this mode"});let ne=Date.now(),x="pass",A="workspace test/build completed for selected projects";try{let r=await a$1({workspacePath:e$1,stage:"test",affected:true,since:s.since,parallel:s.parallel,maxWorkers:s.maxWorkers,strict:true,json:true,enforceGates:false});C=a(e$1,b.join(".workspai","reports",a$2)),await e(e$1,r),V=C;let i=se(r);if(i==="fail")x="fail",A="workspace test stage failed for selected projects",t.push("workspace run test failed for selected projects");else {i==="warn"&&(x="warn",A="workspace test stage completed with warnings",a$3==="enforce"&&t.push("workspace run test reported warnings under enforce mode"));let m=await a$1({workspacePath:e$1,stage:"build",affected:true,since:s.since,parallel:s.parallel,maxWorkers:s.maxWorkers,strict:true,json:true,enforceGates:false});await e(e$1,m),H=C;let w=se(m);w==="fail"?(x="fail",A="workspace build stage failed for selected projects",t.push("workspace run build failed for selected projects")):w==="warn"&&(x="warn",A="workspace test/build completed with warnings",a$3==="enforce"&&t.push("workspace run test/build reported warnings under enforce mode"));}}catch(r){x="fail",A="workspace test/build orchestration failed",f=true,t.push(`workspace run orchestration error: ${r instanceof Error?r.message:String(r)}`);}let ie=Date.now()-ne;o.push({name:"workspace-run-test-build",status:x,durationMs:ie,summary:A});let z=o.filter(r=>r.status==="warn").length,le=o.filter(r=>r.status==="fail").length,_=a$3==="enforce"?o.some(r=>r.status==="warn"||r.status==="fail"):le>0,M=[...new Set(t)],ce=f||_?Math.max(1,M.length):0,pe=he(o),ue=f||_?"blocked":z>0?"partial":"approved",de=f?3:_?1:z>0?2:0,fe=ye({mode:a$3,executionError:f,blockers:M,hasWarnings:z>0}),Q=a(e$1,".workspai/reports"),me=b.join(Q,O),we=b.join(Q,K),d$1={schemaVersion:"autopilot-release-v1",generatedAt:new Date().toISOString(),workspacePath:e$1,mode:a$3,summary:{releaseScore:pe,verdict:ue,blockers:ce,warnings:z,safeFixesApplied:q,manualActions:M.length,exitCode:de},stages:o,blockingReasons:M,nextActions:fe,artifacts:{reportPath:me,aliasEvidencePath:we,analyzeEvidencePath:G,readinessEvidencePath:I,workspaceRunEvidencePath:C,workspaceRunTestPath:V,workspaceRunBuildPath:H},enterpriseControls:{jsonReady:true,evidencePath:`.workspai/reports/${O}`,aliasEvidencePath:`.workspai/reports/${K}`}};if(await d(e$1,`.workspai/reports/${O}`,d$1),await d(e$1,`.workspai/reports/${K}`,d$1),s.output&&await Re(b.resolve(s.output),d$1),!s.json){console.log(l.bold.cyan(`
3
- \u{1F680} Workspai Autopilot Release
4
- `)),console.log(l.bold(`Workspace: ${l.cyan(b.basename(e$1))}`)),console.log(l.gray(`Path: ${e$1}`)),console.log(l.white(`Mode: ${a$3}`)),console.log(l.white(`Verdict: ${d$1.summary.verdict==="approved"?l.green("approved"):d$1.summary.verdict==="partial"?l.yellow("partial"):l.red("blocked")}`)),console.log(l.white(`Release score: ${d$1.summary.releaseScore}`));for(let r of d$1.stages){let i=r.status==="pass"?l.green("PASS"):r.status==="warn"?l.yellow("WARN"):r.status==="skipped"?l.gray("SKIP"):l.red("FAIL");console.log(` - ${r.name}: ${i} ${r.summary} (${r.durationMs}ms)`);}if(d$1.blockingReasons.length>0){console.log(l.bold.red(`
5
- Blocking reasons:`));for(let r of d$1.blockingReasons)console.log(l.red(` - ${r}`));}if(d$1.nextActions.length>0){console.log(l.bold(`
6
- Next actions:`));for(let r of d$1.nextActions)console.log(l.gray(` - ${r}`));}console.log(l.gray(`
7
- Report: ${d$1.artifacts.reportPath}`));}return d$1}export{O as a,K as b,De as c};
@@ -1 +0,0 @@
1
- import {c as c$1,d}from'./chunk-NAAQMSO3.js';import l from'fs-extra';var c="workspace-intelligence-history.v1",f=".workspai/reports/workspace-intelligence-history.json",p=50;function u(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return typeof e.generatedAt!="string"?null:e.kind==="agent-action"?typeof e.actionId!="string"||typeof e.summary!="string"||e.outcome!=="ok"&&e.outcome!=="failed"?null:{kind:"agent-action",generatedAt:e.generatedAt,actionId:e.actionId,scope:typeof e.scope=="string"?e.scope:"workspace",summary:e.summary,outcome:e.outcome,...typeof e.evidenceSha256=="string"?{evidenceSha256:e.evidenceSha256}:{}}:e.kind==="doctor-fix"?e.scope!=="workspace"&&e.scope!=="project"||typeof e.summary!="string"||e.outcome!=="ok"&&e.outcome!=="failed"?null:{kind:"doctor-fix",generatedAt:e.generatedAt,scope:e.scope,summary:e.summary,outcome:e.outcome,applied:typeof e.applied=="number"?e.applied:0,failed:typeof e.failed=="number"?e.failed:0,skipped:typeof e.skipped=="number"?e.skipped:0,remainingBlockers:typeof e.remainingBlockers=="number"?e.remainingBlockers:0}:typeof e.verdict!="string"||typeof e.risk!="string"||typeof e.gatePassed!="boolean"?null:{kind:"verify",generatedAt:e.generatedAt,verdict:e.verdict,risk:String(e.risk),affectedProjects:typeof e.affectedProjects=="number"?e.affectedProjects:0,freshness:e.freshness??"unknown",gatePassed:e.gatePassed,blockingReasons:typeof e.blockingReasons=="number"?e.blockingReasons:0,policyViolations:typeof e.policyViolations=="number"?e.policyViolations:0}}function W(t,e){return {kind:"verify",generatedAt:t.generatedAt,verdict:t.summary.verdict,risk:t.impact.risk,affectedProjects:t.impact.affectedProjects,freshness:t.freshness.verdict,gatePassed:e,blockingReasons:t.blockingReasons.length,policyViolations:t.policyViolations.length}}function H(t){return {kind:"agent-action",generatedAt:t.generatedAt,actionId:t.actionId,scope:t.scope,summary:t.summary,outcome:t.outcome,...t.evidenceSha256?{evidenceSha256:t.evidenceSha256}:{}}}function b(t,e){let r=t.appliedFixes.filter(i=>i.outcome==="applied").length,o=t.appliedFixes.filter(i=>i.outcome==="failed").length,n=t.appliedFixes.filter(i=>i.outcome==="skipped").length,s=t.appliedFixes.filter(i=>i.outcome==="guidance").length,a=t.remainingBlockers.length,m=o>0||a>0?"failed":"ok";return {kind:"doctor-fix",generatedAt:t.generatedAt,scope:e,summary:`${r} applied, ${o} failed, ${n} skipped, ${s} guidance, ${a} blocker(s) remaining`,outcome:m,applied:r,failed:o,skipped:n,remainingBlockers:a}}async function k(t){let e=await c$1(t,f);try{if(!e||!await l.pathExists(e))return null;let r=await l.readJson(e);return r?.schemaVersion!==c||!Array.isArray(r.entries)?null:{schemaVersion:c,retention:typeof r.retention=="number"?r.retention:p,entries:r.entries.map(o=>u(o)).filter(o=>o!=null)}}catch{return null}}function g(t,e,r=p){let o=Math.max(1,Math.floor(r)),n=[...t?.entries??[],e],s=n.slice(Math.max(0,n.length-o));return {schemaVersion:c,retention:o,entries:s}}async function R(t,e,r){let o=await k(t),n=g(o,e,r?.retention??p);return await d(t,f,n),n}export{c as a,f as b,p as c,u as d,W as e,H as f,b as g,k as h,g as i,R as j};
@@ -1,2 +0,0 @@
1
- import {a as a$1,d,c}from'./chunk-NAAQMSO3.js';import {l}from'./chunk-OCGZNSOE.js';import {e}from'./chunk-RO73VVHW.js';import {a}from'./chunk-XZGVNGRB.js';import {p,o}from'./chunk-5XATWNME.js';import u from'path';import h from'fs-extra';var D="unknown-run";function O(e$1){let r=e();return !r||r===D?e$1:{...e$1,runId:r}}var m=".workspai/workspace.contract.json",M=".workspai/reports/workspace-contract-verify-last-run.json",w=1,F="workspace-contract-verify.v1";function _(e){return e.replace(/\\/g,"/")}function E(e){let r=_(e).trim();return !r||r.startsWith("/")||r.startsWith("~")||/^[a-zA-Z]:\//.test(r)||r.includes("\0")?false:!r.split("/").filter(Boolean).some(o=>o===".."||o===".")}function G(e,r){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||r}function K(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0):[]}async function W(e){for(let r of e)if(await h.pathExists(r))return r;return null}async function z(e){for(let r of o(e,"workspace.json"))try{let o=await h.readJson(r);return {name:typeof o.workspace_name=="string"&&o.workspace_name.trim()||typeof o.name=="string"&&o.name.trim()||u.basename(e),profile:typeof o.profile=="string"?o.profile:void 0}}catch{}return {name:u.basename(e)}}async function H(e){let r=[],o=[e],n=new Set,c=new Set([".git","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;o.length>0;){let a=o.shift();if(!a||n.has(a))continue;n.add(a);let i=await W(p(a,"project.json")),l=await W(p(a,"context.json"));if(i||l){r.push(i??l??"");continue}let t;try{t=await h.readdir(a,{withFileTypes:true});}catch{continue}for(let s of t)!s.isDirectory()||c.has(s.name)||o.push(u.join(a,s.name));}return r.sort()}function L(e){let r=(e||"").toLowerCase();if(r.includes("fastapi"))return "fastapi";if(r.includes("nestjs"))return "nestjs";if(r.includes("springboot"))return "springboot";if(r.includes("gofiber"))return "fiber";if(r.includes("gogin"))return "gin"}function B(e,r){let o=(e||"").toLowerCase(),n=(r||"").toLowerCase();return o.includes("fastapi")?8e3:o.includes("nestjs")?3e3:o.includes("springboot")?8080:o.includes("gofiber")?3e3:o.includes("gogin")?8080:n==="node"?3e3:n==="python"?8e3:n==="java"||n==="go"?8080:null}function U(e,r){let o=e;for(;r.has(o)&&o<65535;)o+=1;return o}function A(e,r,o){let n=B(r.kit,r.runtime),c=e?.ports||[],a=c.length>0?c:n?[{name:"http",port:U(n,o),protocol:"http"}]:[];for(let t of a)o.add(t.port);let i={...r,...e,slug:e?.slug||r.slug,relativePath:e?.relativePath&&E(e.relativePath)?e.relativePath:r.relativePath,source:e?.source||r.source,relationship:e?.relationship||r.relationship,externalPath:e?.externalPath||r.externalPath,runtime:e?.runtime||r.runtime,framework:e?.framework||r.framework,kit:e?.kit||r.kit,modules:e?.modules?.length?e.modules:r.modules,ports:a,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||[]}},l=JSON.stringify(e||null)!==JSON.stringify(i);return {project:i,changed:l}}async function V(e){let r=u.resolve(e.workspacePath),o=await z(r),n=await H(r),c=await a(r),a$1=[];for(let t of c){let s=u.resolve(t.path),p$1=await W(p(s,"project.json"))??await W(p(s,"context.json"));!p$1||n.some(g=>u.resolve(g)===u.resolve(p$1))||a$1.push({projectJsonPath:p$1,registryEntry:t});}let i=[],l=[...n.map(t=>({projectJsonPath:t})),...a$1];for(let{projectJsonPath:t,registryEntry:s}of l){let p=u.dirname(u.dirname(t)),g=_(u.relative(r,p)),C=s!==void 0&&!E(g),y=G(s?.name||u.basename(p),u.basename(p)),d=C?`external/${y}`:g||y,f=await h.readJson(t),k=typeof f.kit_name=="string"&&f.kit_name||typeof f.kit=="string"&&f.kit||void 0,I=typeof f.framework=="string"&&f.framework||L(k);i.push({slug:s?.name||d||u.basename(p),relativePath:d,source:s?.source??"workspace",relationship:s?.relationship,externalPath:C?p:void 0,runtime:typeof f.runtime=="string"?f.runtime:void 0,framework:I,kit:k,modules:K(f.modules),ports:[],contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}return {schemaVersion:w,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:o,projects:i}}async function at(e){let r=u.resolve(e.outputPath||a$1(e.workspacePath,m));if(await h.pathExists(r)&&e.force!==true)throw new Error(`Workspace contract already exists: ${r}. Use --force to overwrite.`);let o=await V({workspacePath:e.workspacePath,now:e.now}),n=new Set,c={...o,projects:o.projects.map(i=>A(void 0,i,n).project)};e.outputPath?(await h.ensureDir(u.dirname(r)),await h.writeJson(r,c,{spaces:2})):await d(e.workspacePath,m,c);let{publishWorkspaceRegistrySummary:a}=await import('./workspace-registry-summary-RUJE6RPH.js');return await a(e.workspacePath,{now:e.now}),{contractPath:r,contract:c}}async function ct(e){let r=u.resolve(e.workspacePath),o=a$1(r,m),n=await c(r,m)??o,c$1=await V({workspacePath:r,now:e.now}),a=await h.pathExists(n)?await h.readJson(n):null,i=new Map((a?.projects||[]).map(d=>[d.slug,d])),l=new Set,t=[],s=[],p=[];for(let d of c$1.projects){let f=i.get(d.slug),k=A(f,d,l);f?k.changed&&s.push(d.slug):t.push(d.slug),p.push(k.project),i.delete(d.slug);}for(let d of i.values()){let f=A(d,d,l);p.push(f.project);}let g={schemaVersion:w,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...c$1.workspace,...a?.workspace||{},name:a?.workspace?.name||c$1.workspace.name},projects:p.sort((d,f)=>d.slug.localeCompare(f.slug))};await d(r,m,g);let C=await Y({workspacePath:r}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-RUJE6RPH.js');return await y(r,{now:e.now}),{contractPath:o,contract:g,addedProjects:t,updatedProjects:s,verification:C}}async function N(e){let r=e.contractPath??(await c(e.workspacePath,m)||a$1(e.workspacePath,m)),o=await h.readJson(r);return {contractPath:r,contract:o}}async function it(e){let{contractPath:r,contract:o}=await N(e),n=o.projects.map(t=>({id:t.slug,label:t.slug,relativePath:t.relativePath,source:t.source,relationship:t.relationship,externalPath:t.externalPath,runtime:t.runtime,framework:t.framework,kit:t.kit,modules:t.modules,ports:t.ports,apis:t.contracts.apis,owns:t.contracts.owns,env:t.contracts.env})),c=new Set(n.map(t=>t.id)),a=new Map,i=[];for(let t of o.projects){for(let s of t.contracts.dependsOn||[])c.has(s)&&i.push({from:s,to:t.slug,type:"dependency",label:"dependsOn"});for(let s of t.contracts.publishes||[])a.has(s)||a.set(s,new Set),a.get(s)?.add(t.slug);}for(let t of o.projects)for(let s of t.contracts.consumes||[]){let p=a.get(s);if(p)for(let g of p)g!==t.slug&&i.push({from:g,to:t.slug,type:"event",label:s});}let l={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:o.workspace,generatedAt:new Date().toISOString(),nodes:n.sort((t,s)=>t.id.localeCompare(s.id)),edges:i.sort((t,s)=>`${t.from}:${t.to}:${t.type}:${t.label}`.localeCompare(`${s.from}:${s.to}:${s.type}:${s.label}`)),summary:{projectCount:n.length,dependencyEdges:i.filter(t=>t.type==="dependency").length,eventEdges:i.filter(t=>t.type==="event").length,portCount:n.reduce((t,s)=>t+s.ports.length,0),apiCount:n.reduce((t,s)=>t+s.apis.length,0)}};return {contractPath:r,graph:l}}async function Y(e){let{contractPath:r,contract:o}=await N(e),n=[],c=[];o.kind!=="rapidkit.workspace.contract"&&n.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==w&&n.push(`Contract schemaVersion must be ${w}.`),o.workspace?.name||n.push("Contract workspace.name is required."),Array.isArray(o.projects)||n.push("Contract projects must be an array.");let a=new Set,i=new Map;for(let t of o.projects||[]){if(!t.slug){n.push("Every project must declare slug.");continue}a.has(t.slug)&&n.push(`Duplicate project slug: ${t.slug}.`),a.add(t.slug),t.relativePath?E(t.relativePath)||n.push(`Project ${t.slug} declares unsafe relativePath: ${t.relativePath}.`):n.push(`Project ${t.slug} must declare relativePath.`),t.externalPath&&(t.relationship==="adopted"||t.source==="adopted-local"||t.source==="local-folder"||t.source==="git-url"||n.push(`Project ${t.slug} declares externalPath without imported/adopted provenance.`),u.isAbsolute(t.externalPath)||n.push(`Project ${t.slug} declares non-absolute externalPath.`));for(let s of t.ports||[]){(!Number.isInteger(s.port)||s.port<1||s.port>65535)&&n.push(`Project ${t.slug} declares invalid port: ${s.port}.`);let p=i.get(s.port);p&&n.push(`Port ${s.port} is claimed by both ${p} and ${t.slug}.`),i.set(s.port,t.slug);}for(let s of t.contracts?.apis||[])(!s.name?.trim()||!s.basePath?.startsWith("/"))&&n.push(`Project ${t.slug} declares invalid API contract.`);for(let s of [...t.contracts?.publishes||[],...t.contracts?.consumes||[]])s.trim()||n.push(`Project ${t.slug} declares an empty event contract.`);for(let s of t.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(s)||n.push(`Project ${t.slug} declares invalid env contract: ${s}.`);for(let s of t.contracts?.dependsOn||[])a.has(s);}for(let t of o.projects||[])for(let s of t.contracts?.dependsOn||[])a.has(s)||n.push(`Project ${t.slug} depends on unknown project: ${s}.`);c.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===w?"passed":"failed",message:"Contract schema and kind are valid."}),c.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),c.push({id:"ports",status:n.some(t=>t.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),c.push({id:"dependencies",status:n.some(t=>t.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),c.push({id:"contracts",status:n.some(t=>t.includes("unsafe relativePath")||t.includes("invalid API contract")||t.includes("event contract")||t.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let l$1=await l(e.workspacePath);if(l$1.moduleCount>0){for(let t of l$1.issues)n.push(`${u.basename(t.projectRoot)}: ${t.message} (slug=${t.slug})`);c.push({id:"module-paths",status:l$1.status,message:l$1.status==="passed"?`All ${l$1.moduleCount} registered module(s) resolve under canonical paths.`:`${l$1.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&c.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:n.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:c,violations:n}}async function pt(e){let r=u.resolve(e.workspacePath),o={schemaVersion:F,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 d(r,M,O(o))}
2
- export{O as a,m as b,M as c,w as d,F as e,H as f,V as g,at as h,ct as i,N as j,it as k,Y as l,pt as m};
@@ -1,4 +0,0 @@
1
- import {d,b as b$1,e}from'./chunk-753LOKFZ.js';import {j,q as q$1,n}from'./chunk-T6OR6YOI.js';import {h,i,f,e as e$1}from'./chunk-4KUIFXHM.js';import {d as d$1}from'./chunk-S5KTATOU.js';import {c}from'./chunk-NAAQMSO3.js';import {a}from'./chunk-GZTYAEWX.js';import {e as e$2,g}from'./chunk-LZQNVH7D.js';import {p,l,o}from'./chunk-5XATWNME.js';import _ from'fs';import b from'path';import E from'chalk';import {execa}from'execa';function je(e){return _.existsSync(b.join(e,"bun.lock"))||_.existsSync(b.join(e,"bunfig.toml"))?"bun":_.existsSync(b.join(e,"pnpm-lock.yaml"))?"pnpm":_.existsSync(b.join(e,"yarn.lock"))?"yarn":(_.existsSync(b.join(e,"package-lock.json")),"npm")}function Se(e,t,r=je(e)){return r==="npm"?`npm run ${t}`:`${r} run ${t}`}function Ee(e,t=je(e)){return `${t} install`}var _e={"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:[]}}},Ge={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"],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"],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"],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"],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 oe(e,t){if(t){let r=t.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=e$1(t),a=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:r==="fiber"?"fiber":r==="aspnetcore"||r==="asp-net-core"?"aspnetcore":r}`;return _e[a]}}function Ce(e,t,r){if(t){let n=oe(e,t);if(n&&n.commands[r])return n.commands[r]}if(["init","test","build","start"].includes(r)){let n=Ge[r]?.[e]??[];return n.length>0?n[0]:void 0}}var Be={test:"test",build:"build",start:"start"};function se(e){if(e.stage==="init")return e.runtime==="node"?Ee(e.projectPath):Ce(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let t=Be[e.stage];if(t){let r=n(e.projectPath,t,{framework:e.framework});if(r)return Se(e.projectPath,r.scriptName)}}return Ce(e.runtime,e.framework,e.stage)}function ze(e){let t=h(e).map(r=>r==="python"?"python":r==="node"||r==="bun"?"node":r==="go"?"go":r==="java"?"java":r==="php"?"php":r==="rust"?"rust":r==="dotnet"?"dotnet":r==="elixir"?"elixir":r==="ruby"?"ruby":r==="clojure"||r==="scala"||r==="kotlin"?"jvm-generic":null).filter(r=>r!==null).filter((r,n,o)=>o.indexOf(r)===n);return {primary:t.length>0?t[0]:"unknown",secondary:t.slice(1)}}function Pe(e){return ze(e).primary}function ae(e,t){if(!e)return "unknown";t||(t={setup:["ModuleNotFoundError","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[r,n]of Object.entries(t))for(let o of n)if(new RegExp(o,"i").test(e))return r;return "unknown"}async function q(e){let t=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(t))return {valid:true};try{let n=process.platform==="win32"?"where":"which";if((await execa(n,[t],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${t}' not found or not executable`}}function Fe(e,t,r){if(!t)return e;let n=typeof t=="object"&&!Array.isArray(t)&&("dev"in t||"staging"in t||"prod"in t||"default"in t)&&!Object.keys(t).some(o=>["init","test","build","start"].includes(o))?t:{};return r&&typeof n[r]=="string"?n[r]:typeof n.default=="string"?n.default:e}var Ae={init:"init",test:"test",build:"build",start:"start"};function Ke(e){return e in Ae?Ae[e]:null}function Ve(e,t){let n=j(e)?.contextJson?.commands;if(!n||typeof n!="object"||Array.isArray(n))return;let o=n[t];if(typeof o=="string"&&o.trim().length>0)return o.trim();if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c=a.default??a.dev;if(typeof c=="string"&&c.trim().length>0)return c.trim()}}function De(e,t,r=q$1(e)){let n=Ke(t);if(!n)return Ve(e,t)?{supported:true}:{supported:false,reason:`Workspace stage "${t}" is not part of the Workspai fleet contract.`};if(!r.projectRoot)return {supported:false,reason:"No Workspai project metadata was detected for this target."};let o=r.commandMap[n];return !o||o.status!=="supported"?{supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`}:{supported:true}}var He=new Set(["init","test","build","start"]),Ue=new Set([".git","node_modules",".workspai",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function I(e){try{return await _.promises.access(e,_.constants.F_OK),true}catch{return false}}async function Je(e){for(let t of e)if(await I(t))return true;return false}async function qe(e,t,r){if(t==="python"){let o=[b.join(e,".workspai","cli.py"),b.join(e,".rapidkit","cli.py")];for(let a of o)if(await I(a))return {valid:true};return {valid:false,reason:"Project-local .workspai/cli.py is missing. Run `workspai init` in this project first."}}let n=r.trim().split(/\s+/)[0];if(n&&["npm","npx","pnpm","yarn"].includes(n)){let o=e$2(n);if((await execa(o.command,[...o.prefixArgs,"--version"],{reject:false,env:g()})).exitCode===0)return {valid:true}}return q(r)}async function ce(e){let t=await _.promises.readFile(e,"utf-8");return JSON.parse(t)}function D(e){return e.replace(/\\/g,"/")}function Ye(e){let t=e?.trim();return t?t.startsWith("project:")?t.slice(8).trim()||null:t:null}async function Qe(e){return a(e,{skipDirs:Ue,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t,r)=>await Je([...p(t,"context.json"),...p(t,"project.json")])?true:b.resolve(t)===b.resolve(r)?false:h(t).length>0})}async function Xe(e){for(let t of [b.join(".workspai","project.json"),b.join(".workspai","context.json"),b.join(".rapidkit","project.json"),b.join(".rapidkit","context.json")]){let r=b.join(e,t);if(await I(r))try{let n=await ce(r),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function Ze(e,t,r){let n=Ye(r);if(!n)return {projects:t,normalizedScope:null};let o=D(n).toLowerCase(),a=[];for(let c of t){let u=D(b.relative(e,c)),p=b.basename(c),m=await Xe(c);[u,p,m].filter(s=>typeof s=="string"&&s.length>0).map(s=>D(s).toLowerCase()).includes(o)&&a.push(c);}if(a.length===0)throw new Error(`Workspace run scope did not match any project: ${r}`);return {projects:a,normalizedScope:n}}async function et(e,t,r){let n=await execa("git",["diff","--name-only",`${r}...HEAD`],{cwd:e,reject:false});if(n.exitCode!==0)return new Set(t);let o=n.stdout.split(/\r?\n/).map(c=>c.trim()).filter(c=>c.length>0).map(c=>D(c));if(o.length===0)return new Set;let a=new Set;for(let c of t){let u=D(b.relative(e,c));if(!u||u===".")continue;let p=`${u}/`;o.some(m=>m===u||m.startsWith(p))&&a.add(c);}return a}async function tt(e,t,r){let n=await c(e,".workspai/workspace.contract.json")??l(e,"workspace.contract.json");if(await I(n))try{let g=await rt(e,t,r,n);if(g.graphStatus!=="missing")return g}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let o=await c(e,".workspai/workspace-dependency-graph.json")??l(e,"workspace-dependency-graph.json");if(!await I(o))return {expanded:r,graphStatus:"missing",expansionDepth:0};let a;try{a=await ce(o);}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let c$1=new Set(t.map(g=>b.resolve(g))),u=new Map;if(!a||typeof a!="object"||Array.isArray(a))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let p=Array.isArray(a.projects)?a.projects:[];for(let g of p){if(!g||typeof g!="object"||Array.isArray(g))continue;let s=g,d=typeof s.path=="string"?s.path:"",y=b.resolve(e,d);if(!c$1.has(y))continue;let h=Array.isArray(s.dependsOn)?s.dependsOn.filter(w=>typeof w=="string"):[];for(let w of h){let x=b.resolve(e,w);c$1.has(x)&&(u.has(x)||u.set(x,new Set),u.get(x)?.add(y));}}let m=d$1(u,r);return {expanded:m.reached,graphStatus:"loaded",expansionDepth:m.added}}async function rt(e,t,r,n){let o=await ce(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let a=o,c=Array.isArray(a.projects)?a.projects:null;if(!c)return {expanded:r,graphStatus:"invalid",expansionDepth:0};let u=new Map,p=new Map;for(let y of t){let h=D(b.relative(e,y));p.set(h,b.resolve(y));}let m=new Map,g=new Map,s=new Map;for(let y of c){if(!y||typeof y!="object"||Array.isArray(y))continue;let h=y,w=typeof h.slug=="string"?h.slug:"",x=typeof h.relativePath=="string"?D(h.relativePath):w,R=p.get(x);!w||!R||u.set(w,R);}for(let y of c){if(!y||typeof y!="object"||Array.isArray(y))continue;let h=y,w=typeof h.slug=="string"?h.slug:"",x=u.get(w);if(!x)continue;let R=h.contracts&&typeof h.contracts=="object"&&!Array.isArray(h.contracts)?h.contracts:{},j=Array.isArray(R.dependsOn)?R.dependsOn.filter(v=>typeof v=="string"):[],N=Array.isArray(R.publishes)?R.publishes.filter(v=>typeof v=="string"):[],T=Array.isArray(R.consumes)?R.consumes.filter(v=>typeof v=="string"):[];for(let v of j){let S=u.get(v);S&&(s.has(S)||s.set(S,new Set),s.get(S)?.add(x));}for(let v of N)m.has(v)||m.set(v,new Set),m.get(v)?.add(x);for(let v of T)g.has(v)||g.set(v,new Set),g.get(v)?.add(x);}for(let[y,h]of m.entries()){let w=g.get(y);if(w)for(let x of h){s.has(x)||s.set(x,new Set);for(let R of w)R!==x&&s.get(x)?.add(R);}}let d=d$1(s,r);return {expanded:d.reached,graphStatus:"loaded",expansionDepth:d.added}}async function nt(e,t){if(typeof t=="boolean")return t;let r=o(e,"policies.yml").find(a=>_.existsSync(a))??l(e,"policies.yml");if(!await I(r))return true;let n="";try{n=await _.promises.readFile(r,"utf-8");}catch{return true}let o$1=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o$1?o$1[1]==="true":true}function ot(e){let t=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(t){let r=Number.parseInt(t,10);if(Number.isFinite(r)&&r>0)return r}return e==="init"?12e4:9e4}async function ie(e,t,r){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:t,reject:false,timeout:r,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 st(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"}function at(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}async function it(e){let t=process.cwd();try{process.chdir(e);let{handleInitCommand:r}=await import('./index.js');return {exitCode:await r(["init"]),stdout:"",stderr:""}}finally{process.chdir(t);}}async function ct(e){let t=s=>{let d=f(s);return d==="node"||d==="bun"?"node":d==="python"?"python":d==="go"?"go":d==="java"?"java":d==="php"?"php":d==="ruby"?"ruby":d==="rust"?"rust":d==="dotnet"?"dotnet":d==="elixir"?"elixir":d==="clojure"||d==="scala"||d==="kotlin"?"jvm-generic":Pe(e)},r=s=>{if(!s)return;let d=e$1(s);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(d))return d},n=j(e),o=n?.detection??i(e,n?.projectJson??null),a=n?.contextJson,c=t(o.runtime),u=r(o.key),p={},m=new Set(["init","test","build","start"]);if(a?.commands&&typeof a.commands=="object")for(let[s,d]of Object.entries(a.commands))typeof d=="string"&&m.has(s)&&(p[s]=d);let g;if(a?.commandEnvironments&&typeof a.commandEnvironments=="object"){let s=a.commandEnvironments;g={dev:typeof s.dev=="string"?s.dev:void 0,staging:typeof s.staging=="string"?s.staging:void 0,prod:typeof s.prod=="string"?s.prod:void 0,default:typeof s.default=="string"?s.default:void 0};}return {runtime:c,framework:u,commandOverrides:Object.keys(p).length>0?p:void 0,environmentCommandVariants:g,environment:typeof a?.environment=="string"?a.environment:void 0}}async function ut(e,t,r,n,o,a,c){let u=!o?.[t]&&st(r),p;if(o&&o[t]?p=o[t]:u?p=`rapidkit ${t}`:p=se({projectPath:e,runtime:r,framework:n,stage:t}),!p)return {exitCode:127,command:`<stage not supported for ${r}>`,message:`No stage command found for runtime '${r}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let m=Fe(p,a,c);if(!m)return {exitCode:127,command:p,message:"Failed to resolve stage command",errorCategory:"runtime"};let g=se({projectPath:e,runtime:r,framework:n,stage:t});if(u){if(g){let f=u?await qe(e,r,g):await q(g);if(!f.valid)return {exitCode:127,command:m,message:f.reason||"Command not available",errorCategory:"setup"}}}else {let f=await q(m);if(!f.valid)return {exitCode:127,command:m,message:f.reason||"Command not available",errorCategory:"setup"}}let s=0,d="",y="",h,w=ot(t),x=Date.now();try{let f=u?t==="init"&&at()?await it(e):await ie([t],e,w):await execa(m,[],{cwd:e,reject:false,shell:true,timeout:w});if(s=Number(f.exitCode??0),d=f.stdout,y=f.stderr,s!==0){let C=`${d}
2
- ${y}`,z=Date.now()-x;h=s===124||ae(C)==="timeout"||s===143&&z>=Math.floor(w*.8)?"timeout":ae(C);}}catch(f){let C=typeof f=="object"&&f!==null&&"timedOut"in f&&!!f.timedOut;return {exitCode:C?124:1,command:m,message:C?`Stage timed out after ${w}ms`:f instanceof Error?f.message:"Command execution failed",errorCategory:C?"timeout":"runtime"}}let R,j=`${d}
3
- ${y}`.split(/\r?\n/).map(f=>f.trim()).filter(Boolean),N=j.slice(0,6).join(`
4
- `),T=Date.now()-x,v=s===124||h==="timeout"||s===143&&T>=Math.floor(w*.8),S=s===0?void 0:v?"timeout":h,W=s===0||!S?void 0:{category:S,exitCode:s,command:m,timedOut:v,timeoutMs:w,...N?{outputExcerpt:N}:{}};return {exitCode:s,command:m,errorCategory:S,healthStatus:R,failureDiagnostic:W,message:v?`Stage timed out after ${w}ms`:s!==0?N?`Stage failed with exit code ${s}: ${j[0]}`:`Stage failed with exit code ${s}`:void 0}}function Ne(e){try{return JSON.parse(e)}catch{return null}}function dt(e){switch(e){case "dotnet":return "Install .NET 8+ SDK, then rerun `npx workspai setup dotnet` or `npx workspai init`.";case "go":return "Install Go 1.21+, then rerun `npx workspai setup go` or `npx workspai init`.";case "java":case "jvm-generic":return "Install Java 21+ and Maven/Gradle, then rerun `npx workspai setup java` or `npx workspai init`.";case "node":return "Install Node.js LTS and npm/pnpm/yarn, then rerun `npx workspai setup node` or `npx workspai init`.";case "python":return "Install Python 3.10+ and pip/Poetry, then rerun `npx workspai setup python` or `npx workspai init`.";default:return null}}async function lt(e){let t=[],r=await ie(["doctor","workspace","--json"],e);if(r.exitCode!==0)t.push({gate:"doctor-workspace",status:"fail",summary:"doctor workspace command failed"});else {let a=Ne(r.stdout)?.healthScore,c=Number(a?.errors??0);Number.isFinite(c)&&c>0?t.push({gate:"doctor-workspace",status:"fail",summary:`doctor workspace reports ${c} error(s)`}):t.push({gate:"doctor-workspace",status:"pass",summary:"doctor workspace passed"});}let n=await ie(["readiness","--json"],e);if(n.exitCode!==0)t.push({gate:"readiness",status:"fail",summary:"readiness command failed"});else {let o=Ne(n.stdout),a=String(o?.overallStatus??"").toLowerCase();a==="fail"?t.push({gate:"readiness",status:"fail",summary:"readiness overall status is fail"}):a==="warn"?t.push({gate:"readiness",status:"warn",summary:"readiness overall status is warn"}):t.push({gate:"readiness",status:"pass",summary:"readiness overall status is pass"});}return t}var pt=new Set(["dev","stop"]);function mt(e){let t=e.trim();return !t||pt.has(t.toLowerCase())?false:He.has(t)?true:/^[a-z][a-z0-9_-]*$/i.test(t)}function Oe(e,t,r){let n=D(b.relative(r,t));return (Array.isArray(e.projects)?e.projects:[]).some(a=>{if(!a||typeof a!="object")return false;let c=a,u=[c.relativePath,c.path].filter(p=>typeof p=="string"&&p.length>0).map(p=>D(p));return c.status==="passed"&&(u.includes(n)||u.some(p=>p.endsWith(`/${n}`)))})}function ft(e,t){return oe(e,t)?.dependencies??[]}function gt(e,t){let r=Math.max(1,Math.min(4,t)),n=Number(e??r);return Number.isFinite(n)?Math.max(1,Math.min(16,Math.trunc(n))):r}async function Yt(e$1){if(!mt(e$1.stage))throw new Error(`Unsupported workspace run stage: ${e$1.stage}`);let t=Date.now(),r=b.resolve(e$1.workspacePath),n=await d(r),o=await Qe(r),{projects:a,normalizedScope:c}=await Ze(r,o,e$1.scope),u=e$1.affected===true,p=e$1.blastRadius===true,m=e$1.since?.trim()||"HEAD~1",g=u?await et(r,a,m):new Set(a),s,d$1="not-applicable",y=0,h="all";if(u&&p){let l=await tt(r,o,g);s=l.expanded,d$1=l.graphStatus,y=l.expansionDepth,h="affected+blast-radius";}else u?(s=g,h="affected"):(s=g,h="all");let w=e$1.stage==="init"?false:await nt(r,e$1.enforceGates),x=w?await lt(r):[{gate:"doctor-workspace",status:"skipped",summary:"workspace run gates disabled"},{gate:"readiness",status:"skipped",summary:"workspace run gates disabled"}],R=x.find(l=>l.status==="fail"),j=a.filter(l=>s.has(l)),N=e$1.continueOnError===true||e$1.stage==="init",T=e$1.parallel===true,v=gt(e$1.maxWorkers,j.length),S=j.length,W=0;e$1.json||console.log(E.gray(`Workspace run (${e$1.stage}) started: ${S} target(s), ${T?`parallel x${v}`:"sequential"}`));let f=new Map;for(let l of o){let k=D(b.relative(r,l)),i=a.includes(l),F=i&&s.has(l);f.set(l,{path:l,relativePath:k,projectName:b.basename(k)||b.basename(l),selected:F,affected:F,status:"skipped",exitCode:null,durationMs:0,reason:F?void 0:i?"not affected":"outside scope",framework:void 0,runtimeDetected:void 0,executionCommand:void 0});}if(R)for(let l of j){let k=f.get(l);k&&(k.status="skipped",k.reason=`blocked by ${R.gate}`);}else {let l=async k=>{let i=f.get(k);if(!i)return;let F=D(b.relative(r,k));e$1.json||console.log(E.gray(`\u23F3 [${W}/${S}] ${e$1.stage} ${F}`)),i.selected=true,i.affected=true;let A=Date.now(),{runtime:P,framework:O,commandOverrides:Te,environmentCommandVariants:$e,environment:Ie}=await ct(k);i.runtimeDetected=P,i.framework=O;let pe=De(k,e$1.stage);if(!pe.supported){i.status="skipped",i.reason=pe.reason??`stage "${e$1.stage}" unsupported for project`,i.durationMs=Date.now()-A,i.exitCode=null,W+=1;return}if(e$1.reusePassed&&n){let $=n.stages[e$1.stage]??n.stages[e$1.stage];if($&&Oe($,k,r)){i.status="passed",i.reason="reused passed result from workspace-run-last.json",i.durationMs=Date.now()-A,i.exitCode=0,W+=1,e$1.json||console.log(E.gray(`\u21BA reused passed cache for ${F}`));return}}let me=ft(P,O);if(me.length>0&&n){let $=me.find(Q=>{let L=n.stages[Q];return !L||!Oe(L,k,r)});if($){i.status="skipped",i.reason=`dependency stage "${$}" not satisfied in workspace-run-last.json`,i.durationMs=Date.now()-A,i.exitCode=null,W+=1;return}}let M=await ut(k,e$1.stage,P,O,Te,$e,Ie);if(i.executionCommand=M.command,i.errorCategory=M.errorCategory,i.healthStatus=M.healthStatus,i.failureDiagnostic=M.failureDiagnostic,i.durationMs=Date.now()-A,i.exitCode=M.exitCode,M.exitCode===0?(i.status="passed",i.reason=void 0):(i.status="failed",i.reason=M.message||"stage command failed",i.errorMessage=M.message),W+=1,!e$1.json){let $=S>0?Math.round(W/S*100):100,Q=i.status==="passed"?E.green("\u2705"):E.red("\u274C");if(console.log(E.gray(`${Q} [${W}/${S}] (${$}%) ${F} ${i.durationMs}ms`)),i.status==="failed"){i.reason&&console.log(E.red(` Reason: ${i.reason}`)),i.executionCommand&&console.log(E.gray(` Command: ${i.executionCommand}`));let L=dt(i.runtimeDetected);L&&i.errorCategory==="setup"&&console.log(E.gray(` Hint: ${L}`));}}};if(T&&j.length>1){let k=0,i=false,F=new Array(v).fill(null).map(async()=>{for(;k<j.length;){if(i&&!N)return;let A=k;k+=1;let P=j[A];await l(P),f.get(P)?.status==="failed"&&(i=true);}});if(await Promise.all(F),!N&&i){let A=false;for(let P of j){let O=f.get(P);if(O){if(O.status==="failed"){A=true;continue}A&&O.status==="skipped"&&(O.reason=O.reason||"stopped after failure");}}}}else for(let k of j){await l(k);let i=f.get(k);if(!N&&i?.status==="failed"){let F=j.slice(j.indexOf(k)+1);for(let A of F){let P=f.get(A);P&&(P.status="skipped",P.reason="stopped after failure");}break}}}let C=[];for(let l of o){let k=f.get(l);k&&C.push(k);}let z=C.filter(l=>l.status==="passed").length,K=C.filter(l=>l.status==="failed").length,ue=C.filter(l=>l.status==="skipped").length,de=e$1.strict===true,We=K>0||de&&x.some(l=>l.status==="fail"||l.status==="warn")?1:0,le={schemaVersion:"1.0",workspacePath:r,stage:e$1.stage,generatedAt:new Date().toISOString(),durationMs:Date.now()-t,options:{affected:u,blastRadius:p,since:u?m:null,parallel:T,maxWorkers:v,continueOnError:N,strict:de,enforceGates:w,scope:c,reusePassed:e$1.reusePassed===true},selection:{mode:h,since:u?m:null,scope:c,graphStatus:d$1,expansionDepth:y},gates:{enforced:w,results:x,blocked:!!R,blockingGate:R?.gate},summary:{projectCount:o.length,selectedCount:j.length,passed:z,failed:K,skipped:ue,exitCode:We},projects:C,enterpriseControls:{jsonReady:true,evidencePath:b$1}},Me=b.join(r,b$1);return await e(r,le),e$1.json||(R&&(console.log(E.red(`\u274C Workspace run blocked by ${R.gate}`)),console.log(E.gray(` ${R.summary}`))),console.log(E.cyan(`Workspace run (${e$1.stage}) => passed: ${z}, failed: ${K}, skipped: ${ue}`)),console.log(E.gray(`Report: ${Me}`))),le}export{Yt as a};
@@ -1,33 +0,0 @@
1
- import {b,c as c$1,d}from'./chunk-EWYYLJQY.js';import {d as d$1}from'./chunk-CVTCPPEF.js';import {b as b$1,f,j as j$1,k as k$1,h,i,l as l$1,m,n as n$2,o,p,q,r,t,v,x,s,u,w as w$1,y,z as z$1,A,B as B$1,C,D,E as E$1,F as F$1,G,a,H,I}from'./chunk-DNAY5ALC.js';import {n as n$1,k as k$2,b as b$2,j as j$2}from'./chunk-5SWNSJGW.js';import {j}from'./chunk-VZKSNUEE.js';import {c}from'./chunk-NAAQMSO3.js';import n from'path';import k from'fs-extra';var U=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var it="workspace-operational-skill.v1";function ct(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function Ge(e){let t=ct(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:it,skillId:t,canonicalPath:H(t),title:e.title,triggers:[...e.triggers].sort((r,o)=>r.localeCompare(o)),requiredReports:[...e.requiredReports].sort((r,o)=>r.localeCompare(o)),scopedProjects:[...e.scopedProjects??[]].sort((r,o)=>r.localeCompare(o)),verificationCommands:[...e.verificationCommands],answerContractSections:[...U],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var pt="workspace-skills-index.v1";function He(e){let t=[...e.skills].sort((o,c)=>o.skillId.localeCompare(c.skillId)),r=e.inputsHash??b$2({skillIds:t.map(o=>o.skillId),paths:t.map(o=>o.canonicalPath)});return {schemaVersion:pt,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(o=>({skillId:o.skillId,path:o.canonicalPath,schemaVersion:o.schemaVersion,title:o.title}))}}var Me=[".workspai/reports/INDEX.json",b,d$1],lt=[{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 `.workspai/reports/INDEX.json` and identify fail/warn reports for the scoped project.","Read `.workspai/reports/doctor-last-run.json`, `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 `.workspai/reports/release-readiness-last-run.json` and `pipeline-last-run.json`.","Read `.workspai/reports/workspace-verify-last-run.json` for verdict and blocking reasons.","Read `.workspai/reports/artifact-remediation-plan-last-run.json` 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 `.workspai/workspace.contract.json` 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 z(e){return `npx workspai ${e}`.trim()}function dt(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)","",...Me.map(r=>`- \`${r}\``),"","## Procedure","",...e.template.steps.map((r,o)=>`${o+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",z("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
2
- `)}function ut(e){return e?.safeCommands?.length?e.safeCommands.slice(0,8).map(t=>t.display):[z("workspace verify --json"),z("doctor workspace --json")]}function gt(e){return e?.projects?.length?e.projects.slice(0,12).map(r=>{let o=r.contracts.owns.join(", ")||"none",c=r.contracts.publishes.join(", ")||"none",d=r.contracts.consumes.join(", ")||"none";return `- **${r.slug}**: owns \`${o}\`; publishes \`${c}\`; consumes \`${d}\``}).join(`
3
- `):void 0}function Ke(e){let t=e.model.workspace.name,r=e.model.projects.map(d=>d.name).sort(),o=ut(e.context??null),c=gt(e.contract??null);return lt.map(d=>{let p=dt({template:d,workspaceName:t,scopedProjects:r,verificationCommands:o,contractSummary:c});return Ge({skillId:d.skillId,title:d.title,triggers:d.triggers,requiredReports:[...Me],scopedProjects:r,verificationCommands:o,promptStem:I[d.skillId],markdown:p})})}async function qe(e){let t=n.resolve(e.workspacePath),r=[],o=b$2({skills:e.skills.map(d=>({id:d.skillId,path:d.canonicalPath,hash:b$2({markdown:d.markdown})}))}),c=He({generatedAt:e.generatedAt,skills:e.skills,inputsHash:o});if(e.write){for(let p of e.skills){let s=n.join(t,p.canonicalPath);await k.ensureDir(n.dirname(s)),await k.writeFile(s,p.markdown,"utf8"),r.push(p.canonicalPath);}let d=n.join(t,b$1);await k.ensureDir(n.dirname(d)),await k.writeJson(d,c,{spaces:2}),r.push(b$1);}return {skills:e.skills,index:c,writtenPaths:r}}function $e(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",z("workspace agent-sync --write --refresh-context"),"```",""].join(`
4
- `)}var kt={"workspai-diagnose-api-failure":p,"workspai-release-readiness":t},Ae="## Workspace verification (hydrated)";function mt(e){let t=[Ae,"","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 Ve(e){let t=n.resolve(e.workspacePath),r=[];for(let o of e.skills){let c=kt[o.skillId];if(!c)continue;let d=n.join(t,c);if(!await k.pathExists(d))continue;let p=await k.readFile(d,"utf8"),s=mt(o),m=p.includes(Ae)?p.replace(new RegExp(`${Ae}[\\s\\S]*$`),s.trimEnd()):`${p.trimEnd()}
6
-
7
- ${s}`;e.write&&await k.writeFile(d,`${m.trimEnd()}
8
- `,"utf8"),r.push(c);}return r}var ft="rapidkit-agent-customization-pack.v1";function Ue(){return {schemaVersion:ft,presets:{minimal:{meaning:"Generate the portable grounding index, AGENTS.md, and provider-specific lightweight instructions.",requiredOutputs:[".workspai/reports/INDEX.json",".workspai/reports/agent-customization-pack.json","AGENTS.md"]},enterprise:{meaning:"Generate the full VS Code-native pack: instructions, prompts, skills, custom agents, and validation metadata.",requiredOutputs:[".workspai/reports/INDEX.json",".workspai/reports/agent-customization-pack.json","AGENTS.md",l$1,p,B$1,".github/agents/workspai-advisor.agent.md",D,b$1]}},targets:{all:{meaning:"Generate every supported customization surface.",outputFamilies:["portable","vscode","copilot","cursor","claude"]},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"]},orca:{meaning:"Use AGENTS.md and the report index as the Orca/Grok grounding layer.",outputFamilies:["portable"]}},standardAnswerContract:[...U],requiredReports:N.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}/`],l2PrefixedMirrorRoots:[".github/",".cursor/",".claude/"],l3SharedIndustryFiles:["AGENTS.md",".github/copilot-instructions.md","CLAUDE.md"]}}}var wt="rapidkit-agent-reports-index.v1",ht="rapidkit-agent-customization-pack.v1",Pe=".workspai/reports/INDEX.json",F=".workspai/reports/agent-customization-pack.json";var N=[{relativePath:b,label:"Agent context pack",required:true},{relativePath:b$1,label:"Operational skills index",required:true},{relativePath:".workspai/reports/workspace-model.json",label:"Workspace model graph",required:false},{relativePath:".workspai/reports/doctor-last-run.json",label:"Workspace doctor",required:false},{relativePath:".workspai/reports/doctor-project-last-run.json",label:"Project doctor",required:false},{relativePath:".workspai/reports/doctor-remediation-plan-last-run.json",label:"Doctor remediation plan",required:false},{relativePath:".workspai/reports/artifact-remediation-plan-last-run.json",label:"Artifact remediation plan",required:false},{relativePath:".workspai/reports/doctor-fix-result-last-run.json",label:"Doctor fix result",required:false},{relativePath:".workspai/reports/analyze-last-run.json",label:"Workspace analyze",required:false},{relativePath:".workspai/reports/pipeline-last-run.json",label:"Governance pipeline",required:false},{relativePath:".workspai/reports/release-readiness-last-run.json",label:"Release readiness",required:false},{relativePath:".workspai/reports/workspace-impact-last-run.json",label:"Workspace impact",required:false},{relativePath:".workspai/reports/workspace-verify-last-run.json",label:"Workspace verify",required:false},{relativePath:".workspai/reports/workspace-model-snapshot.json",label:"Workspace model snapshot",required:false},{relativePath:".workspai/reports/workspace-model-diff-last-run.json",label:"Workspace model diff",required:false},{relativePath:".workspai/reports/workspace-explain-last-run.json",label:"Workspace explain",required:false},{relativePath:".workspai/reports/workspace-contract-verify-last-run.json",label:"Workspace contract verify",required:false},{relativePath:".workspai/reports/workspace-intelligence-history.json",label:"Workspace intelligence history",required:false}];function w(e){return `npx workspai ${e}`.trim()}function ot(e){return e&&typeof e=="object"?e:null}function Re(e,t=12){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0).slice(0,t):[]}function At(e){let t=Re(e.blockers,12);if(t.length>0)return t;let r=Re(e.blockingReasons,12);if(r.length>0)return r;let o=ot(e.summary);return o&&Array.isArray(o.blockingReasons)?Re(o.blockingReasons,12):[]}function Pt(e){for(let t of ["generatedAt","timestamp"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}}function Rt(e,t,r){if(!e)return true;let o=Date.parse(e);return Number.isFinite(o)?r.getTime()-o>t*60*60*1e3:true}function St(e){let t=e&&e.length>0?e:["all"];return t.includes("all")?new Set(["all","vscode","agents","copilot","cursor","claude","codex","orca"]):new Set(t)}function P(e,t){return e.has("all")||e.has(t)}function Ot(e){return P(e,"copilot")||P(e,"vscode")}function yt(e){return e??"enterprise"}function Ct(e){return e===b$1?"skills-index":e.includes("workspace-explain-last-run.json")?"explain-report":(e.startsWith(`${a}/`)||e.startsWith(".rapidkit/skills/"))&&e.endsWith(".md")?"operational-skill":e.includes("hooks")||e===F$1||e===G?"hook":e.includes("mcp")||e===D||e===E$1?"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 xt(e){return e.startsWith(".github/")?["vscode","copilot"]:e.startsWith(".cursor/")?["cursor"]:e.startsWith(".claude/")||e==="CLAUDE.md"?["claude"]:e==="AGENTS.md"||e.startsWith(".rapidkit/")?["agents","codex","orca","vscode"]:e.startsWith(".vscode/")?["vscode"]:["agents"]}function Et(e,t){return Ue().presets[t].requiredOutputs.includes(e)}function It(e){return e.schemaVersion===j$2&&typeof e.generatedAt=="string"&&e.summary!=null&&typeof e.summary=="object"&&!Array.isArray(e.summary)&&Array.isArray(e.projects)}async function bt(e,t){if(t)return t;let r=await c(e,k$2)??n.join(e,k$2);if(await k.pathExists(r))try{let o=await k.readJson(r);if(It(o))return o}catch{}return n$1({workspacePath:e,includeEvidence:true})}function _t(e){return e.length>0&&!n.isAbsolute(e)&&!e.split(/[\\/]+/).includes("..")}function Tt(e){return Object.fromEntries(["all","vscode","agents","copilot","cursor","claude","codex","orca"].map(r=>[r,{enabled:e.targets.includes("all")||e.targets.includes(r),outputs:e.outputs.filter(o=>o.targets.includes(r)).map(o=>o.path).sort()}]))}async function jt(e){try{if(!await k.pathExists(e))return null;let t=await k.readJson(e);return ot(t)}catch{return null}}async function ze(e){let t=e.now??new Date,r=e.staleAfterHours??24,o=[],c$1=[];for(let p of N){let s=await c(e.workspacePath,p.relativePath)??n.join(e.workspacePath,p.relativePath),m=await jt(s),I=m!==null;I&&m&&c$1.push(...At(m)),o.push({path:p.relativePath,label:p.label,required:p.required,exists:I,generatedAt:m?Pt(m):void 0,commandId:typeof m?.commandId=="string"?m.commandId:void 0,exitCode:typeof m?.exitCode=="number"?m.exitCode:void 0});}let d=[...new Set(c$1.map(p=>p.trim()).filter(Boolean))].slice(0,16);return {schemaVersion:wt,generatedAt:t.toISOString(),workspaceRoot:e.workspacePath,readOrder:N.map(p=>p.relativePath),blockers:d,staleAfterHours:r,reports:o,refreshCommand:w("workspace agent-sync --write --refresh-context")}}function Fe(e){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. `.workspai/reports/INDEX.json` \u2014 latest blockers, timestamps, and report paths","2. `.workspai/reports/workspace-context-agent.json` \u2014 canonical agent context pack","3. Evidence artifacts listed in the index (doctor, analyze, pipeline, readiness, impact, verify)","","Do **not** full-repo scan until these reports are read or regenerated.","","## Regenerate intelligence","","```bash",w("workspace agent-sync --write --refresh-context"),w("workspace context --for-agent --json --write"),w("pipeline --json --write"),"```",""];if(e.index.blockers.length>0){t.push("## Current blockers","");for(let r of e.index.blockers.slice(0,12))t.push(`- ${r}`);t.push("");}if(e.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let r of e.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.",""),t.join(`
9
- `)}function vt(e){return ["# Workspai agent grounding","",`Generated: ${e.generatedAt}`,"","This file is tool-agnostic. Synced agents should read it together with `.workspai/reports/INDEX.json`.","","## Mandatory read order","",...e.readOrder.map((t,r)=>`${r+1}. \`${t}\``),"",e.blockers.length>0?"## Blockers":"",...e.blockers.length>0?e.blockers.map(t=>`- ${t}`):[],"","## Refresh","","```bash",e.refreshCommand,"```",""].filter(t=>t!=="").join(`
10
- `)}function Wt(){return ["# Workspai workspace grounding","","Before answering workspace, release, or architecture questions:","","1. Read `AGENTS.md` (managed Workspai section).","2. Read `.workspai/reports/INDEX.json` and `.workspai/reports/workspace-context-agent.json`.","3. Use evidence reports before scanning the full repository.","","Regenerate stale intelligence:","","```bash",w("workspace agent-sync --write --refresh-context"),"```",""].join(`
11
- `)}function Nt(){return ["## Claude Code","","- Load `.workspai/reports/INDEX.json` 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 Xe(){return ["---","description: Workspai workspace evidence and intelligence grounding","globs: []","alwaysApply: true","---","","Before proposing fixes in this workspace:","","1. Read `AGENTS.md` and `.workspai/reports/INDEX.json`.","2. Read `.workspai/reports/workspace-context-agent.json`.","3. Prefer evidence in `.workspai/reports/*` over full-repo exploration.","","Refresh when stale:","","```bash",w("workspace agent-sync --write --refresh-context"),"```",""].join(`
13
- `)}function Be(){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 `.workspai/reports/INDEX.json` for read order and blockers.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.",""].join(`
14
- `)}function Ye(){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 `.workspai/reports/INDEX.json` and `.workspai/reports/workspace-context-agent.json`.","- 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(`
15
- `)}function Je(){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(`
16
- `)}function Ze(){return ["---","description: Diagnose Workspai workspace blockers from evidence reports","---","","Diagnose this workspace using Workspai evidence only.","","Read:","","- `.workspai/reports/INDEX.json`","- `.workspai/reports/workspace-context-agent.json`","- 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(`
17
- `)}function X(e){return ["---",`description: ${e.description}`,"---","",e.objective,"","Read first:","","- `.workspai/reports/INDEX.json`","- `.workspai/reports/workspace-context-agent.json`","- Any report referenced by the current blocker or task","","Return:","",...e.expectedOutput.map((t,r)=>`${r+1}. ${t}`),"","Use the standard Workspai answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
18
- `)}function E(e){return ["# "+e.title,"",...e.lines,""].join(`
19
- `)}function Lt(){return E({title:"MCP Tool Design",lines:["Workspai MCP is a future read-mostly bridge. Use the CLI reports today; do not assume a running MCP server exists.","","Candidate read tools:","- `getWorkspaceModel` \u2014 read `.workspai/reports/workspace-model.json`.","- `getEvidenceIndex` \u2014 read `.workspai/reports/INDEX.json`.","- `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 `.workspai/reports/workspace-skills-index.json`.","- `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 Qe(e){return `${JSON.stringify({schemaVersion:"workspai-mcp-design.v1",generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,status:"design-only",mode:"read-mostly",safety:{writeToolsEnabled:false,approvalRequiredForRefresh:true,artifactReadsMustStayInsideWorkspace:true},candidateTools:[{name:"getWorkspaceModel",reads:[".workspai/reports/workspace-model.json"],mutates:false},{name:"getEvidenceIndex",reads:[".workspai/reports/INDEX.json"],mutates:false},{name:"getBlockers",reads:[".workspai/reports/INDEX.json",".workspai/reports/workspace-verify-last-run.json",".workspai/reports/pipeline-last-run.json"],mutates:false},{name:"getSafeCommands",reads:[".workspai/reports/workspace-context-agent.json"],mutates:false},{name:"getProjectContext",reads:[".workspai/reports/workspace-model.json",".workspai/reports/workspace-context-agent.json"],mutates:false},{name:"getArtifact",reads:["requested workspace-relative artifact path"],mutates:false},{name:"listOperationalSkills",reads:[".workspai/reports/workspace-skills-index.json"],mutates:false},{name:"getWorkspaceExplain",reads:[".workspai/reports/workspace-explain-last-run.json",".workspai/reports/workspace-verify-last-run.json",".workspai/reports/workspace-impact-last-run.json"],mutates:false},{name:"refreshWorkspaceIntelligence",command:w("workspace agent-sync --write --refresh-context"),mutates:true,approvalRequired:true}]},null,2)}
20
- `}function et(e){return `${JSON.stringify({schemaVersion:"workspai-agent-hooks.v1",generatedAt:e.generatedAt,workspaceRoot:e.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:[w("doctor workspace"),w("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:[".workspai/reports/INDEX.json",".workspai/reports/workspace-context-agent.json"]}]},null,2)}
21
- `}function tt(e){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 `.workspai/reports/INDEX.json`.","3. Load `.workspai/reports/workspace-context-agent.json`.","4. Load `.workspai/reports/workspace-skills-index.json` 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?.trim()&&t.push(e.trim(),""),t.join(`
22
- `)}function B(e){return ["---",`name: ${e.name}`,`description: ${e.description}`,`tools: [${e.tools.map(t=>`'${t}'`).join(", ")}]`,"---","",`You are the ${e.name} agent for Workspai Workspace Intelligence.`,"",`Mode: ${e.mode}.`,"","Start every task by reading `.workspai/reports/INDEX.json` and `.workspai/reports/workspace-context-agent.json`.","","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(`
23
- `)}function rt(){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 `.workspai/reports/INDEX.json`","2. Read `.workspai/reports/workspace-context-agent.json`","3. Read fail/warn evidence artifacts listed in the index","4. Propose the smallest safe fix with explicit verification commands","","## Refresh stale evidence","","```bash",w("workspace agent-sync --write --refresh-context"),"```",""].join(`
24
- `)}async function l(e,t,r){return r?(await k.ensureDir(n.dirname(e)),await k.writeFile(e,t,"utf8"),"written"):"skipped"}async function Se(e){if(!e.write)return "skipped";let t=await k.pathExists(e.absolutePath)?await k.readFile(e.absolutePath,"utf8"):null,{upsertManagedAgentSection:r}=await import('./managed-agent-markers-AXUM75OE.js'),o=r(t,e.generatedBody),c=e.preamble?`${e.preamble.trimEnd()}
25
-
26
- ${o}`:o;return await k.ensureDir(n.dirname(e.absolutePath)),await k.writeFile(e.absolutePath,c,"utf8"),"written"}function Pr(e){if(!e?.trim())return;let t=new Set(["all","vscode","agents","copilot","cursor","claude","codex","orca"]),r=e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>t.has(o));return r.length>0?r:void 0}function Dt(e){let t=[...e.outputs].sort((r,o)=>r.path.localeCompare(o.path));return {schemaVersion:ht,generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,preset:e.preset,targets:[...e.targets].sort(),sourceReports:e.index.reports.filter(r=>r.exists).map(r=>r.path).sort(),outputInventory:t,capabilityMatrix:Tt({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:w(`workspace agent-sync --write --refresh-context --preset ${e.preset}`),experimental:{hooksEnabled:e.experimentalHooks,mcpReady:t.some(r=>r.kind==="mcp-design")}}}async function Rr(e){let t$1=n.resolve(e.workspacePath),r$1=new Date,o$1=e.staleAfterHours??24,c=St(e.targets),d$1=[...c].sort(),p$1=yt(e.preset),s$1=e.write===true,m$1=e.strict===true,I,b=null,Y;e.refreshContext&&(Y=await n$1({workspacePath:t$1,includeEvidence:true}),b=await c$1({workspacePath:t$1,model:Y,agent:e.agent??"generic",scope:e.scope,includeEvidence:true}),s$1&&(I=await d(b,t$1)));let h$1=await ze({workspacePath:t$1,staleAfterHours:o$1,now:r$1}),_=[],J=[],Z=[],Q=[],a=(i,g)=>{i==="written"?J.push(g):Z.push(g),Q.push({path:g,kind:Ct(g),targets:xt(g),required:Et(g,p$1),status:i==="written"?"written":e.dryRun?"planned":"skipped"});};a(await l(n.join(t$1,Pe),`${JSON.stringify(h$1,null,2)}
27
- `,s$1),Pe),a(await l(n.join(t$1,f),`${vt(h$1)}
28
- `,s$1),f);let ee="",st=await bt(t$1,Y),te=null;try{te=(await j({workspacePath:t$1})).contract;}catch{te=null;}let nt=Ke({model:st,context:b,contract:te}),re=await qe({workspacePath:t$1,skills:nt,generatedAt:r$1.toISOString(),write:s$1});for(let i of re.skills)a(s$1?"written":"skipped",i.canonicalPath);if(a(s$1?"written":"skipped",b$1),ee=$e(re.index),(P(c,"agents")||P(c,"vscode"))&&a(await Se({absolutePath:n.join(t$1,"AGENTS.md"),generatedBody:Fe({index:h$1,context:b}),write:s$1}),"AGENTS.md"),P(c,"claude")){let i=n.join(t$1,"CLAUDE.md");if(s$1){let{upsertManagedAgentSection:g}=await import('./managed-agent-markers-AXUM75OE.js'),u=await k.pathExists(i)?await k.readFile(i,"utf8"):"",f=g(u,Nt()),R=f.includes("@AGENTS.md")?f:`@AGENTS.md
29
-
30
- ${f}`;await k.ensureDir(n.dirname(i)),await k.writeFile(i,R,"utf8"),J.push("CLAUDE.md");}else Z.push("CLAUDE.md");a(await l(n.join(t$1,j$1),`${Je()}
31
- `,s$1),j$1),a(await l(n.join(t$1,k$1),`${Je()}
32
- `,s$1),k$1);}if(P(c,"cursor")&&(a(await l(n.join(t$1,h),Xe(),s$1),h),a(await l(n.join(t$1,i),Xe(),s$1),i)),Ot(c)){if(a(await Se({absolutePath:n.join(t$1,".github/copilot-instructions.md"),generatedBody:Wt(),write:s$1}),".github/copilot-instructions.md"),a(await l(n.join(t$1,l$1),Ye(),s$1),l$1),a(await l(n.join(t$1,m),Ye(),s$1),m),a(await l(n.join(t$1,n$2),Be(),s$1),n$2),a(await l(n.join(t$1,o),Be(),s$1),o),a(await l(n.join(t$1,p),Ze(),s$1),p),a(await l(n.join(t$1,q),Ze(),s$1),q),p$1==="enterprise"){let i=[[r,X({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,X({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,X({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, external create-adopt, or adopt-only lane","Safe commands","Post-onboarding verification"]})],[x,X({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[u,f]of i)a(await l(n.join(t$1,u),f,s$1),u);let g=[[s,i[0][1]],[u,i[1][1]],[w$1,i[2][1]],[y,i[3][1]]];for(let[u,f]of g)a(await l(n.join(t$1,u),f,s$1),u);if(e.hydratePrompts===true)for(let u of await Ve({workspacePath:t$1,skills:re.skills,write:s$1}))a(s$1?"written":"skipped",u);}if(a(await l(n.join(t$1,z$1),rt(),s$1),z$1),a(await l(n.join(t$1,A),rt(),s$1),A),p$1==="enterprise"){a(await l(n.join(t$1,B$1),tt(ee),s$1),B$1),a(await l(n.join(t$1,C),tt(ee),s$1),C);let i=[["artifact-map.md",E({title:"Artifact Map",lines:N.map(u=>`- \`${u.relativePath}\` \u2014 ${u.label}`)})],["command-map.md",E({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",E({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",E({title:"Runtime Support",lines:["- Native create is available only for Workspai-owned scaffold contracts.","- Unsupported stacks should use external-create-adopt when a stable ecosystem generator exists.","- Existing projects should use adopt-only when native create is unavailable."]})],["create-planner-capabilities.md",E({title:"Create Planner Capabilities",lines:["- Use `contracts/create-planner-capabilities.v1.json` to decide native-create, external-create-adopt, or adopt-only.","- 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",Lt()]];for(let[u,f]of i){let R=`${n.dirname(B$1)}/resources/${u}`;a(await l(n.join(t$1,R),f,s$1),R);let ye=`${n.dirname(C)}/resources/${u}`;a(await l(n.join(t$1,ye),f,s$1),ye);}let g=[["workspai-advisor.agent.md",B({name:"Workspai Advisor",description:"Read-only workspace and project guidance using Workspai evidence",mode:"read-only",tools:["search","read"]})],["workspai-repair.agent.md",B({name:"Workspai Repair",description:"Turn Workspai blockers into minimal fixes and verification steps",mode:"repair",tools:["search","read","edit"]})],["workspai-release.agent.md",B({name:"Workspai Release",description:"Assess readiness, governance gates, and release safety from evidence",mode:"release",tools:["search","read"]})],["workspai-project-onboarder.agent.md",B({name:"Workspai Project Onboarder",description:"Guide create, import, and adopt flows with Workspai contracts",mode:"onboard",tools:["search","read","edit"]})]];for(let[u,f]of g){let R=`.github/agents/${u}`;a(await l(n.join(t$1,R),f,s$1),R);}}}p$1==="enterprise"&&(a(await l(n.join(t$1,D),Qe({workspacePath:t$1,generatedAt:h$1.generatedAt}),s$1),D),a(await l(n.join(t$1,E$1),Qe({workspacePath:t$1,generatedAt:h$1.generatedAt}),s$1),E$1)),p$1==="enterprise"&&e.experimentalHooks===true&&(a(await l(n.join(t$1,F$1),et({workspacePath:t$1,generatedAt:h$1.generatedAt}),s$1),F$1),a(await l(n.join(t$1,G),et({workspacePath:t$1,generatedAt:h$1.generatedAt}),s$1),G)),(P(c,"codex")||P(c,"orca"))&&(P(c,"agents")||a(await Se({absolutePath:n.join(t$1,"AGENTS.md"),generatedBody:Fe({index:h$1,context:b}),write:s$1}),"AGENTS.md"));let oe=s$1?await ze({workspacePath:t$1,staleAfterHours:o$1,now:r$1}):h$1,L=oe.reports.filter(i=>i.required&&!i.exists).map(i=>i.path),D$1=oe.reports.filter(i=>i.exists&&Rt(i.generatedAt,o$1,r$1)).map(i=>i.path);if(m$1){L.length>0&&_.push(`Missing required reports: ${L.join(", ")}`),D$1.length>0&&_.push(`Stale reports (>${o$1}h): ${D$1.join(", ")}`);let i=Q.map(g=>g.path).filter(g=>!_t(g));i.length>0&&_.push(`Unsafe generated output paths: ${i.join(", ")}`);}let Oe=Dt({workspacePath:t$1,generatedAt:r$1.toISOString(),preset:p$1,targets:d$1,index:oe,outputs:[...Q,{path:F,kind:"report",targets:["agents","vscode","copilot","codex","orca"],required:true,status:s$1?"written":e.dryRun?"planned":"skipped"}],missingRequired:L,staleReports:D$1,strictViolations:_,experimentalHooks:e.experimentalHooks===true});return a(await l(n.join(t$1,F),`${JSON.stringify(Oe,null,2)}
33
- `,s$1),F),{workspacePath:t$1,indexPath:n.join(t$1,Pe),packPath:n.join(t$1,F),pack:Oe,contextPath:I,writtenFiles:J,skippedFiles:Z,blockers:h$1.blockers,missingRequired:L,staleReports:D$1,strictViolations:_}}export{it as a,pt as b,wt as c,ht as d,Pe as e,F as f,N as g,ze as h,Pr as i,Rr as j,ft as k};