workspai 0.46.0 → 0.48.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 (143) hide show
  1. package/README.md +225 -81
  2. package/contracts/agent-customization-pack.v1.json +11 -1
  3. package/contracts/bootstrap-compliance.v1.json +14 -0
  4. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +4 -0
  5. package/contracts/extension-cli-compatibility.v1.json +13 -2
  6. package/contracts/mirror-ops.v1.json +16 -0
  7. package/contracts/published-contract-catalog.v1.json +59 -1
  8. package/contracts/runtime-command-surface.v1.json +294 -2
  9. package/contracts/transparency-evidence.v1.json +13 -0
  10. package/contracts/workspace-contract.v1.json +78 -0
  11. package/contracts/workspace-intelligence/model-usage-event.v1.json +82 -0
  12. package/contracts/workspace-intelligence/workspace-context.v1.json +20 -0
  13. package/contracts/workspace-intelligence/workspace-graph-token-efficiency.v1.json +72 -0
  14. package/contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json +53 -0
  15. package/contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json +120 -0
  16. package/contracts/workspace-intelligence/workspace-intelligence-run.v1.json +6 -1
  17. package/contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json +200 -0
  18. package/contracts/workspace-intelligence/workspace-knowledge-graph.v1.json +260 -0
  19. package/contracts/workspace-intelligence/workspace-knowledge-search.v1.json +60 -0
  20. package/contracts/workspace-intelligence-architecture.v1.json +37 -5
  21. package/contracts/workspace-intelligence-chain.v1.json +58 -6
  22. package/contracts/workspace-share-bundle.v1.json +16 -0
  23. package/dist/analyze-EEEU3MIF.js +1 -0
  24. package/dist/artifact-remediation-plan-SPOUHMK5.js +3 -0
  25. package/dist/autopilot-release-XGVXPOZI.js +1 -0
  26. package/dist/chunk-32OJDBIG.js +2 -0
  27. package/dist/chunk-37CVKXBD.js +1 -0
  28. package/dist/chunk-3NU32T4A.js +2 -0
  29. package/dist/chunk-3VFA7D5T.js +1 -0
  30. package/dist/chunk-4HDYADHT.js +13 -0
  31. package/dist/chunk-54EP5CEV.js +8 -0
  32. package/dist/chunk-5S3DJQEP.js +8 -0
  33. package/dist/chunk-AFL3ACCR.js +2 -0
  34. package/dist/{chunk-VFDM65IE.js → chunk-BFLJ2R4D.js} +22 -22
  35. package/dist/chunk-BGPXQQNY.js +4 -0
  36. package/dist/chunk-BMWFQXGW.js +1 -0
  37. package/dist/{chunk-UQWOVV6V.js → chunk-CRHYBQI3.js} +1 -1
  38. package/dist/chunk-CV5HKU4P.js +1 -0
  39. package/dist/chunk-ESLPI3XZ.js +1 -0
  40. package/dist/chunk-FB7SCXAZ.js +1 -0
  41. package/dist/{chunk-WPEEC5BX.js → chunk-HDXNIN4N.js} +1 -1
  42. package/dist/chunk-HZDXO65G.js +36 -0
  43. package/dist/{chunk-J5PIZCAU.js → chunk-I46XEIPL.js} +1 -1
  44. package/dist/chunk-J5ENLXDF.js +1 -0
  45. package/dist/chunk-KB44JP4M.js +2 -0
  46. package/dist/chunk-LHOZXC2M.js +2 -0
  47. package/dist/chunk-NAJCUQ4X.js +2 -0
  48. package/dist/chunk-OA537ZQ5.js +1 -0
  49. package/dist/chunk-OW42TZFB.js +1 -0
  50. package/dist/chunk-P3D5YQB2.js +1 -0
  51. package/dist/chunk-PHXQR6PX.js +2 -0
  52. package/dist/{chunk-ZKAI3PJE.js → chunk-PRTR2DQ2.js} +1 -1
  53. package/dist/{chunk-QA5BGEQW.js → chunk-QNONOO4F.js} +1 -1
  54. package/dist/chunk-RHQW3DTP.js +1 -0
  55. package/dist/chunk-T4YR4RAI.js +2 -0
  56. package/dist/chunk-THIOE2PB.js +2 -0
  57. package/dist/{chunk-4LGXSBCN.js → chunk-VU7NZHPM.js} +1 -1
  58. package/dist/chunk-WDKNMTJQ.js +1 -0
  59. package/dist/{chunk-YUATNVOT.js → chunk-Y5UJLPS4.js} +16 -16
  60. package/dist/{chunk-6IIZJQLV.js → chunk-YJZOMRAS.js} +1 -1
  61. package/dist/{create-WCV3L6XH.js → create-DBQNAMKP.js} +1 -1
  62. package/dist/{doctor-5BWM2EMJ.js → doctor-4NNUDNGZ.js} +1 -1
  63. package/dist/{dotnet-webapi-clean-6TVFBTVI.js → dotnet-webapi-clean-A6MVDYXX.js} +4 -4
  64. package/dist/{gofiber-standard-2BL7GWZB.js → gofiber-standard-I5YPQG5V.js} +1 -1
  65. package/dist/{gogin-standard-XGP3KBXA.js → gogin-standard-VY2L4QT5.js} +1 -1
  66. package/dist/index.d.ts +56 -14
  67. package/dist/index.js +322 -320
  68. package/dist/pipeline-TQM43A3K.js +5 -0
  69. package/dist/{springboot-standard-JJNUID6M.js → springboot-standard-55XKCBIZ.js} +4 -4
  70. package/dist/{workspace-7OXW5YTJ.js → workspace-NCWRINEF.js} +1 -1
  71. package/dist/{workspace-agent-sync-O4IA6VOA.js → workspace-agent-sync-662QHXGF.js} +1 -1
  72. package/dist/{workspace-archive-H74NBBNW.js → workspace-archive-P76EDIUG.js} +1 -1
  73. package/dist/{workspace-context-R7IPUBPG.js → workspace-context-23YYCUCP.js} +1 -1
  74. package/dist/workspace-contract-TU2I7GC2.js +1 -0
  75. package/dist/workspace-dependency-graph-BP4EXYQ5.js +1 -0
  76. package/dist/workspace-explain-MWUEN643.js +1 -0
  77. package/dist/workspace-explain-contract-ZPI3JXJU.js +1 -0
  78. package/dist/{workspace-feedback-REOS36ZZ.js → workspace-feedback-SUVH2LUJ.js} +1 -1
  79. package/dist/{workspace-foundation-KXT4QI5O.js → workspace-foundation-WXJ6I7ES.js} +1 -1
  80. package/dist/workspace-graph-token-efficiency-CFGFCJ5V.js +1 -0
  81. package/dist/{workspace-history-OGOVSKZG.js → workspace-history-BANOJRQ2.js} +1 -1
  82. package/dist/workspace-intelligence-MFJE7W67.js +1 -0
  83. package/dist/workspace-intelligence-evaluation-IPH7M3WV.js +1 -0
  84. package/dist/workspace-intelligence-runner-THYLHHMF.js +1 -0
  85. package/dist/workspace-knowledge-graph-ARDC6HHG.js +1 -0
  86. package/dist/workspace-knowledge-graph-change-overlay-XG6FC4IX.js +1 -0
  87. package/dist/workspace-knowledge-graph-export-UYAYFTWX.js +10 -0
  88. package/dist/workspace-knowledge-graph-query-VOSPPH4W.js +1 -0
  89. package/dist/workspace-mcp-serve-EZR6O76D.js +3 -0
  90. package/dist/workspace-model-7OU2M3LE.js +1 -0
  91. package/dist/workspace-model-hash-MHXK5MEI.js +1 -0
  92. package/dist/{workspace-registry-summary-SZ46R5PD.js → workspace-registry-summary-ORDK7A36.js} +1 -1
  93. package/dist/workspace-run-RLIYSOTN.js +1 -0
  94. package/dist/{workspace-verify-MFQ7IXGD.js → workspace-verify-EBVL7FWT.js} +1 -1
  95. package/dist/workspace-watch-3BPGLFLB.js +1 -0
  96. package/docs/AI_DYNAMIC_INTEGRATION.md +73 -428
  97. package/docs/AI_EXAMPLES.md +37 -395
  98. package/docs/AI_FEATURES.md +76 -456
  99. package/docs/AI_QUICKSTART.md +49 -212
  100. package/docs/GLOSSARY.md +64 -0
  101. package/docs/OPEN_SOURCE_USER_SCENARIOS.md +68 -7
  102. package/docs/README.md +70 -41
  103. package/docs/README_CONTENT_CONTRACT.md +154 -0
  104. package/docs/commands-reference.md +64 -4
  105. package/docs/config-file-guide.md +6 -2
  106. package/docs/contracts/ARTIFACT_CATALOG.md +76 -37
  107. package/docs/contracts/README.md +47 -8
  108. package/docs/graph-benchmark-methodology.md +121 -0
  109. package/docs/workspace-intelligence-evaluation.md +147 -0
  110. package/docs/workspace-knowledge-graph.md +316 -0
  111. package/docs/workspace-operations.md +49 -0
  112. package/package.json +2 -1
  113. package/dist/analyze-BEBEZSZK.js +0 -1
  114. package/dist/artifact-remediation-plan-FFQSESAM.js +0 -3
  115. package/dist/autopilot-release-WUR4CQIT.js +0 -1
  116. package/dist/chunk-2G7FASAO.js +0 -2
  117. package/dist/chunk-4EPHWD27.js +0 -8
  118. package/dist/chunk-CVHMUSRX.js +0 -1
  119. package/dist/chunk-DIPD72H4.js +0 -2
  120. package/dist/chunk-EFYHGCGX.js +0 -2
  121. package/dist/chunk-FWRXA435.js +0 -2
  122. package/dist/chunk-HDURFXW5.js +0 -2
  123. package/dist/chunk-HMUKBW2S.js +0 -4
  124. package/dist/chunk-K4WNYXKK.js +0 -33
  125. package/dist/chunk-LG6RFLPZ.js +0 -1
  126. package/dist/chunk-N7DV5L7C.js +0 -1
  127. package/dist/chunk-PRBVYW3T.js +0 -1
  128. package/dist/chunk-QZLIURER.js +0 -13
  129. package/dist/chunk-RIEF2DDX.js +0 -8
  130. package/dist/chunk-SXMTSV5M.js +0 -1
  131. package/dist/chunk-SXPY523X.js +0 -1
  132. package/dist/chunk-V3LRQZ36.js +0 -1
  133. package/dist/chunk-WYFPXTTS.js +0 -2
  134. package/dist/pipeline-ORIWVVYM.js +0 -5
  135. package/dist/workspace-contract-HKCMOMFE.js +0 -1
  136. package/dist/workspace-explain-GOPQYTPQ.js +0 -1
  137. package/dist/workspace-explain-contract-SVFJAAEI.js +0 -1
  138. package/dist/workspace-intelligence-7IESQSXY.js +0 -1
  139. package/dist/workspace-intelligence-runner-6GJ5M4HB.js +0 -1
  140. package/dist/workspace-mcp-serve-FRVWBO36.js +0 -3
  141. package/dist/workspace-model-PPYX7B4S.js +0 -1
  142. package/dist/workspace-run-V3KKHTVF.js +0 -1
  143. package/dist/workspace-watch-SOPZHRWA.js +0 -1
@@ -0,0 +1 @@
1
+ import {b as b$1}from'./chunk-NHN4QXPP.js';import {i}from'./chunk-MER6ZBN2.js';import {c}from'./chunk-PHXQR6PX.js';import {a}from'./chunk-Y45WZR5N.js';import {f}from'./chunk-7YHK5NM3.js';import {b}from'./chunk-RO73VVHW.js';import {h as h$1,g}from'./chunk-5XATWNME.js';import {promises}from'fs';import c$1 from'path';import v,{homedir}from'os';import {pathToFileURL}from'url';import d from'process';function E(t){let e=t.label.indexOf(" \u2014 ");return e>=0?t.label.slice(e+3).trim():t.label.trim()}function F(){let t=c().map(e=>({value:e.id,label:E(e),hint:e.description,name:e.label})),o=i().map(e=>({value:e.kitId,label:e.displayName,hint:e.commandDisplay("my-app"),name:`${e.displayName} \u2014 ${e.framework}`}));return [...t,...o]}var I=".workspairc.json",N=".rapidkitrc.json",D=["workspai.config.js","workspai.config.mjs","workspai.config.cjs","rapidkit.config.js","rapidkit.config.mjs","rapidkit.config.cjs"],S=["workspai.config.json","rapidkit.config.json"];function W(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT"}function h(t,o){let e=o instanceof Error?o.message:String(o),n=t.endsWith(".js")&&/module is not defined in ES module scope/i.test(e)?' CommonJS syntax in a .js config is not valid when the project package uses "type": "module"; rename the file to .cjs or use export default.':"";return `Failed to load Workspai config at ${t}.${n} Cause: ${e}`}async function he(){for(let t of [c$1.join(v.homedir(),I),c$1.join(v.homedir(),N)])try{let o=await promises.readFile(t,"utf-8"),e=JSON.parse(o);return f.debug(`Loaded config from ${t}`),e}catch{}return f.debug("No user config found, using defaults"),{}}async function ke(t=process.cwd(),o={}){let e=t,n=c$1.parse(e).root;for(;e!==n;){for(let r of S){let i=c$1.join(e,r);try{let s=await promises.readFile(i,"utf-8"),a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("configuration root must be a JSON object");return f.debug(`Loaded data-only Workspai config from ${r}`),a}catch(s){if(W(s))continue;throw new Error(h(i,s))}}for(let r of D){let i=c$1.join(e,r);try{await promises.access(i);}catch(s){if(W(s))continue;throw new Error(h(i,s))}if(f.debug(`Found config file: ${i}`),!o.trustExecutableConfig)throw new Error(`Refusing to execute Workspai config at ${i} without explicit trust. Use a data-only workspai.config.json file, pass --trust-config, or set WORKSPAI_TRUST_CONFIG=1.`);try{let a=await import(pathToFileURL(i).href),u=a.default||a;return f.debug(`Loaded Workspai config from ${r}`),u}catch(s){throw new Error(h(i,s))}}e=c$1.dirname(e);}return f.debug("No Workspai config file found, using defaults"),{}}function ye(t,o,e){return {author:e.author||o.workspace?.defaultAuthor||t.author,pythonVersion:e.pythonVersion||o.workspace?.pythonVersion||t.pythonVersion,defaultInstallMethod:e.defaultInstallMethod||o.workspace?.installMethod||t.defaultInstallMethod,defaultKit:e.defaultKit||o.projects?.defaultKit||t.defaultKit,skipGit:e.skipGit??o.projects?.skipGit??t.skipGit,license:e.license||t.license,testRapidKitPath:e.testRapidKitPath||t.testRapidKitPath}}function we(t){return a("DEV_PATH")||t.testRapidKitPath||void 0}function A(t,o){let e=t.indexOf(o);if(e>=0&&e+1<t.length)return t[e+1];let n=t.find(r=>r.startsWith(`${o}=`));if(n)return n.slice(o.length+1)}function L(t){return t.includes("--here")}function j(t,o=d.cwd()){if(L(t))return c$1.resolve(o);let e=A(t,"--output");if(e)return c$1.resolve(e)}function Fe(t,o=d.cwd()){let e=c$1.resolve(t),n=c$1.resolve(o),r=c$1.relative(n,e);return r.length>0&&!r.startsWith("..")&&!c$1.isAbsolute(r)?`cd ${r}`:`cd ${e}`}function Ke(t,o={}){let e=o.argv??[],n=o.outputParent??j(e,d.cwd());return h$1(t.trim(),{homeDir:o.homeDir,outputDir:n})}function Ie(t,o,e={}){return t?c$1.resolve(t)===c$1.resolve(o)?true:e.outputParent===void 0:false}async function Ne(t,o={}){let e=o.cwd??d.cwd(),n=o.homeDir??homedir(),r=j(t,e);if(r!==void 0)return r;let i=o.hasYes??(t.includes("--yes")||t.includes("-y"));if(!(o.interactive??(!i&&!!d.stdin.isTTY&&!b())))return;let a=g(n),{location:u}=await b$1([{type:"rawlist",name:"location",message:"Where should the workspace be created?",choices:[{value:"managed",label:"Managed home",hint:a},{value:"here",label:"Current directory",hint:e}],default:0}]);if(u==="here")return c$1.resolve(e)}export{F as a,he as b,ke as c,ye as d,we as e,Fe as f,Ke as g,Ie as h,Ne as i};
@@ -0,0 +1,2 @@
1
+ import {a as a$1,c as c$1,i,g,h as h$1}from'./chunk-4KUIFXHM.js';import {p,q}from'./chunk-5XATWNME.js';import T from'fs';import a from'path';import y from'fs-extra';var V=[{id:"fastapi.standard",aliases:["fastapi","fastapi.standard"],label:"fastapi \u2014 FastAPI Standard Kit",description:"Core-backed FastAPI service scaffold.",owner:"core",runtime:"python",framework:"fastapi",moduleSupport:true,stability:"stable"},{id:"fastapi.ddd",aliases:["fastapi.ddd","fastapi-ddd"],label:"fastapi \u2014 FastAPI DDD Kit",description:"Core-backed FastAPI DDD service scaffold.",owner:"core",runtime:"python",framework:"fastapi",moduleSupport:true,stability:"stable"},{id:"nestjs.standard",aliases:["nestjs","nest","nestjs.standard"],label:"nestjs \u2014 NestJS Standard Kit",description:"Core-backed NestJS service scaffold.",owner:"core",runtime:"node",framework:"nestjs",moduleSupport:true,stability:"stable"},{id:"springboot.standard",aliases:["spring","springboot","springboot.standard","java"],label:"spring \u2014 Spring Boot Standard Kit",description:"npm-backed Spring Boot service scaffold.",owner:"npm",runtime:"java",framework:"springboot",moduleSupport:false,stability:"stable",generator:"springboot",createUsage:"workspai create project springboot.standard <name> [--java-version <major>] [--spring-boot-version <semver>] [--group-id <com.example>] [--package-name <com.example.app>] [--port <number>]"},{id:"gofiber.standard",aliases:["go","go.standard","fiber","gofiber","gofiber.standard","go/fiber"],label:"go/fiber \u2014 Go Fiber Standard Kit",description:"npm-backed Go Fiber service scaffold.",owner:"npm",runtime:"go",framework:"gofiber",moduleSupport:false,stability:"stable",generator:"gofiber",createUsage:"workspai create project gofiber.standard <name> [--output <dir>]"},{id:"gogin.standard",aliases:["gin","gogin","gogin.standard","go/gin"],label:"go/gin \u2014 Go Gin Standard Kit",description:"npm-backed Go Gin service scaffold.",owner:"npm",runtime:"go",framework:"gogin",moduleSupport:false,stability:"stable",generator:"gogin",createUsage:"workspai create project gogin.standard <name> [--output <dir>]"},{id:"dotnet.webapi.clean",aliases:["dotnet","dotnet.webapi","dotnet.webapi.clean","aspnet","aspnetcore","asp.net","asp.net-core","csharp","c#"],label:"dotnet \u2014 ASP.NET Core Clean Web API",description:"npm-backed ASP.NET Core Web API with clean architecture boundaries.",owner:"npm",runtime:"dotnet",framework:"dotnet",moduleSupport:false,stability:"preview",generator:"dotnet-webapi-clean",createUsage:"workspai create project dotnet.webapi.clean <name> [--target-framework net8.0] [--root-namespace <Company.Product>] [--port <number>]"}],O=new Map;for(let e of V){O.set(e.id.toLowerCase(),e);for(let t of e.aliases)O.set(t.toLowerCase(),e);}function P(e){return e?O.get(e.trim().toLowerCase())??null:null}function qe(e){return P(e)?.id??e}function Ye(){return V.filter(e=>e.owner==="core"||e.generator)}function He(e){return P(e)?.owner==="npm"}async function ze(e,t){if(!e.generator)throw new Error(`Kit is not backed by an npm generator: ${e.id}`);if(e.generator==="gofiber"){let{generateGoFiberKit:r}=await import('./gofiber-standard-I5YPQG5V.js');await r(t.projectPath,{project_name:t.projectName,module_path:t.projectName,skipGit:t.skipGit,skipInstall:t.skipInstall});return}if(e.generator==="gogin"){let{generateGoGinKit:r}=await import('./gogin-standard-VY2L4QT5.js');await r(t.projectPath,{project_name:t.projectName,module_path:t.projectName,skipGit:t.skipGit,skipInstall:t.skipInstall});return}if(e.generator==="springboot"){let{generateSpringBootKit:r}=await import('./springboot-standard-55XKCBIZ.js');await r(t.projectPath,{project_name:t.projectName,artifact_id:t.projectName,java_version:c(t.args,"--java-version")?.trim(),spring_boot_version:c(t.args,"--spring-boot-version")?.trim(),springdoc_version:c(t.args,"--springdoc-version")?.trim(),group_id:c(t.args,"--group-id")?.trim(),package_name:c(t.args,"--package-name")?.trim(),description:c(t.args,"--description")?.trim(),port:c(t.args,"--port")?.trim(),skipGit:t.skipGit,skipInstall:t.skipInstall});return}if(e.generator==="dotnet-webapi-clean"){let{generateDotnetWebApiCleanKit:r}=await import('./dotnet-webapi-clean-A6MVDYXX.js');await r(t.projectPath,{project_name:t.projectName,target_framework:c(t.args,"--target-framework")?.trim(),root_namespace:c(t.args,"--root-namespace")?.trim(),description:c(t.args,"--description")?.trim(),port:c(t.args,"--port")?.trim(),skipGit:t.skipGit,skipInstall:t.skipInstall});return}throw new Error(`Unhandled npm kit generator: ${e.generator}`)}function c(e,t){let r=e.indexOf(t);if(r>=0&&r+1<e.length)return e[r+1];let n=e.find(i=>i.startsWith(`${t}=`));return n?n.slice(t.length+1):void 0}var j=["init","dev","start","build","test","lint","format","help"],X={python:{runtime:"python",displayName:"Python",tier:"first-class",scaffoldSupport:true,importSupport:true,lifecycleCommands:j,moduleCommands:true,doctorSupport:"full",notes:["Core-backed Python projects support RapidKit Core modules and lifecycle commands."]},node:{runtime:"node",displayName:"Node.js",tier:"extended",scaffoldSupport:true,importSupport:true,lifecycleCommands:j,moduleCommands:true,doctorSupport:"full",notes:["Node projects support npm-owned lifecycle commands; NestJS is the first-class Node framework."]},go:{runtime:"go",displayName:"Go",tier:"extended",scaffoldSupport:true,importSupport:true,lifecycleCommands:j,moduleCommands:false,doctorSupport:"readiness",notes:["Go projects support workspace governance and lifecycle commands via Go tooling."]},java:{runtime:"java",displayName:"Java / Spring Boot",tier:"extended",scaffoldSupport:true,importSupport:true,lifecycleCommands:j,moduleCommands:false,doctorSupport:"readiness",notes:["Java projects support Maven/Gradle lifecycle commands and workspace governance."]},dotnet:{runtime:"dotnet",displayName:".NET / ASP.NET Core",tier:"extended",scaffoldSupport:true,importSupport:true,lifecycleCommands:j,moduleCommands:false,doctorSupport:"readiness",notes:[".NET projects support dotnet CLI lifecycle commands and workspace governance."]},php:{runtime:"php",displayName:"PHP",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["PHP projects are importable and governed as observed projects until a kit exists."]},ruby:{runtime:"ruby",displayName:"Ruby",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["Ruby projects are importable and governed as observed projects until a kit exists."]},rust:{runtime:"rust",displayName:"Rust",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["Rust projects are importable and governed as observed projects until a kit exists."]},elixir:{runtime:"elixir",displayName:"Elixir",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["Elixir projects are importable and governed as observed projects until a kit exists."]},clojure:{runtime:"clojure",displayName:"Clojure",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["Clojure projects are importable and governed as observed projects until a kit exists."]},scala:{runtime:"scala",displayName:"Scala",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["Scala projects are importable and governed as observed projects until a kit exists."]},kotlin:{runtime:"kotlin",displayName:"Kotlin",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["Kotlin projects are importable and governed as observed projects until a kit exists."]},deno:{runtime:"deno",displayName:"Deno",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["Deno projects are importable and governed as observed projects until a kit exists."]},bun:{runtime:"bun",displayName:"Bun",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["Bun projects are importable and governed as observed projects until a kit exists."]},unknown:{runtime:"unknown",displayName:"Unknown",tier:"observed",scaffoldSupport:false,importSupport:true,lifecycleCommands:["help"],moduleCommands:false,doctorSupport:"observed",notes:["Unknown projects are tracked safely but require manual command configuration."]}},fe=["fastapi","nestjs"],ge=["django","flask","nextjs","remix","nuxt","react","vite","vue","sveltekit","svelte","angular","astro","solid","express","fastify","koa","echo","gofiber","gogin","springboot","dotnet","laravel","symfony","rails","sinatra","actix","axum","rocket","phoenix","clojure","scala","kotlin","deno","bun"];function x(e){return X[e||"unknown"]??X.unknown}function Q(e){return fe.includes(e)?"first-class":ge.includes(e)?"extended":"observed"}function Z(e){let t=x(e.runtime);return {lifecycleCommands:t.lifecycleCommands,moduleCommands:e.moduleSupport&&t.moduleCommands,unsupportedLifecycleCommands:j.filter(r=>!t.lifecycleCommands.includes(r))}}var ye=["python","node","go","java","dotnet"];function w(e){return !!e&&ye.includes(e)}function E(e,t){return t!=="lint"&&t!=="format"&&t!=="docs"?false:e==="python"}function ee(e){let t=x(e),r=w(t.runtime),n=be[t.runtime]??[],i=Ce[t.runtime]??[];return {runtime:t.runtime,displayName:t.displayName,lifecycleCommands:t.lifecycleCommands,hasExecutor:r,packageManagers:n,primaryFiles:i,notes:t.notes}}var be={python:["poetry","pip","uv"],node:["npm","pnpm","yarn","bun"],go:["go"],java:["maven","gradle"],dotnet:["dotnet"],php:["composer"],ruby:["bundle"],rust:["cargo"],elixir:["mix"],kotlin:["gradle"],deno:["deno"],bun:["bun"]},Ce={python:["pyproject.toml","requirements.txt","requirements.in"],node:["package.json"],go:["go.mod"],java:["pom.xml","build.gradle","build.gradle.kts"],dotnet:["*.csproj","*.sln"],php:["composer.json"],ruby:["Gemfile"],rust:["Cargo.toml"],elixir:["mix.exs"],kotlin:["settings.gradle.kts"],deno:["deno.json","deno.jsonc"],bun:["package.json","bunfig.toml"]};function h(e,t){let r=g({runtime:typeof e?.runtime=="string"?e.runtime:void 0,framework:typeof e?.framework=="string"?e.framework:void 0,kitName:typeof e?.kit_name=="string"?e.kit_name:typeof e?.kit=="string"?e.kit:void 0});return r.runtime!=="unknown"?r.runtime:i(t,e).runtime}function re(e){let t=e;for(;;){for(let n of p(t,"project.json"))if(T.existsSync(n))try{return JSON.parse(T.readFileSync(n,"utf8"))}catch{return null}let r=a.dirname(t);if(r===t)break;t=r;}return null}function st(e,t){return h(e,t)==="go"}function mt(e,t){return h(e,t)==="node"}function ct(e,t){return h(e,t)==="java"}function dt(e,t){return h(e,t)==="dotnet"}function pt(e,t){return h(e,t)==="python"}var Se=["project.json","context.json","file-hashes.json"];async function jt(e){let t=a.resolve(e),r=[];for(let n of Se){let i=q(t,n);if(await y.pathExists(i))continue;let m=a.join(t,".rapidkit",n);if(!await y.pathExists(m))continue;let f=await y.readJson(m);await y.ensureDir(a.dirname(i));let C=`${i}.${process.pid}.${Date.now()}.tmp`;try{await y.writeJson(C,f,{spaces:2}),await y.move(C,i,{overwrite:false}),r.push(i);}finally{await y.remove(C).catch(()=>{});}}return r}function je(e){for(let t of p(e,"context.json"))if(T.existsSync(t))try{return JSON.parse(T.readFileSync(t,"utf8"))}catch{return null}return null}function we(e){let t=e?.engine;return t==="npm"||t==="pip"||t==="python"?t:"unknown"}function xe(e,t){if(e?.module_support===false||t?.module_support===false||!e&&t)return false;let r=typeof e?.kit_name=="string"?e.kit_name:typeof e?.kit=="string"?e.kit:typeof t?.kit=="string"?t.kit:void 0,n=r?P(r):void 0;return n?.owner==="core"&&n.moduleSupport===true}function he(e,t,r){let n=g({runtime:typeof t?.runtime=="string"?t.runtime:typeof r?.runtime=="string"?r.runtime:void 0,framework:typeof t?.framework=="string"?t.framework:typeof r?.framework=="string"?r.framework:void 0,kitName:typeof t?.kit_name=="string"?t.kit_name:typeof t?.kit=="string"?t.kit:typeof r?.kit=="string"?r.kit:void 0});return n.key!=="unknown"?n:i(e,t)}function ne(e){let t=a.resolve(e);if(![...p(t,"project.json"),...p(t,"context.json")].some(f=>T.existsSync(f)))return null;let n=re(t),i=je(t),m=he(t,n,i);return {projectRoot:t,projectJson:n,contextJson:i,detection:m,moduleSupport:xe(n,i),engine:we(i)}}var Ne=["build","dev","start","test","lint","format"],I=["init","test","build","start"],ht=["lint","format","docs"];function Nt(e){return !!e&&Ne.includes(e)}var ve={dev:["dev","start:dev"],start:["start","start:prod","preview"],build:["build"],test:["test","test:unit","test:ci"],lint:["lint"],format:["format","prettier"]},ie={nestjs:{dev:["dev","start:dev"],start:["start","start:prod"],build:["build"],test:["test","test:e2e"],lint:["lint"],format:["format"]},express:{dev:["dev","start:dev"],start:["start"],build:["build"],test:["test"],lint:["lint"],format:["format"]},fastify:{dev:["dev","start:dev"],start:["start"],build:["build"],test:["test"],lint:["lint"],format:["format"]},koa:{dev:["dev","start:dev"],start:["start"],build:["build"],test:["test"],lint:["lint"],format:["format"]}};function Re(e){let t=a.join(e,"package.json");if(!T.existsSync(t))return {};try{let n=JSON.parse(T.readFileSync(t,"utf8")).scripts??{};return Object.fromEntries(Object.entries(n).filter(i=>typeof i[1]=="string"))}catch{return {}}}function Pe(e,t){let r=t?c$1(t):"unknown",n=r!=="unknown"?a$1(r,e):[],i=t?ie[t]?.[e]??[]:[],m=ve[e]??[],f=[...n,...i,...m];return [...new Set(f)]}function ae(e,t,r){let n=Re(e),i=new Set(Object.keys(n));if(i.has(t))return {scriptName:t,source:"package.json"};for(let m of Pe(t,r?.framework))if(i.has(m))return {scriptName:m,source:a$1(c$1(r?.framework??"unknown"),t).includes(m)||ie[r?.framework??""]?.[t]?.includes(m)?"framework-candidate":"generic-candidate"};return null}function B(e){return T.existsSync(a.join(e,"package.json"))}function se(e){let t=ee(e);return t.runtime==="unknown"&&e!=="unknown"?null:{runtime:t.runtime,displayName:t.displayName,supportedCommands:t.lifecycleCommands,packageManagers:t.packageManagers,primaryFiles:t.primaryFiles,notes:t.notes,hasExecutor:t.hasExecutor}}function s(e){try{return T.existsSync(e)}catch{return false}}function b(e){try{return s(e)?T.readFileSync(e,"utf8"):""}catch{return ""}}function u(e,t){let r=b(a.join(e,"Makefile"));return r?new RegExp(`^${t}\\s*:`).test(r):false}function Ee(e){let t=[e];for(;t.length>0;){let r=t.shift();if(!r)break;let n=[];try{n=T.readdirSync(r,{withFileTypes:true});}catch{continue}for(let i of n){if(i.name==="node_modules"||i.name===".git"||i.name==="dist")continue;let m=a.join(r,i.name);if(i.isFile()&&i.name.endsWith(".csproj"))return true;i.isDirectory()&&t.push(m);}}return false}function me(e,t){let r=s(a.join(e,"pyproject.toml")),n=s(a.join(e,"requirements.txt"))||s(a.join(e,"requirements.in")),i=s(a.join(e,"manage.py"));switch(t){case "init":return r||n;case "dev":case "start":return r||i||n;case "test":return r||n||s(a.join(e,"tests"));case "build":return r||n;case "lint":case "format":return r||n||i||s(a.join(e,"setup.py"))||s(a.join(e,"setup.cfg"));default:return false}}function Me(e,t){if(!s(a.join(e,"go.mod")))return false;switch(t){case "init":return true;case "dev":return u(e,"run")||s(a.join(e,"main.go"));case "test":return true;case "build":return true;case "start":return u(e,"run")||s(a.join(e,"main.go"))||s(a.join(e,"cmd"));case "lint":return s(a.join(e,".golangci.yml"))||s(a.join(e,".golangci.yaml"))||u(e,"lint");case "format":return u(e,"fmt")||u(e,"format");default:return false}}function _e(e,t){let r=s(a.join(e,"pom.xml")),n=s(a.join(e,"build.gradle"))||s(a.join(e,"build.gradle.kts"));if(!r&&!n)return false;switch(t){case "init":case "test":case "build":case "dev":case "start":return true;case "lint":return u(e,"lint")||b(a.join(e,"pom.xml")).includes("checkstyle")||b(a.join(e,"build.gradle")).includes("checkstyle")||b(a.join(e,"build.gradle.kts")).includes("checkstyle");case "format":return u(e,"format")||b(a.join(e,"build.gradle")).includes("spotless")||b(a.join(e,"build.gradle.kts")).includes("spotless");default:return false}}function Ae(e,t){if(!Ee(e))return false;switch(t){case "init":case "dev":case "test":case "build":case "start":return true;case "lint":return u(e,"lint")||b(a.join(e,"Directory.Build.props")).includes("EnforceCodeStyleInBuild");case "format":return u(e,"format")||s(a.join(e,".editorconfig"));default:return false}}function Fe(e,t,r){return t==="init"?B(e):ae(e,t,{framework:r})!==null}function Le(e,t,r){switch(t){case "php":return r==="init"&&s(a.join(e,"composer.json"));case "ruby":return r==="init"&&s(a.join(e,"Gemfile"));case "rust":return s(a.join(e,"Cargo.toml"))?r==="init"||r==="test"||r==="build"||r==="start":false;case "elixir":return r==="init"&&s(a.join(e,"mix.exs"));case "deno":return s(a.join(e,"deno.json"))||s(a.join(e,"deno.jsonc"))?r==="init"||r==="dev"||r==="test"||r==="start":r==="init"&&s(a.join(e,"package.json"));case "bun":return s(a.join(e,"bunfig.toml"))||s(a.join(e,"bun.lock"))?r==="init"||r==="dev"||r==="test"||r==="build"||r==="start":r==="init"&&s(a.join(e,"package.json"));default:return false}}function _(e,t,r,n){if(E(t,r))return me(e,r);if(!w(t))return Le(e,t,r);switch(t){case "node":return Fe(e,r,n);case "python":return me(e,r);case "go":return Me(e,r);case "java":return _e(e,r);case "dotnet":return Ae(e,r);default:return false}}function De(e,t,r){return ["init","dev","start","build","test","lint","format"].filter(i=>_(e,t,i,r))}function ce(e){let t=Z({runtime:e.runtime,moduleSupport:e.moduleSupport});if(!e.projectPath)return t;let r=De(e.projectPath,e.runtime,e.framework),n=new Set(["help"]);for(let m of r)t.lifecycleCommands.includes(m)&&n.add(m);e.runtime==="node"&&B(e.projectPath)&&n.add("init");let i=[...n].sort();return {lifecycleCommands:i,moduleCommands:t.moduleCommands,unsupportedLifecycleCommands:t.lifecycleCommands.filter(m=>!i.includes(m)).sort()}}var W=["version","commands","doctor","project","help"],A=["init","dev","start","build","test","lint","format"],$=["add","modules","upgrade","diff","merge","reconcile","rollback","uninstall","checkpoint","snapshot","optimize"],J=["create","list","info","frameworks","license"];W.filter(e=>e!=="help");function Te(e){let t=a.resolve(e);for(;;){if([...p(t,"project.json"),...p(t,"context.json")].some(i=>T.existsSync(i)))return t;let n=a.dirname(t);if(n===t)break;t=n;}return null}function N(e,t){return {command:e,...t}}var Ie=new Set(["dev","lint","format"]),Ke=new Set(I);function Be(e,t){return t?Ke.has(e)?{executionScope:"fleet",fleetEligible:true}:Ie.has(e)?{executionScope:"local-only",fleetEligible:false}:{executionScope:"local-only",fleetEligible:false}:{executionScope:"local-only",fleetEligible:false}}function Ge(e,t){return E(t.runtime,e)?"core":"runtime"}function Ue(e,t,r,n){return !e||!n.lifecycleCommands.includes(t)?false:_(e,r.runtime,t,r.key)}function We(e,t){let r=!!e&&(t.runtime==="python"||w(t.runtime)&&_(e,t.runtime,"build",t.key));return N("docs",{owner:t.runtime==="python"?"core":"runtime",status:r?"supported":"unsupported",reason:r?t.runtime==="python"?"Documentation generation is delegated to Python Core for this project.":"Project documentation commands are available through the npm wrapper for this runtime.":"Documentation commands require a supported Python or npm-executor project manifest."})}function $e(e){let t=a.resolve(e),r=Te(e);return r||(h$1(t).length>0?t:null)}function Je(e=process.cwd()){let t=$e(e),r=t?ne(t):null,n=r?.detection??i(e,r?.projectJson??null),i$1=r?.moduleSupport??false,m=r?.engine??"unknown",f=se(n.runtime),C=x(n.runtime),pe=ce({runtime:n.runtime,moduleSupport:i$1,projectPath:t??void 0,framework:n.key}),g={};for(let o of W)g[o]=N(o,{owner:o==="project"?"core":"npm",status:"supported",reason:o==="project"?"Project detection is a Core contract; workspace project lifecycle remains npm-owned.":o==="help"?"Help is available for every Workspai project through the npm CLI.":"Universal command available across Workspai project types."});for(let o of A){let k=Ue(t,o,n,pe),Y=Ge(o,n),F=Be(o,k);g[o]=N(o,{owner:Y,status:k?"supported":"unsupported",executionScope:F.executionScope,fleetEligible:F.fleetEligible,reason:k?Y==="core"?`Delegated to Python Core for ${n.displayName} projects.`:F.fleetEligible?`Handled by runtime adapter and eligible for workspace fleet stages (${o}).`:o==="dev"?"Local development command only; workspace fleet excludes dev by design.":n.runtime==="node"?`Handled by npm/pnpm/yarn via the resolved ${o} script in package.json.`:`Handled by the ${f?.displayName??n.displayName} runtime adapter for local project execution.`:t?n.runtime==="node"?`No ${o} script was found in package.json for this ${n.displayName} project.`:w(n.runtime)?`The ${n.displayName} runtime is tracked, but ${o} is not available from detected project manifests.`:`${n.displayName} is tracked as an observed runtime; ${o} requires project manifests or explicit scripts.`:"No Workspai project was detected."});}g.docs=We(t,n);for(let o of $)g[o]=N(o,{owner:i$1?"core":"none",status:i$1?"supported":"unsupported",reason:i$1?"Core module/template command supported for this project.":`Core module/template commands are not available for ${n.displayName} projects.`});for(let o of J)g[o]=N(o,{owner:o==="create"?"npm":"core",status:"global",reason:o==="create"?"Create is orchestrated by npm for multi-language workspace support.":"Engine catalog command; not specific to the selected project runtime."});let v=Object.values(g),q=v.filter(o=>A.includes(o.command)).filter(o=>o.status==="supported"),le=I.filter(o=>q.some(k=>k.fleetEligible===true&&k.command===o)),ue=q.filter(o=>o.executionScope==="local-only").map(o=>o.command).sort();return {schemaVersion:1,scope:"project",projectRoot:t,engine:m,runtime:n.runtime,framework:n.key,frameworkDisplayName:n.displayName,frameworkConfidence:n.confidence,frameworkSupportTier:Q(n.key),runtimeSupportTier:C.tier,runtimeDoctorSupport:C.doctorSupport,moduleSupport:i$1,fleetStages:le,localOnlyCommands:ue,commandMap:g,supportedCommands:v.filter(o=>o.status==="supported").map(o=>o.command).sort(),unsupportedCommands:v.filter(o=>o.status==="unsupported").map(o=>o.command).sort(),globalCommands:v.filter(o=>o.status==="global").map(o=>o.command).sort()}}function ir(e,t=process.cwd()){let r=e[0];return r?Je(t).commandMap[r]??null:null}function ar(e){if(e[0]==="project"&&e[1]==="commands")return true;if(e[0]==="commands"&&e.includes("--scope")){let t=e.indexOf("--scope");return e[t+1]==="project"}return e.some(t=>t==="--scope=project")&&e[0]==="commands"}function sr(e,t){return [`Workspai command not supported for this project: ${e.command}`,"",`Project: ${t.projectRoot??"not detected"}`,`Runtime: ${t.runtime}`,`Framework: ${t.frameworkDisplayName}`,`Reason: ${e.reason??"Unsupported for this project type."}`,"","Run `workspai project commands` to inspect supported commands for this project."].join(`
2
+ `)}export{P as a,qe as b,Ye as c,He as d,ze as e,x as f,Q as g,w as h,re as i,st as j,mt as k,ct as l,dt as m,pt as n,jt as o,ne as p,Ne as q,ht as r,Nt as s,ae as t,ce as u,Te as v,Je as w,ir as x,ar as y,sr as z};
@@ -1 +1 @@
1
- import {b}from'./chunk-CVHMUSRX.js';import {a,b as b$1}from'./chunk-S5KTATOU.js';function f(r){let s=new Map;for(let n of r.projects)s.has(n.name)||s.set(n.name,b(n));return s}function j(r){let s=f(r),n=r.graph??{nodes:r.projects.map(t=>({id:t.name,path:t.path})),edges:[]},a$1=a(n),o=new Map;for(let t of n.nodes){let e=s.get(t.id)??b({missing:t.id}),g=[...b$1(a$1,[t.id],{direction:"dependencies"}).keys()].filter(c=>c!==t.id).sort((c,l)=>c.localeCompare(l)).map(c=>({id:c,hash:s.get(c)??"<unknown>"}));o.set(t.id,{id:t.id,ownHash:e,transitiveInputsHash:b({own:e,dependencies:g})});}return o}function v(r,s){if(!s||Object.keys(s).length===0)return {verdict:"unknown",baseline:"none",changed:[],added:[],removed:[]};let n=[],a=[];for(let[e,i]of r.entries())e in s?s[e]!==i.transitiveInputsHash&&n.push(e):a.push(e);let o=[];for(let e of Object.keys(s))r.has(e)||o.push(e);return n.sort((e,i)=>e.localeCompare(i)),a.sort((e,i)=>e.localeCompare(i)),o.sort((e,i)=>e.localeCompare(i)),{verdict:n.length>0||a.length>0||o.length>0?"stale":"fresh",baseline:"recorded",changed:n,added:a,removed:o}}function w(r){let s={};for(let[n,a]of [...r.entries()].sort((o,t)=>o[0].localeCompare(t[0])))s[n]=a.transitiveInputsHash;return s}export{f as a,j as b,v as c,w as d};
1
+ import {b}from'./chunk-J5ENLXDF.js';import {a,b as b$1}from'./chunk-S5KTATOU.js';function f(r){let s=new Map;for(let n of r.projects)s.has(n.name)||s.set(n.name,b(n));return s}function j(r){let s=f(r),n=r.graph??{nodes:r.projects.map(t=>({id:t.name,path:t.path})),edges:[]},a$1=a(n),o=new Map;for(let t of n.nodes){let e=s.get(t.id)??b({missing:t.id}),g=[...b$1(a$1,[t.id],{direction:"dependencies"}).keys()].filter(c=>c!==t.id).sort((c,l)=>c.localeCompare(l)).map(c=>({id:c,hash:s.get(c)??"<unknown>"}));o.set(t.id,{id:t.id,ownHash:e,transitiveInputsHash:b({own:e,dependencies:g})});}return o}function v(r,s){if(!s||Object.keys(s).length===0)return {verdict:"unknown",baseline:"none",changed:[],added:[],removed:[]};let n=[],a=[];for(let[e,i]of r.entries())e in s?s[e]!==i.transitiveInputsHash&&n.push(e):a.push(e);let o=[];for(let e of Object.keys(s))r.has(e)||o.push(e);return n.sort((e,i)=>e.localeCompare(i)),a.sort((e,i)=>e.localeCompare(i)),o.sort((e,i)=>e.localeCompare(i)),{verdict:n.length>0||a.length>0||o.length>0?"stale":"fresh",baseline:"recorded",changed:n,added:a,removed:o}}function w(r){let s={};for(let[n,a]of [...r.entries()].sort((o,t)=>o[0].localeCompare(t[0])))s[n]=a.transitiveInputsHash;return s}export{f as a,j as b,v as c,w as d};
@@ -1,4 +1,4 @@
1
- import {d,b as b$1,e}from'./chunk-WPEEC5BX.js';import {j,q as q$1,n}from'./chunk-DIPD72H4.js';import {h,i,f as f$1,e as e$1}from'./chunk-4KUIFXHM.js';import {d as d$1}from'./chunk-S5KTATOU.js';import {f}from'./chunk-HDURFXW5.js';import {a}from'./chunk-GZTYAEWX.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {p,l,o}from'./chunk-5XATWNME.js';import {e as e$2,g}from'./chunk-EYJ2CQSK.js';import _ from'fs';import b from'path';import E from'chalk';import {execa}from'execa';function Se(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 Ee(e,t,r=Se(e)){return r==="npm"?`npm run ${t}`:`${r} run ${t}`}function Ce(e,t=Se(e)){return `${t} install`}var Ge={"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:[]}}},Be={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 se(e,t){if(t){let r=t.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=e$1(t),s=`${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 Ge[s]}}function Pe(e,t,r){if(t){let n=se(e,t);if(n&&n.commands[r])return n.commands[r]}if(["init","test","build","start"].includes(r)){let n=Be[r]?.[e]??[];return n.length>0?n[0]:void 0}}var ze={test:"test",build:"build",start:"start"};function ae(e){if(e.stage==="init")return e.runtime==="node"?Ce(e.projectPath):Pe(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let t=ze[e.stage];if(t){let r=n(e.projectPath,t,{framework:e.framework});if(r)return Ee(e.projectPath,r.scriptName)}}return Pe(e.runtime,e.framework,e.stage)}function Ke(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 Fe(e){return Ke(e).primary}function ie(e,t){if(!e)return "unknown";t||(t={setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[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 Ae(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 Ne={init:"init",test:"test",build:"build",start:"start"};function Ve(e){return e in Ne?Ne[e]:null}function He(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 s=o,c=s.default??s.dev;if(typeof c=="string"&&c.trim().length>0)return c.trim()}}function Oe(e,t,r=q$1(e)){let n=Ve(t);if(!n)return He(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];if(!o||o.status!=="supported"){let s=r.runtimeSupportTier==="observed"||r.frameworkSupportTier==="observed";return {supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!s}}return {supported:true}}var Ue=new Set(["init","test","build","start"]),Je=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 qe(e){for(let t of e)if(await I(t))return true;return false}async function Ye(e,t,r){if(t==="python"){let o=[b.join(e,".workspai","cli.py"),b.join(e,".rapidkit","cli.py")];for(let s of o)if(await I(s))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 ue(e){let t=await _.promises.readFile(e,"utf-8");return JSON.parse(t)}function N(e){return e.replace(/\\/g,"/")}function Qe(e){let t=e?.trim();return t?t.startsWith("project:")?t.slice(8).trim()||null:t:null}async function Xe(e){return a(e,{skipDirs:Je,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t,r)=>await qe([...p(t,"context.json"),...p(t,"project.json")])?true:b.resolve(t)===b.resolve(r)?false:h(t).length>0})}async function Ze(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 ue(r),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function et(e,t,r){let n=Qe(r);if(!n)return {projects:t,normalizedScope:null};let o=N(n).toLowerCase(),s=[];for(let c of t){let u=N(b.relative(e,c)),p=b.basename(c),m=await Ze(c);[u,p,m].filter(a=>typeof a=="string"&&a.length>0).map(a=>N(a).toLowerCase()).includes(o)&&s.push(c);}if(s.length===0)throw new Error(`Workspace run scope did not match any project: ${r}`);return {projects:s,normalizedScope:n}}async function tt(e,t,r){let n=await execa("git",["diff","--name-only",`${r}...HEAD`],{cwd:e,reject:false,env:a$1()});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=>N(c));if(o.length===0)return new Set;let s=new Set;for(let c of t){let u=N(b.relative(e,c));if(!u||u===".")continue;let p=`${u}/`;o.some(m=>m===u||m.startsWith(p))&&s.add(c);}return s}async function rt(e,t,r){let n=await f(e,".workspai/workspace.contract.json")??l(e,"workspace.contract.json");if(await I(n))try{let g=await nt(e,t,r,n);if(g.graphStatus!=="missing")return g}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let o=await f(e,".workspai/workspace-dependency-graph.json")??l(e,"workspace-dependency-graph.json");if(!await I(o))return {expanded:r,graphStatus:"missing",expansionDepth:0};let s;try{s=await ue(o);}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let c=new Set(t.map(g=>b.resolve(g))),u=new Map;if(!s||typeof s!="object"||Array.isArray(s))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let p=Array.isArray(s.projects)?s.projects:[];for(let g of p){if(!g||typeof g!="object"||Array.isArray(g))continue;let a=g,d=typeof a.path=="string"?a.path:"",y=b.resolve(e,d);if(!c.has(y))continue;let h=Array.isArray(a.dependsOn)?a.dependsOn.filter(w=>typeof w=="string"):[];for(let w of h){let x=b.resolve(e,w);c.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 nt(e,t,r,n){let o=await ue(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let s=o,c=Array.isArray(s.projects)?s.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=N(b.relative(e,y));p.set(h,b.resolve(y));}let m=new Map,g=new Map,a=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"?N(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"):[],O=Array.isArray(R.publishes)?R.publishes.filter(v=>typeof v=="string"):[],W=Array.isArray(R.consumes)?R.consumes.filter(v=>typeof v=="string"):[];for(let v of j){let S=u.get(v);S&&(a.has(S)||a.set(S,new Set),a.get(S)?.add(x));}for(let v of O)m.has(v)||m.set(v,new Set),m.get(v)?.add(x);for(let v of W)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){a.has(x)||a.set(x,new Set);for(let R of w)R!==x&&a.get(x)?.add(R);}}let d=d$1(a,r);return {expanded:d.reached,graphStatus:"loaded",expansionDepth:d.added}}async function ot(e,t){if(typeof t=="boolean")return t;let r=o(e,"policies.yml").find(s=>_.existsSync(s))??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 st(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 ce(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 at(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"}function it(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}async function ct(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 ut(e){let t=a=>{let d=f$1(a);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":Fe(e)},r=a=>{if(!a)return;let d=e$1(a);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),s=n?.contextJson,c=t(o.runtime),u=r(o.key),p={},m=new Set(["init","test","build","start"]);if(s?.commands&&typeof s.commands=="object")for(let[a,d]of Object.entries(s.commands))typeof d=="string"&&m.has(a)&&(p[a]=d);let g;if(s?.commandEnvironments&&typeof s.commandEnvironments=="object"){let a=s.commandEnvironments;g={dev:typeof a.dev=="string"?a.dev:void 0,staging:typeof a.staging=="string"?a.staging:void 0,prod:typeof a.prod=="string"?a.prod:void 0,default:typeof a.default=="string"?a.default:void 0};}return {runtime:c,framework:u,commandOverrides:Object.keys(p).length>0?p:void 0,environmentCommandVariants:g,environment:typeof s?.environment=="string"?s.environment:void 0}}async function dt(e,t,r,n,o,s,c){let u=!o?.[t]&&at(r),p;if(o&&o[t]?p=o[t]:u?p=`rapidkit ${t}`:p=ae({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=Ae(p,s,c);if(!m)return {exitCode:127,command:p,message:"Failed to resolve stage command",errorCategory:"runtime"};let g=ae({projectPath:e,runtime:r,framework:n,stage:t});if(u){if(g){let f=u?await Ye(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 a=0,d="",y="",h,w=st(t),x=Date.now();try{let f=u?t==="init"&&it()?await ct(e):await ce([t],e,w):await execa(m,[],{cwd:e,reject:false,shell:true,timeout:w});if(a=Number(f.exitCode??0),d=f.stdout,y=f.stderr,a!==0){let C=`${d}
1
+ import {d,b as b$1,e}from'./chunk-HDXNIN4N.js';import {d as d$2}from'./chunk-S5KTATOU.js';import {p as p$1,w,t}from'./chunk-PHXQR6PX.js';import {h,i,f,e as e$1}from'./chunk-4KUIFXHM.js';import {d as d$1}from'./chunk-32OJDBIG.js';import {a}from'./chunk-GZTYAEWX.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {p,l,o}from'./chunk-5XATWNME.js';import {e as e$2,g}from'./chunk-EYJ2CQSK.js';import _ from'fs';import b from'path';import E from'chalk';import {execa}from'execa';function Se(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 Ee(e,t,r=Se(e)){return r==="npm"?`npm run ${t}`:`${r} run ${t}`}function Ce(e,t=Se(e)){return `${t} install`}var Ge={"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:[]}}},Be={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 se(e,t){if(t){let r=t.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=e$1(t),s=`${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 Ge[s]}}function Pe(e,t,r){if(t){let n=se(e,t);if(n&&n.commands[r])return n.commands[r]}if(["init","test","build","start"].includes(r)){let n=Be[r]?.[e]??[];return n.length>0?n[0]:void 0}}var ze={test:"test",build:"build",start:"start"};function ae(e){if(e.stage==="init")return e.runtime==="node"?Ce(e.projectPath):Pe(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let t$1=ze[e.stage];if(t$1){let r=t(e.projectPath,t$1,{framework:e.framework});if(r)return Ee(e.projectPath,r.scriptName)}}return Pe(e.runtime,e.framework,e.stage)}function Ke(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 Fe(e){return Ke(e).primary}function ie(e,t){if(!e)return "unknown";t||(t={setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[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 Ae(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 Ne={init:"init",test:"test",build:"build",start:"start"};function Ve(e){return e in Ne?Ne[e]:null}function He(e,t){let n=p$1(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 s=o,c=s.default??s.dev;if(typeof c=="string"&&c.trim().length>0)return c.trim()}}function Oe(e,t,r=w(e)){let n=Ve(t);if(!n)return He(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];if(!o||o.status!=="supported"){let s=r.runtimeSupportTier==="observed"||r.frameworkSupportTier==="observed";return {supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!s}}return {supported:true}}var Ue=new Set(["init","test","build","start"]),Je=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 qe(e){for(let t of e)if(await I(t))return true;return false}async function Ye(e,t,r){if(t==="python"){let o=[b.join(e,".workspai","cli.py"),b.join(e,".rapidkit","cli.py")];for(let s of o)if(await I(s))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 ue(e){let t=await _.promises.readFile(e,"utf-8");return JSON.parse(t)}function N(e){return e.replace(/\\/g,"/")}function Qe(e){let t=e?.trim();return t?t.startsWith("project:")?t.slice(8).trim()||null:t:null}async function Xe(e){return a(e,{skipDirs:Je,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t,r)=>await qe([...p(t,"context.json"),...p(t,"project.json")])?true:b.resolve(t)===b.resolve(r)?false:h(t).length>0})}async function Ze(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 ue(r),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function et(e,t,r){let n=Qe(r);if(!n)return {projects:t,normalizedScope:null};let o=N(n).toLowerCase(),s=[];for(let c of t){let u=N(b.relative(e,c)),p=b.basename(c),m=await Ze(c);[u,p,m].filter(a=>typeof a=="string"&&a.length>0).map(a=>N(a).toLowerCase()).includes(o)&&s.push(c);}if(s.length===0)throw new Error(`Workspace run scope did not match any project: ${r}`);return {projects:s,normalizedScope:n}}async function tt(e,t,r){let n=await execa("git",["diff","--name-only",`${r}...HEAD`],{cwd:e,reject:false,env:a$1()});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=>N(c));if(o.length===0)return new Set;let s=new Set;for(let c of t){let u=N(b.relative(e,c));if(!u||u===".")continue;let p=`${u}/`;o.some(m=>m===u||m.startsWith(p))&&s.add(c);}return s}async function rt(e,t,r){let n=await d$1(e,".workspai/workspace.contract.json")??l(e,"workspace.contract.json");if(await I(n))try{let g=await nt(e,t,r,n);if(g.graphStatus!=="missing")return g}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let o=await d$1(e,".workspai/workspace-dependency-graph.json")??l(e,"workspace-dependency-graph.json");if(!await I(o))return {expanded:r,graphStatus:"missing",expansionDepth:0};let s;try{s=await ue(o);}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let c=new Set(t.map(g=>b.resolve(g))),u=new Map;if(!s||typeof s!="object"||Array.isArray(s))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let p=Array.isArray(s.projects)?s.projects:[];for(let g of p){if(!g||typeof g!="object"||Array.isArray(g))continue;let a=g,d=typeof a.path=="string"?a.path:"",y=b.resolve(e,d);if(!c.has(y))continue;let h=Array.isArray(a.dependsOn)?a.dependsOn.filter(w=>typeof w=="string"):[];for(let w of h){let x=b.resolve(e,w);c.has(x)&&(u.has(x)||u.set(x,new Set),u.get(x)?.add(y));}}let m=d$2(u,r);return {expanded:m.reached,graphStatus:"loaded",expansionDepth:m.added}}async function nt(e,t,r,n){let o=await ue(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let s=o,c=Array.isArray(s.projects)?s.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=N(b.relative(e,y));p.set(h,b.resolve(y));}let m=new Map,g=new Map,a=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"?N(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"):[],O=Array.isArray(R.publishes)?R.publishes.filter(v=>typeof v=="string"):[],W=Array.isArray(R.consumes)?R.consumes.filter(v=>typeof v=="string"):[];for(let v of j){let S=u.get(v);S&&(a.has(S)||a.set(S,new Set),a.get(S)?.add(x));}for(let v of O)m.has(v)||m.set(v,new Set),m.get(v)?.add(x);for(let v of W)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){a.has(x)||a.set(x,new Set);for(let R of w)R!==x&&a.get(x)?.add(R);}}let d=d$2(a,r);return {expanded:d.reached,graphStatus:"loaded",expansionDepth:d.added}}async function ot(e,t){if(typeof t=="boolean")return t;let r=o(e,"policies.yml").find(s=>_.existsSync(s))??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 st(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 ce(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 at(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"}function it(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}async function ct(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 ut(e){let t=a=>{let d=f(a);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":Fe(e)},r=a=>{if(!a)return;let d=e$1(a);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=p$1(e),o=n?.detection??i(e,n?.projectJson??null),s=n?.contextJson,c=t(o.runtime),u=r(o.key),p={},m=new Set(["init","test","build","start"]);if(s?.commands&&typeof s.commands=="object")for(let[a,d]of Object.entries(s.commands))typeof d=="string"&&m.has(a)&&(p[a]=d);let g;if(s?.commandEnvironments&&typeof s.commandEnvironments=="object"){let a=s.commandEnvironments;g={dev:typeof a.dev=="string"?a.dev:void 0,staging:typeof a.staging=="string"?a.staging:void 0,prod:typeof a.prod=="string"?a.prod:void 0,default:typeof a.default=="string"?a.default:void 0};}return {runtime:c,framework:u,commandOverrides:Object.keys(p).length>0?p:void 0,environmentCommandVariants:g,environment:typeof s?.environment=="string"?s.environment:void 0}}async function dt(e,t,r,n,o,s,c){let u=!o?.[t]&&at(r),p;if(o&&o[t]?p=o[t]:u?p=`rapidkit ${t}`:p=ae({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=Ae(p,s,c);if(!m)return {exitCode:127,command:p,message:"Failed to resolve stage command",errorCategory:"runtime"};let g=ae({projectPath:e,runtime:r,framework:n,stage:t});if(u){if(g){let f=u?await Ye(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 a=0,d="",y="",h,w=st(t),x=Date.now();try{let f=u?t==="init"&&it()?await ct(e):await ce([t],e,w):await execa(m,[],{cwd:e,reject:false,shell:true,timeout:w});if(a=Number(f.exitCode??0),d=f.stdout,y=f.stderr,a!==0){let C=`${d}
2
2
  ${y}`,z=Date.now()-x;h=a===124||ie(C)==="timeout"||a===143&&z>=Math.floor(w*.8)?"timeout":ie(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
3
  ${y}`.split(/\r?\n/).map(f=>f.trim()).filter(Boolean),O=j.slice(0,6).join(`
4
4
  `),W=Date.now()-x,v=a===124||h==="timeout"||a===143&&W>=Math.floor(w*.8),S=a===0?void 0:v?"timeout":h,T=a===0||!S?void 0:{category:S,exitCode:a,command:m,timedOut:v,timeoutMs:w,...O?{outputExcerpt:O}:{}};return {exitCode:a,command:m,errorCategory:S,healthStatus:R,failureDiagnostic:T,message:v?`Stage timed out after ${w}ms`:a!==0?O?`Stage failed with exit code ${a}: ${j[0]}`:`Stage failed with exit code ${a}`:void 0}}function De(e){try{return JSON.parse(e)}catch{return null}}function lt(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 pt(e){let t=[],r=await ce(["doctor","workspace","--json"],e);if(r.exitCode!==0)t.push({gate:"doctor-workspace",status:"fail",summary:"doctor workspace command failed"});else {let s=De(r.stdout)?.healthScore,c=Number(s?.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 ce(["readiness","--json"],e);if(n.exitCode!==0)t.push({gate:"readiness",status:"fail",summary:"readiness command failed"});else {let o=De(n.stdout),s=String(o?.overallStatus??"").toLowerCase();s==="fail"?t.push({gate:"readiness",status:"fail",summary:"readiness overall status is fail"}):s==="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 mt=new Set(["dev","stop"]);function ft(e){let t=e.trim();return !t||mt.has(t.toLowerCase())?false:Ue.has(t)?true:/^[a-z][a-z0-9_-]*$/i.test(t)}function Te(e,t,r){let n=N(b.relative(r,t));return (Array.isArray(e.projects)?e.projects:[]).some(s=>{if(!s||typeof s!="object")return false;let c=s,u=[c.relativePath,c.path].filter(p=>typeof p=="string"&&p.length>0).map(p=>N(p));return c.status==="passed"&&(u.includes(n)||u.some(p=>p.endsWith(`/${n}`)))})}function gt(e,t){return se(e,t)?.dependencies??[]}function yt(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 Xt(e$1){if(!ft(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 Xe(r),{projects:s,normalizedScope:c}=await et(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 tt(r,s,m):new Set(s),a,d$1="not-applicable",y=0,h="all";if(u&&p){let l=await rt(r,o,g);a=l.expanded,d$1=l.graphStatus,y=l.expansionDepth,h="affected+blast-radius";}else u?(a=g,h="affected"):(a=g,h="all");let w=e$1.stage==="init"?false:await ot(r,e$1.enforceGates),x=w?await pt(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=s.filter(l=>a.has(l)),O=e$1.continueOnError===true||e$1.stage==="init",W=e$1.parallel===true,v=yt(e$1.maxWorkers,j.length),S=j.length,T=0;e$1.json||console.log(E.gray(`Workspace run (${e$1.stage}) started: ${S} target(s), ${W?`parallel x${v}`:"sequential"}`));let f=new Map;for(let l of o){let k=N(b.relative(r,l)),i=s.includes(l),F=i&&a.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=N(b.relative(r,k));e$1.json||console.log(E.gray(`\u23F3 [${T}/${S}] ${e$1.stage} ${F}`)),i.selected=true,i.affected=true;let A=Date.now(),{runtime:P,framework:D,commandOverrides:$e,environmentCommandVariants:Ie,environment:Le}=await ut(k);i.runtimeDetected=P,i.framework=D;let Q=Oe(k,e$1.stage);if(!Q.supported){i.status=Q.shouldFail===false?"skipped":"failed",i.reason=Q.reason??`stage "${e$1.stage}" unsupported for project`,i.durationMs=Date.now()-A,i.exitCode=i.status==="failed"?127:null,i.status==="failed"&&(i.errorCategory="setup",i.errorMessage=i.reason),T+=1;return}if(e$1.reusePassed&&n){let $=n.stages[e$1.stage]??n.stages[e$1.stage];if($&&Te($,k,r)){i.status="passed",i.reason="reused passed result from workspace-run-last.json",i.durationMs=Date.now()-A,i.exitCode=0,T+=1,e$1.json||console.log(E.gray(`\u21BA reused passed cache for ${F}`));return}}let me=gt(P,D);if(me.length>0&&n){let $=me.find(X=>{let L=n.stages[X];return !L||!Te(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,T+=1;return}}let M=await dt(k,e$1.stage,P,D,$e,Ie,Le);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),T+=1,!e$1.json){let $=S>0?Math.round(T/S*100):100,X=i.status==="passed"?E.green("\u2705"):E.red("\u274C");if(console.log(E.gray(`${X} [${T}/${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=lt(i.runtimeDetected);L&&i.errorCategory==="setup"&&console.log(E.gray(` Hint: ${L}`));}}};if(W&&j.length>1){let k=0,i=false,F=new Array(v).fill(null).map(async()=>{for(;k<j.length;){if(i&&!O)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),!O&&i){let A=false;for(let P of j){let D=f.get(P);if(D){if(D.status==="failed"){A=true;continue}A&&D.status==="skipped"&&(D.reason=D.reason||"stopped after failure");}}}}else for(let k of j){await l(k);let i=f.get(k);if(!O&&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,de=C.filter(l=>l.status==="skipped").length,le=e$1.strict===true,Me=K>0||le&&x.some(l=>l.status==="fail"||l.status==="warn")?1:0,pe={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:W,maxWorkers:v,continueOnError:O,strict:le,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:de,exitCode:Me},projects:C,enterpriseControls:{jsonReady:true,evidencePath:b$1}},We=b.join(r,b$1);return await e(r,pe),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: ${de}`)),console.log(E.gray(`Report: ${We}`))),pe}export{Xt as a};
@@ -0,0 +1 @@
1
+ import {d as d$1,m}from'./chunk-T4YR4RAI.js';import {d,e}from'./chunk-32OJDBIG.js';import {a as a$1}from'./chunk-A5FBGRJA.js';import {o}from'./chunk-5XATWNME.js';import {r,p}from'./chunk-EYJ2CQSK.js';import a from'path';import {existsSync}from'fs';import u from'fs-extra';var f=".workspai/workspace-registry.v1.json",w="workspace-registry.v1";function x(r){return {slug:r.slug,relativePath:r.relativePath,framework:r.framework,kit:r.kit,source:r.source}}async function A(r){let e=o(r,"workspace.json").find(t=>existsSync(t));if(!e)return {exists:false,legacyProjectCount:0};try{let t=await u.readJson(e),c=Array.isArray(t.projects)?t.projects.length:0,o=typeof t.workspace_name=="string"&&t.workspace_name.trim()||typeof t.name=="string"&&t.name.trim()||a.basename(r);return {exists:true,manifestPath:e,workspaceName:o,profile:typeof t.profile=="string"?t.profile:void 0,legacyProjectCount:c}}catch{return {exists:true,manifestPath:e,legacyProjectCount:0,workspaceName:a.basename(r)}}}async function b(r$1){let e=a$1(r$1);for(let t of r())if(await u.pathExists(t))try{let o=((await u.readJson(t)).workspaces||[]).find(s=>a$1(s.path)===e);if(o)return {exists:true,projectCount:Array.isArray(o.projects)?o.projects.length:0,registryPath:t}}catch{continue}return {exists:false,projectCount:0,registryPath:a.join(p(),"workspaces.json")}}async function E(r,e){let t=a.resolve(r),c=await d(t,d$1),o=await A(t),s=await b(t),i=e?.contract!==void 0||!!c,n=[];if(e?.contract)n=e.contract.projects||[];else if(i)try{let{contract:d}=await m({workspacePath:t});n=d.projects||[];}catch{n=[];}let S={contract:{exists:i,projectCount:n.length,path:d$1},globalRegistry:{exists:s.exists,projectCount:s.projectCount,path:s.registryPath},legacyWorkspaceJson:{exists:o.exists,projectCount:o.legacyProjectCount,path:o.manifestPath?a.relative(t,o.manifestPath):void 0}},p="none",m$1=[],y=0;return i?(p="workspace.contract.json",m$1=n.map(x),y=m$1.length):s.projectCount>0?(p="global-registry",y=s.projectCount):o.legacyProjectCount>0&&(p="legacy-workspace.json",y=o.legacyProjectCount),{contractExists:i,summary:{schemaVersion:w,kind:"rapidkit.workspace.registry",workspacePath:t,workspaceName:o.workspaceName||a.basename(t),profile:o.profile,projectCount:y,authority:p,contractPath:d$1,projects:m$1,sources:S}}}async function Y(r){let e=await d(r,f);if(!e)return null;try{let t=await u.readJson(e);return t?.schemaVersion!==w?null:t}catch{return null}}async function D(r,e$1){let t=await _(r,e$1);return await e(r,f,t),t}async function _(r,e){return {...(await E(r,{contract:e?.contract})).summary,generatedAt:(e?.now??new Date).toISOString(),registrySummaryPath:f}}function H(r,e=""){return r.projectCount>0?r.authority==="workspace.contract.json"?`${r.projectCount} project(s) registered in workspace contract${e}.`:r.authority==="global-registry"?`${r.projectCount} project(s) registered in global workspace registry${e}.`:`${r.projectCount} project(s) registered in legacy workspace manifest${e}.`:`Workspace state exists, but no projects are registered yet${e}.`}export{f as a,w as b,E as c,Y as d,D as e,_ as f,H as g};
@@ -0,0 +1,2 @@
1
+ import {a as a$1}from'./chunk-FXQJX34Z.js';import {w}from'./chunk-PHXQR6PX.js';import {a as a$2,d,c,e as e$1}from'./chunk-32OJDBIG.js';import {b as b$1}from'./chunk-3NU32T4A.js';import {a,b}from'./chunk-BMWFQXGW.js';import {e}from'./chunk-RO73VVHW.js';import {p,o}from'./chunk-5XATWNME.js';import {l}from'./chunk-OCGZNSOE.js';import m from'path';import g from'fs-extra';var ne="unknown-run";function M(e$1){let t=e();return !t||t===ne?e$1:{...e$1,runId:t}}var be="workspace-dependency-graph.v1",L=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],U=["inferred","contract","manual"];var C=".workspai/workspace.contract.json",ae=a.contractVerify,v=1,se=b.contractVerify,j=class extends Error{constructor(o){super(`Workspace contract verification failed: ${o.violations.join("; ")}`);this.verification=o;this.name="WorkspaceContractVerificationError";}verification};function Z(e){return e.replace(/\\/g,"/")}function O(e){let t=Z(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(o=>o===".."||o===".")}function z(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function ce(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function ie(e){let o=(Array.isArray(e.ports)?e.ports:[]).map(c=>{if(!c||typeof c!="object"||Array.isArray(c))return null;let d=c,f=Number(d.port);if(!Number.isInteger(f)||f<1||f>65535)return null;let u=d.protocol==="https"||d.protocol==="grpc"||d.protocol==="tcp"||d.protocol==="udp"?d.protocol:"http";return {name:typeof d.name=="string"&&d.name.trim()?d.name:"http",port:f,protocol:u}}).filter(c=>c!==null);if(o.length>0)return o;let n=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,s=Number(e.port??n?.default_port);return Number.isInteger(s)&&s>=1&&s<=65535?[{name:"http",port:s,protocol:"http"}]:[]}async function A(e){for(let t of e)if(await g.pathExists(t))return t;return null}async function pe(e){for(let t of o(e,"workspace.json"))try{let o=await g.readJson(t);return {name:typeof o.workspace_name=="string"&&o.workspace_name.trim()||typeof o.name=="string"&&o.name.trim()||m.basename(e),profile:typeof o.profile=="string"?o.profile:void 0}}catch{}return {name:m.basename(e)}}async function de(e){let t=[],o=[e],n=new Set,s=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;o.length>0;){let c=o.shift();if(!c||n.has(c))continue;n.add(c);let d=await A(p(c,"project.json")),f=await A(p(c,"context.json"));if(d||f){t.push(d??f??"");continue}let u;try{u=await g.readdir(c,{withFileTypes:true});}catch{continue}for(let l of u)!l.isDirectory()||s.has(l.name)||o.push(m.join(c,l.name));}return t.sort()}function ue(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function le(e,t){let o=(e||"").toLowerCase(),n=(t||"").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 Y(e,t){let o=e;for(;t.has(o)&&o<65535;)o+=1;return o}function _(e,t,o){let n=e!==void 0&&e.source===void 0,s=le(t.kit,t.runtime),c=e?.ports||[],d=t.ports||[],u=(c.length>0?c:d.length>0?d:s?[{name:"http",port:Y(s,o),protocol:"http"}]:[]).map(i=>({...i,port:Y(i.port,o)}));for(let i of u)o.add(i.port);let l={...t,...e,slug:e?.slug||t.slug,relativePath:n&&e?.relativePath&&O(e.relativePath)?e.relativePath:t.relativePath,source:n&&e?.source||t.source,relationship:n&&e?.relationship||t.relationship,externalPath:n&&e?.externalPath||t.externalPath,runtime:e?.runtime||t.runtime,framework:e?.framework||t.framework,kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:u,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||[]}},a=JSON.stringify(e||null)!==JSON.stringify(l);return {project:l,changed:a}}async function Q(e){let t=m.resolve(e.workspacePath),o=await pe(t),n=await de(t),s=await a$1(t),c=[];for(let l of s){let a=m.resolve(l.path),i=await A(p(a,"project.json"))??await A(p(a,"context.json"));!i||n.some(k=>m.resolve(k)===m.resolve(i))||c.push({projectJsonPath:i,registryEntry:l});}let d=[],f=[...n.map(l=>({projectJsonPath:l})),...c];for(let{projectJsonPath:l,registryEntry:a}of f){let i=m.dirname(m.dirname(l)),k=Z(m.relative(t,i)),h=a!==void 0&&!O(k),r=z(a?.name||m.basename(i),m.basename(i)),p=h?`external/${r}`:k||r,w=await g.readJson(l),y=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,R=typeof w.framework=="string"&&w.framework||ue(y);d.push({slug:a?.name||p||m.basename(i),relativePath:p,source:a?.source??"workspace",relationship:a?.relationship,externalPath:h?i:void 0,runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:R,kit:y,modules:ce(w.modules),ports:ie(w),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let u=new Map;for(let l of d){let a=z(l.slug,l.relativePath),i=u.get(a);(!i||i.source!=="workspace"&&l.source==="workspace")&&u.set(a,l);}return {schemaVersion:v,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:o,projects:[...u.values()]}}async function Te(e){let t=m.resolve(e.outputPath||a$2(e.workspacePath,C));if(await g.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let o=await Q({workspacePath:e.workspacePath,now:e.now}),n=new Set,s={...o,projects:o.projects.map(d=>_(void 0,d,n).project)},c=await te({workspacePath:e.workspacePath,contractPath:t,contract:s});if(e.strict&&c.status==="failed")throw new j(c);return await X({workspacePath:e.workspacePath,contractPath:t,contract:s,now:e.now}),{contractPath:t,contract:s}}async function Ve(e){let t=m.resolve(e.workspacePath),o=a$2(t,C),n=await d(t,C)??o,s=await Q({workspacePath:t,now:e.now}),c=await g.pathExists(n)?await g.readJson(n):null,d$1=new Map((c?.projects||[]).map(h=>[h.slug,h])),f=new Set,u=[],l=[],a=[];for(let h of s.projects){let r=d$1.get(h.slug),p=_(r,h,f);r?p.changed&&l.push(h.slug):u.push(h.slug),a.push(p.project),d$1.delete(h.slug);}for(let h of d$1.values()){if(h.source)continue;let r=_(h,h,f);a.push(r.project);}let i={schemaVersion:v,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...s.workspace,...c?.workspace||{},name:c?.workspace?.name||s.workspace.name},projects:a.sort((h,r)=>h.slug.localeCompare(r.slug))},k=await te({workspacePath:t,contractPath:o,contract:i});if(e.strict&&k.status==="failed")throw new j(k);return await X({workspacePath:t,contractPath:o,contract:i,now:e.now}),{contractPath:o,contract:i,addedProjects:u,updatedProjects:l,verification:k}}async function q(e){return await g.pathExists(e)?{exists:true,contents:await g.readFile(e)}:{exists:false}}async function B(e,t){if(!t.exists){await g.remove(e);return}await g.outputFile(e,t.contents);}async function X(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:o}=await import('./workspace-registry-summary-ORDK7A36.js'),n=await t(e.workspacePath,{now:e.now,contract:e.contract}),s=a$2(e.workspacePath,o),c$1=d=>{if(!d||typeof d!="object"||Array.isArray(d))return JSON.stringify(d);let{generatedAt:f,...u}=d;return JSON.stringify(u)};if(await g.pathExists(e.contractPath)&&await g.pathExists(s)){let[d,f]=await Promise.all([g.readJson(e.contractPath),g.readJson(s)]);if(c$1(d)===c$1(e.contract)&&c$1(f)===c$1(n))return}b$1(C,e.contract),b$1(o,n),await c(e.workspacePath,C,async()=>{let[d,f]=await Promise.all([q(e.contractPath),q(s)]);try{if(e.contractPath===a$2(e.workspacePath,C)?await e$1(e.workspacePath,C,e.contract):(await g.ensureDir(m.dirname(e.contractPath)),await g.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await e$1(e.workspacePath,o,n);}catch(u){let a=(await Promise.allSettled([B(e.contractPath,d),B(s,f)])).filter(i=>i.status==="rejected");throw a.length>0?new AggregateError([u,...a.map(i=>i.reason)],"Workspace contract publication failed and rollback was incomplete."):u}});}async function ee(e){let t=e.contractPath??(await d(e.workspacePath,C)||a$2(e.workspacePath,C)),o=await g.readJson(t);return {contractPath:t,contract:o}}var me={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function ge(e,t){return t.externalPath?m.resolve(t.externalPath):m.resolve(e,t.relativePath)}async function fe(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[o,n]of Object.entries(me))for(let s of n)await g.pathExists(m.join(e,s))&&t[o].push(s);try{let o=await g.readdir(e,{withFileTypes:true});for(let n of o)n.isFile()&&(n.name.endsWith(".csproj")||n.name.endsWith(".sln"))&&t.manifests.push(n.name),n.isFile()&&n.name.endsWith(".tf")&&t.infrastructure.push(n.name);}catch{}for(let o of Object.values(t))o.sort((n,s)=>n.localeCompare(s));return t}function W(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,o)=>t.localeCompare(o))}async function he(e){try{let t=await g.readJson(m.join(e,"package.json")),o={runtime:W(t.dependencies),development:W(t.devDependencies),peer:W(t.peerDependencies),optional:W(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:W(t.scripts),dependencies:o,dependencyCount:new Set(Object.values(o).flat()).size}}catch{return}}async function ke(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await g.readFile(m.join(e,t),"utf8")).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#")&&n.includes("=")).map(n=>n.slice(0,n.indexOf("=")).trim()).filter(n=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)).sort((n,s)=>n.localeCompare(s))}catch{}return []}function we(e,t){try{let o=w(e);if(o.engine!=="unknown")return o;let n=g.pathExistsSync(m.join(e,"package.json"))?"npm":g.pathExistsSync(m.join(e,"pyproject.toml"))?"python":g.pathExistsSync(m.join(e,"requirements.txt"))?"pip":"unknown";return {...o,engine:n,runtime:t.runtime??o.runtime,framework:t.framework??o.framework,frameworkDisplayName:t.framework??o.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Pe(e,t,o){let n=e.projects.map(s=>({id:s.slug,path:s.relativePath,runtime:s.runtime,framework:s.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:n,edges:[],stats:{nodeCount:n.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:n.length,connectedNodeCount:0,density:0,edgeCoverageRatio:n.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:o,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function Ke(e){let{contractPath:t,contract:o}=await ee(e),n=e.now??new Date,s=n.toISOString(),c;try{let{inferWorkspaceDependencyGraph:r}=await import('./workspace-dependency-graph-BP4EXYQ5.js');c=await r({workspacePath:e.workspacePath,contract:o,now:n,model:{projects:o.projects.map(p=>({name:p.slug,path:p.relativePath,...p.externalPath?{absolutePath:p.externalPath}:{},...p.runtime?{runtime:p.runtime}:{},...p.framework?{framework:p.framework}:{},...p.framework?{kind:p.framework}:{}}))}});}catch(r){c=Pe(o,s,`Graph enrichment failed: ${r instanceof Error?r.message:String(r)}`);}let d=new Map(c.nodes.map(r=>[r.id,r.operationalProfile])),{buildWorkspaceKnowledgeGraph:f}=await import('./workspace-knowledge-graph-ARDC6HHG.js'),u=await f({workspacePath:e.workspacePath,workspace:o.workspace,contract:o,projectTopology:c,now:n,projects:o.projects.map(r=>({id:r.slug,path:r.relativePath,...r.externalPath?{absolutePath:r.externalPath}:{},...r.runtime?{runtime:r.runtime}:{},...r.framework?{framework:r.framework}:{},...r.kit?{kit:r.kit}:{}}))}),l=await Promise.all(o.projects.map(async r=>{let p=ge(e.workspacePath,r),[w,y,R]=await Promise.all([fe(p),he(p),ke(p)]),P=we(p,r);return {id:r.slug,label:r.slug,relativePath:r.relativePath,source:r.source,relationship:r.relationship,externalPath:r.externalPath,runtime:r.runtime??P.runtime,framework:r.framework??P.framework,kit:r.kit,modules:r.modules,ports:r.ports,apis:r.contracts.apis,owns:r.contracts.owns,env:[...new Set([...r.contracts.env,...R])].sort((re,oe)=>re.localeCompare(oe)),contracts:{owns:[...r.contracts.owns],apis:[...r.contracts.apis],publishes:[...r.contracts.publishes],consumes:[...r.contracts.consumes],dependsOn:[...r.contracts.dependsOn],env:[...r.contracts.env]},capabilities:{engine:P.engine,supportTier:P.frameworkSupportTier,runtimeSupportTier:P.runtimeSupportTier,doctorSupport:P.runtimeDoctorSupport,moduleSupport:P.moduleSupport,fleetStages:[...P.fleetStages],localOnlyCommands:[...P.localOnlyCommands],supportedCommands:[...P.supportedCommands]},files:w,...y?{package:y}:{},...d.get(r.slug)?{operationalProfile:d.get(r.slug)}:{}}})),a=new Set(l.map(r=>r.id)),i=new Map,k=[];for(let r of o.projects){for(let p of r.contracts.dependsOn||[])a.has(p)&&k.push({from:p,to:r.slug,type:"dependency",label:"dependsOn"});for(let p of r.contracts.publishes||[])i.has(p)||i.set(p,new Set),i.get(p)?.add(r.slug);}for(let r of o.projects)for(let p of r.contracts.consumes||[]){let w=i.get(p);if(w)for(let y of w)y!==r.slug&&k.push({from:y,to:r.slug,type:"event",label:p});}let h={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:o.workspace,generatedAt:s,nodes:l.sort((r,p)=>r.id.localeCompare(p.id)),edges:k.sort((r,p)=>`${r.from}:${r.to}:${r.type}:${r.label}`.localeCompare(`${p.from}:${p.to}:${p.type}:${p.label}`)),dependencyGraph:c,knowledgeGraph:u,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:l.length,dependencyEdges:k.filter(r=>r.type==="dependency").length,eventEdges:k.filter(r=>r.type==="event").length,portCount:l.reduce((r,p)=>r+p.ports.length,0),apiCount:l.reduce((r,p)=>r+p.apis.length,0),relationshipEdges:c.stats.edgeCount,inferredEdges:c.stats.inferredEdges,authoritativeEdges:c.stats.authoritativeEdges,orphanProjects:c.stats.orphanCount,hotspotProjects:c.stats.hotspotCount,evidenceCoverageRatio:c.stats.evidenceCoverageRatio,edgeCoverageRatio:c.stats.edgeCoverageRatio,connectedProjects:c.stats.connectedNodeCount,lowConfidenceEdges:c.stats.lowConfidenceEdges,hasCycle:c.stats.hasCycle,manifestCount:l.reduce((r,p)=>r+p.files.manifests.length,0),entrypointCount:l.reduce((r,p)=>r+p.files.entrypoints.length,0),diagnostics:c.diagnostics?.length??0,relationshipKinds:Object.fromEntries(L.map(r=>[r,c.edges.filter(p=>p.kind===r).length])),relationshipSources:Object.fromEntries(U.map(r=>[r,c.edges.filter(p=>p.source===r).length])),entityCount:u.quality.entityCount,knowledgeRelations:u.quality.relationCount,proofCount:u.quality.proofCount,providerCount:u.providers.length,knowledgeUnknowns:u.quality.unknownCount}};return {contractPath:t,graph:h}}async function te(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,C),contract:e.contract}:await ee(e),{contractPath:o,contract:n}=t,s=[],c=[];n.kind!=="rapidkit.workspace.contract"&&s.push("Contract kind must be rapidkit.workspace.contract."),n.schemaVersion!==v&&s.push(`Contract schemaVersion must be ${v}.`),n.workspace?.name||s.push("Contract workspace.name is required."),Array.isArray(n.projects)||s.push("Contract projects must be an array.");let d=new Set,f=new Map;for(let a of n.projects||[]){if(!a.slug){s.push("Every project must declare slug.");continue}d.has(a.slug)&&s.push(`Duplicate project slug: ${a.slug}.`),d.add(a.slug),a.relativePath?O(a.relativePath)||s.push(`Project ${a.slug} declares unsafe relativePath: ${a.relativePath}.`):s.push(`Project ${a.slug} must declare relativePath.`),a.externalPath&&(a.relationship==="adopted"||a.source==="adopted-local"||a.source==="local-folder"||a.source==="git-url"||s.push(`Project ${a.slug} declares externalPath without imported/adopted provenance.`),m.isAbsolute(a.externalPath)||s.push(`Project ${a.slug} declares non-absolute externalPath.`));for(let i of a.ports||[]){(!Number.isInteger(i.port)||i.port<1||i.port>65535)&&s.push(`Project ${a.slug} declares invalid port: ${i.port}.`);let k=f.get(i.port);k&&s.push(`Port ${i.port} is claimed by both ${k} and ${a.slug}.`),f.set(i.port,a.slug);}for(let i of a.contracts?.apis||[])(!i.name?.trim()||!i.basePath?.startsWith("/"))&&s.push(`Project ${a.slug} declares invalid API contract.`);for(let i of [...a.contracts?.publishes||[],...a.contracts?.consumes||[]])i.trim()||s.push(`Project ${a.slug} declares an empty event contract.`);for(let i of a.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(i)||s.push(`Project ${a.slug} declares invalid env contract: ${i}.`);for(let i of a.contracts?.dependsOn||[])d.has(i);}for(let a of n.projects||[])for(let i of a.contracts?.dependsOn||[])d.has(i)||s.push(`Project ${a.slug} depends on unknown project: ${i}.`);c.push({id:"schema",status:n.kind==="rapidkit.workspace.contract"&&n.schemaVersion===v?"passed":"failed",message:"Contract schema and kind are valid."}),c.push({id:"projects",status:Array.isArray(n.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(n.projects)?n.projects.length:0} project(s).`}),c.push({id:"ports",status:s.some(a=>a.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),c.push({id:"dependencies",status:s.some(a=>a.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),c.push({id:"contracts",status:s.some(a=>a.includes("unsafe relativePath")||a.includes("invalid API contract")||a.includes("event contract")||a.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let u=await l(e.workspacePath);if(u.moduleCount>0){for(let a of u.issues)s.push(`${m.basename(a.projectRoot)}: ${a.message} (slug=${a.slug})`);c.push({id:"module-paths",status:u.status,message:u.status==="passed"?`All ${u.moduleCount} registered module(s) resolve under canonical paths.`:`${u.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:s.length>0?"failed":"passed",contractPath:o,projectCount:Array.isArray(n.projects)?n.projects.length:0,checks:c,violations:s}}async function $e(e){let t=m.resolve(e.workspacePath),o={schemaVersion:se,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return e$1(t,ae,M(o))}
2
+ export{M as a,be as b,L as c,C as d,ae as e,v as f,se as g,j as h,de as i,Q as j,Te as k,Ve as l,ee as m,Ke as n,te as o,$e as p};
@@ -0,0 +1,2 @@
1
+ import d from'crypto';import {constants}from'fs';import a from'fs/promises';import n from'path';var E="workspai.lifecycle-transaction",L=1,b="manifest.json",O="lifecycle-transaction-";async function p(r){try{return await a.lstat(r)}catch(e){if(e.code==="ENOENT")return null;throw e}}function k(r){let e=r?.code;return process.platform==="win32"&&(e==="EPERM"||e==="EINVAL"||e==="ENOSYS")}async function v(r){try{await r.sync();}catch(e){if(!k(e))throw e}}function j(r){if(typeof r!="string"||!n.isAbsolute(r))throw new Error("Lifecycle transaction journal contains a non-absolute target path.")}function A(r){if(typeof r!="string"||r.length===0||n.basename(r)!==r||r==="."||r==="..")throw new Error("Lifecycle transaction journal contains an unsafe backup reference.")}function F(r){if(!r||typeof r!="object")throw new Error("Lifecycle transaction journal is not an object.");let e=r;if(e.kind!==E||e.version!==L)throw new Error("Lifecycle transaction journal has an unsupported format.");if(!Number.isInteger(e.ownerPid)||e.ownerPid<=0)throw new Error("Lifecycle transaction journal has an invalid owner process.");if(!["active","committed","rolling-back"].includes(e.phase))throw new Error("Lifecycle transaction journal has an invalid phase.");if(!Array.isArray(e.operations))throw new Error("Lifecycle transaction journal has invalid operations.");for(let t of e.operations){if(!t||typeof t!="object")throw new Error("Lifecycle transaction journal contains an invalid operation.");let i=t;if(j(i.path),i.type!=="tree"){if(i.type!=="file"||!["absent","regular"].includes(i.state))throw new Error("Lifecycle transaction journal contains an invalid operation.");if(i.state==="regular"){if(!Number.isInteger(i.mode)||i.mode<0||i.mode>4095)throw new Error("Lifecycle transaction journal contains an invalid file mode.");A(i.backup);}}}return e}async function g(r){let e;try{e=await a.open(r,constants.O_RDONLY);}catch(t){if(k(t))return;throw t}try{await v(e);}finally{await e.close();}}async function N(r,e){let t=n.join(n.dirname(r),`.${n.basename(r)}.${process.pid}.${d.randomUUID()}.tmp`);try{let i=await a.open(t,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL,384);try{await i.writeFile(e),await v(i);}finally{await i.close();}await a.rename(t,r),await g(n.dirname(r));}catch(i){throw await a.rm(t,{force:true}).catch(()=>{}),i}}async function D(r,e){await N(n.join(r,b),Buffer.from(`${JSON.stringify(e,null,2)}
2
+ `));}async function S(r,e){let t=await p(r.path);if(t?.isSymbolicLink()||t&&!t.isFile())throw new Error(`Refusing to restore over a non-regular file: ${r.path}`);if(r.state==="absent"){t&&await a.unlink(r.path);return}if(!e)throw new Error(`Missing durable backup for: ${r.path}`);if(!await p(n.dirname(r.path)))return;let i=n.join(e,r.backup),o=await a.lstat(i).catch(s=>{if(s.code==="ENOENT"&&t?.isFile())return t;throw s});if(o===t)return;if(!o.isFile()||o.isSymbolicLink())throw new Error(`Lifecycle transaction backup is not a regular file: ${i}`);let c=await a.readFile(i),f=n.join(n.dirname(r.path),`.${n.basename(r.path)}.${process.pid}.${d.randomUUID()}.rollback`),l=await a.open(f,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL,r.mode);try{await l.writeFile(c),await l.chmod(r.mode),await v(l);}finally{await l.close();}try{await a.rename(f,r.path),await g(n.dirname(r.path));}catch(s){throw await a.rm(f,{force:true}).catch(()=>{}),s}}async function P(r){let e=await p(r.path);if(e){if(e.isSymbolicLink()||!e.isDirectory())throw new Error(`Refusing to remove a non-directory owned tree: ${r.path}`);await a.rm(r.path,{recursive:true});}}async function T(r,e){let t=[];for(let i of [...r].reverse())try{i.type==="file"?await S(i,e):await P(i);}catch(o){t.push(o);}if(t.length>0)throw new AggregateError(t,"Lifecycle transaction rollback failed.")}var m=class r{constructor(e){this.transactionDirectory=e;this.journalPath=e?n.join(e,b):void 0;}transactionDirectory;journalPath;actions=[];durableOperations=[];phase="active";finished=false;static async create(e={}){if(!e.journalDirectory)return new r;let t=n.resolve(e.journalDirectory);await a.mkdir(t,{recursive:true});let i=await a.mkdtemp(n.join(t,O));await g(t);let o=new r(i);return await o.persist(),o}assertActive(){if(this.finished||this.phase!=="active")throw new Error("Lifecycle transaction is no longer active.")}async persist(e=this.durableOperations){this.transactionDirectory&&await D(this.transactionDirectory,{kind:E,version:L,ownerPid:process.pid,phase:this.phase,operations:e});}async addDurableOperation(e){let t=[...this.durableOperations,e];await this.persist(t),this.durableOperations.push(e),this.actions.push(e);}async captureFile(e){this.assertActive();let t=n.resolve(e),i=await p(t);if(!i){await this.addDurableOperation({type:"file",path:t,state:"absent"});return}if(i.isSymbolicLink()||!i.isFile())throw new Error(`Lifecycle transaction can only capture regular files: ${t}`);let o;try{o=await a.open(t,constants.O_RDONLY|(constants.O_NOFOLLOW??0));}catch(c){throw c.code==="ENOENT"?new Error(`File changed while being captured: ${t}`,{cause:c}):c}try{let c=await o.stat();if(!c.isFile())throw new Error(`Lifecycle transaction can only capture regular files: ${t}`);let f=await o.readFile(),l=c.mode&4095;if(this.transactionDirectory){let s=`file-${this.durableOperations.length}-${d.randomUUID()}.bin`;await N(n.join(this.transactionDirectory,s),f),await this.addDurableOperation({type:"file",path:t,state:"regular",mode:l,backup:s});}else {let s=`memory-${this.durableOperations.length}`,w={type:"file",path:t,state:"regular",mode:l,backup:s};this.durableOperations.push(w),this.actions.push({type:"compensation",run:async()=>{let h=await p(t);if(h?.isSymbolicLink()||h&&!h.isFile())throw new Error(`Refusing to restore over a non-regular file: ${t}`);let y=n.join(n.dirname(t),`.${n.basename(t)}.${process.pid}.${d.randomUUID()}.rollback`);await a.writeFile(y,f,{flag:"wx",mode:l}),await a.chmod(y,l);try{await a.rename(y,t);}catch(R){throw await a.rm(y,{force:true}).catch(()=>{}),R}}});}}finally{await o.close();}}async captureOwnedTree(e){this.assertActive();let t=n.resolve(e),i=await p(t);if(!i)return await this.addDurableOperation({type:"tree",path:t}),true;if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Lifecycle transaction tree must be absent or a directory: ${t}`);return false}registerCompensation(e){this.assertActive(),this.actions.push({type:"compensation",run:async()=>e()});}async commit(){if(!this.finished){this.assertActive(),this.phase="committed";try{await this.persist(),this.finished=true,this.actions.length=0,this.transactionDirectory&&await a.rm(this.transactionDirectory,{recursive:true}).catch(()=>{});}catch(e){throw this.phase="active",e}}}async rollback(){if(this.finished||this.phase==="committed")return;this.assertActive(),this.phase="rolling-back";try{await this.persist();}catch(t){throw this.phase="active",t}let e=[];for(let t of [...this.actions].reverse())try{t.type==="compensation"?await t.run():t.type==="file"?await S(t,this.transactionDirectory):await P(t);}catch(i){e.push(i);}if(e.length>0)throw new AggregateError(e,"Lifecycle transaction rollback failed.");this.finished=true,this.transactionDirectory&&await a.rm(this.transactionDirectory,{recursive:true});}};async function M(r={}){return m.create(r)}async function C(r){let e=n.resolve(r),t=await a.readdir(e,{withFileTypes:true}).catch(c=>{if(c.code==="ENOENT")return [];throw c}),i=[],o=[];for(let c of t){if(!c.isDirectory()||!c.name.startsWith(O))continue;let f=n.join(e,c.name);try{let l;try{l=await a.readFile(n.join(f,b),"utf8");}catch(h){if(h.code==="ENOENT")continue;throw h}let s=F(JSON.parse(l));if(s.phase==="committed"){await a.rm(f,{recursive:true});continue}let w=false;try{process.kill(s.ownerPid,0),w=true;}catch(h){w=h.code==="EPERM";}if(w)continue;s.phase==="active"&&(s.phase="rolling-back",await D(f,s)),await T(s.operations,f),await a.rm(f,{recursive:true}),i.push(f);}catch(l){o.push(l);}}if(o.length>0)throw new AggregateError(o,"Lifecycle transaction recovery failed.");return i}export{M as a,C as b};
@@ -1 +1 @@
1
- import {b}from'./chunk-N7DV5L7C.js';var i=b.explain,g=["project","release-blocked","blocker","trace"];function s(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 u(t){let r=t.trim();if(!r)return null;if(r.startsWith("trace:")){let n=s(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 A(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let r=t;return r.schemaVersion===i&&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{i as a,g as b,s as c,u as d,A as e};
1
+ import {b}from'./chunk-BMWFQXGW.js';var i=b.explain,g=["project","release-blocked","blocker","trace"];function s(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 u(t){let r=t.trim();if(!r)return null;if(r.startsWith("trace:")){let n=s(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 A(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let r=t;return r.schemaVersion===i&&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{i as a,g as b,s as c,u as d,A as e};
@@ -0,0 +1 @@
1
+ var M="workspace-knowledge-search.v1";function k(o){return o.trim().toLowerCase()}var I=new WeakMap;function h(o){let n=I.get(o);if(n)return n;let r=new Map(o.relations.map(t=>[t.id,t])),s=new Map(o.entities.map(t=>[t.id,t])),i=new Map(o.proofs.map(t=>[t.id,t])),a=new Map,d=new Map,l=(t,c)=>{let f=d.get(t)??[];f.push(c),d.set(t,f);};for(let t of o.entities){let c=[t.id,t.label,t.identity.key,...t.kind==="project"&&t.projectId?[t.projectId]:[],...t.identity.aliases];for(let f of new Set(c.map(k))){let w=a.get(f)??[];w.push(t),a.set(f,w);}}for(let t of o.relations)l(t.from,{from:t.from,to:t.to,relationId:t.id,kind:t.kind,direction:"forward",proofIds:t.proofIds}),l(t.to,{from:t.to,to:t.from,relationId:t.id,kind:t.kind,direction:"reverse",proofIds:t.proofIds});for(let t of a.values())t.sort((c,f)=>c.id.localeCompare(f.id));for(let t of d.values())t.sort((c,f)=>c.to.localeCompare(f.to)||c.relationId.localeCompare(f.relationId));let p={entitiesById:s,relationsById:r,entitiesByAlias:a,proofsById:i,adjacency:d};return I.set(o,p),p}function W(o,n){let r=h(o),s=r.relationsById.get(n);if(s)return {found:true,targetType:"relation",relation:s};let i=k(n),a=r.entitiesByAlias.get(i)??[];return a.length===1?{found:true,targetType:"entity",entity:a[0]}:{found:false,query:n,candidates:a.map(d=>d.id).sort()}}function S(o,n){let r=W(o,n);if(!r.found)return {query:n,found:false,target:null,proofs:[],candidates:r.candidates};let s=r.targetType==="entity"?r.entity:r.relation,i=new Set(s.proofIds);return {query:n,found:true,target:s,candidates:[],proofs:[...i].map(a=>h(o).proofsById.get(a)).filter(a=>!!a).sort((a,d)=>a.id.localeCompare(d.id))}}function b(o,n,r){let s=W(o,n),i=W(o,r);if(!s.found||s.targetType!=="entity"||!i.found||i.targetType!=="entity")return {from:n,to:r,found:false,resolvedFrom:s.found&&s.targetType==="entity"?s.entity.id:null,resolvedTo:i.found&&i.targetType==="entity"?i.entity.id:null,entityPath:[],hops:[],proofs:[]};let a=h(o),d=[s.entity.id],l=new Map,p=new Set(d),t=0;for(;t<d.length&&!p.has(i.entity.id);){let g=d[t++];for(let y of a.adjacency.get(g)??[])p.has(y.to)||(p.add(y.to),l.set(y.to,y),d.push(y.to));}if(!p.has(i.entity.id))return {from:n,to:r,found:false,resolvedFrom:s.entity.id,resolvedTo:i.entity.id,entityPath:[],hops:[],proofs:[]};let c=[],f=i.entity.id;for(;f!==s.entity.id;){let g=l.get(f);if(!g)break;c.push(g),f=g.from;}c.reverse();let w=new Set(c.flatMap(g=>g.proofIds));return {from:n,to:r,found:true,resolvedFrom:s.entity.id,resolvedTo:i.entity.id,entityPath:[s.entity.id,...c.map(g=>g.to)],hops:c,proofs:[...w].map(g=>a.proofsById.get(g)).filter(g=>!!g).sort((g,y)=>g.id.localeCompare(y.id))}}function B(o,n){return o.entities.filter(r=>!n||r.kind===n).sort((r,s)=>r.kind.localeCompare(s.kind)||r.label.localeCompare(s.label))}function P(o){let n=Object.values(o.attributes).flatMap(r=>Array.isArray(r)?r:[r]);return [o.id,o.kind,o.label,o.projectId??"",o.identity.key,...o.identity.aliases,...n.map(r=>String(r??""))].join(" ").toLowerCase()}function x(o,n,r){let s=k(o.label),i=k(o.identity.key),a=o.identity.aliases.map(k),d=P(o),l=0;(s===n||i===n||a.includes(n))&&(l+=1e3),(s.startsWith(n)||i.startsWith(n))&&(l+=250),d.includes(n)&&(l+=100);for(let p of r)s===p?l+=80:s.includes(p)&&(l+=30),i.includes(p)&&(l+=20),d.includes(p)&&(l+=10);return l}function R(o,n){let r=k(n.query),s=[...new Set(r.split(/[^a-z0-9_.:/@-]+/u).filter(e=>e.length>1))],i=Math.max(1,Math.min(Math.trunc(n.limit??12),100)),a=Math.max(0,Math.min(Math.trunc(n.relationsPerEntity??4),20)),d=o.entities.filter(e=>!n.kind||e.kind===n.kind).map(e=>({entity:e,score:x(e,r,s)})).filter(e=>r.length===0||e.score>0).sort((e,u)=>u.score-e.score||e.entity.kind.localeCompare(u.entity.kind)||e.entity.label.localeCompare(u.entity.label)),l=d.slice(0,i).map(e=>e.entity),p=new Set(l.map(e=>e.id)),t=new Map,c=o.relations.filter(e=>{if(!(p.has(e.from)||p.has(e.to)))return false;let K=p.has(e.from)?e.from:e.to,m=t.get(K)??0;return m>=a?false:(t.set(K,m+1),true)}),f=h(o),g=[...new Set(c.flatMap(e=>[e.from,e.to]).filter(e=>!p.has(e)))].map(e=>f.entitiesById.get(e)).filter(e=>!!e).map(({id:e,kind:u,label:K,projectId:m})=>({id:e,kind:u,label:K,...m?{projectId:m}:{}})).sort((e,u)=>e.kind.localeCompare(u.kind)||e.label.localeCompare(u.label)),E=[...new Set([...l.flatMap(e=>e.proofIds),...c.flatMap(e=>e.proofIds)])].map(e=>f.proofsById.get(e)).filter(e=>!!e).sort((e,u)=>e.id.localeCompare(u.id));return {schemaVersion:M,query:n.query,kind:n.kind??null,limit:i,totalMatches:d.length,truncated:d.length>l.length,entities:l,relatedEntities:g,relations:c,proofs:E}}export{M as a,W as b,S as c,b as d,B as e,R as f};
@@ -1,8 +1,8 @@
1
- import {c as c$2}from'./chunk-6IIZJQLV.js';import {a}from'./chunk-A5FBGRJA.js';import {a as a$2}from'./chunk-GZTYAEWX.js';import {c as c$1}from'./chunk-Y45WZR5N.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {p as p$1,o}from'./chunk-5XATWNME.js';import {p as p$2,r,q as q$1}from'./chunk-EYJ2CQSK.js';import {promises}from'fs';import {randomUUID}from'crypto';import p from'path';import c from'chalk';import oe from'fs-extra';import S from'ora';import {execa}from'execa';async function ae(e){try{let r=await execa("git",["rev-parse","--show-toplevel"],{cwd:e,env:a$1()});return r.stdout.trim()?p.resolve(e,r.stdout.trim()):null}catch{return null}}async function H(e,r,t){if(await ae(e)){r.warn("Git initialization skipped because target is already inside a git worktree");return}r.start("Initializing git repository...");try{await execa("git",["init"],{cwd:e,env:a$1()}),await execa("git",["add","."],{cwd:e,env:a$1()}),await execa("git",["-c","user.name=Workspai","-c","user.email=workspai@localhost","commit","-m",t],{cwd:e,env:a$1()}),r.succeed("Git repository initialized");}catch{r.warn("Could not initialize git repository");}}function q(e){let r=a(e.path),t=Array.isArray(e.projects)?e.projects:[],a$1=[],o=new Set;for(let s of t){if(!s||typeof s.name!="string"||typeof s.path!="string")continue;let i=a(s.path);o.has(i)||(o.add(i),a$1.push({name:s.name,path:i}));}return {name:e.name,path:r,mode:e.mode,projects:a$1}}function W(e){let r=[],t=new Set;for(let a of e.workspaces||[]){if(!a||typeof a.name!="string"||typeof a.path!="string")continue;let o=q(a);t.has(o.path)||(t.add(o.path),r.push(o));}return {workspaces:r}}async function ie(e){let r;try{r=await promises.readFile(e,"utf8");}catch(t){if(t.code==="ENOENT")return {workspaces:[]};throw t}try{let t=JSON.parse(r);if(!t||!Array.isArray(t.workspaces))throw new Error("missing workspaces array");return W(t)}catch(t){throw new Error(`Workspace registry is invalid: ${e}`,{cause:t})}}async function se(e){let r;try{r=await promises.readFile(e,"utf8");}catch(a){if(a.code==="ENOENT")return {workspaces:[]};throw a}let t;try{t=JSON.parse(r);}catch(a){throw new Error(`Workspace registry is invalid: ${e}`,{cause:a})}if(!t||typeof t!="object"||!Array.isArray(t.workspaces))throw new Error(`Workspace registry is invalid: ${e}`);for(let a of t.workspaces)if(!a||typeof a.name!="string"||typeof a.path!="string"||a.mode!==void 0&&typeof a.mode!="string"||a.projects!==void 0&&!Array.isArray(a.projects)||Array.isArray(a.projects)&&a.projects.some(o=>!o||typeof o.name!="string"||typeof o.path!="string"))throw new Error(`Workspace registry contains an invalid entry: ${e}`);return W(t)}async function B(){let e={workspaces:[]},r$1=new Set;for(let t of r()){let a=await ie(t);for(let o of a.workspaces)r$1.has(o.path)||(r$1.add(o.path),e.workspaces.push(o));}return e}async function ne(){let e={workspaces:[]},r$1=new Set;for(let t of r()){let a=await se(t);for(let o of a.workspaces)r$1.has(o.path)||(r$1.add(o.path),e.workspaces.push(o));}return e}function ce(e){let r=e?.code;return process.platform==="win32"&&(r==="EPERM"||r==="EINVAL"||r==="ENOSYS")}async function X(e){try{await e.sync();}catch(r){if(!ce(r))throw r}}async function M(e,r){let t=p.dirname(e);await promises.mkdir(t,{recursive:true});let a=`${p.basename(e)}.`,o=Date.now();for(let i of await promises.readdir(t)){if(!i.startsWith(a)||!i.endsWith(".tmp"))continue;let n=p.join(t,i),d=await promises.stat(n).catch(()=>null);d&&o-d.mtimeMs>3e4&&await promises.rm(n,{force:true}).catch(()=>{});}let s=await promises.readFile(e,"utf8").catch(()=>null);if(s!==null){let i=false;try{let n=JSON.parse(s);i=Array.isArray(n.workspaces);}catch{i=false;}if(!i){let n=`${e}.corrupt-${Date.now()}`;await promises.copyFile(e,n);}}await Q(e,`${JSON.stringify(W(r),null,2)}
2
- `);}async function Q(e,r){let t=p.dirname(e);await promises.mkdir(t,{recursive:true});let a=`${e}.${process.pid}.${randomUUID()}.tmp`;try{await promises.writeFile(a,r);let o=await promises.open(a,"r");try{await X(o);}finally{await o.close();}try{await promises.rename(a,e);}catch(s){let i=s.code;if(i!=="EEXIST"&&i!=="EPERM")throw s;await oe.move(a,e,{overwrite:true});}}finally{await promises.rm(a,{force:true}).catch(()=>{});}}async function V(e){try{return {exists:true,content:await promises.readFile(e)}}catch(r){if(r.code==="ENOENT")return {exists:false};throw r}}async function Y(e,r){if(!r.exists){await promises.rm(e,{force:true});return}await Q(e,r.content);}async function pe(e){let r=p$2(),t=p.join(r,"workspaces.json.lock");await promises.mkdir(r,{recursive:true});let a=Date.now(),o;for(;!o;)try{o=await promises.open(t,"wx"),await o.writeFile(`${JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})}
3
- `),await X(o);}catch(s){if(s.code!=="EEXIST")throw s;let i=await promises.stat(t).catch(()=>null);if(i&&Date.now()-i.mtimeMs>3e4){let n=await promises.readFile(t,"utf8").then(w=>JSON.parse(w)).catch(()=>null),d=Number(n?.pid),m=false;if(Number.isInteger(d)&&d>0)try{process.kill(d,0),m=true;}catch(w){m=w.code==="EPERM";}if(!m){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>1e4)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(n=>setTimeout(n,25));}try{return await e()}finally{await o.close().catch(()=>{}),await promises.rm(t,{force:true}).catch(()=>{});}}async function P(e){return pe(async()=>{let r=p.join(p$2(),"workspaces.json"),t=p.join(q$1(),"workspaces.json"),[a,o]=await Promise.all([V(r),V(t)]),s=await ne();await e(s);let i=W(s);try{await M(r,i),await M(t,i);}catch(n){let m=(await Promise.allSettled([Y(r,a),Y(t,o)])).filter(w=>w.status==="rejected").map(w=>w.reason);throw m.length>0?new AggregateError([n,...m],"Workspace registry transaction failed and could not be fully restored"):n}return i})}async function K(e,r){let t=a(e);await P(a=>{let o=a.workspaces.find(s=>s.path===t);if(o){o.name=r,o.mode=o.mode||"full",o.projects=Array.isArray(o.projects)?o.projects:[];return}a.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function le(e,r){try{await K(e,r);}catch{console.warn(c.gray("Note: Could not register workspace in shared registry"));}}async function Le(e,r=false){let t=a(e),a$1={workspacePath:t,workspaceFound:false,added:[],skipped:0};try{let o=await B(),s=o.workspaces.find(u=>u.path===t);if(!s){if(await le(t,p.basename(p.resolve(e))),o=await B(),s=o.workspaces.find(u=>u.path===t),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),a$1;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,n=0,d=[],m=[],w=[e],g=new Set;for(;w.length>0;){let u=w.shift();if(!u||g.has(u))continue;g.add(u);let y=await promises.readdir(u,{withFileTypes:true});for(let h of y){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let j=p.join(u,h.name),k=a(j);try{let f=false;for(let $ of [...p$1(k,"context.json"),...p$1(k,"project.json")])try{await promises.access($),f=true;break}catch{}if(f){let $=p.basename(k),E=s.projects.some(C=>C.path===k);m.push({name:$,path:k}),E?n++:(s.projects.push({name:$,path:k}),i++,d.push(k),r||console.log(`\u2714 Added: ${p.relative(e,k)}`));continue}}catch{}w.push(j);}}return await P(u=>{let y=u.workspaces.find(k=>k.path===t);if(!y)return;let h=`${t}${p.sep}`,j=(y.projects||[]).filter(k=>k.path!==t&&!k.path.startsWith(h));y.projects=q({...y,projects:[...j,...m]}).projects;}),i>0?r||console.log(`
1
+ import {c as c$2}from'./chunk-YJZOMRAS.js';import {a as a$2}from'./chunk-GZTYAEWX.js';import {a}from'./chunk-A5FBGRJA.js';import {b}from'./chunk-3NU32T4A.js';import {c as c$1}from'./chunk-Y45WZR5N.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {p as p$1,o}from'./chunk-5XATWNME.js';import {p as p$2,q,r}from'./chunk-EYJ2CQSK.js';import {promises}from'fs';import {randomUUID}from'crypto';import p from'path';import c from'chalk';import ae from'fs-extra';import S from'ora';import {execa}from'execa';async function se(e){try{let r=await execa("git",["rev-parse","--show-toplevel"],{cwd:e,env:a$1()});return r.stdout.trim()?p.resolve(e,r.stdout.trim()):null}catch{return null}}async function X(e,r,t){if(await se(e)){r.warn("Git initialization skipped because target is already inside a git worktree");return}r.start("Initializing git repository...");try{await execa("git",["init"],{cwd:e,env:a$1()}),await execa("git",["add","."],{cwd:e,env:a$1()}),await execa("git",["-c","user.name=Workspai","-c","user.email=workspai@localhost","commit","-m",t],{cwd:e,env:a$1()}),r.succeed("Git repository initialized");}catch{r.warn("Could not initialize git repository");}}function Q(e){let r=a(e.path),t=Array.isArray(e.projects)?e.projects:[],o=[],a$1=new Set;for(let s of t){if(!s||typeof s.name!="string"||typeof s.path!="string")continue;let i=a(s.path);a$1.has(i)||(a$1.add(i),o.push({name:s.name,path:i}));}return {name:e.name,path:r,mode:e.mode,projects:o}}function W(e){let r=[],t=new Set;for(let o of e.workspaces||[]){if(!o||typeof o.name!="string"||typeof o.path!="string")continue;let a=Q(o);t.has(a.path)||(t.add(a.path),r.push(a));}return {workspaces:r}}async function ie(e){let r;try{r=await promises.readFile(e,"utf8");}catch(t){if(t.code==="ENOENT")return {workspaces:[]};throw t}try{let t=JSON.parse(r);if(!t||!Array.isArray(t.workspaces))throw new Error("missing workspaces array");return W(t)}catch(t){throw new Error(`Workspace registry is invalid: ${e}`,{cause:t})}}async function ne(e){let r;try{r=await promises.readFile(e,"utf8");}catch(o){if(o.code==="ENOENT")return {workspaces:[]};throw o}let t;try{t=JSON.parse(r);}catch(o){throw new Error(`Workspace registry is invalid: ${e}`,{cause:o})}if(!t||typeof t!="object"||!Array.isArray(t.workspaces))throw new Error(`Workspace registry is invalid: ${e}`);for(let o of t.workspaces)if(!o||typeof o.name!="string"||typeof o.path!="string"||o.mode!==void 0&&typeof o.mode!="string"||o.projects!==void 0&&!Array.isArray(o.projects)||Array.isArray(o.projects)&&o.projects.some(a=>!a||typeof a.name!="string"||typeof a.path!="string"))throw new Error(`Workspace registry contains an invalid entry: ${e}`);return W(t)}async function B(){let e={workspaces:[]},r$1=new Set;for(let t of r()){let o=await ie(t);for(let a of o.workspaces)r$1.has(a.path)||(r$1.add(a.path),e.workspaces.push(a));}return e}async function ce(e=r()){let r={workspaces:[]},t=new Set;for(let o of e){let a=await ne(o);for(let s of a.workspaces)t.has(s.path)||(t.add(s.path),r.workspaces.push(s));}return r}function pe(e){let r=e?.code;return process.platform==="win32"&&(r==="EPERM"||r==="EINVAL"||r==="ENOSYS")}async function K(e){try{await e.sync();}catch(r){if(!pe(r))throw r}}async function V(e,r){let t=p.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${p.basename(e)}.`,a=Date.now();for(let i of await promises.readdir(t)){if(!i.startsWith(o)||!i.endsWith(".tmp"))continue;let n=p.join(t,i),d=await promises.stat(n).catch(()=>null);d&&a-d.mtimeMs>3e4&&await promises.rm(n,{force:true}).catch(()=>{});}let s=await promises.readFile(e,"utf8").catch(()=>null);if(s!==null){let i=false;try{let n=JSON.parse(s);i=Array.isArray(n.workspaces);}catch{i=false;}if(!i){let n=`${e}.corrupt-${Date.now()}`;await promises.copyFile(e,n);}}await Z(e,`${JSON.stringify(W(r),null,2)}
2
+ `);}async function Z(e,r){let t=p.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${e}.${process.pid}.${randomUUID()}.tmp`;try{await promises.writeFile(o,r);let a=await promises.open(o,"r");try{await K(a);}finally{await a.close();}try{await promises.rename(o,e);}catch(s){let i=s.code;if(i!=="EEXIST"&&i!=="EPERM")throw s;await ae.move(o,e,{overwrite:true});}}finally{await promises.rm(o,{force:true}).catch(()=>{});}}async function Y(e){try{return {exists:true,content:await promises.readFile(e)}}catch(r){if(r.code==="ENOENT")return {exists:false};throw r}}async function H(e,r){if(!r.exists){await promises.rm(e,{force:true});return}await Z(e,r.content);}async function le(e,r){let t=p.join(e,"workspaces.json.lock"),o=randomUUID();await promises.mkdir(e,{recursive:true});let a=Date.now(),s;for(;!s;)try{s=await promises.open(t,"wx"),await s.writeFile(`${JSON.stringify({pid:process.pid,lockId:o,createdAt:new Date().toISOString()})}
3
+ `),await K(s);}catch(i){if(i.code!=="EEXIST")throw i;let n=await promises.stat(t).catch(()=>null);if(n&&Date.now()-n.mtimeMs>3e4){let d=await promises.readFile(t,"utf8").then(m=>JSON.parse(m)).catch(()=>null),u=Number(d?.pid),f=false;if(Number.isInteger(u)&&u>0)try{process.kill(u,0),f=true;}catch(m){f=m.code==="EPERM";}if(!f){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>1e4)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(d=>setTimeout(d,25));}try{return await r()}finally{await s.close().catch(()=>{}),await promises.readFile(t,"utf8").then(n=>JSON.parse(n).lockId===o).catch(()=>false)&&await promises.rm(t,{force:true}).catch(()=>{});}}async function P(e){let r$1=p$2(),t=p.join(r$1,"workspaces.json"),o=p.join(q(),"workspaces.json"),a=[...new Set(r())];return le(r$1,async()=>{let[s,i]=await Promise.all([Y(t),Y(o)]),n=await ce(a);await e(n);let d=W(n);try{await V(t,d),await V(o,d);}catch(u){let m=(await Promise.allSettled([H(t,s),H(o,i)])).filter(g=>g.status==="rejected").map(g=>g.reason);throw m.length>0?new AggregateError([u,...m],"Workspace registry transaction failed and could not be fully restored"):u}return d})}async function ee(e,r){let t=a(e);await P(o=>{let a=o.workspaces.find(s=>s.path===t);if(a){a.name=r,a.mode=a.mode||"full",a.projects=Array.isArray(a.projects)?a.projects:[];return}o.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function de(e,r){try{await ee(e,r);}catch{console.warn(c.gray("Note: Could not register workspace in shared registry"));}}async function Fe(e,r=false){let t=a(e),o={workspacePath:t,workspaceFound:false,added:[],skipped:0};try{let a$1=await B(),s=a$1.workspaces.find(g=>g.path===t);if(!s){if(await de(t,p.basename(p.resolve(e))),a$1=await B(),s=a$1.workspaces.find(g=>g.path===t),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),o;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,n=0,d=[],u=[],f=[e],m=new Set;for(;f.length>0;){let g=f.shift();if(!g||m.has(g))continue;m.add(g);let y=await promises.readdir(g,{withFileTypes:true});for(let h of y){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let j=p.join(g,h.name),k=a(j);try{let w=false;for(let $ of [...p$1(k,"context.json"),...p$1(k,"project.json")])try{await promises.access($),w=true;break}catch{}if(w){let $=p.basename(k),E=s.projects.some(C=>C.path===k);u.push({name:$,path:k}),E?n++:(s.projects.push({name:$,path:k}),i++,d.push(k),r||console.log(`\u2714 Added: ${p.relative(e,k)}`));continue}}catch{}f.push(j);}}return await P(g=>{let y=g.workspaces.find(k=>k.path===t);if(!y)return;let h=`${t}${p.sep}`,j=(y.projects||[]).filter(k=>k.path!==t&&!k.path.startsWith(h));y.projects=Q({...y,projects:[...j,...u]}).projects;}),i>0?r||console.log(`
4
4
  \u2705 Synced ${i} project(s) to registry`):r||console.log(`
5
- \u2705 All projects already registered (${n} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:n}}catch(o){return r||console.error("\u274C Failed to sync projects:",o.message),a$1}}async function de(e,r,t){let a$1=a(e),o=a(t);await P(s=>{let i=s.workspaces.find(m=>m.path===a$1);if(!i)throw new Error(`Workspace is not registered: ${a$1}`);i.projects=Array.isArray(i.projects)?i.projects:[];let n=i.projects.findIndex(m=>m.path===o||m.name===r),d={name:r,path:o};n>=0?i.projects[n]=d:i.projects.push(d);});}async function Oe(e,r,t){try{await de(e,r,t);}catch{}}async function Fe(e,r){let t=S("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(p.join(e,".workspai"),{recursive:true});let a={workspace_name:r.name,author:r.author,rapidkit_version:c$1(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(p.join(e,".workspai","config.json"),JSON.stringify(a,null,2));let{syncWorkspaceFoundationFiles:o}=await import('./create-WCV3L6XH.js');await o(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=me();await promises.writeFile(p.join(e,"rapidkit"),s),await promises.chmod(p.join(e,"rapidkit"),493);let i=ge();await promises.writeFile(p.join(e,"rapidkit.cmd"),i);let n=ue(r.name);await promises.writeFile(p.join(e,"README.md"),n),await promises.writeFile(p.join(e,".gitignore"),`# Workspai workspace
5
+ \u2705 All projects already registered (${n} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:n}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function me(e,r,t){let o=a(e),a$1=a(t);await P(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let n=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};n>=0?i.projects[n]=d:i.projects.push(d);});}async function Be(e,r,t){try{await me(e,r,t);}catch{}}async function Te(e,r){let t=S("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(p.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:c$1(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(p.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-DBQNAMKP.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=ge();await promises.writeFile(p.join(e,"rapidkit"),s),await promises.chmod(p.join(e,"rapidkit"),493);let i=ue();await promises.writeFile(p.join(e,"rapidkit.cmd"),i);let n=we(r.name);await promises.writeFile(p.join(e,"README.md"),n),await promises.writeFile(p.join(e,".gitignore"),`# Workspai workspace
6
6
  .env
7
7
  .env.*
8
8
  !.env.example
@@ -17,7 +17,7 @@ Thumbs.db
17
17
 
18
18
  # Logs
19
19
  *.log
20
- `),await we(e),t.succeed("Workspace created!"),r.skipGit||await H(e,S(),"Initial commit: Workspai workspace"),await K(e,r.name);let{publishWorkspaceRegistrySummary:m}=await import('./workspace-registry-summary-SZ46R5PD.js');await m(e),console.log(`
20
+ `),await fe(e),t.succeed("Workspace created!"),r.skipGit||await X(e,S(),"Initial commit: Workspai workspace"),await ee(e,r.name);let{publishWorkspaceRegistrySummary:u}=await import('./workspace-registry-summary-ORDK7A36.js');await u(e),console.log(`
21
21
  ${c.green("\u2728 Workspai workspace created successfully!")}
22
22
 
23
23
  ${c.bold("\u{1F4C2} Workspace structure:")}
@@ -54,7 +54,7 @@ ${c.bold("\u{1F4DA} Commands:")}
54
54
 
55
55
  ${c.gray("Alternative: npx workspai dev, make dev")}
56
56
  ${c.gray("\u{1F4A1} Tip: Install globally (npm i -g workspai) to use without npx")}
57
- `);}catch(a){throw t.fail("Failed to create workspace"),a}}function me(){return `#!/usr/bin/env bash
57
+ `);}catch(o){throw t.fail("Failed to create workspace"),o}}function ge(){return `#!/usr/bin/env bash
58
58
  #
59
59
  # Workspai CLI - local workspace commands
60
60
  # This script provides legacy ./rapidkit commands within the workspace
@@ -440,7 +440,7 @@ main() {
440
440
  }
441
441
 
442
442
  main "$@"
443
- `}function ge(){return `@echo off
443
+ `}function ue(){return `@echo off
444
444
  setlocal enabledelayedexpansion
445
445
 
446
446
  set "SCRIPT_DIR=%~dp0"
@@ -460,7 +460,7 @@ if %ERRORLEVEL%==0 (
460
460
  echo [Workspai] No sh/bash found. Falling back to npx workspai.
461
461
  npx workspai %*
462
462
  exit /b %ERRORLEVEL%
463
- `}function ue(e){return `# ${e}
463
+ `}function we(e){return `# ${e}
464
464
 
465
465
  Workspai workspace for building API projects.
466
466
 
@@ -517,7 +517,7 @@ instructions start at \`AGENTS.md\`.
517
517
 
518
518
  - [Workspai Documentation](https://workspai.dev)
519
519
  - [GitHub Repository](https://github.com/rapidkitlabs/workspai)
520
- `}async function we(e){let{fileURLToPath:r}=await import('url'),t=r(import.meta.url),a=p.dirname(t),o=p.resolve(a,".."),s=p.join(o,"templates","kits"),i=p.join(e,".workspai","templates"),{default:n}=await import('fs-extra');await n.copy(s,i);let d=p.join(o,"templates","generator.js"),m=p.join(e,".workspai","generator.js");await n.copy(d,m);}async function Be(e,r){let t=r.template==="fastapi",a=t?"FastAPI":"NestJS",o=S(`Creating ${a} project...`).start();try{let{fileURLToPath:s}=await import('url'),i=s(import.meta.url),n=p.dirname(i),d=p.resolve(n,".."),m=t?"fastapi-standard":"nestjs-standard",w=p.join(d,"templates","kits",m);await promises.mkdir(e,{recursive:true});let g={project_name:t?r.name.replace(/-/g,"_").toLowerCase():r.name.replace(/_/g,"-").toLowerCase(),author:r.author,description:r.description||`${a} application generated with Workspai`,app_version:"0.1.0",license:"MIT",package_manager:r.package_manager||"npm",created_at:new Date().toISOString(),rapidkit_version:c$1()};await Z(w,e,g);let u=t?`# Python
520
+ `}async function fe(e){let{fileURLToPath:r}=await import('url'),t=r(import.meta.url),o=p.dirname(t),a=p.resolve(o,".."),s=p.join(a,"templates","kits"),i=p.join(e,".workspai","templates"),{default:n}=await import('fs-extra');await n.copy(s,i);let d=p.join(a,"templates","generator.js"),u=p.join(e,".workspai","generator.js");await n.copy(d,u);}async function Je(e,r){let t=r.template==="fastapi",o=t?"FastAPI":"NestJS",a=S(`Creating ${o} project...`).start();try{let{fileURLToPath:s}=await import('url'),i=s(import.meta.url),n=p.dirname(i),d=p.resolve(n,".."),u=t?"fastapi-standard":"nestjs-standard",f=p.join(d,"templates","kits",u);await promises.mkdir(e,{recursive:true});let m={project_name:t?r.name.replace(/-/g,"_").toLowerCase():r.name.replace(/_/g,"-").toLowerCase(),author:r.author,description:r.description||`${o} application generated with Workspai`,app_version:"0.1.0",license:"MIT",package_manager:r.package_manager||"npm",created_at:new Date().toISOString(),rapidkit_version:c$1()};await te(f,e,m);let g=t?`# Python
521
521
  __pycache__/
522
522
  *.py[cod]
523
523
  *$py.class
@@ -585,7 +585,7 @@ Thumbs.db
585
585
 
586
586
  # Coverage
587
587
  coverage/
588
- `;if(await promises.writeFile(p.join(e,".gitignore"),u),o.succeed(`${a} project created!`),r.skipGit||await H(e,S(),`Initial commit: ${a} project via Workspai`),!r.skipInstall&&!t){let h=r.package_manager||"npm",j=S(`Installing dependencies with ${h}...`).start();try{await execa(h,["install"],{cwd:e}),j.succeed("Dependencies installed");}catch{j.warn(`Could not install dependencies. Run '${h} install' manually.`);}}let y=p.basename(e);console.log(t?`
588
+ `;if(await promises.writeFile(p.join(e,".gitignore"),g),a.succeed(`${o} project created!`),r.skipGit||await X(e,S(),`Initial commit: ${o} project via Workspai`),!r.skipInstall&&!t){let h=r.package_manager||"npm",j=S(`Installing dependencies with ${h}...`).start();try{await execa(h,["install"],{cwd:e}),j.succeed("Dependencies installed");}catch{j.warn(`Could not install dependencies. Run '${h} install' manually.`);}}let y=p.basename(e);console.log(t?`
589
589
  ${c.green("\u2728 FastAPI project created successfully!")}
590
590
 
591
591
  ${c.bold("\u{1F4C2} Project structure:")}
@@ -651,16 +651,16 @@ ${c.bold("\u{1F310} API endpoints:")}
651
651
  http://localhost:8000/examples/notes # Example API
652
652
 
653
653
  ${c.gray("\u{1F4A1} Tip: Install globally (npm i -g workspai) to use without npx")}
654
- `);}catch(s){throw o.fail(`Failed to create ${a} project`),s}}async function Z(e,r,t){let a=await promises.readdir(e,{withFileTypes:true});for(let o of a){let s=p.join(e,o.name),i=o.name.replace(/\.j2$/,""),n=p.join(r,i);if(o.isDirectory())await promises.mkdir(n,{recursive:true}),await Z(s,n,t);else {let d=await promises.readFile(s,"utf-8");o.name.endsWith(".j2")&&(d=fe(d,t)),await promises.writeFile(n,d),(i==="rapidkit"||i==="activate"||i.endsWith(".py")&&(n.includes(".workspai")||n.includes(".rapidkit")))&&await promises.chmod(n,493);}}}function fe(e,r){let t=e;for(let[a,o]of Object.entries(r)){let s=new RegExp(`\\{\\{\\s*${a}\\s*\\}\\}`,"g");t=t.replace(s,String(o));let i=new RegExp(`\\{\\{\\s*${a}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\}\\}`,"g");t=t.replace(i,(m,w,g)=>String(o).replace(new RegExp(w,"g"),g));let n=new RegExp(`\\{\\{\\s*${a}\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(n,String(o).toLowerCase());let d=new RegExp(`\\{\\{\\s*${a}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(d,(m,w,g)=>String(o).replace(new RegExp(w,"g"),g).toLowerCase());}return t}async function Te(e={}){let r=p$2(),t=p.join(r,"workspaces.json"),a=await B();if(a.workspaces.length===0){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:false}},null,2));return}console.log(c.yellow(`
654
+ `);}catch(s){throw a.fail(`Failed to create ${o} project`),s}}async function te(e,r,t){let o=await promises.readdir(e,{withFileTypes:true});for(let a of o){let s=p.join(e,a.name),i=a.name.replace(/\.j2$/,""),n=p.join(r,i);if(a.isDirectory())await promises.mkdir(n,{recursive:true}),await te(s,n,t);else {let d=await promises.readFile(s,"utf-8");a.name.endsWith(".j2")&&(d=ke(d,t)),await promises.writeFile(n,d),(i==="rapidkit"||i==="activate"||i.endsWith(".py")&&(n.includes(".workspai")||n.includes(".rapidkit")))&&await promises.chmod(n,493);}}}function ke(e,r){let t=e;for(let[o,a]of Object.entries(r)){let s=new RegExp(`\\{\\{\\s*${o}\\s*\\}\\}`,"g");t=t.replace(s,String(a));let i=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\}\\}`,"g");t=t.replace(i,(u,f,m)=>String(a).replace(new RegExp(f,"g"),m));let n=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(n,String(a).toLowerCase());let d=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(d,(u,f,m)=>String(a).replace(new RegExp(f,"g"),m).toLowerCase());}return t}async function Ge(e={}){let r=p$2(),t=p.join(r,"workspaces.json"),o=await B();if(o.workspaces.length===0){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:false}},null,2));return}console.log(c.yellow(`
655
655
  \u26A0\uFE0F No workspaces registered yet.
656
656
  `)),console.log(c.gray(`Create a workspace with: npx workspai <workspace-name>
657
- `));return}try{let o=a;if(!o||typeof o!="object"||!Array.isArray(o.workspaces)){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:true,registryValid:false},error:{code:"workspace.registry.invalid",message:"Workspace registry is invalid."}},null,2));return}console.log(c.yellow(`
657
+ `));return}try{let a=o;if(!a||typeof a!="object"||!Array.isArray(a.workspaces)){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:true,registryValid:false},error:{code:"workspace.registry.invalid",message:"Workspace registry is invalid."}},null,2));return}console.log(c.yellow(`
658
658
  \u26A0\uFE0F Workspace registry is invalid; resetting to empty state.
659
- `)),await P(g=>{g.workspaces=[];});return}let s=W(o),i=[],n=0;for(let g of s.workspaces)await promises.stat(g.path).catch(()=>null)?i.push(g):n+=1;let d={workspaces:i},m=JSON.stringify(o),w=JSON.stringify(d);if(!e.json&&m!==w){let g=new Set(i.map(u=>u.path));await P(u=>{u.workspaces=u.workspaces.filter(y=>g.has(y.path));});}if(!d.workspaces||d.workspaces.length===0){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:n,registryExists:true,registryValid:true,cleanupApplied:false}},null,2));return}console.log(c.yellow(`
659
+ `)),await P(m=>{m.workspaces=[];});return}let s=W(a),i=[],n=0;for(let m of s.workspaces)await promises.stat(m.path).catch(()=>null)?i.push(m):n+=1;let d={workspaces:i},u=JSON.stringify(a),f=JSON.stringify(d);if(!e.json&&u!==f){let m=new Set(i.map(g=>g.path));await P(g=>{g.workspaces=g.workspaces.filter(y=>m.has(y.path));});}if(!d.workspaces||d.workspaces.length===0){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:n,registryExists:true,registryValid:true,cleanupApplied:false}},null,2));return}console.log(c.yellow(`
660
660
  \u26A0\uFE0F No workspaces registered yet.
661
661
  `)),n>0&&console.log(c.gray(`Cleaned ${n} stale workspace entr${n===1?"y":"ies"}.
662
662
  `));return}if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:d.workspaces,summary:{total:d.workspaces.length,missing:n,registryExists:true,registryValid:true,cleanupApplied:false}},null,2));return}console.log(c.bold(`
663
663
  \u{1F4E6} Registered Workspai Workspaces:
664
- `));for(let g of d.workspaces)console.log(c.cyan(` ${g.name}`)),console.log(c.gray(` Path: ${g.path}`)),console.log(c.gray(` Projects: ${g.projects?.length||0}`)),console.log();n>0&&console.log(c.gray(`Cleaned ${n} stale workspace entr${n===1?"y":"ies"}.`)),console.log(c.gray(`Total: ${d.workspaces.length} workspace(s)
665
- `));}catch(o){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:true,registryValid:false},error:{code:"workspace.registry.read_failed",message:o.message}},null,2));return}console.error(c.red(`
666
- \u274C Failed to read workspace registry`)),console.error(c.gray(String(o)));}}async function ke(e){try{let r=await promises.readFile(e,"utf8");return JSON.parse(r)}catch{return null}}async function L(e){for(let r of e){let t=await ke(r);if(t!==null)return t}return null}function he(e){return c$2(e)}async function ye(e){return a$2(e,{skipDirs:new Set(["node_modules","dist","build","target","coverage","htmlcov"]),includeHiddenDirs:false,descendIntoMatchedProjects:true})}async function O(e){try{return (await promises.readdir(e,{withFileTypes:true})).filter(t=>t.isFile()&&t.name.toLowerCase().endsWith(".json")).map(t=>t.name).sort((t,a)=>t.localeCompare(a))}catch{return []}}async function Je(e,r){let t=r?.includePaths===true,a=r?.includeDoctorEvidence!==false,o$1=r?.includeBlueprint!==false,s=p.resolve(e),i=await L(o(s,"workspace.json")),n=typeof i?.workspace_name=="string"&&i.workspace_name.trim()||p.basename(s),d=typeof i?.profile=="string"?i.profile:void 0,m=typeof i?.rapidkit_version=="string"?i.rapidkit_version:void 0,w=await ye(s),g=[];for(let f of w){let $=await L(p$1(f,"project.json")),E=p.relative(s,f)||".",C=p.dirname(p$1(f,p.join("reports","placeholder"))[0]),T=p.dirname(p$1(f,p.join("reports","placeholder"))[1]),N={name:p.basename(f),relative_path:E,runtime:typeof $?.runtime=="string"?$.runtime:void 0,kit_name:typeof $?.kit_name=="string"?$.kit_name:void 0,modules:Array.isArray($?.modules)?$.modules.filter(_=>typeof _=="string"):void 0};if(t&&(N.absolute_path=f),a){let _=await L([p.join(C,"doctor-last-run.json"),p.join(T,"doctor-last-run.json")]);he(_)&&(N.doctor_report=_);}let J=[...await O(C),...await O(T)].filter((_,ee,te)=>te.indexOf(_)===ee);J.length>0&&(N.reports=J),g.push(N);}let u=o(s,"reports"),y=[...await O(u[0]),...await O(u[1])].filter((f,$,E)=>E.indexOf(f)===$),h=await L(o(s,"workspace.contract.json")),j={schema_version:"1.1",generated_at:new Date().toISOString(),generated_by:"workspai",workspace:{name:n,relative_root:".",profile:d,rapidkit_version:m,...t?{absolute_root:s}:{}},summary:{project_count:g.length,doctor_evidence_included:a,contract_included:!!h},reports:{workspace:y},projects:g,...h?{contract:h}:{}};o$1&&(j.blueprint={schema_version:"rapidkit.workspace-blueprint.v1",purpose:"portable-reproducibility",workspace:{name:n,profile:d},projects:g.map(f=>({name:f.name,relative_path:f.relative_path,runtime:f.runtime,kit_name:f.kit_name,modules:f.modules??[],recreate_commands:[...f.kit_name?[`npx workspai create project ${f.kit_name} ${f.name} --yes --skip-install`]:[],`cd ${f.relative_path}`,"npx workspai init","npx workspai test"]})),recommended_commands:["npx workspai workspace contract verify --strict","npx workspai doctor workspace","npx workspai workspace run init --json","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"]});let k=r?.outputPath?p.resolve(r.outputPath):p.join(u[0],"share-bundle.json");return await promises.mkdir(p.dirname(k),{recursive:true}),await promises.writeFile(k,JSON.stringify(j,null,2),"utf8"),k}export{q as a,K as b,le as c,Le as d,de as e,Oe as f,Fe as g,Be as h,Te as i,Je as j};
664
+ `));for(let m of d.workspaces)console.log(c.cyan(` ${m.name}`)),console.log(c.gray(` Path: ${m.path}`)),console.log(c.gray(` Projects: ${m.projects?.length||0}`)),console.log();n>0&&console.log(c.gray(`Cleaned ${n} stale workspace entr${n===1?"y":"ies"}.`)),console.log(c.gray(`Total: ${d.workspaces.length} workspace(s)
665
+ `));}catch(a){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:true,registryValid:false},error:{code:"workspace.registry.read_failed",message:a.message}},null,2));return}console.error(c.red(`
666
+ \u274C Failed to read workspace registry`)),console.error(c.gray(String(a)));}}async function he(e){try{let r=await promises.readFile(e,"utf8");return JSON.parse(r)}catch{return null}}async function L(e){for(let r of e){let t=await he(r);if(t!==null)return t}return null}function ye(e){return c$2(e)}async function $e(e){return a$2(e,{skipDirs:new Set(["node_modules","dist","build","target","coverage","htmlcov"]),includeHiddenDirs:false,descendIntoMatchedProjects:true})}async function O(e){try{return (await promises.readdir(e,{withFileTypes:true})).filter(t=>t.isFile()&&t.name.toLowerCase().endsWith(".json")).map(t=>t.name).sort((t,o)=>t.localeCompare(o))}catch{return []}}async function ze(e,r){let t=r?.includePaths===true,o$1=r?.includeDoctorEvidence!==false,a=r?.includeBlueprint!==false,s=p.resolve(e),i=await L(o(s,"workspace.json")),n=typeof i?.workspace_name=="string"&&i.workspace_name.trim()||p.basename(s),d=typeof i?.profile=="string"?i.profile:void 0,u=typeof i?.rapidkit_version=="string"?i.rapidkit_version:void 0,f=await $e(s),m=[];for(let w of f){let $=await L(p$1(w,"project.json")),E=p.relative(s,w)||".",C=p.dirname(p$1(w,p.join("reports","placeholder"))[0]),T=p.dirname(p$1(w,p.join("reports","placeholder"))[1]),N={name:p.basename(w),relative_path:E,runtime:typeof $?.runtime=="string"?$.runtime:void 0,kit_name:typeof $?.kit_name=="string"?$.kit_name:void 0,modules:Array.isArray($?.modules)?$.modules.filter(_=>typeof _=="string"):void 0};if(t&&(N.absolute_path=w),o$1){let _=await L([p.join(C,"doctor-last-run.json"),p.join(T,"doctor-last-run.json")]);ye(_)&&(N.doctor_report=_);}let J=[...await O(C),...await O(T)].filter((_,re,oe)=>oe.indexOf(_)===re);J.length>0&&(N.reports=J),m.push(N);}let g=o(s,"reports"),y=[...await O(g[0]),...await O(g[1])].filter((w,$,E)=>E.indexOf(w)===$),h=await L(o(s,"workspace.contract.json")),j={schema_version:"1.1",generated_at:new Date().toISOString(),generated_by:"workspai",workspace:{name:n,relative_root:".",profile:d,rapidkit_version:u,...t?{absolute_root:s}:{}},summary:{project_count:m.length,doctor_evidence_included:o$1,contract_included:!!h},reports:{workspace:y},projects:m,...h?{contract:h}:{}};a&&(j.blueprint={schema_version:"rapidkit.workspace-blueprint.v1",purpose:"portable-reproducibility",workspace:{name:n,profile:d},projects:m.map(w=>({name:w.name,relative_path:w.relative_path,runtime:w.runtime,kit_name:w.kit_name,modules:w.modules??[],recreate_commands:[...w.kit_name?[`npx workspai create project ${w.kit_name} ${w.name} --yes --skip-install`]:[],`cd ${w.relative_path}`,"npx workspai init","npx workspai test"]})),recommended_commands:["npx workspai workspace contract verify --strict","npx workspai doctor workspace","npx workspai workspace run init --json","npx workspai workspace run test --strict --json","npx workspai readiness --strict --json"]});let k=r?.outputPath?p.resolve(r.outputPath):p.join(g[0],"share-bundle.json");return r?.outputPath||b(".workspai/reports/share-bundle.json",j),await promises.mkdir(p.dirname(k),{recursive:true}),await promises.writeFile(k,JSON.stringify(j,null,2),"utf8"),k}export{Q as a,ee as b,de as c,Fe as d,me as e,Be as f,Te as g,Je as h,Ge as i,ze as j};
@@ -1 +1 @@
1
- import {b}from'./chunk-N7DV5L7C.js';var i=b.doctor,s="doctor-project-evidence-v1";function f(r){return !r||typeof r!="object"||Array.isArray(r)?null:r}function u(r,n){let t=f(r);if(!t)return false;let o=t.schemaVersion,e=t.evidenceType;return !(typeof o=="string"&&(o!==i&&o!==s||n==="workspace"&&o!==i||n==="project"&&o!==s)||typeof e=="string"&&(e!=="workspace"&&e!=="project"||n&&e!==n))}export{i as a,s as b,u as c};
1
+ import {b}from'./chunk-BMWFQXGW.js';var i=b.doctor,s="doctor-project-evidence-v1";function f(r){return !r||typeof r!="object"||Array.isArray(r)?null:r}function u(r,n){let t=f(r);if(!t)return false;let o=t.schemaVersion,e=t.evidenceType;return !(typeof o=="string"&&(o!==i&&o!==s||n==="workspace"&&o!==i||n==="project"&&o!==s)||typeof e=="string"&&(e!=="workspace"&&e!=="project"||n&&e!==n))}export{i as a,s as b,u as c};
@@ -1 +1 @@
1
- export{c as PYTHON_FREE_WORKSPACE_PROFILES,a as buildWorkspaceManifest,f as createProject,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,b as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-J5PIZCAU.js';
1
+ export{c as PYTHON_FREE_WORKSPACE_PROFILES,a as buildWorkspaceManifest,f as createProject,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,b as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-I46XEIPL.js';
@@ -1 +1 @@
1
- export{a as DOCTOR_WORKSPACE_REPORT_PATH,m as applyEnvKeyAddFix,i as applyFileAppendFix,j as applyFileCopyFix,h as applyFileCreateFix,l as applyJsonEditFix,n as applyMakefileTargetFix,g as applyPackageScriptFix,f as assertOperationPathInsideProject,e as buildRepairOperationIdentity,p as computeDoctorFixAwareExitCode,o as computeDoctorGateExitCode,k as decodeJsonPointerSegment,d as parseInternalRepairCommand,c as parsePackageScriptFix,b as resolveDoctorPolicyProfile,q as runDoctor}from'./chunk-VFDM65IE.js';
1
+ export{a as DOCTOR_WORKSPACE_REPORT_PATH,m as applyEnvKeyAddFix,i as applyFileAppendFix,j as applyFileCopyFix,h as applyFileCreateFix,l as applyJsonEditFix,n as applyMakefileTargetFix,g as applyPackageScriptFix,f as assertOperationPathInsideProject,e as buildRepairOperationIdentity,p as computeDoctorFixAwareExitCode,o as computeDoctorGateExitCode,k as decodeJsonPointerSegment,d as parseInternalRepairCommand,c as parsePackageScriptFix,b as resolveDoctorPolicyProfile,q as runDoctor}from'./chunk-BFLJ2R4D.js';